import type { AgentAutomation_Serialize, AgentEntry, AgentProvider, AgentTask, AutomationRun_Serialize, AutomationTrigger, CreateSessionScheduleInput, SaveAutomationInput_Deserialize, SessionSchedule_Serialize as SessionSchedule, } from "../src/bindings"; import { expect, stubDesktop, stubSettingsWrites, test } from "./fixtures"; const claudeProvider: AgentProvider = { id: "claude", name: "Claude Code", command: "claude", program: "claude", args: [], defaultProgram: "claude", defaultArgs: [], loginHint: null, commandOverridden: false, commandEditable: true, commandReadOnlyReason: null, installed: true, env: {}, commands: [], source: { kind: "builtin" }, config: [ { id: "model", category: "model", name: "Model", description: null, current: "claude-sonnet-4.6", via: "option", values: [{ value: "claude-sonnet-4.6", name: "Claude Sonnet 4.6", description: null }], }, ], thoughtLevels: {}, }; const manualSession: AgentTask = { id: "manual-session-1", title: "Refactor auth middleware", provider: "claude", status: "ready", isolation: "local", model: "claude-sonnet-4.6", cwd: "/dev/acme-api", branch: "main", base: null, baseCommit: null, error: null, createdMs: 1_000, updatedMs: 5_000, config: claudeProvider.config, commands: [], usage: null, queue: [], mcpOverrides: {}, skillOverrides: {}, }; async function installAutomationDesktopHarness(page: import("@playwright/test").Page) { await stubDesktop(page); await stubSettingsWrites(page); await page.evaluate( async ({ claudeProvider, manualSession }) => { const storeModule = "/src/features/agents/store.ts"; const autoModule = "/src/features/agents/automationsModel.ts"; const store = await import(/* @vite-ignore */ storeModule); const autoMod = await import(/* @vite-ignore */ autoModule); let seq = 1; let autoStartService = false; let automations: AgentAutomation_Serialize[] = []; let runs: AutomationRun_Serialize[] = []; let sessionSchedules: SessionSchedule[] = []; const tasks = new Map([[manualSession.id, structuredClone(manualSession)]]); const entriesByTask = new Map([ [ manualSession.id, [ { type: "user", text: "Inspect auth middleware.", attachments: [] }, { type: "agent", text: "Ready for follow-up or scheduled turns." }, ], ], ]); const handlers = window.__ipc.handlers; handlers.agent_subscribe = () => [...tasks.values()]; handlers.agent_providers = () => [claudeProvider]; handlers.agent_refresh_models = () => ({ provider: claudeProvider.id, config: claudeProvider.config, thoughtLevels: {}, refreshing: false, refreshedAtMs: Date.now(), retryAtMs: null, error: null, }); handlers.agent_probe = () => null; handlers.agent_entries = ({ task }) => entriesByTask.get(task as string) ?? []; handlers.agent_changes = () => []; handlers.agent_grouped_changes = () => ({ uncommitted: [], commits: [] }); handlers.agent_commands = () => []; handlers.agent_skills_list = () => []; handlers.agent_memory_list = () => ({ entries: [], providers: [], autoMemory: "inherit", autoMemoryOrigin: "none", }); handlers.mcp_list = () => ({ servers: [], external: [] }); handlers.vcs_branch_info = () => ({ head: "main" }); handlers.vcs_branches = () => [{ name: "main", remote: false, current: true }]; handlers.agent_set_unread = () => null; const buildSnapshot = () => { for (const a of automations) { a.unreadRuns = runs.filter((r) => r.automationId === a.id && r.unread).length; } const activeSchedules = automations.filter((a) => autoMod.isAutomationActivelyScheduled(a)).length; const unreadRuns = runs.filter((r) => r.unread).length; const needsInputRuns = runs.filter((r) => r.status === "needsInput").length; const runningRuns = runs.filter((r) => r.status === "running").length; const nextRunMs = automations .filter((a) => a.enabled && a.nextRunMs != null) .map((a) => a.nextRunMs!) .sort((x, y) => x - y)[0] ?? null; const bootRegistered = autoStartService && activeSchedules > 0; return { automations: structuredClone(automations), runs: structuredClone(runs), runsNextCursor: null, sessionSchedules: structuredClone(sessionSchedules), host: { remote: false, hostLabel: "Local Host", activeSchedules, runningRuns, needsInputRuns, unreadRuns, nextRunMs, bootServiceKind: "LaunchAgent", bootServiceRegistered: bootRegistered, bootServicePath: bootRegistered ? "/Users/dev/Library/LaunchAgents/ai.l0ng.openidea.scheduler.plist" : null, bootServiceError: null, linuxLingerEnabled: null, }, }; }; const prevSettingsSet = handlers.settings_set; handlers.settings_set = (args) => { if (args.key === "agents.automations.autoStartService") { autoStartService = JSON.parse(String(args.value)) === true; } return prevSettingsSet ? prevSettingsSet(args) : null; }; handlers.agent_automation_snapshot = () => buildSnapshot(); handlers.agent_automation_preview_schedule = ({ trigger, count }) => { try { return autoMod.previewTriggerBrowser(trigger as AutomationTrigger, Date.now(), (count as number | null) ?? 3); } catch (err) { throw { kind: "invalid", message: err instanceof Error ? err.message : String(err), detail: null }; } }; handlers.agent_automation_save = ({ input }) => { const req = input as SaveAutomationInput_Deserialize; const now = Date.now(); const regularNext = autoMod.previewTriggerBrowser(req.trigger, now, 1)[0] ?? null; const idx = req.id ? automations.findIndex((a) => a.id === req.id) : -1; const prev = idx >= 0 ? automations[idx] : undefined; const allowSelf = req.allowAgentSchedule ?? false; const triggerUnchanged = Boolean(prev && autoMod.triggersEqual(prev.trigger, req.trigger)); const maxRunsReached = req.maxRuns != null && (prev?.runCount ?? 0) >= req.maxRuns; const preservedOverride = prev && req.enabled && allowSelf && !req.clearOverride && triggerUnchanged && !maxRunsReached && prev.nextRunOverrideMs != null && prev.nextRunOverrideMs > now && (req.disableAfterMs == null || prev.nextRunOverrideMs < req.disableAfterMs) ? prev.nextRunOverrideMs : null; if (req.enabled && preservedOverride == null && req.trigger.kind === "oneShot" && regularNext == null) { throw { kind: "invalid", message: "one-shot timestamp must be in the future when enabled", detail: null }; } const saved: AgentAutomation_Serialize = { id: prev?.id ?? `auto-${seq++}`, name: req.name, enabled: req.enabled, prompt: req.prompt, workspace: req.workspace.kind === "chatOnly" ? { kind: "chatOnly" } : { kind: "project", root: req.workspace.root, isolation: req.workspace.isolation ?? "worktree", base: req.workspace.base ?? null, autoCleanWorktree: req.workspace.autoCleanWorktree ?? true, }, continuity: req.continuity ?? "newTask", lastTaskId: prev?.lastTaskId ?? null, provider: req.provider, config: req.config ?? [], permissions: req.permissions ?? "assisted", mcpOverrides: req.mcpOverrides ?? {}, skillOverrides: req.skillOverrides ?? {}, memoryOverrides: req.memoryOverrides ?? null, trigger: req.trigger, allowAgentSchedule: allowSelf, misfirePolicy: req.misfirePolicy ?? null, disableAfterMs: req.disableAfterMs ?? null, maxRuns: req.maxRuns ?? null, nextRunOverrideMs: preservedOverride, nextPromptOverride: preservedOverride != null ? (prev?.nextPromptOverride ?? null) : null, nextRunMs: req.enabled ? (preservedOverride ?? regularNext) : null, runCount: prev?.runCount ?? 0, unreadRuns: prev?.unreadRuns ?? 0, createdMs: prev?.createdMs ?? now, updatedMs: now, }; if (idx >= 0) automations[idx] = saved; else automations.unshift(saved); window.__ipc.emit({ type: "automationsChanged" }); return saved; }; handlers.agent_automation_set_enabled = ({ id, enabled }) => { const found = automations.find((a) => a.id === id)!; found.enabled = Boolean(enabled); found.nextRunMs = found.enabled ? (autoMod.previewTriggerBrowser(found.trigger, Date.now(), 1)[0] ?? null) : null; window.__ipc.emit({ type: "automationsChanged" }); return structuredClone(found); }; handlers.agent_automation_delete = ({ id }) => { automations = automations.filter((a) => a.id !== id); runs = runs.filter((r) => r.automationId !== id); window.__ipc.emit({ type: "automationsChanged" }); return null; }; handlers.__test_set_override = ({ id, nextRunOverrideMs, nextPromptOverride, trigger }) => { const found = automations.find((a) => a.id === id); if (found) { if (trigger) found.trigger = trigger as AutomationTrigger; found.nextRunOverrideMs = (nextRunOverrideMs as number | null) ?? null; found.nextPromptOverride = (nextPromptOverride as string | null) ?? null; if (found.nextRunOverrideMs != null) found.nextRunMs = found.nextRunOverrideMs; window.__ipc.emit({ type: "automationsChanged" }); } return null; }; handlers.agent_automation_pause_all = () => { let n = 0; for (const a of automations) { if (a.enabled) { a.enabled = false; a.nextRunMs = null; n += 1; } } window.__ipc.emit({ type: "automationsChanged" }); return n; }; handlers.agent_automation_mark_read = ({ runId, automationId }) => { for (const r of runs) { if ( (runId && r.id === runId) || (!runId && automationId && r.automationId === automationId) || (!runId && !automationId) ) { r.unread = false; } } window.__ipc.emit({ type: "automationsChanged" }); return null; }; handlers.agent_automation_run_now = ({ id }) => { const found = automations.find((a) => a.id === id)!; found.runCount += 1; const needsApproval = found.prompt.text.includes("NEEDS_APPROVAL"); const reuseTask = found.continuity === "sameTask" && found.lastTaskId && tasks.has(found.lastTaskId) ? tasks.get(found.lastTaskId)! : null; const taskId = reuseTask ? reuseTask.id : `auto-task-${seq++}`; found.lastTaskId = taskId; const taskObj: AgentTask = reuseTask ? { ...reuseTask, status: needsApproval ? "needsInput" : "ready", updatedMs: Date.now(), automation: { automationId: found.id, automationName: found.name, runId: `run-${seq}`, runNumber: found.runCount, triggerSummary: "Scheduled", }, } : { id: taskId, title: found.continuity === "sameTask" ? found.name : `${found.name} (#${found.runCount})`, provider: found.provider, status: needsApproval ? "needsInput" : "ready", isolation: found.workspace.kind === "project" ? found.workspace.isolation : "local", model: "claude-sonnet-4.6", cwd: "/dev/acme-api", branch: found.workspace.kind === "project" && found.workspace.isolation === "worktree" ? `agent/auto-${found.runCount}` : "main", base: "main", baseCommit: null, error: null, createdMs: Date.now(), updatedMs: Date.now(), config: claudeProvider.config, commands: [], usage: null, queue: [], mcpOverrides: {}, skillOverrides: {}, automation: { automationId: found.id, automationName: found.name, runId: `run-${seq}`, runNumber: found.runCount, triggerSummary: "Scheduled", }, }; tasks.set(taskId, taskObj); entriesByTask.set(taskId, [ { type: "user", text: found.prompt.text, attachments: [] }, ...(needsApproval ? ([ { type: "permission", id: 1, title: "Run gh pr edit --add-label triaged", command: "gh pr edit --add-label triaged", options: [ { id: "allow", kind: "allow_once", name: "Allow once" }, { id: "deny", kind: "reject_once", name: "Decline" }, ], chosen: null, }, ] as AgentEntry[]) : ([ { type: "agent", text: `Completed automated run #${found.runCount} cleanly.`, }, ] as AgentEntry[])), ]); store.useAgents.setState((s: { tasks: Map }) => ({ tasks: new Map(s.tasks).set(taskId, taskObj), })); const run: AutomationRun_Serialize = { id: `run-${seq++}`, automationId: found.id, automationName: found.name, runNumber: found.runCount, taskId, projectRoot: "/dev/acme-api", provider: found.provider, origin: { kind: "manual" }, status: needsApproval ? "needsInput" : "completed", startedMs: Date.now(), finishedMs: needsApproval ? null : Date.now(), error: null, unread: true, added: needsApproval ? 0 : 0, removed: 0, branch: taskObj.branch ?? null, worktreeCleaned: !needsApproval && found.continuity === "newTask" && found.workspace.kind === "project" && found.workspace.isolation === "worktree" && found.workspace.autoCleanWorktree, }; runs.unshift(run); window.__ipc.emit({ type: "automationsChanged" }); return run; }; handlers.agent_automation_export_markdown = ({ id }) => { const found = automations.find((a) => a.id === id)!; return `---\nversion: 1\nid: ${found.id}\nname: "${found.name}"\nschedule:\n kind: cron\n expression: "0 9,15 * * MON-FRI"\n timeZone: "America/Los_Angeles"\n---\n\n${found.prompt.text}\n`; }; handlers.agent_automation_import_markdown = ({ markdown, chatOnly, provider }) => { const m = /name:\s*"?([^"\n]+)"?/.exec(markdown as string); const name = m?.[1]?.trim() || "Imported Schedule"; const body = (markdown as string).split("---").slice(2).join("---").trim(); return handlers.agent_automation_save!({ input: { name, enabled: false, prompt: { text: body || "Imported prompt", files: [], images: [] }, workspace: chatOnly ? { kind: "chatOnly" } : { kind: "project", root: "/dev/acme-api", isolation: "worktree", autoCleanWorktree: true }, continuity: "newTask", provider: provider as string, trigger: { kind: "cron", expression: "0 9,15 * * MON-FRI", timeZone: "America/Los_Angeles" }, }, }); }; handlers.agent_session_schedule_create = ({ input }) => { const req = input as CreateSessionScheduleInput; const created: SessionSchedule = { id: `ssched-${seq++}`, taskId: req.taskId, projectRoot: "/dev/acme-api", prompt: req.prompt, kind: req.kind, paused: false, nextRunMs: req.kind.kind === "sendLater" ? (req.kind.runAtMs ?? Date.now() + 900_000) : Date.now() + req.kind.intervalSecs * 1000, runs: 0, createdMs: Date.now(), }; sessionSchedules.push(created); window.__ipc.emit({ type: "automationsChanged" }); return created; }; handlers.agent_session_schedule_set_paused = ({ id, paused }) => { const sc = sessionSchedules.find((s) => s.id === id)!; sc.paused = Boolean(paused); window.__ipc.emit({ type: "automationsChanged" }); return structuredClone(sc); }; handlers.agent_session_schedule_run_now = ({ id }) => { const idx = sessionSchedules.findIndex((s) => s.id === id); if (idx >= 0) { const sc = sessionSchedules[idx]!; if (sc.kind.kind === "sendLater") sessionSchedules.splice(idx, 1); else sc.runs = (sc.runs ?? 0) + 1; } window.__ipc.emit({ type: "automationsChanged" }); return null; }; handlers.agent_session_schedule_delete = ({ id }) => { sessionSchedules = sessionSchedules.filter((s) => s.id !== id); window.__ipc.emit({ type: "automationsChanged" }); return null; }; await store.connect(); await autoMod.refreshAutomations(); }, { claudeProvider, manualSession }, ); } test("creates, validates cron, runs, inspects provenance, exports/imports .automation.md, and deletes automations", async ({ workbench: page, }) => { await page.setViewportSize({ width: 1320, height: 860 }); await installAutomationDesktopHarness(page); // Open Agents tool window and use the existing Automations options entry await page.evaluate(async () => { const actionsModule = "/src/platform/actions.ts"; const { executeAction } = await import(/* @vite-ignore */ actionsModule); await executeAction("agents.showToolWindow"); }); const header = page.locator('[data-toolwindow="agents"] header'); await expect(header.getByRole("button", { name: "Agent Automations", exact: true })).toHaveCount(0); await expect(header.getByRole("button", { name: "Agent Settings", exact: true })).toBeVisible(); await header.getByRole("button", { name: "Options", exact: true }).click(); await page.getByRole("menuitem", { name: "Automations…", exact: true }).click(); const editor = page.getByTestId("automations-editor"); await expect(editor).toBeVisible(); await expect(editor).toContainText("Automate recurring agent workflows"); // Click a starter template to open New Automation dialog pre-populated await editor.getByRole("button", { name: /Morning PR & CI Triage/ }).click(); const dialog = page.getByRole("dialog", { name: "New Automation" }); await expect(dialog).toBeVisible(); await expect(dialog.getByLabel("Name")).toHaveValue("Morning PR & CI Triage"); // Switch to 5-field Cron expression and verify live validation rejects invalid syntax await dialog.getByRole("button", { name: "Schedule", exact: true }).click(); await page.getByRole("option", { name: "Cron expression" }).click(); const cronInput = dialog.getByLabel("Cron Expression (5-field)"); await cronInput.fill("99 9 * * *"); await expect(dialog.getByTestId("automation-schedule-preview")).toContainText("out of range"); await expect(dialog.getByRole("button", { name: "Create Automation" })).toBeDisabled(); // Fix cron + timezone -> verify live Upcoming runs preview and enable Create await cronInput.fill("0 9,15 * * MON-FRI"); await dialog.getByLabel("Time Zone").fill("America/Los_Angeles"); await expect(dialog.getByTestId("automation-schedule-preview")).toContainText("Upcoming runs:"); await expect(dialog.getByRole("button", { name: "Create Automation" })).toBeEnabled(); await dialog.getByRole("button", { name: /Advanced/ }).click(); await dialog.getByLabel("Stop After Runs (optional)").fill("25"); await dialog.getByRole("button", { name: "Create Automation" }).click(); await expect(dialog).toHaveCount(0); // Verify dashboard row, default-off login service, inline toggle registration, and status bar item await expect(page.getByTestId("scheduler-host-pill")).toContainText("1 active schedule"); await expect(page.getByTestId("scheduler-host-pill")).not.toContainText("Auto-starts on login"); await editor.getByRole("checkbox", { name: "Keep automations running when OpenIDEA is closed" }).click(); await expect(page.getByTestId("scheduler-host-pill")).toContainText("Auto-starts on login"); await expect(page.getByTestId("status-scheduler-button")).toContainText("1 scheduled"); // Trigger Run Now -> switches to Run History and opens SessionEditor with Provenance Banner await editor.getByRole("button", { name: "Run Now" }).click(); const provenance = page.getByTestId("automation-provenance-banner"); await expect(provenance).toBeVisible(); await expect(provenance).toContainText("Automated by"); await expect(provenance).toContainText("Morning PR & CI Triage"); await expect(provenance).toContainText("#1"); // Click Open Automation on provenance banner to jump back to Automations dashboard await provenance.getByRole("button", { name: "Open Automation" }).click(); await expect(editor).toBeVisible(); // Check Run History tab -> zero-diff worktree auto-GC badge + Mark All as Read await editor.getByRole("tab", { name: /Run History/ }).click(); await expect(editor).toContainText("Zero-diff worktree cleaned"); await editor.getByRole("button", { name: "Mark All as Read" }).click(); // Switch back to Schedules -> Export .automation.md -> Import .automation.md (starts Paused!) await editor.getByRole("tab", { name: /Schedules/ }).click(); await editor.getByRole("button", { name: "More Actions" }).click(); await page.getByRole("menuitem", { name: "Export .automation.md…" }).click(); const exportDialog = page.getByRole("dialog", { name: "Export .automation.md" }); await expect(exportDialog.getByLabel("Exported Automation Markdown")).toHaveValue( /expression: "0 9,15 \* \* MON-FRI"/, ); const exportedMd = await exportDialog.getByLabel("Exported Automation Markdown").inputValue(); await exportDialog.getByRole("button", { name: "Close" }).click(); await editor.getByRole("button", { name: "Options" }).click(); await page.getByRole("menuitem", { name: "Import .automation.md" }).click(); const importDialog = page.getByRole("dialog", { name: "Import .automation.md" }); await importDialog .getByLabel("Automation Markdown") .fill(exportedMd.replace("Morning PR & CI Triage", "Imported Security Audit")); await importDialog.getByRole("button", { name: "Import Disabled" }).click(); await expect(editor).toContainText("Imported Security Audit"); 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 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"); }); test("supports SameTask rolling continuity, NeedsInput approval flow, and sidebar automated-run visibility filters", async ({ workbench: page, }) => { await page.setViewportSize({ width: 1320, height: 860 }); await installAutomationDesktopHarness(page); await page.evaluate(async () => { const actionsModule = "/src/platform/actions.ts"; const { executeAction } = await import(/* @vite-ignore */ actionsModule); await executeAction("agents.showToolWindow"); await executeAction("agents.automations"); }); const editor = page.getByTestId("automations-editor"); // 1) Create a completed clean automation (NewTask) and run it TWICE -> #1 and #2 both completed & read await editor.getByRole("button", { name: "New Automation" }).click(); let dialog = page.getByRole("dialog", { name: "New Automation" }); await dialog.getByLabel("Name").fill("Quiet Clean Sweep"); await dialog.getByLabel("Prompt Instructions").fill("Check formatting cleanly."); await dialog.getByRole("button", { name: "Create Automation" }).click(); await editor.getByRole("button", { name: "Run Now" }).first().click(); await page.getByTestId("automation-provenance-banner").getByRole("button", { name: "Open Automation" }).click(); await editor.getByRole("tab", { name: /Schedules/ }).click(); await editor.getByRole("button", { name: "Run Now" }).first().click(); // Return to Automations and mark read so Quiet Clean Sweep #1 & #2 are both completed + read await page .getByTestId("automation-provenance-banner") .locator("visible=true") .getByRole("button", { name: "Open Automation" }) .click(); await editor.getByRole("tab", { name: /Run History/ }).click(); await editor.getByRole("button", { name: "Mark All as Read" }).click(); await editor.getByRole("tab", { name: /Schedules/ }).click(); // 2) Create a SameTask rolling automation that requests tool approval (NEEDS_APPROVAL) await editor.getByRole("button", { name: "New Automation" }).click(); dialog = page.getByRole("dialog", { name: "New Automation" }); await dialog.getByLabel("Name").fill("Rolling PR Labeler"); await dialog.getByLabel("Prompt Instructions").fill("NEEDS_APPROVAL label triaged PRs"); await dialog.getByRole("button", { name: /Advanced/ }).click(); await dialog.getByRole("button", { name: "Session Continuity" }).click(); await page.getByRole("option", { name: "Reuse rolling session" }).click(); await dialog.getByRole("button", { name: "Create Automation" }).click(); // Run twice -> SameTask reuses the same rolling task id and lands in needsInput! await editor.getByRole("button", { name: "Run Now" }).first().click(); const visibleBanner = page.getByTestId("automation-provenance-banner").locator("visible=true"); await expect(visibleBanner).toContainText("Rolling PR Labeler"); await expect(visibleBanner).toContainText("#1"); await expect(visibleBanner).toContainText("Waiting for approval"); // Trigger a second run on the same rolling session and verify #2 reuses the exact same task! await visibleBanner.getByRole("button", { name: "Open Automation" }).click(); await editor.getByRole("tab", { name: /Schedules/ }).click(); await editor.getByRole("button", { name: "Run Now" }).first().click(); await expect(visibleBanner).toContainText("#2"); // Check sidebar task tree under default filter ("Latest & Active"): // - Escalated automated NeedsInput task (`Rolling PR Labeler #2`) appears in Needs Input with Automated cue // - Manual task stays in Ready to Review // - Dedicated Automations group shows latest completed run (`Quiet Clean Sweep #2`), hiding older `#1` const taskTree = page.getByRole("tree", { name: "Agent tasks" }); await expect(taskTree).toContainText("Needs Input"); await expect(taskTree).toContainText("Ready to Review"); await expect(taskTree).toContainText("Automations"); await expect(taskTree).toContainText("Refactor auth middleware"); await expect(taskTree).toContainText("Rolling PR Labeler"); await expect(taskTree.locator('[data-tree-key="g:automated"]')).toBeVisible(); await expect(taskTree).toContainText("Quiet Clean Sweep"); await expect(taskTree.locator('[role="treeitem"]', { hasText: "Quiet Clean Sweep" })).toHaveCount(1); await expect(taskTree.locator('[role="treeitem"]', { hasText: "Quiet Clean Sweep" }).first()).toContainText("#2"); // Switch filter to Show All -> older Quiet Clean Sweep #1 also appears inside Automations await page.evaluate(async () => { const actionsModule = "/src/platform/actions.ts"; const { executeAction } = await import(/* @vite-ignore */ actionsModule); await executeAction("agents.automatedRunsAll"); }); await expect(taskTree.locator('[role="treeitem"]', { hasText: "Quiet Clean Sweep" })).toHaveCount(2); // Switch filter to Hide All -> all automated tasks and Automations group hide, manual task stays! await page.evaluate(async () => { const actionsModule = "/src/platform/actions.ts"; const { executeAction } = await import(/* @vite-ignore */ actionsModule); await executeAction("agents.automatedRunsHidden"); }); await expect(taskTree).toContainText("Refactor auth middleware"); await expect(taskTree).not.toContainText("Rolling PR Labeler"); await expect(taskTree).not.toContainText("Quiet Clean Sweep"); await expect(taskTree.locator('[data-tree-key="g:automated"]')).toHaveCount(0); }); test("running composer replaces Send with Stop and keeps the Agents header focused", async ({ workbench: page, }, testInfo) => { await page.setViewportSize({ width: 1280, height: 840 }); await installAutomationDesktopHarness(page); await page.evaluate(async () => { const storeModule = "/src/features/agents/store.ts"; const actionsModule = "/src/platform/actions.ts"; const { executeAction } = await import(/* @vite-ignore */ actionsModule); const store = await import(/* @vite-ignore */ storeModule); await executeAction("agents.showToolWindow"); const task = store.useAgents.getState().tasks.get("manual-session-1"); store.useAgents.setState((s: { tasks: Map }) => ({ tasks: new Map(s.tasks).set(task.id, { ...task, status: "running" }), })); store.openTask(task.id); }); await expect(page.getByRole("button", { name: "Agent Settings", exact: true })).toBeVisible(); await expect(page.getByRole("button", { name: "Agent Automations", exact: true })).toHaveCount(0); const stop = page.getByRole("button", { name: "Stop", exact: true }); await expect(stop).toBeEnabled(); await expect(page.getByRole("button", { name: "Queue", exact: true })).toHaveCount(0); await page.locator('[data-toolwindow="agents"] header').hover(); await page.screenshot({ path: testInfo.outputPath("running-composer.png"), animations: "disabled" }); const before = (await stop.boundingBox())!; await page.getByRole("textbox", { name: "Message" }).fill("Follow up"); const queue = page.getByRole("button", { name: "Queue", exact: true }); await expect(queue).toBeEnabled(); await expect(stop).toHaveCount(0); const after = (await queue.boundingBox())!; expect(after.x).toBeCloseTo(before.x, 0); expect(after.width).toBeCloseTo(before.width, 0); await page.getByRole("button", { name: "Message Actions" }).click(); await expect(page.getByRole("menuitem", { name: "Stop", exact: true })).toBeVisible(); }); test("opens persistent automation scheduling directly from a new agent task", async ({ workbench: page }) => { await page.setViewportSize({ width: 1280, height: 840 }); await installAutomationDesktopHarness(page); await page.evaluate(async () => { const storeModule = "/src/features/agents/store.ts"; const store = await import(/* @vite-ignore */ storeModule); store.openHome(); }); const composer = page.getByRole("textbox", { name: "Message", exact: true }); await composer.fill("Review the weekly changelog"); const clock = page.getByRole("button", { name: "New Agent Automation…" }); await expect(clock).toBeVisible(); await clock.click(); const dialog = page.getByRole("dialog", { name: "New Automation" }); await expect(dialog).toBeVisible(); await expect(dialog.getByLabel("Prompt Instructions")).toHaveValue("Review the weekly changelog"); await expect(dialog.getByRole("button", { name: "Agent", exact: true })).toContainText("Claude Code"); await dialog.getByRole("button", { name: "Cancel" }).click(); await expect(dialog).not.toBeVisible(); await expect(composer).toHaveText("Review the weekly changelog"); }); test("schedules in-session Send Later, /loop recurring prompts, and /automate from SessionComposer", async ({ workbench: page, }) => { await page.setViewportSize({ width: 1280, height: 840 }); await installAutomationDesktopHarness(page); await page.evaluate(async () => { const storeModule = "/src/features/agents/store.ts"; const store = await import(/* @vite-ignore */ storeModule); store.openTask("manual-session-1"); }); const composerBox = page.getByRole("textbox", { name: "Message" }); await expect(composerBox).toBeVisible(); // 1) Type a message and schedule via the clock menu ("Send in 15 minutes") await composerBox.click(); await page.keyboard.type("Verify staging deployment health"); await page.getByRole("button", { name: "Schedule or Loop Message" }).click(); await page.getByRole("menuitem", { name: "Send in 15 minutes" }).click(); const strip = page.getByTestId("session-schedule-strip"); await expect(strip).toBeVisible(); await expect(strip).toContainText("Send at"); await expect(strip).toContainText("Verify staging deployment health"); // 2) Type /loop 10m and submit with Enter await composerBox.click(); await page.keyboard.type("/loop 10m poll workflow status"); await page.keyboard.press("Enter"); await expect(strip).toContainText("Every 10m"); await expect(strip).toContainText("poll workflow status"); // Pause & Resume the loop item, then fire Send Now on the one-shot item, then Cancel loop const rows = strip.locator('[data-testid^="session-schedule-"]'); await expect(rows).toHaveCount(2); await rows.nth(1).getByRole("button", { name: "Pause" }).click(); await expect(rows.nth(1)).toContainText("Paused"); await rows.nth(1).getByRole("button", { name: "Resume" }).click(); // Send Now on Send Later removes the one-shot item await rows.nth(0).getByRole("button", { name: "Send Now" }).click(); await expect(rows).toHaveCount(1); // Cancel the remaining /loop item await rows.nth(0).getByRole("button", { name: "Cancel Schedule" }).click(); await expect(page.getByTestId("session-schedule-strip")).toHaveCount(0); // 3) Type /automate -> opens New Automation dialog prefilled with prompt! await composerBox.click(); await page.keyboard.type("/automate audit weekly flaky tests"); await page.keyboard.press("Enter"); const dialog = page.getByRole("dialog", { name: "New Automation" }); await expect(dialog).toBeVisible(); await expect(dialog.getByLabel("Prompt Instructions")).toHaveValue("audit weekly flaky tests"); await dialog.getByRole("button", { name: "Cancel" }).click(); }); test("manages status-bar scheduler popover, Settings › Agents › Automations persistence, and untrusted banner", async ({ workbench: page, }) => { await page.setViewportSize({ width: 1280, height: 840 }); await installAutomationDesktopHarness(page); // Create one active schedule first await page.evaluate(async () => { const actionsModule = "/src/platform/actions.ts"; const { executeAction } = await import(/* @vite-ignore */ actionsModule); await executeAction("agents.newAutomation"); }); const dialog = page.getByRole("dialog", { name: "New Automation" }); await dialog.getByLabel("Name").fill("Hourly Health Ping"); await dialog.getByLabel("Prompt Instructions").fill("Ping health endpoint."); await dialog.getByRole("button", { name: "Create Automation" }).click(); // Click status bar scheduler pill -> inspect popover -> Pause All const statusBtn = page.getByTestId("status-scheduler-button"); await expect(statusBtn).toContainText("1 scheduled"); await statusBtn.click(); const popover = page.getByTestId("status-scheduler-popover"); await expect(popover).toBeVisible(); await expect(popover).toContainText("Local Host Scheduler"); await expect(popover).toContainText("Idle"); await popover.getByRole("button", { name: "Pause All" }).click(); await expect(statusBtn).toHaveCount(0); // Open Settings › Agents › Automations and verify settings write through IPC await page.evaluate(async () => { const actionsModule = "/src/platform/actions.ts"; const { executeAction } = await import(/* @vite-ignore */ actionsModule); await executeAction("file.settings", "agents.automations"); }); const settingsPage = page.getByTestId("automations-settings-page"); await expect(settingsPage).toBeVisible(); await expect(settingsPage).toContainText("OS login service idle"); await settingsPage.getByRole("checkbox", { name: "Keep automations running when OpenIDEA is closed" }).click(); await settingsPage.getByRole("button", { name: "Default missed schedule policy" }).click(); await page.getByRole("option", { name: "Skip missed runs until next scheduled tick" }).click(); await page.getByRole("dialog", { name: "Settings" }).getByRole("button", { name: "Apply" }).click(); const savedKeys = await page.evaluate(() => window.__ipc.calls.filter((c) => c.cmd === "settings_set").map((c) => c.args.key), ); expect(savedKeys).toContain("agents.automations.autoStartService"); expect(savedKeys).toContain("agents.automations.misfirePolicy"); await page.getByRole("dialog", { name: "Settings" }).getByRole("button", { name: "OK" }).click(); // Mark workspace untrusted -> verify AutomationsEditor shows the untrusted workspace banner await page.evaluate(async () => { const projectModule = "/src/platform/project.ts"; const actionsModule = "/src/platform/actions.ts"; const { useProject } = await import(/* @vite-ignore */ projectModule); const cur = useProject.getState().project!; useProject.setState({ project: { ...cur, trusted: false } }); const { executeAction } = await import(/* @vite-ignore */ actionsModule); await executeAction("agents.automations"); }); await expect(page.getByTestId("automations-editor")).toContainText( "This project is untrusted. Workspace automations stay paused until you trust the project.", ); }); test("supports Weekly day picker, Local Autonomous warning, ChatOnly workspace, Duplicate, Pause/Resume, and Remote Daemon linger warning", async ({ workbench: page, }) => { await page.setViewportSize({ width: 1320, height: 860 }); await installAutomationDesktopHarness(page); // Switch host snapshot to Remote Daemon with Linux systemd linger disabled await page.evaluate(() => { const orig = window.__ipc.handlers.agent_automation_snapshot!; window.__ipc.handlers.agent_automation_snapshot = (args) => { const snap = orig(args) as { host: Record }; snap.host.remote = true; snap.host.hostLabel = "Remote Daemon"; snap.host.bootServiceKind = "systemdUser"; snap.host.linuxLingerEnabled = false; return snap; }; }); await page.evaluate(async () => { const actionsModule = "/src/platform/actions.ts"; const { executeAction } = await import(/* @vite-ignore */ actionsModule); await executeAction("agents.automations"); }); const editor = page.getByTestId("automations-editor"); await expect(page.getByTestId("scheduler-host-pill")).toContainText("Remote Daemon"); // Open New Automation -> test Local checkout + Autonomous warning, Weekly day buttons, then switch to ChatOnly await editor.getByRole("button", { name: "New Automation" }).click(); const dialog = page.getByRole("dialog", { name: "New Automation" }); await dialog.getByLabel("Name").fill("Weekly Release Notes"); await dialog.getByLabel("Prompt Instructions").fill("Draft release notes from merged PRs."); await dialog.getByRole("button", { name: "Checkout Isolation" }).click(); await page.getByRole("option", { name: "Local checkout" }).click(); await dialog.getByRole("button", { name: /Advanced/ }).click(); await dialog.getByRole("button", { name: "Unattended Permissions" }).click(); await page.getByRole("option", { name: /Allow all/ }).click(); await expect(dialog).toContainText( "Warning: Autonomous mode on a local checkout can modify your working files directly.", ); // Switch to Weekly schedule and toggle Friday + Tuesday, and switch Workspace Target to No workspace (chat only) await dialog.getByRole("button", { name: "Schedule", exact: true }).click(); await page.getByRole("option", { name: "Weekly" }).click(); await dialog.getByRole("button", { name: "Tue" }).click(); await expect(dialog.getByRole("button", { name: "Tue" })).toHaveAttribute("aria-pressed", "true"); await dialog.getByRole("button", { name: "Workspace Target" }).click(); await page.getByRole("option", { name: "No workspace (chat only)" }).click(); await dialog.getByRole("button", { name: "Create Automation" }).click(); await expect(editor).toContainText("Weekly Release Notes"); await expect(editor).toContainText("Chat only"); // Duplicate -> creates "(Copy)" paused, then Resume and Pause schedule await editor.getByRole("button", { name: "More Actions" }).click(); await page.getByRole("menuitem", { name: "Duplicate" }).click(); await expect(editor).toContainText("Weekly Release Notes (Copy)"); 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(); await expect(page.getByTestId("scheduler-host-pill")).toContainText("1 active schedule"); // Open Settings › Agents › Automations -> verify Remote Daemon Scheduler + Linux linger hint! await editor.getByRole("button", { name: "Automation Settings" }).click(); const settingsPage = page.getByTestId("automations-settings-page"); await expect(settingsPage).toContainText("Remote Daemon Scheduler"); await expect(settingsPage).toContainText("loginctl enable-linger $USER"); }); test("requires McpConfirmHost confirmation even when MCP brave mode is enabled and surfaces rejected recursive calls in unattended runs", async ({ workbench: page, }) => { const captureDir = process.env.OPENIDEA_CAPTURE_MCP_AUTOMATION_SHOTS; await page.setViewportSize({ width: 1320, height: 860 }); await installAutomationDesktopHarness(page); // Configure MCP Server settings with `enabled = true` and `runWithoutConfirmation = true` (brave mode), // plus stub `mcp_server_status` and `mcp_respond`. await page.evaluate(async () => { const projectMod = "/src/platform/project.ts"; const { useProject } = await import(/* @vite-ignore */ projectMod); const handlers = window.__ipc.handlers; handlers.settings_set?.({ key: "mcpServer.enabled", value: "true" }); handlers.settings_set?.({ key: "mcpServer.runWithoutConfirmation", value: "true" }); handlers.settings_set?.({ key: "agents.newTaskApprovals", value: '"ask"' }); handlers.settings_get = () => useProject.getState().settings; handlers.mcp_server_status = () => ({ running: true, address: "127.0.0.1", port: 26371, portUnavailable: null, url: "http://127.0.0.1:26371/mcp?project=%2Fdev%2Facme-api", token: "tok_preview_live", stdioCommand: ["/Applications/OpenIDEA.app/Contents/MacOS/openidea", "--mcp-stdio", "--project", "/dev/acme-api"], error: null, }); handlers.mcp_respond = () => null; }); // 1. Verify Settings › Agents › IDE MCP Server reflects brave mode (`Run tools without confirmation`), // then show the interactive agent session calling `save_automation` and triggering `McpConfirmHost`! await page.evaluate(async () => { const actionsMod = "/src/platform/actions.ts"; const { executeAction } = await import(/* @vite-ignore */ actionsMod); await executeAction("agents.showToolWindow"); await executeAction("file.settings", "agents.mcpServer"); }); const settingsDialog = page.getByRole("dialog", { name: "Settings" }); await expect(settingsDialog).toBeVisible(); await expect(settingsDialog.getByRole("checkbox", { name: "Enable MCP server" })).toBeChecked(); await expect(settingsDialog.getByRole("checkbox", { name: "Run tools without confirmation" })).toBeChecked(); await settingsDialog.getByRole("button", { name: "OK" }).click(); await expect(settingsDialog).toHaveCount(0); await page.evaluate(async () => { const storeMod = "/src/features/agents/store.ts"; const mcpMod = "/src/features/mcp/requests.ts"; const { useAgents, openTask } = await import(/* @vite-ignore */ storeMod); const { handleMcpRequest } = await import(/* @vite-ignore */ mcpMod); const interactiveSetupTask: AgentTask = { id: "interactive-mcp-setup", title: "Set up weekday PR triage schedule", provider: "claude", status: "running", isolation: "local", model: "claude-sonnet-4.6", cwd: "/dev/acme-api", projectRoot: "/dev/acme-api", branch: "main", base: null, baseCommit: null, error: null, createdMs: Date.now() - 18_000, updatedMs: Date.now() - 1_000, config: [ { id: "model", category: "model", name: "Model", description: null, current: "claude-sonnet-4.6", via: "option", values: [{ value: "claude-sonnet-4.6", name: "Claude Sonnet 4.6", description: null }], }, ], commands: [], usage: null, queue: [], mcpOverrides: {}, skillOverrides: {}, }; const setupEntries: AgentEntry[] = [ { type: "user", text: "Set up a weekday 9:00 AM PT automation in an isolated worktree to triage open PRs and failing CI checks.", attachments: [], sentMs: Date.now() - 16_000, }, { type: "tool", id: "mcp-preview-1", title: "OpenIDEA · preview_automation_schedule", kind: "read", status: "completed", locations: [], output: "Weekdays 09:00 (America/Los_Angeles)", diffs: [], startedMs: Date.now() - 14_000, endedMs: Date.now() - 13_800, }, { type: "tool", id: "mcp-save-live-1", title: "OpenIDEA · save_automation (Weekday PR & CI Triage)", kind: "other", status: "running", locations: [], output: null, diffs: [], startedMs: Date.now() - 12_000, }, ]; const prevEntries = window.__ipc.handlers.agent_entries; window.__ipc.handlers.agent_entries = (args: Record) => args.task === "interactive-mcp-setup" ? setupEntries : (prevEntries?.(args) ?? []); useAgents.setState((s: { tasks: Map }) => ({ tasks: new Map(s.tasks).set(interactiveSetupTask.id, interactiveSetupTask), })); await openTask("interactive-mcp-setup"); await handleMcpRequest(901, { type: "confirm", client: "claude-code", tool: "save_automation", subject: "create automation `Weekday PR & CI Triage`", project: "/dev/acme-api", background: false, detail: [ 'Note: automation schedules always ask first, even with "Run tools without confirmation" (brave mode) on.', "", "Name: Weekday PR & CI Triage", "Schedule: Weekdays 09:00 (America/Los_Angeles) (enabled: true)", "Provider: claude", "Isolation: worktree (base: main)", "Continuity: newTask", "Permissions: allowAll — capped at runtime to `ask` by Settings › Agents › New task approvals", "Prompt:", "Review open pull requests and failing CI checks, summarize root causes, and draft review notes.", ].join("\n"), }); }); const confirmDialog = page.getByRole("dialog", { name: "claude-code wants to run create automation `Weekday PR & CI Triage`", }); await expect(confirmDialog).toBeVisible(); await expect(confirmDialog).toContainText("Tool: save_automation"); await expect(confirmDialog).toContainText("capped at runtime to `ask`"); await expect(confirmDialog).toContainText( 'Note: automation schedules always ask first, even with "Run tools without confirmation" (brave mode) on.', ); if (captureDir) { await page.screenshot({ path: `${captureDir}/mcp-automation-confirm-brave-mode.png`, animations: "disabled" }); } await confirmDialog.getByRole("button", { name: "Deny" }).click(); await expect(confirmDialog).toHaveCount(0); // 2. Unattended scheduled run attempting a recursive `save_automation` call over built-in MCP: // `list_automations` succeeds (`completed`), `save_automation` fails (`failed`) with the // explicit recursive-run refusal and NO `McpConfirmHost` modal opens! await page.evaluate(async () => { const storeMod = "/src/features/agents/store.ts"; const { useAgents, openTask } = await import(/* @vite-ignore */ storeMod); const scheduledTask: AgentTask = { id: "auto-run-4", title: "Morning PR & CI Triage · #4", provider: "claude", status: "ready", isolation: "worktree", model: "claude-sonnet-4.6", cwd: "/dev/acme-api/.openidea-worktrees/auto-run-4", projectRoot: "/dev/acme-api", branch: "agent/morning-pr-ci-triage-4", base: "main", baseCommit: "cb887dad8", error: null, createdMs: Date.now() - 42_000, updatedMs: Date.now() - 5_000, config: [ { id: "model", category: "model", name: "Model", description: null, current: "claude-sonnet-4.6", via: "option", values: [{ value: "claude-sonnet-4.6", name: "Claude Sonnet 4.6", description: null }], }, ], commands: [], usage: null, queue: [], mcpOverrides: {}, skillOverrides: {}, automation: { automationId: "auto_triage_1", automationName: "Morning PR & CI Triage", runId: "arun_4", runNumber: 4, triggerSummary: "Weekdays 09:00 (America/Los_Angeles)", permissions: "assisted", scheduledForMs: Date.now() - 45_000, catchUp: false, }, }; const entries: AgentEntry[] = [ { type: "user", text: "Inspect open pull requests and recent CI runs, and schedule a follow-up sweep if any check is still pending.", attachments: [], sentMs: Date.now() - 40_000, doneMs: Date.now() - 5_000, }, { type: "tool", id: "mcp-list-1", title: "OpenIDEA · list_automations", kind: "read", status: "completed", locations: [], output: JSON.stringify( { total: 1, automations: [ { id: "auto_triage_1", name: "Morning PR & CI Triage", enabled: true, triggerSummary: "Weekdays 09:00 (America/Los_Angeles)", }, ], }, null, 2, ), diffs: [], startedMs: Date.now() - 36_000, endedMs: Date.now() - 35_400, }, { type: "tool", id: "mcp-save-blocked-1", title: "OpenIDEA · save_automation (Follow-up CI Sweep)", kind: "other", status: "failed", locations: [], output: "Unattended scheduled runs cannot create, modify, enable, delete, or trigger automations", diffs: [], startedMs: Date.now() - 34_000, endedMs: Date.now() - 33_900, }, { type: "agent", text: "Triaged **3 open pull requests** (all green except `#7319`, which has 1 macOS check still running).\n\nOpenIDEA rejected the `save_automation` tool call because unattended scheduled runs cannot create, modify, enable, delete, or trigger automations recursively. Ask in an interactive session if you want to add a separate follow-up schedule.", }, ]; const prevHandlers = window.__ipc.handlers.agent_entries; window.__ipc.handlers.agent_entries = (args: Record) => args.task === "auto-run-4" ? entries : (prevHandlers?.(args) ?? []); useAgents.setState((s: { tasks: Map }) => ({ tasks: new Map(s.tasks).set(scheduledTask.id, scheduledTask), })); await openTask("auto-run-4"); }); const provenance = page.getByTestId("automation-provenance-banner"); await expect(provenance).toBeVisible(); await expect(provenance).toContainText("Morning PR & CI Triage"); await expect(provenance).toContainText("#4"); // Expand the collapsed process group inside the visible scheduled run session, then expand the failed tool entry const processGroup = page.locator("summary", { hasText: /^Read 1 file · 1 other tool call$/ }); await expect(processGroup).toBeVisible(); await processGroup.click(); const failedSummary = page.locator("summary", { hasText: "OpenIDEA · save_automation (Follow-up CI Sweep)" }); await expect(failedSummary).toBeVisible(); await failedSummary.click(); await expect( page.locator("pre", { hasText: "Unattended scheduled runs cannot create, modify, enable, delete, or trigger automations", }), ).toBeVisible(); // Confirm NO McpConfirmHost dialog is shown for the rejected unattended call await expect(page.getByRole("dialog")).toHaveCount(0); if (captureDir) { await page.screenshot({ path: `${captureDir}/mcp-automation-rejected-unattended-run.png`, animations: "disabled", }); } // 3. Self-chaining automation (`allowAgentSchedule: true`): // - Configure an automation with "Allow agent to schedule its next run (unattended)" checked, // verify the `Self-scheduling` badge on the dashboard + Edit dialog hint, AND // - Inspect Run #2 calling `schedule_next_run` unattended with ZERO confirmation modal! await page.evaluate(async () => { const actionsMod = "/src/platform/actions.ts"; const { executeAction } = await import(/* @vite-ignore */ actionsMod); await executeAction("agents.automations"); }); const editor = page.getByTestId("automations-editor"); await expect(editor).toBeVisible(); await editor.getByRole("button", { name: "New Automation" }).click(); const newDialog = page.getByRole("dialog", { name: "New Automation" }); await expect(newDialog).toBeVisible(); await newDialog.getByLabel("Name").fill("Online Farm Game Bot"); await newDialog .getByLabel("Prompt Instructions") .fill("Harvest mature plots, read Daily Gazette buffs, replant, and call schedule_next_run for the next harvest."); await newDialog.getByRole("button", { name: "Workspace Target" }).click(); await page.getByRole("option", { name: "No workspace (chat only)" }).click(); await newDialog.getByRole("button", { name: "Schedule", exact: true }).click(); await page.getByRole("option", { name: "One-shot" }).click(); await newDialog.getByRole("button", { name: /Advanced/ }).click(); await newDialog.getByRole("button", { name: "Session Continuity" }).click(); await page.getByRole("option", { name: "Reuse rolling session" }).click(); const selfSchedCheckbox = newDialog.getByRole("checkbox", { name: "Allow agent to schedule its next run (unattended)", }); await selfSchedCheckbox.click(); await expect(selfSchedCheckbox).toBeChecked(); await expect(newDialog).toContainText( "Active runs of this automation can call schedule_next_run over MCP to set a one-time next-run override", ); await newDialog.getByLabel("Stop After Runs (optional)").fill("50"); await newDialog.getByRole("button", { name: "Create Automation" }).click(); await expect(newDialog).toHaveCount(0); // Simulate an active one-time override scheduled by the agent so the dashboard row displays both // the `Self-scheduling` badge AND the pending `Next run override:` notice! await page.evaluate(async () => { type AutoRecord = { name?: string; [key: string]: unknown }; type SnapRecord = { automations: AutoRecord[]; [key: string]: unknown }; const autoMod = "/src/features/agents/automationsModel.ts"; const { useAutomations } = (await import(/* @vite-ignore */ autoMod)) as { useAutomations: { getState: () => { snapshot: SnapRecord }; setState: (partial: { snapshot: SnapRecord }) => void; }; }; const overrideMs = Date.now() + 137 * 60_000; const withOverride = (snap: SnapRecord): SnapRecord => ({ ...snap, automations: snap.automations.map((a: AutoRecord) => a.name === "Online Farm Game Bot" ? { ...a, nextRunMs: overrideMs, nextRunOverrideMs: overrideMs, nextPromptOverride: "Harvest Starfruit on plots 1–6, fulfill batch order #4, and schedule the next cycle.", } : a, ), }); const cur = useAutomations.getState().snapshot; const origSnap = window.__ipc.handlers.agent_automation_snapshot; if (origSnap) { window.__ipc.handlers.agent_automation_snapshot = (args) => withOverride(origSnap(args) as SnapRecord); } useAutomations.setState({ snapshot: withOverride(cur) }); }); const gameRow = editor.locator('[data-testid^="automation-row-"]', { hasText: "Online Farm Game Bot" }); await expect(gameRow).toContainText("Self-scheduling"); await expect(gameRow).toContainText("Next run override:"); await expect(gameRow).toContainText( "Harvest Starfruit on plots 1–6, fulfill batch order #4, and schedule the next cycle.", ); if (captureDir) { await page.screenshot({ path: `${captureDir}/mcp-automation-self-scheduling-dashboard.png`, animations: "disabled", }); } await gameRow.getByRole("button", { name: "Edit" }).first().click(); const editDialog = page.getByRole("dialog", { name: "Edit Automation" }); await expect(editDialog).toBeVisible(); await expect( editDialog.getByRole("checkbox", { name: "Allow agent to schedule its next run (unattended)" }), ).toBeChecked(); if (captureDir) { // Scroll the dialog form so the Schedule preview, Self-scheduling checkbox + hint, and Stop After Runs are centered await editDialog .getByRole("checkbox", { name: "Allow agent to schedule its next run (unattended)" }) .scrollIntoViewIfNeeded(); await page.screenshot({ path: `${captureDir}/mcp-automation-self-scheduling-dialog.png`, animations: "disabled", }); } await editDialog.getByRole("button", { name: "Cancel" }).click(); await expect(editDialog).toHaveCount(0); // Open self-chaining Run #2 showing `OpenIDEA · schedule_next_run` succeeding unattended (`completed`, no dialog!) await page.evaluate(async () => { const storeMod = "/src/features/agents/store.ts"; const { useAgents, openTask } = await import(/* @vite-ignore */ storeMod); const gameTask: AgentTask = { id: "farm-bot-run-2", title: "Online Farm Game Bot · #2", provider: "claude", status: "ready", isolation: "local", model: "claude-sonnet-4.6", cwd: "/Users/dev/.openidea/automations/chat_workspace", branch: null, base: null, baseCommit: null, error: null, createdMs: Date.now() - 28_000, updatedMs: Date.now() - 3_000, config: [ { id: "model", category: "model", name: "Model", description: null, current: "claude-sonnet-4.6", via: "option", values: [{ value: "claude-sonnet-4.6", name: "Claude Sonnet 4.6", description: null }], }, ], commands: [], usage: null, queue: [], mcpOverrides: {}, skillOverrides: {}, automation: { automationId: "auto-1", automationName: "Online Farm Game Bot", runId: "arun_farm_2", runNumber: 2, triggerSummary: "One-shot · Self-scheduling", permissions: "allowAll", scheduledForMs: Date.now() - 30_000, catchUp: false, }, }; const nextRunIso = "2026-12-01T23:32:00-08:00[America/Los_Angeles]"; const gameEntries: AgentEntry[] = [ { type: "user", text: "Harvest plots 1–6 (Moonberry), check Daily Gazette buffs, replant optimal crops, and schedule the next harvest run.", attachments: [], sentMs: Date.now() - 26_000, doneMs: Date.now() - 3_000, }, { type: "tool", id: "mcp-next-run-ok", title: "OpenIDEA · schedule_next_run (delayMinutes: 137)", kind: "other", status: "completed", locations: [], output: JSON.stringify( { scheduled: true, nextRunIso, nextPromptOverride: "Harvest Starfruit on plots 1–6, fulfill batch order #4, and schedule the next cycle.", automation: { id: "auto_farm_bot", name: "Online Farm Game Bot", enabled: true, allowAgentSchedule: true, runCount: 2, maxRuns: 50, prompt: "Harvest mature plots, read Daily Gazette buffs, replant, and call schedule_next_run for the next harvest.", }, }, null, 2, ), diffs: [], startedMs: Date.now() - 8_000, endedMs: Date.now() - 7_920, }, { type: "agent", text: "Harvested **6 Moonberry plots** (+420 coins) and planted **Starfruit** (2x Gazette buff, matures in **2h 17m**).\n\nScheduled **Run #3** automatically for `2026-12-01 23:32:00 PST` (`delayMinutes: 137`, `2/50` runs used) via `schedule_next_run` with no human approval required.", }, ]; const prevHandlers = window.__ipc.handlers.agent_entries; window.__ipc.handlers.agent_entries = (args: Record) => args.task === "farm-bot-run-2" ? gameEntries : (prevHandlers?.(args) ?? []); useAgents.setState((s: { tasks: Map }) => ({ tasks: new Map(s.tasks).set(gameTask.id, gameTask), })); await openTask("farm-bot-run-2"); }); const nextRunSummary = page.locator("summary", { hasText: "OpenIDEA · schedule_next_run (delayMinutes: 137)" }); await expect(nextRunSummary).toBeVisible(); await nextRunSummary.click(); await expect(page.locator("pre", { hasText: '"allowAgentSchedule": true' })).toBeVisible(); await expect(page.getByRole("dialog")).toHaveCount(0); if (captureDir) { await page.screenshot({ path: `${captureDir}/mcp-automation-self-chaining-session.png`, animations: "disabled", }); } }); test("displays, preserves, and clears agent schedule overrides in Edit dialog, elapsed One-shot, and provenance banner", async ({ workbench: page, }) => { await page.setViewportSize({ width: 1320, height: 860 }); await installAutomationDesktopHarness(page); await page.evaluate(async () => { const autoMod = "/src/features/agents/automationsModel.ts"; const { openAutomations, refreshAutomations } = await import(/* @vite-ignore */ autoMod); const now = Date.now(); const dailyOverrideMs = now + 45 * 60_000; const oneshotSeedPastMs = now - 15 * 60_000; const oneshotOverrideMs = now + 60 * 60_000; // Create Daily + One-shot automations via stubbed IPC, then attach active agent overrides. const daily = (await window.__ipc.handlers.agent_automation_save!({ input: { name: "Daily Harvest Watch", enabled: true, prompt: { text: "Check crops and schedule next run.", files: [], images: [] }, workspace: { kind: "project", root: "/dev/acme-api", isolation: "local", autoCleanWorktree: false }, continuity: "sameTask", provider: "claude", config: [], permissions: "allowAll", trigger: { kind: "daily", hour: 8, minute: 30, timeZone: "America/Los_Angeles" }, allowAgentSchedule: true, }, })) as AgentAutomation_Serialize; const oneshot = (await window.__ipc.handlers.agent_automation_save!({ input: { name: "Canary Rollout Seed", enabled: true, prompt: { text: "Watch canary until healthy.", files: [], images: [] }, workspace: { kind: "project", root: "/dev/acme-api", isolation: "worktree", autoCleanWorktree: true }, continuity: "sameTask", provider: "claude", config: [], permissions: "assisted", trigger: { kind: "oneShot", runAtMs: now + 3_600_000 }, allowAgentSchedule: true, }, })) as AgentAutomation_Serialize; // Seed live agent overrides directly in the harness state (and move the One-shot seed into the past). window.__ipc.handlers.__test_set_override!({ id: daily.id, nextRunOverrideMs: dailyOverrideMs, nextPromptOverride: "Harvest plots 1 & 2 and collect kitchen order.", }); window.__ipc.handlers.__test_set_override!({ id: oneshot.id, trigger: { kind: "oneShot", runAtMs: oneshotSeedPastMs }, nextRunOverrideMs: oneshotOverrideMs, nextPromptOverride: "Re-check error budget at 50% traffic.", }); await refreshAutomations(); await openAutomations(); }); const editor = page.getByTestId("automations-editor"); await expect(editor).toBeVisible(); // 1. Edit Daily automation -> override card + Fallback schedule shown; rename & Save preserves override! const dailyRow = editor.locator('[data-testid^="automation-row-"]', { hasText: "Daily Harvest Watch" }); await expect(dailyRow).toContainText("Next (by agent):"); await dailyRow.getByRole("button", { name: "Edit Automation" }).click(); const dialog = page.getByRole("dialog", { name: "Edit Automation" }); await expect(dialog.getByTestId("automation-dialog-override")).toContainText("Next run (scheduled by agent):"); await expect(dialog.getByTestId("automation-dialog-override")).toContainText("Harvest plots 1 & 2"); await expect(dialog.getByTestId("automation-schedule-preview")).toContainText("Fallback schedule:"); await dialog.getByLabel("Name").fill("Daily Harvest Watch (Opus)"); await dialog.getByRole("button", { name: "Save Changes" }).click(); await expect(dialog).toHaveCount(0); const renamedDaily = editor.locator('[data-testid^="automation-row-"]', { hasText: "Daily Harvest Watch (Opus)" }); await expect(renamedDaily).toContainText("Next run override:"); await expect(renamedDaily).toContainText("Next (by agent):"); // 2. Re-open Edit -> click Clear override -> Save clears override cleanly await renamedDaily.getByRole("button", { name: "Edit Automation" }).click(); await dialog.getByRole("button", { name: "Clear override" }).click(); await expect(dialog.getByTestId("automation-dialog-override")).toContainText("Will be cleared when you save."); await dialog.getByRole("button", { name: "Save Changes" }).click(); await expect(dialog).toHaveCount(0); await expect(renamedDaily).not.toContainText("Next run override:"); // 3. Edit elapsed One-shot with active override -> shows seed-completed message & saves without error! const oneshotRow = editor.locator('[data-testid^="automation-row-"]', { hasText: "Canary Rollout Seed" }); await oneshotRow.getByRole("button", { name: "Edit Automation" }).click(); await expect(dialog.getByTestId("automation-dialog-override")).toContainText("Re-check error budget at 50% traffic."); await expect(dialog.getByTestId("automation-schedule-preview")).toContainText( "Seed run already completed; next run is scheduled by the agent above.", ); await dialog.getByLabel("Name").fill("Canary Rollout Seed (v2)"); await dialog.getByRole("button", { name: "Save Changes" }).click(); await expect(dialog).toHaveCount(0); // 4. Open rolling session for the One-shot automation -> provenance banner shows Next (by agent) await page.evaluate(async () => { const autoMod = "/src/features/agents/automationsModel.ts"; const storeMod = "/src/features/agents/store.ts"; const { useAutomations } = await import(/* @vite-ignore */ autoMod); const { useAgents, openTask } = await import(/* @vite-ignore */ storeMod); const auto = useAutomations .getState() .snapshot.automations.find((a: AgentAutomation_Serialize) => a.name === "Canary Rollout Seed (v2)")!; const task: AgentTask = { id: "canary-session-1", title: `${auto.name} (#1)`, provider: "claude", status: "ready", isolation: "worktree", model: "claude-sonnet-4.6", cwd: "/dev/acme-api", branch: "agent/auto-1", base: "main", baseCommit: null, error: null, createdMs: Date.now() - 10_000, updatedMs: Date.now() - 1_000, config: [], commands: [], usage: null, queue: [], mcpOverrides: {}, skillOverrides: {}, automation: { automationId: auto.id, automationName: auto.name, runId: "run-canary-1", runNumber: 1, triggerSummary: "One-shot", }, }; useAgents.setState((s: { tasks: Map }) => ({ tasks: new Map(s.tasks).set(task.id, task), })); await openTask(task.id); }); await expect(page.getByTestId("automation-provenance-next")).toContainText("Next (by agent):"); }); test("configures effort level and context window in Edit Automation dialog and preserves them across reopen", async ({ workbench: page, }) => { await page.setViewportSize({ width: 1320, height: 860 }); await installAutomationDesktopHarness(page); await page.evaluate(async () => { const storeMod = "/src/features/agents/store.ts"; const autoMod = "/src/features/agents/automationsModel.ts"; const { useAgents } = await import(/* @vite-ignore */ storeMod); const { openAutomations, refreshAutomations } = await import(/* @vite-ignore */ autoMod); const copilotProvider: AgentProvider = { id: "copilot", name: "GitHub Copilot", command: "copilot", program: "copilot", args: [], defaultProgram: "copilot", defaultArgs: [], loginHint: null, commandOverridden: false, commandEditable: true, commandReadOnlyReason: null, installed: true, env: {}, commands: [], source: { kind: "builtin" }, config: [ { id: "model", category: "model", name: "Model", description: null, current: "gemini-4-neon", via: "option", values: [ { value: "gemini-4-neon", name: "Gemini 4 Neon", description: null }, { value: "gpt-5", name: "GPT-5", description: null }, ], }, ], thoughtLevels: { "gemini-4-neon": [ { id: "reasoning_effort", category: "thought_level", name: "Effort Level", description: null, current: "medium", via: "option", values: [ { value: "low", name: "Low", description: "Minimal reasoning before responding." }, { value: "medium", name: "Medium", description: "Balanced reasoning and speed." }, { value: "high", name: "High", description: "More thorough reasoning." }, { value: "xhigh", name: "Extra High", description: "Extensive reasoning for the hardest tasks." }, ], }, { id: "context_tier", category: "model_config", name: "Context Size", description: null, current: "default", via: "option", values: [ { value: "default", name: "200K", description: "Default recommended context size" }, { value: "long_context", name: "1M", description: "Maximum context window for longer sessions" }, ], }, ], "gpt-5": [ { id: "reasoning_effort", category: "thought_level", name: "Effort Level", description: null, current: "low", via: "option", values: [ { value: "low", name: "Low", description: null }, { value: "high", name: "High", description: null }, ], }, ], }, }; useAgents.setState((s: { providers: AgentProvider[] }) => ({ providers: [...s.providers.filter((p) => p.id !== "copilot"), copilotProvider], })); const prevRefresh = window.__ipc.handlers.agent_refresh_models; window.__ipc.handlers.agent_refresh_models = (args) => { if (args.provider === "copilot") { return { provider: "copilot", config: copilotProvider.config, thoughtLevels: copilotProvider.thoughtLevels, refreshing: false, refreshedAtMs: Date.now(), retryAtMs: null, error: null, }; } return prevRefresh ? prevRefresh(args) : null; }; await window.__ipc.handlers.agent_automation_save!({ input: { name: "Daily Farm (Self-Scheduling)", enabled: true, prompt: { text: "Run daily farm workflow.", files: [], images: [] }, workspace: { kind: "project", root: "/dev/acme-api", isolation: "local", autoCleanWorktree: false }, continuity: "sameTask", provider: "copilot", config: [{ id: "model", value: "gemini-4-neon" }], permissions: "allowAll", trigger: { kind: "daily", hour: 20, minute: 0, timeZone: "America/Los_Angeles" }, allowAgentSchedule: true, }, }); await refreshAutomations(); await openAutomations(); }); const editor = page.getByTestId("automations-editor"); const row = editor.locator('[data-testid^="automation-row-"]', { hasText: "Daily Farm (Self-Scheduling)" }); await expect(row).toBeVisible(); await row.getByRole("button", { name: "Edit Automation" }).click(); const dialog = page.getByRole("dialog", { name: "Edit Automation" }); await expect(dialog.getByRole("button", { name: "Model", exact: true })).toContainText("Gemini 4 Neon"); const settingsChip = dialog.getByRole("button", { name: /^Model settings:/ }); await expect(settingsChip).toContainText("Medium · 200K"); // Pick Extra High effort + 1M context size and save await settingsChip.click(); const settingsPopup = page.getByRole("dialog", { name: "Model settings" }); await expect(settingsPopup).toContainText("Effort Level"); await expect(settingsPopup).toContainText("Context Size"); await settingsPopup.getByRole("option", { name: /Extra High/ }).click(); await settingsPopup.getByRole("option", { name: /1M/ }).click(); await expect(dialog.getByRole("button", { name: /^Model settings:/ })).toContainText("Extra High · 1M"); // Dismiss popup then save await page.keyboard.press("Escape"); await expect(settingsPopup).toHaveCount(0); await dialog.getByRole("button", { name: "Save Changes" }).click(); await expect(dialog).toHaveCount(0); // Reopen Edit Automation -> Extra High · 1M is restored! await row.getByRole("button", { name: "Edit Automation" }).click(); await expect(dialog.getByRole("button", { name: /^Model settings:/ })).toContainText("Extra High · 1M"); }); test("scrolls overflowing Schedules and Run History lists without clipping while keeping header, tabs, and footer pinned", async ({ workbench: page, }) => { await page.setViewportSize({ width: 1120, height: 680 }); await installAutomationDesktopHarness(page); const ids = await page.evaluate(async () => { const autoMod = "/src/features/agents/automationsModel.ts"; const { openAutomations, refreshAutomations } = await import(/* @vite-ignore */ autoMod); const createdIds: string[] = []; const now = Date.now(); for (let i = 1; i <= 10; i++) { const saved = (await window.__ipc.handlers.agent_automation_save!({ input: { name: `Daily Workflow ${i} (Self-Scheduling)`, enabled: true, prompt: { text: `Run recurring workflow #${i} and inspect CI, repository status, and pending follow-ups.`, files: [], images: [], }, workspace: { kind: "project", root: "/dev/acme-api", isolation: "local", autoCleanWorktree: false }, continuity: "sameTask", provider: "claude", config: [], permissions: "allowAll", trigger: { kind: "daily", hour: (8 + i) % 24, minute: 0, timeZone: "UTC" }, allowAgentSchedule: i % 2 === 1, }, })) as AgentAutomation_Serialize; createdIds.push(saved.id); if (i <= 3) { window.__ipc.handlers.__test_set_override!({ id: saved.id, nextRunOverrideMs: now + i * 1_800_000, nextPromptOverride: `Follow up on workflow #${i} after cooldown completes.`, }); } } // Trigger runs across automations so Run History also overflows the viewport. for (let i = 0; i < 10; i++) { await window.__ipc.handlers.agent_automation_run_now!({ id: createdIds[i % createdIds.length]! }); await window.__ipc.handlers.agent_automation_run_now!({ id: createdIds[i % createdIds.length]! }); } await refreshAutomations(); await openAutomations({ tab: "schedules" }); return createdIds; }); const editor = page.getByTestId("automations-editor"); const scrollBody = page.getByTestId("automations-scroll-body"); await expect(editor).toBeVisible(); await expect(editor.locator('[data-testid^="automation-row-"]')).toHaveCount(10); // 1. Scroll container must overflow vertically, and the framed list must NOT clip its rows. const schedulesMetrics = await scrollBody.evaluate((el) => { const firstRow = el.querySelector('[data-testid^="automation-row-"]'); const listFrame = firstRow?.parentElement; return { clientHeight: el.clientHeight, scrollHeight: el.scrollHeight, listClientHeight: listFrame?.clientHeight ?? 0, listScrollHeight: listFrame?.scrollHeight ?? 0, }; }); expect(schedulesMetrics.scrollHeight).toBeGreaterThan(schedulesMetrics.clientHeight + 100); expect(schedulesMetrics.listScrollHeight).toBeLessThanOrEqual(schedulesMetrics.listClientHeight + 1); // 2. Scroll to the bottom -> last row is fully reachable & clickable while header, tabs, and footer stay pinned. const rows = editor.locator('[data-testid^="automation-row-"]'); const lastRow = rows.last(); const lastRowId = (await lastRow.getAttribute("data-testid"))!.replace("automation-row-", ""); await scrollBody.evaluate((el) => { el.scrollTop = el.scrollHeight; }); const afterScroll = await scrollBody.evaluate((el) => ({ scrollTop: el.scrollTop, rect: el.getBoundingClientRect(), })); expect(afterScroll.scrollTop).toBeGreaterThan(100); const lastRowBox = await lastRow.boundingBox(); expect(lastRowBox).not.toBeNull(); expect(lastRowBox!.y).toBeGreaterThanOrEqual(afterScroll.rect.y - 1); expect(lastRowBox!.y + lastRowBox!.height).toBeLessThanOrEqual(afterScroll.rect.y + afterScroll.rect.height + 1); // Pinned chrome remains visible inside the editor while scrolled to the bottom. const editorBox = (await editor.boundingBox())!; const newBtnBox = (await editor.getByRole("button", { name: "New Automation" }).boundingBox())!; const footerBox = (await editor.getByRole("checkbox", { name: /Keep automations running/ }).boundingBox())!; expect(newBtnBox.y).toBeGreaterThanOrEqual(editorBox.y); expect(newBtnBox.y + newBtnBox.height).toBeLessThanOrEqual(afterScroll.rect.y + 1); expect(footerBox.y).toBeGreaterThanOrEqual(afterScroll.rect.y + afterScroll.rect.height - 1); expect(footerBox.y + footerBox.height).toBeLessThanOrEqual(editorBox.y + editorBox.height + 1); // Bottom row action button is genuinely interactive. await lastRow.getByRole("button", { name: "Edit Automation" }).click(); await expect(page.getByRole("dialog", { name: "Edit Automation" })).toBeVisible(); await page.keyboard.press("Escape"); await expect(page.getByRole("dialog", { name: "Edit Automation" })).toHaveCount(0); // 3. Switch to Run History -> scroll resets to top and Run History also scrolls cleanly to its last run. await editor.getByRole("tab", { name: /Run History/ }).click(); await expect(editor.locator('[data-testid^="automation-run-"]')).toHaveCount(20); await expect.poll(() => scrollBody.evaluate((el) => el.scrollTop)).toBe(0); const runsMetrics = await scrollBody.evaluate((el) => ({ clientHeight: el.clientHeight, scrollHeight: el.scrollHeight, })); expect(runsMetrics.scrollHeight).toBeGreaterThan(runsMetrics.clientHeight + 100); await scrollBody.evaluate((el) => { el.scrollTop = el.scrollHeight; }); const lastRunBox = (await editor.locator('[data-testid^="automation-run-"]').last().boundingBox())!; const runsRect = await scrollBody.evaluate((el) => el.getBoundingClientRect()); expect(lastRunBox.y + lastRunBox.height).toBeLessThanOrEqual(runsRect.y + runsRect.height + 1); // 4. Deep-linking back to the bottom-most schedule scrolls that focused row into view automatically. expect(ids).toContain(lastRowId); await page.evaluate(async (targetId) => { const autoMod = "/src/features/agents/automationsModel.ts"; const { openAutomations } = await import(/* @vite-ignore */ autoMod); openAutomations({ tab: "schedules", automationId: targetId }); }, lastRowId); await expect.poll(() => scrollBody.evaluate((el) => el.scrollTop)).toBeGreaterThan(100); const focusedBox = (await editor.getByTestId(`automation-row-${lastRowId}`).boundingBox())!; const schedulesRect = await scrollBody.evaluate((el) => el.getBoundingClientRect()); expect(focusedBox.y).toBeGreaterThanOrEqual(schedulesRect.y - 1); expect(focusedBox.y + focusedBox.height).toBeLessThanOrEqual(schedulesRect.y + schedulesRect.height + 1); });