fix(e2e): follow current routine form and schedule controls (#22821)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The scheduled-routine journey checks creation, timed execution,
saved output and pause.
> - The routine page redesign changed its form and schedule controls.
> - The journey still used the old title placeholder, Responsible picker
and trigger editor.
> - It stopped before it could measure scheduling, even after the New
routine button fix.
> - This pull request follows the current controls and adds a
production-component browser regression.
> - The benefit is a usable schedule test with the same independent
behavior checks.

## Linked Issues or Issue Description

Refs #22182 and #22205. Related open #22340 changes other routine page
details; it does not update this journey.

**What happened?**
The scheduled-routine journey opens New routine, then times out on the
removed Routine title placeholder. The current form labels that field
Title. It has a Default agent picker and a separate Project picker. The
old journey also expects the removed Schedule trigger region and Enable
trigger control.

**Expected behavior**
The journey must use the current form, resume its owned schedule,
observe one attributed scheduled run, pause it, and check the next full
schedule boundary.

**Steps to reproduce**
Run the new credential-free browser control against the previous UI
actions. It renders the production RoutineEditDialog and fails waiting
for the old Routine title placeholder. The same control passes with this
repair.

**Paperclip version or commit**
Reproduced from master at d128e2db6f.
Published on current master after checking that all four existing
changed files were unchanged.

**Deployment mode**
Local Chromium production-component control, with no app server, model
or testing credentials. The observed staging failure supplied the
original report. This PR has no fresh full-stack staging pass.

## What Changed

- Extract the routine browser actions into a small journey-owned module.
- Fill Title and Instructions by accessible name. Open the agent and
project pickers explicitly.
- Use the schedule popover's Resume and Pause controls. Wait for each
exact trigger PATCH.
- Read created-task history on the base routine page. Keep configuration
version history separate.
- Add a Chromium control using the actual form, entity selectors and
routine page. It checks exact owner/project selection, missing-choice
refusal and the two owned trigger mutations. Unrelated display/editor
boundaries are stubbed.
- Keep the scheduler, native run, output, reload, duplicate-run,
deadline and cleanup oracles intact.
- Document the control and its limited acceptance scope.

## Verification

- Red: the production-component browser control timed out on
`getByPlaceholder("Routine title")` with the original actions.
- Green: `BROWSER_EXECUTABLE_PATH=/usr/bin/chromium node --import
/tmp/pap5819-tools/node_modules/tsx/dist/loader.mjs
tests/runner-e2e/product-journeys/routine-schedule-ui.browser.mjs`
passes.
- Focused Vitest: all 17 tests in routine-schedule-entry,
routine-schedule-evidence and routine-schedule-flow pass. The temporary
config selects only those suites.
- Local tools: Node 25.9.0, Vitest 5.0.3, Playwright 1.62.1 and system
Chromium. Dependencies were installed outside the checkout; no lockfile
changed.
- `pnpm verify` could not select tests: the managed Git storage guard
rejects `git ls-files`. This attempt has no verification verdict. The
first head passed selected CI. Those results do not qualify the revised
head; fresh CI and review remain pending.
- No new paid run, protected test-harness pin change or staging
deployment was made. Full scheduled acceptance remains separate.

- Review regression: the production route resolver rejects the old
/history task read; all 17 focused tests pass after the correction.
- Isolated dependency layout: the previous browser check cannot resolve
React without root React/React DOM. The revised check resolves UI-owned
peers and passes in that layout.

## Risks

- These actions target the current redesigned routine UI. An old UI
paired with this harness would not match the controls.
- The browser regression stubs unrelated display/editor boundaries. It
proves the real control actions, not a complete scheduler or
native-provider run.
- The fixture owns one schedule. Multiple matching schedule controls
cause an error rather than selecting an arbitrary trigger.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

OpenAI GPT-6 in Codex, with tool use for source edits, Chromium, local
tests and GitHub API operations.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-24 15:19:57 -06:00
1 parent 137bd29531
commit 823e90d8b2
6 files changed
+207 -49

No files matched your search

+23
View File
@@ -487,6 +487,29 @@ saved daily TestOps plan only after an inspected real QA Cloud pass including
usage, artifact/decision evidence and cleanup. The daily driver runs that saved
plan against the registered QA tenant; it does not substitute a local instance.
The scheduled-routine browser actions use the current routine form's Title,
Default agent, Project and Instructions controls. Each picker opens explicitly;
agent selection does not imply project focus. The schedule's normal popover
owns Resume and Pause, and both actions wait for the exact trigger PATCH.
The task-history read returns to the routine page's History field; the separate
/history route contains configuration revisions. The existing scheduled-run,
output attribution, duplicate-run and pause-window checks remain independent.
A credential-free control renders the production form, entity pickers and
routine page in Chromium. It resolves React from the UI workspace, as required
by an isolated pnpm install. It checks exact owner/project selection, refusal of a
missing agent or project, and one Resume/Pause mutation for the owned trigger. Its unrelated
editor/display boundaries are stubbed: AgentAvatar, Identity initials, style
joining, router Link, MarkdownBody, RunButton, TaskSummaryList, MarkdownEditor,
RoutineVariablesEditor, EnvironmentVariablesEditor, and ScheduleEditor (including
its schedule-description formatter). The stub map is next to the browser fixture.
The real Markdown serialization, task-history content and schedule-expression
editor are outside this control's scope. It is not full-stack or QA qualification:
```sh
node --import ./cli/node_modules/tsx/dist/loader.mjs tests/runner-e2e/product-journeys/routine-schedule-ui.browser.mjs
```
The scheduled-routine pause oracle uses a full 65 seconds of monotonic elapsed
time after both pause acknowledgement and work completion. Its enable receipt
uses the server's timestamp; client and server wall clocks are never compared.
@@ -4,6 +4,7 @@ import path from "node:path";
import { createHash } from "node:crypto";
import { afterEach, expect, it, vi } from "vitest";
import { runScheduledRoutine } from "./routine-schedule-flow.js";
import { resolveRoutineAddress } from "../../../ui/src/components/routine-page/routine-routes.js";
import type { JourneyContext, JourneyEvidence, TargetSession } from "./types.js";
// Browser rendering is covered by the real Routines component tests. This entry
@@ -34,6 +35,7 @@ async function fixture(fault: "body" | "document-author" | "revision-run" | "cre
const revision = { id: "revision", documentId: document.id, body, createdByAgentId: agent.id,
createdByRunId: fault === "revision-run" ? "foreign-run" : run.id };
const reads: string[] = [];
const visited: string[] = [];
let instructions = "", pastes = 0, triggerCreated = false, responseResolver: ((value: unknown) => void) | undefined;
const routine = () => ({ id: "routine", companyId: "company", title: `Journey QA scheduled routine ${campaignId}`,
projectId: fault === "creation-project" ? "foreign-project" : project.id, assigneeAgentId: agent.id,
@@ -41,7 +43,7 @@ async function fixture(fault: "body" | "document-author" | "revision-run" | "cre
description: fault === "creation-description" ? instructions.replaceAll("`", "\\`") : instructions,
concurrencyPolicy: "always_enqueue", triggers: triggerCreated ? [trigger] : [] });
const locator = (name = ""): any => ({ first() { return this; }, getByRole: (_role: string, options: { name?: string } = {}) => locator(options.name),
getByPlaceholder: () => locator(), locator: () => ({
getByPlaceholder: () => locator(), focus: async () => {}, locator: () => ({
fill: async (value: string) => { instructions = value; }, focus: async () => {},
// The real MDX browser discriminator covers serialization. Keep this unit
// editor boundary separate from the production API reads and grade.
@@ -50,9 +52,13 @@ async function fixture(fault: "body" | "document-author" | "revision-run" | "cre
pastes += 1; instructions = text;
},
}),
fill: async () => {}, click: async () => {
if (name === "Enable trigger") { trigger.enabled = true; responseResolver?.({ status: () => 200, json: async () => ({ ...trigger }) }); }
if (name === "Pause trigger") trigger.enabled = false;
fill: async (value: string) => { if (name === "Instructions") instructions = value; },
evaluate: async (_action: unknown, text?: string) => {
if (text === undefined) return false;
pastes += 1; instructions = text;
}, click: async () => {
if (name === "Resume") { trigger.enabled = true; responseResolver?.({ status: () => 200, json: async () => ({ ...trigger }) }); }
if (name === "Pause") { trigger.enabled = false; responseResolver?.({ status: () => 200 }); }
if (name === "Create routine") responseResolver?.({ status: () => 201, json: async () => routine() });
} });
const api = { origin: "https://qa.example.test", async post(route: string) {
@@ -76,13 +82,20 @@ async function fixture(fault: "body" | "document-author" | "revision-run" | "cre
if (route === "/api/issues/task/documents/scheduled-summary/revisions/revision") return revision;
throw new Error(`Unexpected fixture read ${route}`);
} };
const page = { getByRole: (_role: string, options: { name?: string } = {}) => locator(options.name), getByPlaceholder: () => locator(),
async goto(url: string) { if (url.endsWith("/routines/routine/runs")) throw new Error("Stop the positive control before the real pause window"); },
const page = { getByRole: (role: string, options: { name?: string } = {}) => {
if (role === "link" && options.name === task.identifier) {
// Stop at the task-link assertion, independently of the address chosen.
// The test below checks that address using the production route resolver.
throw new Error("Stop the positive control before the real pause window");
}
return locator(options.name);
}, getByPlaceholder: () => locator(),
async goto(url: string) { visited.push(url); }, async reload() {},
waitForResponse: () => new Promise(resolve => { responseResolver = resolve; }) };
const context = { api, page, company: { id: "company", issuePrefix: "QA" }, user: { id: "user" }, agent, environmentId: "environment" } as unknown as JourneyContext;
const directory = await mkdtemp(path.join(os.tmpdir(), "routine-attribution-")); directories.push(directory);
const evidence = { checks: [] } as unknown as JourneyEvidence;
return { expectedBody, body, instructions: () => instructions, pastes: () => pastes, evidence, trigger, directory, reads,
return { expectedBody, body, instructions: () => instructions, pastes: () => pastes, evidence, trigger, directory, reads, visited,
run: () => runScheduledRoutine(context, { async own() {} } as unknown as TargetSession, campaignId, evidence,
{ directory, deadlineAt: Date.now() + 10_000 }) };
}
@@ -125,6 +138,10 @@ it("keeps the real journey attribution failure when final trigger disabling also
it("sends the unchanged exact two-line body as a delimited instruction and accepts valid attribution", async () => {
const f = await fixture();
await expect(f.run()).rejects.toMatchObject({ code: "routine_open_history_failed" });
const historyUrl = new URL(f.visited.at(-1)!);
const section = historyUrl.pathname.split("/")[4];
expect(resolveRoutineAddress({ routineId: "routine", section }).view).toBe("routine");
expect(historyUrl.pathname).toBe("/QA/routines/routine");
const block = f.instructions().match(/```text\n([\s\S]*?)\n```/);
expect(block?.[1]).toBe(f.expectedBody);
expect(f.instructions()).toContain("including the final period");
@@ -1,8 +1,9 @@
import { enableRoutineScheduleTrigger } from "./routine-schedule-ui.js";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, it, vi } from "vitest";
import { enableRoutineScheduleTrigger, routineUiStep, withRoutineTriggerCleanup } from "./routine-schedule-flow.js";
import { routineUiStep, withRoutineTriggerCleanup } from "./routine-schedule-flow.js";
import { JourneyError } from "./types.js";
describe("routine trigger cleanup failure reporting", () => {
@@ -31,11 +32,11 @@ describe("routine trigger cleanup failure reporting", () => {
describe("routine UI failure evidence", () => {
it("retains a closed step code without browser messages or form values", async () => {
const error = await routineUiStep("select_project", async () => {
const error = await routineUiStep("fill_form", async () => {
throw new Error("Timeout at https://private.example/?token=secret with form value private-project");
}).catch(value => value);
expect(error).toBeInstanceOf(JourneyError);
expect(error).toMatchObject({ outcome: "failed", code: "routine_select_project_failed", message: "routine_select_project_failed" });
expect(error).toMatchObject({ outcome: "failed", code: "routine_fill_form_failed", message: "routine_fill_form_failed" });
expect(JSON.stringify(error)).not.toMatch(/private|token|secret/);
});
it("keeps a semantic journey failure instead of replacing its evidence code", async () => {
@@ -52,20 +53,16 @@ describe("routine UI failure evidence", () => {
describe("schedule trigger controls", () => {
it("opens the collapsed schedule editor before its single enable action", async () => {
it("opens the schedule popover before one attributed resume action", async () => {
let expanded = false, clicks = 0, resolveResponse!: (value: any) => void;
const response = { status: () => 200 };
const pending = new Promise<any>(resolve => { resolveResponse = resolve; });
const schedule = { getByRole: (_role: string, options: { name: string }) => ({ click: async () => {
if (options.name === "Edit schedule") { expanded = true; return; }
if (options.name !== "Enable trigger" || !expanded) throw new Error("schedule control is not rendered");
const page = { getByRole: (_role: string, options: { name: string | RegExp }) => ({ click: async () => {
if (options.name instanceof RegExp && options.name.test("Change schedule: Every minute")) { expanded = true; return; }
if (options.name !== "Resume" || !expanded) throw new Error("schedule control is not rendered");
clicks += 1;
resolveResponse(response);
} }) };
const page = { getByRole: (role: string, options: { name: string }) => {
if (role === "region" && options.name === "Schedule trigger") return schedule;
return schedule.getByRole(role, options);
}, waitForResponse: () => pending } as unknown as Parameters<typeof enableRoutineScheduleTrigger>[0];
} }), waitForResponse: () => pending } as unknown as Parameters<typeof enableRoutineScheduleTrigger>[0];
expect(await enableRoutineScheduleTrigger(page, "/api/routine-triggers/owned-trigger")).toBe(response);
expect(expanded).toBe(true);
expect(clicks).toBe(1);
@@ -1,10 +1,11 @@
import { fillRoutineCreateForm, enableRoutineScheduleTrigger, setRoutineScheduleEnabled } from "./routine-schedule-ui.js";
import { createObservedReader } from "./observation-read.js";
import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, type Page } from "@playwright/test";
import { expect } from "@playwright/test";
import { ConnectionFailure } from "../connection-config.js";
import { fillTaskPrompt, withBrowserEvent } from "../user-actions.js";
import { withBrowserEvent } from "../user-actions.js";
import { validateAgentTaskState, waitFor } from "./agent-flows.js";
import { openDocumentAuthoring } from "./task-document-flow.js";
import { scheduledInvocationMatches, schedulePauseMatches, schedulePauseObservationMs, type ScheduledInvocation, type ScheduledTask } from "./routine-schedule-evidence.js";
@@ -12,7 +13,7 @@ import { JourneyError, type JourneyContext, type JourneyEvidence, type TargetSes
type Row = Record<string, any>;
const journeyId = "routine-scheduled-run" as const;
type RoutineUiStep = "open_composer" | "select_responsible" | "select_project" | "fill_instructions" | "submit" | "enable_trigger" | "pause_trigger" | "open_history" | "reopen_result";
type RoutineUiStep = "open_composer" | "fill_form" | "submit" | "enable_trigger" | "pause_trigger" | "open_history" | "reopen_result";
export async function routineUiStep<T>(step: RoutineUiStep, action: () => Promise<T>): Promise<T> {
try { return await action(); }
catch (error) {
@@ -21,15 +22,6 @@ export async function routineUiStep<T>(step: RoutineUiStep, action: () => Promis
throw new JourneyError("failed", `routine_${step}_failed`);
}
}
export async function enableRoutineScheduleTrigger(page: Pick<Page, "getByRole" | "waitForResponse">, triggerRoute: string) {
const schedule = page.getByRole("region", { name: "Schedule trigger", exact: true });
// The enable/pause controls are children of the collapsed schedule editor.
await schedule.getByRole("button", { name: "Edit schedule", exact: true }).click();
return withBrowserEvent(
() => page.waitForResponse(response => response.request().method() === "PATCH"
&& new URL(response.url()).pathname === triggerRoute),
() => schedule.getByRole("button", { name: "Enable trigger", exact: true }).click());
}
export async function withRoutineTriggerCleanup<T>(input: {
api: Pick<JourneyContext["api"], "patch">; triggerRoute: string; directory: string; run(): Promise<T>;
}): Promise<T> {
@@ -86,21 +78,9 @@ export async function runScheduledRoutine(context: JourneyContext, session: Targ
await page.getByRole("button", { name: "New routine", exact: true }).first().click();
});
const dialog = page.getByRole("dialog");
await routineUiStep("select_responsible", async () => {
await dialog.getByPlaceholder("Routine title", { exact: true }).fill(title);
await dialog.getByRole("button", { name: "Responsible", exact: true }).click();
await page.getByPlaceholder("Search responsible...", { exact: true }).fill(agent.name);
await page.getByRole("button", { name: agent.name, exact: true }).click();
});
await routineUiStep("select_project", async () => {
// Selecting Responsible focuses Project and opens its picker. Clicking
// its trigger again closes the picker before the search field can fill.
const projectSearch = page.getByPlaceholder("Search projects...", { exact: true });
await expect(projectSearch).toBeVisible();
await projectSearch.fill(projectName);
await page.getByRole("button", { name: projectName, exact: true }).click();
});
await routineUiStep("fill_instructions", () => fillTaskPrompt(dialog.locator('[contenteditable="true"]'), prompt));
await routineUiStep("fill_form", () => fillRoutineCreateForm(page, {
title, agentName: agent.name, projectName, prompt,
}));
await session.own({ kind: "routine", name: title, journeyId });
const response = await routineUiStep("submit", () => withBrowserEvent(
() => page.waitForResponse(response => response.request().method() === "POST"
@@ -149,7 +129,7 @@ export async function runScheduledRoutine(context: JourneyContext, session: Targ
let pausedAt = 0;
await withRoutineTriggerCleanup({ api, triggerRoute, directory: options.directory, run: async () => {
const enabledResponse = await routineUiStep("enable_trigger", async () => {
await page.goto(`${api.origin}/${company.issuePrefix}/routines/${routine.id}/triggers`, { waitUntil: "domcontentloaded" });
await page.goto(`${api.origin}/${company.issuePrefix}/routines/${routine.id}`, { waitUntil: "domcontentloaded" });
return enableRoutineScheduleTrigger(page, triggerRoute);
});
if (enabledResponse.status() !== 200) throw new JourneyError("failed", "routine_schedule_enable_failed");
@@ -159,7 +139,8 @@ export async function runScheduledRoutine(context: JourneyContext, session: Targ
|| enabledTrigger.enabled !== true || !Number.isFinite(enabledAt)) throw new JourneyError("failed", "routine_schedule_enable_receipt_missing");
await expect.poll(async () => (await readTrigger()).enabled).toBe(true);
const first = await waitFor(options.deadlineAt, runs, rows => rows.length > 0 && Boolean(rows[0]?.linkedIssueId), "scheduled_invocation_missing");
await routineUiStep("pause_trigger", () => page.getByRole("button", { name: "Pause trigger", exact: true }).click());
const pausedResponse = await routineUiStep("pause_trigger", () => setRoutineScheduleEnabled(page, triggerRoute, false));
if (pausedResponse.status() !== 200) throw new JourneyError("failed", "routine_schedule_pause_failed");
await expect.poll(async () => (await readTrigger()).enabled).toBe(false);
pausedAt = performance.now();
const task = await readObserved<ScheduledTask & { title: string }>(`/api/issues/${first[0]!.linkedIssueId}`);
@@ -205,7 +186,7 @@ export async function runScheduledRoutine(context: JourneyContext, session: Targ
check("routine-result-attributed", Object.values(matches).every(Boolean));
if (typeof state.currentIssue.identifier !== "string" || !state.currentIssue.identifier) throw new JourneyError("failed", "routine_task_identifier_missing");
await routineUiStep("open_history", async () => {
await page.goto(`${api.origin}/${company.issuePrefix}/routines/${routine.id}/runs`, { waitUntil: "domcontentloaded" });
await page.goto(`${api.origin}/${company.issuePrefix}/routines/${routine.id}`, { waitUntil: "domcontentloaded" });
await page.reload();
await expect(page.getByRole("link", { name: state.currentIssue.identifier, exact: false }).first()).toBeVisible();
});
@@ -0,0 +1,106 @@
import assert from "node:assert/strict";
import path from "node:path";
import { existsSync } from "node:fs";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import { build } from "esbuild";
import { chromium } from "@playwright/test";
import { fillRoutineCreateForm, enableRoutineScheduleTrigger, setRoutineScheduleEnabled } from "./routine-schedule-ui.ts";
// Render the production form, entity pickers, schedule rows and Radix primitives.
// Only unrelated display/editor boundaries are replaced. No app, provider or QA
// credential is needed. The full journey retains independent API readback/grades.
const root = fileURLToPath(new URL("../../../", import.meta.url));
const uiRoot = path.join(root, "ui");
const uiRequire = createRequire(path.join(uiRoot, "package.json"));
const stubs = {
"@/components/AgentAvatar": "export const AgentAvatar = () => null;",
"@/components/Identity": "export const deriveInitials = name => name.slice(0, 2);",
"@/lib/utils": "export const cn = (...values) => values.filter(Boolean).join(' ');",
"../lib/utils": "export const cn = (...values) => values.filter(Boolean).join(' ');",
"@/lib/router": "export const Link = ({to, children, ...props}) => <a href={to} {...props}>{children}</a>;",
"@/components/MarkdownBody": "export const MarkdownBody = () => null;",
"@/components/AgentActionButtons": "export const RunButton = () => null;",
"@/components/TaskSummaryList": "export const TaskSummaryList = () => null;",
"@/components/MarkdownEditor": `export const MarkdownEditor = ({value, onChange, ariaLabel}) =>
<textarea aria-label={ariaLabel} value={value} onChange={event => onChange(event.target.value)} />;`,
"@/components/RoutineVariablesEditor": "export const RoutineVariablesEditor = () => null;",
"@/components/environment-variables-editor": "export const EnvironmentVariablesEditor = () => null;",
"@/components/ScheduleEditor": `export const ScheduleEditor = () => null;
export const describeSchedule = () => 'Every minute';`,
};
const compiled = await build({
absWorkingDir: root,
stdin: { resolveDir: uiRoot, loader: "tsx", contents: `
import React, { useState } from 'react';
import { createRoot } from 'react-dom/client';
import { RoutineEditDialog, EMPTY_ROUTINE_FORM_DRAFT } from './src/components/routine-page/RoutineEditDialog';
import { RoutinePage } from './src/components/routine-page/RoutinePage';
const agent = { id: 'owned-agent', name: 'Owned QA agent' };
const project = { id: 'owned-project', name: 'Owned QA project' };
function Form() { return <RoutineEditDialog mode="create" open initial={EMPTY_ROUTINE_FORM_DRAFT}
onOpenChange={() => {}} agents={[{id:'other-agent',name:'Other agent'},agent]}
projects={[{id:'other-project',name:'Other project'},project]} people={[]} secrets={[]}
onSave={draft => { window.saved = draft; window.saves++; }} />; }
function Detail() {
const [enabled,setEnabled] = useState(false);
const routine = { id:'owned-routine', title:'Schedule control', status:'active', assigneeAgentId:agent.id,
description:'', variables:[], env:null, triggers:[{id:'owned-trigger',kind:'schedule',enabled,
cronExpression:'* * * * *',timezone:'America/Chicago'}] };
return <RoutinePage routine={routine} agent={agent} project={project} history={[]} responsibilities={[]}
onEdit={() => {}} onSaveSchedule={() => {}} onRemoveSchedule={() => {}}
onSetTriggerPaused={async (id, paused) => { await fetch('/api/routine-triggers/'+id,
{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({enabled:!paused})}); setEnabled(!paused); }} />;
}
window.saves=0; window.show = mode => createRoot(document.getElementById('root')).render(mode==='form'?<Form/>:<Detail/>);
` },
bundle: true, write: false, format: "iife", jsx: "automatic",
plugins: [{ name: "unrelated-ui-boundaries", setup(builder) {
builder.onResolve({ filter: /.*/ }, args => {
// React is owned by ui, not by the repository root in an isolated pnpm install.
if (/^react(?:-dom)?(?:\/|$)/.test(args.path)) return { path: uiRequire.resolve(args.path) };
if (stubs[args.path]) return { path: args.path, namespace: "fixture" };
if (args.path.startsWith("@/")) {
const base = path.join(root, "ui/src", args.path.slice(2));
return { path: [base, base+".ts", base+".tsx"].find(existsSync) ?? base };
}
});
builder.onLoad({ filter: /.*/, namespace: "fixture" }, args => ({ contents: stubs[args.path], loader: "tsx", resolveDir: uiRoot }));
} }],
});
const browser = await chromium.launch({ headless: true,
...(process.env.BROWSER_EXECUTABLE_PATH ? { executablePath: process.env.BROWSER_EXECUTABLE_PATH } : {}) });
try {
const page = await browser.newPage();
page.setDefaultTimeout(1500);
await page.route('https://routine.fixture/**', route => route.fulfill({contentType:'text/html',body:'<div id="root"></div>'}));
const mount = async mode => { await page.goto('https://routine.fixture/'); await page.addScriptTag({content:compiled.outputFiles[0].text}); await page.evaluate(mode => window.show(mode),mode); };
await mount('form');
const input = {title:'Scheduled check',agentName:'Owned QA agent',projectName:'Owned QA project',prompt:'Save the exact scheduled result.'};
await fillRoutineCreateForm(page,input);
await page.getByRole('button',{name:'Create routine',exact:true}).click();
const saved = await page.evaluate(() => ({draft:window.saved,count:window.saves}));
assert.equal(saved.count,1);
assert.equal(saved.draft.title,input.title);
assert.equal(saved.draft.assigneeAgentId,'owned-agent');
assert.equal(saved.draft.projectId,'owned-project');
assert.equal(saved.draft.description,input.prompt);
assert.equal(saved.draft.schedule,null,'creation must not start a schedule');
await mount('form');
await assert.rejects(fillRoutineCreateForm(page,{...input,agentName:'Missing agent'}));
assert.equal(await page.evaluate(() => window.saves),0,'a missing agent cannot submit or silently use another owner');
await mount('form');
await assert.rejects(fillRoutineCreateForm(page,{...input,projectName:'Missing project'}));
assert.equal(await page.evaluate(() => window.saves),0,'a missing project cannot silently select another project');
await mount('detail');
const patches=[];
await page.route('https://routine.fixture/api/routine-triggers/*',async route => {
patches.push({path:new URL(route.request().url()).pathname,body:route.request().postDataJSON()});
await route.fulfill({contentType:'application/json',body:JSON.stringify({id:'owned-trigger',enabled:patches.at(-1).body.enabled})});
});
assert.equal((await enableRoutineScheduleTrigger(page,'/api/routine-triggers/owned-trigger')).status(),200);
assert.equal((await setRoutineScheduleEnabled(page,'/api/routine-triggers/owned-trigger',false)).status(),200);
assert.deepEqual(patches,[{path:'/api/routine-triggers/owned-trigger',body:{enabled:true}},
{path:'/api/routine-triggers/owned-trigger',body:{enabled:false}}]);
console.log('Production routine form, exact owner/project, missing agent/project refusal and schedule resume/pause passed.');
} finally { await browser.close(); }
@@ -0,0 +1,34 @@
import { type Page } from "@playwright/test";
import { fillTaskPrompt, withBrowserEvent } from "../user-actions.js";
/** Use the production form's labels and explicitly open each independent picker. */
export async function fillRoutineCreateForm(page: Page, input: {
title: string; agentName: string; projectName: string; prompt: string;
}) {
const dialog = page.getByRole("dialog");
await dialog.getByRole("textbox", { name: "Title", exact: true }).fill(input.title);
// Focus is idempotent: InlineEntitySelector opens on focus, while a click
// can close a picker that keyboard focus has already opened.
await dialog.getByRole("button", { name: "Choose an agent", exact: true }).focus();
await dialog.getByPlaceholder("Search agents…", { exact: true }).fill(input.agentName);
await dialog.getByRole("button", { name: input.agentName, exact: true }).click();
await dialog.getByRole("button", { name: "No project", exact: true }).focus();
await dialog.getByPlaceholder("Search projects…", { exact: true }).fill(input.projectName);
await dialog.getByRole("button", { name: input.projectName, exact: true }).click();
await fillTaskPrompt(dialog.getByRole("textbox", { name: "Instructions", exact: true }), input.prompt);
}
/** The fixture owns exactly one schedule; use its normal page popover. */
export async function setRoutineScheduleEnabled(
page: Pick<Page, "getByRole" | "waitForResponse">, triggerRoute: string, enabled: boolean,
) {
await page.getByRole("button", { name: /^Change schedule:/ }).click();
return withBrowserEvent(
() => page.waitForResponse(response => response.request().method() === "PATCH"
&& new URL(response.url()).pathname === triggerRoute),
() => page.getByRole("button", { name: enabled ? "Resume" : "Pause", exact: true }).click());
}
export async function enableRoutineScheduleTrigger(page: Pick<Page, "getByRole" | "waitForResponse">, triggerRoute: string) {
return setRoutineScheduleEnabled(page, triggerRoute, true);
}