Files
fusion/packages/dashboard/app/components/__tests__/RoutineEditor.test.tsx
gsxdsm e9e63d8e0f consolidate/capacity: --strict was red on main (my #2621), 14 stale baselines, routines seeding a deleted column, worktrees-off audit (#2652)
Capacity unit consolidation. Three coherent themes, small commits
inside.

## Census before/after (`node scripts/lifecycle-column-census.mjs`)

| | before | after |
|---|---:|---:|
| triage column guards (the bar) | 10 | **10** |
| `--strict` on main | ❌ **RED** | ✅ green |
| baseline staleness | 14 files stale | **0** |

This branch does **not** move the triage bar — its remaining 10 are
moves.ts (dies with the flag), the dashboard cluster, and one deliberate
site. It fixes the instrument that measures the bar, plus a live defect
the comparison count cannot see.

---

## 1. `--strict` was RED on clean `origin/main`, and it was my fault

```
packages/dashboard/src/routes/register-task-workflow-routes.ts: 22 -> 23
```

My merged #2621 added a v1-IR pre-WIP fallback answering a greptile P1
and shipped no marker or baseline update, so the program's measuring
instrument has been failing on main since it landed.

Fixed **at the site** with a `DELIBERATE-LITERAL` marker, not by bumping
the baseline. That branch runs only when the IR declares no columns and
no nodes, so there is no role to resolve — `resolveLifecycleColumns`
returns nothing and the legacy pre-implementation ids are the only
pre-WIP signal that exists there. It is *unconvertible*, not unfinished;
the sibling `else` two lines down is the trait path for every IR that
can answer. A rise that is genuinely correct belongs where a reader will
see it.

## 2. The baseline was stale for 14 files — a hole, not cosmetics

A stale allowance lets converted guards return while the check stays
green. Measured gaps:

```
self-healing.ts          allows 126, tree has 111
executor.ts              allows 112, tree has 104
moves.ts                 allows  44, tree has  39
default-workflow-hooks   allows  25, tree has   7
mission-feature-sync     allows   5, tree has   0
MissionControlPanel      allows   4, tree has   0        (+8 more)
```

**Only two of the fourteen are mine.** The other twelve are
already-merged conversions by other workers where nobody re-recorded.
Re-recorded all fourteen here rather than waiting for twelve PRs,
because until it happens the ratchet is not holding the 779 it exists to
hold. Flagging it plainly: those drops are other people's work being
locked in, not mine being claimed.

## 3. Routines created tasks into the column U11 deleted

The routine editor's "Target Column" defaulted to `triage`. That value
is submitted as the create step's `taskColumn`, and an **explicit**
column bypasses the workflow entry-column resolution added for
column-less creates (#2589) — so every routine saved with the untouched
default seeded its tasks into a column the board does not declare.

Defaulting to `todo` would be the same mistake one column over: a custom
workflow declaring no `todo` is seeded into an undeclared column just as
surely, because an explicit column overrides entry resolution whatever
its value. So the default sends **nothing** and each workflow's own
intake resolution decides.

The `triage` **option** is removed too, not merely un-defaulted — fixing
the initializer alone left the operator able to pick the deleted column
one click away, and it was the option labelled "Planning", the name the
merged `todo` column now displays. Removing it retires that label
inversion as well.

Found by scanning **membership** forms rather than comparisons: the
comparison census cannot see a `?? "triage"` default, so no count showed
this and nobody was looking. Revert-proof — restoring the default fails
with *"the default must not name a column at all"*.

## 4. "Worktrees off is INERT" had one unaudited reader

The constraint was that `maxWorktrees` become genuinely inert, "not set
very high and not skipped by convention". `resolveWorktreeCapacityLimit`
returns `null` for that, and its unit tests can only prove the
**resolver** is right — they cannot see a second reader, which is the
only way the constraint breaks.

Audited every `maxWorktrees` read that bounds anything. **Exactly two:**
`scheduler.ts` (the admission gate, via the resolver, single call site,
optional gate snapshot) and `self-healing.ts`'s `enforceWorktreeCap` —
`(settings.maxWorktrees ?? 4) * 2`, a **raw** read.

The second is **not a bug** and is left alone: it bounds worktree
*directories on disk* and only removes *idle* ones. Worktrees still
exist in OFF mode, so that bound must keep applying or idle directories
accumulate unbounded. Recorded consequence: in OFF mode the number still
governs disk retention while gating no admission — an edge you scoped
out. The note says explicitly **not** to unify the two readers: routing
hygiene through the resolver returns `null` in OFF mode and silently
removes the disk bound, which is a leak dressed as a simplification.

New ratchet requires every file bounding on `maxWorktrees` to be named
with a reason, and rejects a **stale** allowlist entry. Proven by
injecting `active >= (settings.maxWorktrees ?? 4)` into
`hybrid-executor.ts`.

---

## Deliberately NOT included

- **My own census script.** #2633 landed the canonical one, and it is
better than mine — an AST classifier *plus* an independent text
classifier with `--compare`, and a baseline that fails on unrecorded
**drops** as well as rises. Mine only caught rises. I deleted mine
rather than ship a second measuring instrument; three copies of "strip
comments" is the drift shape this program keeps paying for, so the
worktree ratchet now imports #2633's `stripComments`.
- **My TaskContextMenu fix.** Superseded, and by a better answer: main's
`isPureIntakeColumn` (intake *without* hold) keeps the merged Planning
column shown and suppresses only a bare Ideas capture, which resolves
the exact hold-lane objection coderabbit raised against my version. I
briefly clobbered that merged work by checking my old file out
wholesale, caught it in the diff, and reverted.

## Verification

`pnpm lint` clean · core + dashboard `tsc` clean · census suite 23/23 ·
worktree ratchet 8/8 · RoutineEditor 49/49 ·
`routes-task-retry-planning-column` 16/16 · `lifecycle-column-census
--strict` exits 0.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---

## Added after review (all four greptile threads were real, and two of
them mattered)

**The routine fix was half a fix.** `routine-runner.ts:515` *and*
`cron-runner.ts:982` both did `column: (step.taskColumn as Column) ||
"triage"` **after** the step is read, so every routine — including ones
saved through the fixed editor — still created tasks into the deleted
column. Both now omit it.

**The advanced steps editor MANUFACTURED the defect.**
`ScheduleStepsEditor.tsx` had three `triage` defaults: the new-step
template (`:64`), the per-step initializer (`:95`), and the select still
offering it (`:344`). So the path I had *not* fixed produced the bug by
default, on fresh data. Template names no column; initializer coerces a
persisted `triage`; `triage` removed from the options; empty submits
`undefined`.

**Four pre-existing tests pinned the defect** and are rewritten to the
corrected invariant rather than appeased:

| test | asserted |
|---|---|
| `cron-runner`: "defaults column to triage when taskColumn is not set"
| `column: "triage"` |
| `ScheduleStepsEditor`: "adds a create-task step..." | `taskColumn`
toBe `"triage"` |
| `ScheduleStepsEditor`: "allows saving create-task step..." | the
legacy column is **resubmitted** |
| plus the explicit-column case added beside each, so the fix cannot
swallow a deliberate choice |

**The allowlist hole was the worst finding.** `AUDITED_BOUNDS` was keyed
by FILE, so every bounding expression in an allowlisted file was exempt
— a second raw bound in `scheduler.ts` stayed green, the one case that
ratchet exists for. Per-expression now, and making it so **immediately
surfaced a real second bound the file-level version was hiding**
(`maxWorktreesGate.used >= maxWorktreesGate.limit`, safe by construction
since the snapshot is `undefined` in OFF mode). Proven by injection.

## Found while re-reading my own deletion, not reported

A **rendered tooltip** still named a deleted cap. The "Queued to plan"
badge read *"planning starts when a concurrency slot frees up
(maxConcurrent / globalMaxConcurrent)"*. The cross-project cap is gone —
capacity is two numbers per project — so it told operators their
planning waited on a limiter they can no longer find a setting for.
Names the surviving dimension only now.

## Coding (Ideas): enforcing #2651 rather than repeating it

I took the unowned coding-ideas IR merge, concluded it must not be done,
then found **#2651 had already implemented, reverted and documented
exactly that** — with better grounding than my own argument. It added no
test, so nothing stops the next person reaching the same dead end.

So this ships their reasoning as a ratchet, not a second opinion: triage
discovery keys on the column's `autoTriage`, so a merged column is
either never scanned (cards sit on a bootstrap stub until the **capacity
hold** releases them, sending **unplanned** work into in-progress —
worse than stalling) or scanning wins and the manual gate is gone. Their
scope caveat is kept: `autoTriage` is a general trait field, so only
*this preset's* collapse is dead, not manual intake as a concept. The
registry does not reject the merged shape, which is why prose was not
enough.

## Verification (re-run)

`pnpm lint` clean · core + engine + dashboard-app `tsc` clean ·
`lifecycle-column-census --strict` exits 0 ("every file matches its
baseline exactly") · routine-runner 24/24 · cron-runner 156/156 ·
ScheduleStepsEditor 41/41 · RoutineEditor 49/49 · worktree +
coding-ideas 12/12. TaskCard has 2 failures **pre-existing on main** —
confirmed identical with my changes stashed.

---

## Bears directly on the closing bar: this PR already removes the
67-guard ratchet slack

Measured on current `origin/main` with the census itself:

```
tree total: 787   baseline total: 854   SLACK: 67

FILES ABOVE BASELINE (1):
   +1  packages/dashboard/src/routes/register-task-workflow-routes.ts  (22 -> 23)

FILES BELOW BASELINE: 13, totalling 68 unrecorded conversions
   -18  core/default-workflow-hooks.ts (25->7)   -15  engine/self-healing.ts (126->111)
    -8  engine/executor.ts (112->104)             -5  core/task-store/moves.ts (44->39)
    -5  engine/mission-feature-sync.ts (5->0)     -4  core/live-agent-count.ts (10->6)
```

**The slack is not regression — it is 13 files of merged conversions
nobody re-recorded**, against exactly **one** rise. This PR re-records
the baseline **854 → 782 across 140 files**, which closes it.

**And the "+3 that slipped in" is +1, and it is mine.**
`register-task-workflow-routes.ts 22 → 23` is the v1-IR pre-WIP fallback
my #2621 added; it is justified (that branch runs only when the IR
declares no columns or nodes, so there is no role to resolve) but it
shipped with no marker and no baseline update — which is why `--strict`
has been **red on main since it merged**. Fixed here at the site with a
`DELIBERATE-LITERAL` marker rather than by bumping the baseline, because
a rise that is genuinely correct belongs where a reader will see it.

Sequencing note for the auto-lowering change: if this lands first, that
work is purely the mechanism (auto-lower, or fail with tighten
instructions) rather than a cleanup, and the two re-records will not
collide in the same file.

Also worth carrying into that mechanism, from building the same guard
here: **`--update` must refuse to RAISE.** An earlier version of mine
wrote current counts verbatim, so a developer who added a literal and
ran the documented update command locked the regression in as the new
ceiling — the mirror of the high-water problem. Lowering can be
unattended; raising should be a hand edit with the reason recorded.

## Third piece of residue from my own deletion

`updateGlobalConcurrency` in the dashboard API client PUT to
`/api/global-concurrency`, a route removed when the machine-wide cap
went. Zero callers; the only reference was the `legacy.ts` barrel
re-export. Deleted both. `fetchGlobalConcurrency` **survives on
purpose** — the GET route remains and serves live utilization telemetry
to the footer and Command Center; nothing gates on it.

That is the third: after the second raw `maxWorktrees` reader and the
"Queued to plan" tooltip. A deletion is not finished when the
enforcement goes — the client, the label and the tooltip outlive it.

---

## Re-greened the dashboard API tests: 117 failures on main, ONE root
cause

These would have polluted the closing verification pass, and nobody
owned them.

`api()` builds headers via `new Headers(...)` and returns
`Object.fromEntries(headers.entries())` — and `Headers.entries()`
**lowercases every key**, so the object reaching `fetch` is
`content-type`, not `Content-Type`. `ab87d0d80` then added
`x-fusion-client: dashboard-ui` for run-audit attribution. Both changes
are correct; neither is visible at a call site, so **114 assertions
across 7 files** kept asserting the old shape and went red together.

Fixed by naming the shape **once** in `app/test/apiRequestHeaders.ts`
rather than patching 114 literals — restating a shared fact 114 times is
what made a two-line client change look like 117 failures. Deliberately
not a loose `objectContaining`: these tests are the only thing pinning
that the attribution header is sent *at all*.

**117 → 4.** The remaining 4 are unrelated pre-existing CSS failures
(`task-detail-modal-tablet-width` ×3, `space-token-defined` ×1) —
confirmed identical on clean main with my changes stashed.

### A gap this surfaced, recorded not papered over

Three routes failed in the *opposite* direction — they send the old
shape because they call `fetch()` **directly**, bypassing `api()`, so
they never get the attribution header. `client.ts` claims the opposite:

> "Applied once here rather than per-call so no future mutation route
has to remember it."

That does not hold for a route that bypasses the helper it is applied
in. **Measured in `app/api/`: 8 files make direct `fetch()` calls and 7
include mutations (POST/DELETE)** — among them `ai-sessions.ts`'s
DELETE, which is the same class as the four-delete incident the header
was added for. So the attribution fix has a hole in exactly its
motivating case.

Not fixed here: routing those onto `api()` is a behaviour change across
the API layer and belongs to its owner, not to a test re-green. Those
assertions use a separate `API_JSON_HEADERS_NO_ATTRIBUTION` constant so
the gap stays **visible** — if a route is later moved onto `api()`, its
test fails and points at the note explaining why.

---

## This branch takes the triage bar 10 → 5, and makes `--strict` green

`node scripts/lifecycle-column-census.mjs` on this branch reports
**triage 5**, against **10** on `origin/main`. The five removed are the
ScheduleStepsEditor template/initializer/option and the RoutineEditor
default/option — the automation paths that were creating tasks into the
deleted column.

**`--strict` was also RED on clean main, twice over, and both causes
were the same mistake:** a thorough written rationale the tool cannot
read, because the marker was not where the census looks. The census
reads a comparison node's **leading comments**; a `DELIBERATE-LITERAL`
in the JSDoc above the enclosing function or declaration does not reach
the comparison inside it.

| site | why it is legitimate | why the tool could not see it |
|---|---|---|
| `columnRoles.ts:80` `isHoldColumnRole` | degrades to `columnId ===
"todo"` only when a column has **no resolved traits** — identical in
kind to `LEGACY_PRE_IMPLEMENTATION_COLUMN_IDS` directly above, which
escapes counting only because a Set is a membership form | rationale
written, **no marker token** |
| `MissionControlPanel.tsx` ×3 | the SDLC funnel **alias table** — maps
`to-do`/`ready`/`review`/`shipped` onto one display stage with an
explicit `other` bucket, and nothing branches on it | marker in the
JSDoc; the comparisons are arrow bodies **inside the array literal**,
which it does not reach |

The second only surfaced because converting the `triage` stage to a Set
removed its count and exposed the siblings — red gate, justification
sitting three lines above, unreachable.

Both are markers, no behaviour change. Neither is a conversion
candidate: resolving the funnel table to traits would **drop the
non-column aliases it exists to accept**.

**For the auto-lowering work:** the marker-placement rule is now the
recurring trap — three instances, three different authors, including me.
A marker that does not register is indistinguishable from no marker, and
the failure mode is a red gate with a written explanation nobody can act
on. If the census accepted a marker anywhere in the enclosing
declaration's comments, none of the three would have happened.

Baseline re-recorded per the tool's own instruction ("Re-record the
baseline in the SAME PR that lowered the count").


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **Bug Fixes**
- Task “Actions” menus no longer appear on bare cards in the Planning
column.
- Routines, scheduled tasks, and create-task steps now respect each
board’s configured workflow intake column instead of using a retired
default.
- Legacy tasks saved with the retired intake column are migrated to
automatic workflow resolution.
- Target-column selection now offers only “Automatic (workflow intake)”
and “Planning,” removing the obsolete option.
- Capacity/planning messaging and related UI tooltip text were
clarified; concurrency cap updates are managed per project.

- **Tests**
- Added/updated coverage for workflow intake resolution, create-task
target column behavior (including legacy coercion), capacity safeguards,
and API request consistency.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 03:10:35 -07:00

693 lines
29 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { RoutineEditor } from "../RoutineEditor";
import type { Routine, RoutineTriggerType } from "@fusion/core";
// Mock lucide-react
vi.mock("lucide-react", () => ({
Calendar: () => <span data-testid="icon-calendar">📅</span>,
Webhook: () => <span data-testid="icon-webhook">🔗</span>,
Code: () => <span data-testid="icon-code">💻</span>,
Zap: () => <span data-testid="icon-zap">⚡</span>,
Globe: () => <span data-testid="icon-globe">🌍</span>,
Folder: () => <span data-testid="icon-folder">📁</span>,
}));
// Mock API
vi.mock("../api", () => ({
fetchModels: vi.fn(() => Promise.resolve({
models: [
{ provider: "openai", id: "gpt-4o", name: "GPT-4o", reasoning: false, contextWindow: 128000 },
{ provider: "anthropic", id: "claude-sonnet-4-5", name: "Claude Sonnet", reasoning: false, contextWindow: 200000 },
],
favoriteProviders: [],
favoriteModels: [],
})),
}));
// Mock @fusion/core
vi.mock("@fusion/core", () => ({
AUTOMATION_SELECTABLE_TOOLS: ["Read", "Bash", "Edit", "Write", "Grep", "Find", "Ls"],
}));
vi.mock("../CustomModelDropdown", () => ({
CustomModelDropdown: ({ id, value, onChange, disabled, models, showThinkingLevel, thinkingLevel, onThinkingLevelChange }: any) => (
<div data-testid={`${id}-mock`}>
<select data-testid="model-dropdown" value={value || ""} onChange={(e) => onChange(e.target.value)} disabled={disabled}>
<option value="">Use default</option>
{models?.map((m: any) => (
<option key={`${m.provider}/${m.id}`} value={`${m.provider}/${m.id}`}>{m.name}</option>
))}
</select>
{showThinkingLevel && (
<select data-testid={`${id}-thinking-level`} aria-label={`${id} thinking level`} value={thinkingLevel || ""} onChange={(e) => onThinkingLevelChange?.(e.target.value)}>
<option value="">Default (off)</option>
<option value="off">Off</option>
<option value="high">High</option>
</select>
)}
</div>
),
}));
function makeRoutine(overrides: Partial<Routine> = {}): Routine {
return {
id: "routine-001",
agentId: "agent-001",
name: "Test Routine",
description: "A test routine",
trigger: { type: "cron", cronExpression: "0 * * * *" },
command: "echo test",
executionPolicy: "parallel",
catchUpPolicy: "skip",
enabled: true,
runCount: 0,
runHistory: [],
createdAt: "2026-04-07T00:00:00.000Z",
updatedAt: "2026-04-07T00:00:00.000Z",
...overrides,
};
}
describe("RoutineEditor", () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
const onCancel = vi.fn();
const fillCommand = (value = "echo test") => {
fireEvent.change(screen.getByLabelText("Command"), { target: { value } });
};
beforeEach(() => {
vi.clearAllMocks();
});
// ── Create mode (no routine prop) ─────────────────────────────────────
describe("Create mode (no routine prop)", () => {
it("renders form with empty fields", () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
expect(screen.getByLabelText("Name")).toHaveValue("");
expect(screen.getByLabelText("Description (optional)")).toHaveValue("");
});
it('shows "New Routine" heading', () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
expect(screen.getByText("New Routine")).toBeDefined();
});
it('shows "Create Routine" submit button', () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
expect(screen.getByText("Create Routine")).toBeDefined();
});
it("defaults triggerType to 'cron'", () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
expect(screen.getByText("Cron")).toBeDefined();
// Cron expression input should be visible
expect(screen.getByLabelText("Cron Expression")).toHaveValue("0 * * * *");
});
it("shows frequency dropdown with preset options when triggerType is 'cron'", () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
const frequency = screen.getByLabelText("Frequency");
expect(frequency).toBeDefined();
expect(screen.getByRole("option", { name: "Every hour" })).toBeDefined();
expect(screen.getByRole("option", { name: "Every day (midnight)" })).toBeDefined();
expect(screen.getByRole("option", { name: "Every week (Monday)" })).toBeDefined();
expect(screen.getByRole("option", { name: "Every month (1st)" })).toBeDefined();
expect(screen.getByRole("option", { name: "Custom cron expression" })).toBeDefined();
});
it("selecting a preset auto-fills the cron expression and disables the input", () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.change(screen.getByLabelText("Frequency"), { target: { value: "daily" } });
const cronInput = screen.getByLabelText("Cron Expression");
expect(cronInput).toHaveValue("0 0 * * *");
expect(cronInput).toBeDisabled();
expect(screen.getByText("Auto-filled from preset: 0 0 * * *")).toBeDefined();
});
it("selecting 'Custom' enables the cron expression input", () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.change(screen.getByLabelText("Frequency"), { target: { value: "custom" } });
expect(screen.getByLabelText("Cron Expression")).not.toBeDisabled();
expect(screen.getByText(/crontab\.guru/)).toBeDefined();
});
it("defaults executionPolicy to 'queue'", () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
expect(screen.getByLabelText("Execution Policy")).toHaveValue("queue");
});
it("defaults catchUpPolicy to 'run_one'", () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
expect(screen.getByLabelText("Catch-up Policy")).toHaveValue("run_one");
});
it("defaults enabled to true", () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
expect(screen.getByLabelText("Enabled")).toBeChecked();
});
it("shows cron expression input when triggerType is 'cron'", () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
expect(screen.getByLabelText("Cron Expression")).toBeDefined();
});
it("shows webhook inputs when triggerType is changed to 'webhook'", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.click(screen.getByText("Webhook"));
await waitFor(() => {
expect(screen.getByLabelText("Webhook Path")).toBeDefined();
expect(screen.getByLabelText("Webhook Secret (optional)")).toBeDefined();
});
});
it("shows API info when triggerType is changed to 'api'", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.click(screen.getByText("API"));
await waitFor(() => {
expect(screen.getByLabelText("API Endpoint")).toBeDefined();
});
});
it("shows Manual trigger info when triggerType is changed to 'manual'", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.click(screen.getByText("Manual"));
await waitFor(() => {
expect(screen.getByText(/triggered manually/)).toBeDefined();
});
});
it("hides cron expression input when triggerType is not 'cron'", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.click(screen.getByText("Webhook"));
await waitFor(() => {
expect(screen.queryByLabelText("Cron Expression")).toBeNull();
});
});
});
// ── Edit mode (with routine prop) ─────────────────────────────────────
describe("Edit mode (with routine prop)", () => {
it("pre-fills all fields from the routine prop", () => {
const routine = makeRoutine({
name: "My Routine",
description: "My description",
trigger: { type: "cron", cronExpression: "0 9 * * *" },
executionPolicy: "reject",
catchUpPolicy: "run",
enabled: false,
});
render(<RoutineEditor routine={routine} onSubmit={onSubmit} onCancel={onCancel} />);
expect(screen.getByLabelText("Name")).toHaveValue("My Routine");
expect(screen.getByLabelText("Description (optional)")).toHaveValue("My description");
expect(screen.getByLabelText("Cron Expression")).toHaveValue("0 9 * * *");
expect(screen.getByLabelText("Execution Policy")).toHaveValue("reject");
expect(screen.getByLabelText("Catch-up Policy")).toHaveValue("run");
expect(screen.getByLabelText("Enabled")).not.toBeChecked();
});
it('shows "Edit Routine" heading', () => {
render(<RoutineEditor routine={makeRoutine()} onSubmit={onSubmit} onCancel={onCancel} />);
expect(screen.getByText("Edit Routine")).toBeDefined();
});
it('shows "Save Changes" submit button', () => {
render(<RoutineEditor routine={makeRoutine()} onSubmit={onSubmit} onCancel={onCancel} />);
expect(screen.getByText("Save Changes")).toBeDefined();
});
it("editing an existing routine with a preset cron expression selects the matching preset", () => {
const routine = makeRoutine({
trigger: { type: "cron", cronExpression: "0 0 * * *" },
});
render(<RoutineEditor routine={routine} onSubmit={onSubmit} onCancel={onCancel} />);
expect(screen.getByLabelText("Frequency")).toHaveValue("daily");
expect(screen.getByLabelText("Cron Expression")).toBeDisabled();
});
it("editing an existing routine with a non-preset cron expression selects 'Custom'", () => {
const routine = makeRoutine({
trigger: { type: "cron", cronExpression: "0 9 * * 1-5" },
});
render(<RoutineEditor routine={routine} onSubmit={onSubmit} onCancel={onCancel} />);
expect(screen.getByLabelText("Frequency")).toHaveValue("custom");
expect(screen.getByLabelText("Cron Expression")).not.toBeDisabled();
});
it("pre-fills webhook trigger fields", () => {
const routine = makeRoutine({
trigger: { type: "webhook", webhookPath: "/trigger/test", secret: "secret123" },
});
render(<RoutineEditor routine={routine} onSubmit={onSubmit} onCancel={onCancel} />);
expect(screen.getByText("Webhook")).toBeDefined();
expect(screen.getByLabelText("Webhook Path")).toHaveValue("/trigger/test");
expect(screen.getByLabelText("Webhook Secret (optional)")).toHaveValue("secret123");
});
it("pre-fills api trigger fields", () => {
const routine = makeRoutine({
trigger: { type: "api", endpoint: "/api/test" },
});
render(<RoutineEditor routine={routine} onSubmit={onSubmit} onCancel={onCancel} />);
expect(screen.getByText("API")).toBeDefined();
expect(screen.getByLabelText("API Endpoint")).toHaveValue("/api/test");
});
});
// ── Scope selector ──────────────────────────────────────────────────
describe("Scope selector", () => {
it("clicking Global sets active state", () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} scope="project" projectId="proj-1" />);
const globalButton = screen.getByRole("radio", { name: /Global/i });
const projectButton = screen.getByRole("radio", { name: /Project/i });
expect(globalButton).toHaveAttribute("aria-checked", "false");
expect(projectButton).toHaveAttribute("aria-checked", "true");
fireEvent.click(globalButton);
expect(globalButton).toHaveAttribute("aria-checked", "true");
expect(projectButton).toHaveAttribute("aria-checked", "false");
});
it("clicking Project sets active state", () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} scope="global" projectId="proj-1" />);
const globalButton = screen.getByRole("radio", { name: /Global/i });
const projectButton = screen.getByRole("radio", { name: /Project/i });
expect(globalButton).toHaveAttribute("aria-checked", "true");
expect(projectButton).toHaveAttribute("aria-checked", "false");
fireEvent.click(projectButton);
expect(globalButton).toHaveAttribute("aria-checked", "false");
expect(projectButton).toHaveAttribute("aria-checked", "true");
});
it("calls onScopeChange when clicking scope buttons", () => {
const onScopeChange = vi.fn();
render(
<RoutineEditor
onSubmit={onSubmit}
onCancel={onCancel}
scope="global"
projectId="proj-1"
onScopeChange={onScopeChange}
/>,
);
fireEvent.click(screen.getByRole("radio", { name: /Project/i }));
fireEvent.click(screen.getByRole("radio", { name: /Global/i }));
expect(onScopeChange).toHaveBeenNthCalledWith(1, "project");
expect(onScopeChange).toHaveBeenNthCalledWith(2, "global");
});
it("disables Project scope button when no projectId is provided", () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} scope="global" />);
expect(screen.getByRole("radio", { name: /Project/i })).toBeDisabled();
});
it("disables both scope buttons when editing an existing routine with locked scope", () => {
render(
<RoutineEditor
routine={makeRoutine({ scope: "project" })}
onSubmit={onSubmit}
onCancel={onCancel}
projectId="proj-1"
/>,
);
expect(screen.getByRole("radio", { name: /Global/i })).toBeDisabled();
expect(screen.getByRole("radio", { name: /Project/i })).toBeDisabled();
});
it("submits selected scope from the scope toggle", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} scope="global" projectId="proj-1" />);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Scoped Routine" } });
fillCommand();
fireEvent.click(screen.getByRole("radio", { name: /Project/i }));
fireEvent.click(screen.getByText("Create Routine"));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(
expect.objectContaining({
scope: "project",
}),
);
});
});
it("syncs local scope when parent scope prop changes", () => {
const { rerender } = render(
<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} scope="global" projectId="proj-1" />,
);
expect(screen.getByRole("radio", { name: /Global/i })).toHaveAttribute("aria-checked", "true");
expect(screen.getByRole("radio", { name: /Project/i })).toHaveAttribute("aria-checked", "false");
rerender(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} scope="project" projectId="proj-1" />);
expect(screen.getByRole("radio", { name: /Global/i })).toHaveAttribute("aria-checked", "false");
expect(screen.getByRole("radio", { name: /Project/i })).toHaveAttribute("aria-checked", "true");
});
});
// ── Validation ───────────────────────────────────────────────────────
describe("Validation", () => {
it("shows error when name is empty on submit", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "" } });
fireEvent.click(screen.getByText("Create Routine"));
await waitFor(() => {
expect(screen.getByText("Name is required")).toBeDefined();
});
expect(onSubmit).not.toHaveBeenCalled();
});
it("shows error when triggerType is 'cron' and custom cronExpression is empty", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.change(screen.getByLabelText("Frequency"), { target: { value: "custom" } });
fireEvent.change(screen.getByLabelText("Cron Expression"), { target: { value: "" } });
fireEvent.click(screen.getByText("Create Routine"));
await waitFor(() => {
expect(screen.getByText("Cron expression is required")).toBeDefined();
});
expect(onSubmit).not.toHaveBeenCalled();
});
it("shows error when triggerType is 'cron' and custom cronExpression is invalid", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.change(screen.getByLabelText("Frequency"), { target: { value: "custom" } });
fireEvent.change(screen.getByLabelText("Cron Expression"), { target: { value: "invalid" } });
fireEvent.click(screen.getByText("Create Routine"));
await waitFor(() => {
expect(screen.getByText(/Invalid cron format/)).toBeDefined();
});
expect(onSubmit).not.toHaveBeenCalled();
});
it("shows error when triggerType is 'webhook' and webhookPath is empty", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.click(screen.getByText("Webhook"));
fireEvent.change(screen.getByLabelText("Webhook Path"), { target: { value: "" } });
fireEvent.click(screen.getByText("Create Routine"));
await waitFor(() => {
expect(screen.getByText("Webhook path is required")).toBeDefined();
});
expect(onSubmit).not.toHaveBeenCalled();
});
it("shows error when triggerType is 'api' and endpoint is empty", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.click(screen.getByText("API"));
fireEvent.change(screen.getByLabelText("API Endpoint"), { target: { value: "" } });
fireEvent.click(screen.getByText("Create Routine"));
await waitFor(() => {
expect(screen.getByText("API endpoint is required")).toBeDefined();
});
expect(onSubmit).not.toHaveBeenCalled();
});
});
// ── Submission ───────────────────────────────────────────────────────
describe("Submission", () => {
it("calls onSubmit with correct RoutineCreateInput shape on valid create", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "New Routine" } });
fillCommand();
fireEvent.click(screen.getByText("Create Routine"));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(
expect.objectContaining({
name: "New Routine",
trigger: { type: "cron", cronExpression: "0 * * * *" },
executionPolicy: "queue",
catchUpPolicy: "run_one",
enabled: true,
})
);
});
});
it("omits thinkingLevel by default for simple AI Prompt routines", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "AI Routine" } });
fireEvent.click(screen.getByRole("radio", { name: "AI Prompt" }));
expect(screen.getByTestId("routine-model-thinking-level")).toBeDefined();
fireEvent.change(screen.getByLabelText("Prompt"), { target: { value: "Summarize recent activity" } });
fireEvent.click(screen.getByText("Create Routine"));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(
expect.objectContaining({
steps: [expect.objectContaining({ type: "ai-prompt", thinkingLevel: undefined })],
}),
);
});
});
it("submits explicit thinkingLevel and shares it with simple Create Task routines", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Task Routine" } });
fireEvent.click(screen.getByRole("radio", { name: "AI Prompt" }));
fireEvent.change(screen.getByTestId("routine-model-thinking-level"), { target: { value: "high" } });
fireEvent.click(screen.getByRole("radio", { name: "Create Task" }));
expect(screen.getByTestId("routine-task-model-thinking-level")).toHaveValue("high");
fireEvent.change(screen.getByLabelText("Task Description"), { target: { value: "Review dependencies" } });
fireEvent.click(screen.getByText("Create Routine"));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(
expect.objectContaining({
steps: [expect.objectContaining({ type: "create-task", thinkingLevel: "high" })],
}),
);
});
});
it("clears thinkingLevel when editing a simple AI Prompt routine", async () => {
const routine = makeRoutine({
command: undefined,
steps: [
{
id: "step-1",
type: "ai-prompt",
name: "AI Routine",
prompt: "Summarize recent activity",
thinkingLevel: "high",
},
],
});
render(<RoutineEditor routine={routine} onSubmit={onSubmit} onCancel={onCancel} />);
expect(screen.getByTestId("routine-model-thinking-level")).toHaveValue("high");
fireEvent.change(screen.getByTestId("routine-model-thinking-level"), { target: { value: "" } });
fireEvent.click(screen.getByText("Save Changes"));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(
expect.objectContaining({
steps: [expect.objectContaining({ thinkingLevel: undefined })],
}),
);
});
});
it("submitting with a preset sends the correct cron expression", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Weekly Routine" } });
fireEvent.change(screen.getByLabelText("Frequency"), { target: { value: "weekly" } });
fillCommand();
fireEvent.click(screen.getByText("Create Routine"));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(
expect.objectContaining({
name: "Weekly Routine",
trigger: { type: "cron", cronExpression: "0 0 * * 1" },
})
);
});
});
it("calls onSubmit with correct shape on valid edit", async () => {
const routine = makeRoutine({ name: "Old Name" });
render(<RoutineEditor routine={routine} onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Updated Name" } });
fireEvent.click(screen.getByText("Save Changes"));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(
expect.objectContaining({
name: "Updated Name",
trigger: { type: "cron", cronExpression: "0 * * * *" },
})
);
});
});
it("disables submit button and shows 'Saving…' during submission", async () => {
const slowSubmit = vi.fn().mockImplementation(() => new Promise((resolve) => setTimeout(resolve, 100)));
render(<RoutineEditor onSubmit={slowSubmit} onCancel={onCancel} />);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "New Routine" } });
fillCommand();
// Use role and name to find the submit button specifically
const submitButton = screen.getByRole("button", { name: "Create Routine" });
fireEvent.click(submitButton);
await waitFor(() => {
expect(screen.getByText("Saving…")).toBeDefined();
});
expect(screen.getByRole("button", { name: "Saving…" })).toBeDisabled();
});
it("re-enables submit button after submission completes", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "New Routine" } });
fillCommand();
fireEvent.click(screen.getByText("Create Routine"));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalled();
});
// Button should return from the transient "Saving…" state and be enabled again.
await waitFor(() => {
expect(screen.getByRole("button", { name: "Create Routine" })).not.toBeDisabled();
});
});
it("builds correct webhook trigger on submit", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Webhook Routine" } });
fireEvent.click(screen.getByText("Webhook"));
fireEvent.change(screen.getByLabelText("Webhook Path"), { target: { value: "/trigger/my-hook" } });
fireEvent.change(screen.getByLabelText("Webhook Secret (optional)"), { target: { value: "my-secret" } });
fillCommand();
fireEvent.click(screen.getByText("Create Routine"));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(
expect.objectContaining({
trigger: {
type: "webhook",
webhookPath: "/trigger/my-hook",
secret: "my-secret",
},
})
);
});
});
it("builds correct api trigger on submit", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "API Routine" } });
fireEvent.click(screen.getByText("API"));
fireEvent.change(screen.getByLabelText("API Endpoint"), { target: { value: "/api/my-routine" } });
fillCommand();
fireEvent.click(screen.getByText("Create Routine"));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(
expect.objectContaining({
trigger: {
type: "api",
endpoint: "/api/my-routine",
},
})
);
});
});
it("builds correct manual trigger on submit", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Manual Routine" } });
fireEvent.click(screen.getByText("Manual"));
fillCommand();
fireEvent.click(screen.getByText("Create Routine"));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(
expect.objectContaining({
trigger: { type: "manual" },
})
);
});
});
});
// ── Cancel ──────────────────────────────────────────────────────────
describe("Cancel", () => {
it("calls onCancel when cancel button is clicked", () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.click(screen.getByText("Cancel"));
expect(onCancel).toHaveBeenCalled();
});
it("does not call onSubmit when cancel is clicked", () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.click(screen.getByText("Cancel"));
expect(onSubmit).not.toHaveBeenCalled();
});
});
/*
FNXC:Automations 2026-07-30-15:45 (U11 merged planning column):
The "Target Column" default was `triage`, which U11 deletes from the default workflow. It is
submitted as the create step's `taskColumn`, and an EXPLICIT column bypasses the workflow
entry-column resolution added for column-less creates — so a routine saved with the untouched
default seeded tasks into a column the board does not declare.
Asserted on the RENDERED control and on the SUBMITTED step, so it covers what the operator actually
sends rather than the constant.
*/
describe("create-task target column (U11)", () => {
it("sends NO column by default, so each workflow's own intake resolution decides", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.click(screen.getByRole("radio", { name: "Create Task" }));
const select = await waitFor(() => screen.getByLabelText("Target Column") as HTMLSelectElement);
expect(select.value, "the default must not name a column at all").toBe("");
expect(select.value).not.toBe("triage");
// `todo` would be the same mistake one column over — a custom workflow declaring no `todo`
// would be seeded into an undeclared column just as surely.
expect(select.value).not.toBe("todo");
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "nightly" } });
fireEvent.change(screen.getByLabelText("Task Description"), { target: { value: "Review deps" } });
fireEvent.click(screen.getByText("Create Routine"));
await waitFor(() => expect(onSubmit).toHaveBeenCalled());
expect(onSubmit.mock.calls[0][0].steps[0].taskColumn).toBeUndefined();
});
it("no longer offers the deleted column at all", async () => {
render(<RoutineEditor onSubmit={onSubmit} onCancel={onCancel} />);
fireEvent.click(screen.getByRole("radio", { name: "Create Task" }));
const select = await waitFor(() => screen.getByLabelText("Target Column") as HTMLSelectElement);
const values = Array.from(select.options).map((o) => o.value);
expect(values, "an operator must not be able to pick a column the workflow does not declare").not.toContain("triage");
expect(values).toContain("");
expect(values).toContain("todo");
});
});
});