Файли
openidea/e2e/agentAutomations.spec.ts
T
Deng Liuтаdengliu f8ba067e1d feat(agents): add host-owned local and remote agent automations (#7084)
Adds agent automations owned by the host rather than a window: scheduled, one-shot and manual automations, in-session /loop and Send Later, and .automation.md import/export.

- Schedules run while OpenIDEA or openidea-server --daemon is running. An optional login service (LaunchAgent, systemd --user unit or Windows Startup entry), off by default, keeps them running when OpenIDEA is closed; a schedule that came due while nothing was running follows the missed-run policy.
- Every automated turn is capped at the interactive approval setting. A run fails and its schedule pauses unless the provider confirms the required ceiling, including for turns that waited in the queue.
- Scheduled turns re-check project and repository trust at dispatch; Restricted Mode pauses them.
- Worktree runs use new agent/* branches, keep the working directory confined to the worktree, and cleanup never deletes branches. Imported .automation.md files only create disabled copies.
- Automation state is shared across processes with one lock order, and in-memory claims roll back when persisting fails. Windows and peers can only act on tasks of projects they own.

Closes #6942

Co-authored-by: dengliu <[email protected]>
2026-12-02 09:19:54 +08:00

815 рядки
36 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,
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 click the pinned Automations hub row
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("agents.showToolWindow");
});
const hub = page.getByTestId("agents-automations-hub");
await expect(hub).toBeVisible();
await hub.getByRole("button", { name: /Automations/ }).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.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: "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: "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("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: "Unattended Permissions" }).click();
await page.getByRole("option", { name: "Allow all (capped by your interactive approval setting)" }).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");
});