Файли
openidea/e2e/agentAutomations.spec.ts
T
Deng Liuтаdengliu 391b91539f feat(mcp): built-in MCP tools for project automations (#7377)
Agents can list, inspect and schedule the project's automations through built-in MCP tools. Calls carry an unspoofable per-session capability nonce, scheduling authority is tied to the live session that owns the active turn, project writes always ask for confirmation, and a run cannot undo a user pause. Self-scheduling needs an enabled automation, and the configured trigger and prompt survive an override. The Edit Automation dialog shows pending overrides and gets consistent insets.

Co-authored-by: dengliu <[email protected]>
2026-12-03 02:15:13 +08:00

1387 рядки
58 KiB
TypeScript
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
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<string, AgentTask>([[manualSession.id, structuredClone(manualSession)]]);
const entriesByTask = new Map<string, AgentEntry[]>([
[
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) => a.enabled && a.trigger.kind !== "manual").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 nextList = autoMod.previewTriggerBrowser(req.trigger, Date.now(), 1);
const now = Date.now();
const idx = req.id ? automations.findIndex((a) => a.id === req.id) : -1;
const prev = idx >= 0 ? automations[idx] : undefined;
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: req.allowAgentSchedule ?? false,
misfirePolicy: req.misfirePolicy ?? null,
disableAfterMs: req.disableAfterMs ?? null,
maxRuns: req.maxRuns ?? null,
nextRunMs: req.enabled ? (nextList[0] ?? null) : 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.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.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<string, AgentTask> }) => ({
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");
await expect(editor.locator('[data-testid^="automation-row-"]').first()).toContainText("Paused");
// 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 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 once -> 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();
// Return to Automations and mark read so Quiet Clean Sweep (#1) is completed + read
await page.getByTestId("automation-provenance-banner").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 ("Active & Needs Input"):
// Manual task + NeedsInput automated task are shown; completed read automated task is hidden!
const taskTree = page.getByRole("tree", { name: "Agent tasks" });
await expect(taskTree).toContainText("Refactor auth middleware");
await expect(taskTree).toContainText("Rolling PR Labeler (#1)");
await expect(taskTree).not.toContainText("Quiet Clean Sweep (#1)");
// Switch filter to Show All -> Quiet Clean Sweep (#1) appears
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("agents.automatedRunsAll");
});
await expect(taskTree).toContainText("Quiet Clean Sweep (#1)");
// Switch filter to Hide All -> both automated tasks 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 (#1)");
await expect(taskTree).not.toContainText("Quiet Clean Sweep (#1)");
});
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<string, AgentTask> }) => ({
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("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 <prompt> 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 <prompt> -> 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<string, unknown> };
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-"]').first();
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<string, unknown>) =>
args.task === "interactive-mcp-setup" ? setupEntries : (prevEntries?.(args) ?? []);
useAgents.setState((s: { tasks: Map<string, AgentTask> }) => ({
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<string, unknown>) =>
args.task === "auto-run-4" ? entries : (prevHandlers?.(args) ?? []);
useAgents.setState((s: { tasks: Map<string, AgentTask> }) => ({
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<string, unknown>) =>
args.task === "farm-bot-run-2" ? gameEntries : (prevHandlers?.(args) ?? []);
useAgents.setState((s: { tasks: Map<string, AgentTask> }) => ({
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",
});
}
});