Files
fusion/packages/dashboard/app/components/RoutineEditor.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

843 lines
40 KiB
TypeScript

import { useState, useCallback, useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { Calendar, Webhook, Code, Zap, Globe, Folder } from "lucide-react";
import type {
Routine,
RoutineCreateInput,
RoutineTrigger,
RoutineTriggerType,
RoutineCronTrigger,
RoutineWebhookTrigger,
RoutineApiTrigger,
RoutineManualTrigger,
RoutineCatchUpPolicy,
RoutineExecutionPolicy,
AutomationStep,
} from "@fusion/core";
import { ScheduleStepsEditor } from "./ScheduleStepsEditor";
import { CustomModelDropdown } from "./CustomModelDropdown";
import { fetchModels, type ModelInfo } from "../api";
type CronPresetType = "hourly" | "daily" | "weekly" | "monthly" | "custom";
const CRON_PRESETS: Record<Exclude<CronPresetType, "custom">, string> = {
hourly: "0 * * * *",
daily: "0 0 * * *",
weekly: "0 0 * * 1",
monthly: "0 0 1 * *",
};
// CRON_PRESET_LABELS are now built inside the component with t() — see useCronPresetLabels below
function resolveCronPreset(cronExpression: string): CronPresetType {
const normalizedCron = cronExpression.trim();
for (const [preset, value] of Object.entries(CRON_PRESETS)) {
if (value === normalizedCron) {
return preset as Exclude<CronPresetType, "custom">;
}
}
return "custom";
}
/**
* Simple cron expression validator (5-field format).
* Checks basic structure — authoritative validation happens server-side.
*/
function isLikelyCron(expr: string): boolean {
const parts = expr.trim().split(/\s+/);
if (parts.length !== 5) return false;
// Each field should contain digits, *, /, -, or ,
return parts.every((p) => /^[\d*,/-]+$/.test(p));
}
/**
* Build a trigger object from form state.
*/
function buildTrigger(
triggerType: RoutineTriggerType,
cronExpression: string,
webhookPath: string,
webhookSecret: string,
endpoint: string,
): RoutineTrigger {
switch (triggerType) {
case "cron":
return { type: "cron", cronExpression } as RoutineCronTrigger;
case "webhook":
return {
type: "webhook",
webhookPath: webhookPath || "/trigger/" + Math.random().toString(36).slice(2, 10),
secret: webhookSecret || undefined,
} as RoutineWebhookTrigger;
case "api":
return {
type: "api",
endpoint: endpoint || "/api/routine/" + Math.random().toString(36).slice(2, 10),
} as RoutineApiTrigger;
case "manual":
return { type: "manual" } as RoutineManualTrigger;
}
}
/**
* Extract trigger fields from a Routine object.
*/
function extractTriggerFields(routine: Routine) {
const trigger = routine.trigger;
switch (trigger.type) {
case "cron":
return {
triggerType: "cron" as RoutineTriggerType,
cronExpression: (trigger as RoutineCronTrigger).cronExpression,
webhookPath: "",
webhookSecret: "",
endpoint: "",
};
case "webhook":
return {
triggerType: "webhook" as RoutineTriggerType,
cronExpression: "",
webhookPath: (trigger as RoutineWebhookTrigger).webhookPath,
webhookSecret: (trigger as RoutineWebhookTrigger).secret || "",
endpoint: "",
};
case "api":
return {
triggerType: "api" as RoutineTriggerType,
cronExpression: "",
webhookPath: "",
webhookSecret: "",
endpoint: (trigger as RoutineApiTrigger).endpoint,
};
case "manual":
return {
triggerType: "manual" as RoutineTriggerType,
cronExpression: "",
webhookPath: "",
webhookSecret: "",
endpoint: "",
};
}
}
// EXECUTION_POLICY_OPTIONS and CATCH_UP_POLICY_OPTIONS labels are now built inside the component with t()
function generateStepId(): string {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
return `step-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
}
function normalizeThinkingLevel(value: string): AutomationStep["thinkingLevel"] {
return (value.trim() || undefined) as AutomationStep["thinkingLevel"];
}
type ActionMode = "simple" | "advanced";
type SimpleActionType = "command" | "ai-prompt" | "create-task";
interface RoutineEditorProps {
/** Existing routine for editing. Omit for create mode. */
routine?: Routine;
/** Called with form data on submit. */
onSubmit: (input: RoutineCreateInput) => Promise<void>;
/** Called when the user cancels. */
onCancel: () => void;
/** Scope for the routine (global or project). Defaults to routine.scope or "project". */
scope?: "global" | "project";
/** Project ID for project-scoped routines. */
projectId?: string;
/** Called when the user changes the scope via the toggle buttons. */
onScopeChange?: (scope: "global" | "project") => void;
}
export function RoutineEditor({ routine, onSubmit, onCancel, scope: formScope, projectId, onScopeChange }: RoutineEditorProps) {
const { t } = useTranslation("app");
const isEditing = !!routine;
const CRON_PRESET_LABELS: Record<CronPresetType, string> = {
hourly: t("schedule.cronPresetHourly", "Every hour"),
daily: t("schedule.cronPresetDaily", "Every day (midnight)"),
weekly: t("schedule.cronPresetWeekly", "Every week (Monday)"),
monthly: t("schedule.cronPresetMonthly", "Every month (1st)"),
custom: t("schedule.cronPresetCustom", "Custom cron expression"),
};
const EXECUTION_POLICY_OPTIONS: { value: RoutineExecutionPolicy; label: string }[] = [
{ value: "parallel", label: t("schedule.executionPolicyParallel", "Allow concurrent runs") },
{ value: "queue", label: t("schedule.executionPolicyQueue", "Queue after current (one at a time)") },
{ value: "reject", label: t("schedule.executionPolicyReject", "Reject new runs while running") },
];
const CATCH_UP_POLICY_OPTIONS: { value: RoutineCatchUpPolicy; label: string }[] = [
{ value: "skip", label: t("schedule.catchUpPolicySkip", "Skip missed runs") },
{ value: "run_one", label: t("schedule.catchUpPolicyRunOne", "Run the most recent missed run") },
{ value: "run", label: t("schedule.catchUpPolicyRunAll", "Run all missed runs") },
];
// Extract trigger fields if editing
const initialTriggerFields = routine ? extractTriggerFields(routine) : {
triggerType: "cron" as RoutineTriggerType,
cronExpression: "0 * * * *",
webhookPath: "",
webhookSecret: "",
endpoint: "",
};
const [name, setName] = useState(routine?.name ?? "");
const [description, setDescription] = useState(routine?.description ?? "");
const [triggerType, setTriggerType] = useState<RoutineTriggerType>(initialTriggerFields.triggerType);
const [cronExpression, setCronExpression] = useState(initialTriggerFields.cronExpression);
const [cronPreset, setCronPreset] = useState<CronPresetType>(() => {
if (initialTriggerFields.triggerType !== "cron") return "custom";
return resolveCronPreset(initialTriggerFields.cronExpression);
});
const [webhookPath, setWebhookPath] = useState(initialTriggerFields.webhookPath);
const [webhookSecret, setWebhookSecret] = useState(initialTriggerFields.webhookSecret);
const [endpoint, setEndpoint] = useState(initialTriggerFields.endpoint);
const [executionPolicy, setExecutionPolicy] = useState<RoutineExecutionPolicy>(
routine?.executionPolicy ?? "queue"
);
const [catchUpPolicy, setCatchUpPolicy] = useState<RoutineCatchUpPolicy>(
routine?.catchUpPolicy ?? "run_one"
);
const [enabled, setEnabled] = useState(routine?.enabled ?? true);
const isSimpleAiPrompt = routine?.steps && routine.steps.length === 1 &&
routine.steps[0].type === "ai-prompt" && !routine.command;
const isSimpleCreateTask = routine?.steps && routine.steps.length === 1 &&
routine.steps[0].type === "create-task" && !routine.command;
const [actionMode, setActionMode] = useState<ActionMode>(
routine?.steps && routine.steps.length > 0 && !isSimpleAiPrompt && !isSimpleCreateTask ? "advanced" : "simple"
);
const [simpleActionType, setSimpleActionType] = useState<SimpleActionType>(() => {
if (isSimpleAiPrompt) return "ai-prompt";
if (isSimpleCreateTask) return "create-task";
return "command";
});
const [command, setCommand] = useState(routine?.command ?? "");
const [steps, setSteps] = useState<AutomationStep[]>(routine?.steps ?? []);
const [hasEditingSteps, setHasEditingSteps] = useState(false);
const [timeoutMs, setTimeoutMs] = useState<number>(routine?.timeoutMs ?? 300000);
const [prompt, setPrompt] = useState(isSimpleAiPrompt ? routine.steps?.[0]?.prompt ?? "" : "");
const [taskTitle, setTaskTitle] = useState(isSimpleCreateTask ? routine.steps?.[0]?.taskTitle ?? "" : "");
const [taskDescription, setTaskDescription] = useState(isSimpleCreateTask ? routine.steps?.[0]?.taskDescription ?? "" : "");
/*
FNXC:Automations 2026-07-30-15:40 (U11 merged planning column):
Defaulted to `triage`, which U11 DELETES from the default workflow, and this value is submitted as
the create step's `taskColumn`. 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, left for reconciliation to re-home.
Defaulting to `todo` instead would be the same mistake one column over: a custom workflow declaring
no `todo` gets seeded into an undeclared column just as surely. So the default sends NOTHING and each
workflow's own intake resolution decides — the only answer correct for every board. `taskColumn` is
optional on the step, and an empty selection submits as `undefined`.
*/
const persistedTaskColumn = isSimpleCreateTask ? routine.steps?.[0]?.taskColumn ?? "" : "";
/*
FNXC:Automations 2026-07-30-17:15 DELIBERATE-LITERAL:
A MIGRATION of a stored legacy value, not a lifecycle decision. It recognises the exact string a
routine was persisted with before this fix; there is no workflow IR in scope (a routine names no
workflow), so there is no role to resolve — and resolving one would be wrong anyway, since the point
is to identify that specific legacy value and discard it.
Why coerce at all: the select no longer offers `triage`, so a routine saved earlier held a value the
operator could neither see nor change, and saving an unrelated edit resubmitted it — keeping the old
behaviour alive indefinitely. Coercing on load means the next save of any routine repairs it, and the
control shows what will actually happen.
*/
const [taskColumn, setTaskColumn] = useState(persistedTaskColumn === "triage" ? "" : persistedTaskColumn);
const [modelProvider, setModelProvider] = useState(
isSimpleAiPrompt || isSimpleCreateTask ? routine.steps?.[0]?.modelProvider ?? "" : ""
);
const [modelId, setModelId] = useState(
isSimpleAiPrompt || isSimpleCreateTask ? routine.steps?.[0]?.modelId ?? "" : ""
);
/*
FNXC:Automations 2026-07-12-19:14:
Simple routine AI-capable model selectors also capture an optional per-step thinking level. Empty string means inherit the default; concrete values persist on the AutomationStep JSON payload.
*/
const [thinkingLevel, setThinkingLevel] = useState(
isSimpleAiPrompt || isSimpleCreateTask ? routine.steps?.[0]?.thinkingLevel ?? "" : ""
);
const [models, setModels] = useState<ModelInfo[]>([]);
const [modelsLoading, setModelsLoading] = useState(false);
const [modelsError, setModelsError] = useState<string | null>(null);
// Scope toggle state
const [localScope, setLocalScope] = useState<"global" | "project">(formScope ?? "global");
const [errors, setErrors] = useState<Record<string, string>>({});
const [submitting, setSubmitting] = useState(false);
const isMountedRef = useRef(true);
useEffect(() => {
return () => {
isMountedRef.current = false;
};
}, []);
// Sync localScope when formScope prop changes (e.g., when parent resets)
useEffect(() => {
if (formScope) setLocalScope(formScope);
}, [formScope]);
useEffect(() => {
let cancelled = false;
setModelsLoading(true);
setModelsError(null);
fetchModels()
.then((response) => {
if (!cancelled) setModels(response.models);
})
.catch((err: unknown) => {
if (!cancelled) setModelsError(err instanceof Error ? err.message : t("schedule.errorLoadModels", "Failed to load models"));
})
.finally(() => {
if (!cancelled) setModelsLoading(false);
});
return () => {
cancelled = true;
};
}, []);
const modelValue = modelProvider && modelId ? `${modelProvider}/${modelId}` : "";
const handleModelChange = useCallback((value: string) => {
if (!value) {
setModelProvider("");
setModelId("");
return;
}
const slashIdx = value.indexOf("/");
if (slashIdx !== -1) {
setModelProvider(value.slice(0, slashIdx));
setModelId(value.slice(slashIdx + 1));
}
}, []);
const validate = useCallback((): boolean => {
const e: Record<string, string> = {};
if (!name.trim()) e.name = t("schedule.errorNameRequired", "Name is required");
// Scope validation: project scope requires projectId
if (localScope === "project" && !projectId) {
e.scope = t("schedule.errorScopeNoProject", "Project-specific entries require an active project.");
}
if (triggerType === "cron" && cronPreset === "custom") {
if (!cronExpression.trim()) {
e.cronExpression = t("schedule.errorCronRequired", "Cron expression is required");
} else if (!isLikelyCron(cronExpression)) {
e.cronExpression = t("schedule.errorCronInvalid", "Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')");
}
}
if (triggerType === "webhook" && !webhookPath.trim()) {
e.webhookPath = t("schedule.errorWebhookPathRequired", "Webhook path is required");
}
if (triggerType === "api" && !endpoint.trim()) {
e.endpoint = t("schedule.errorApiEndpointRequired", "API endpoint is required");
}
if (actionMode === "simple") {
if (simpleActionType === "command" && !command.trim()) e.command = t("schedule.errorCommandRequired", "Command is required");
if (simpleActionType === "ai-prompt" && !prompt.trim()) e.prompt = t("schedule.errorPromptRequired", "Prompt is required");
if (simpleActionType === "create-task" && !taskDescription.trim()) e.taskDescription = t("schedule.errorTaskDescriptionRequired", "Task description is required");
if ((modelProvider.trim() && !modelId.trim()) || (!modelProvider.trim() && modelId.trim())) {
e.model = t("schedule.errorModelIncomplete", "Both model provider and model ID must be set, or both must be empty");
}
} else {
if (steps.length === 0) e.steps = t("schedule.errorStepsRequired", "At least one step is required");
if (hasEditingSteps) e.stepsEditing = t("schedule.errorStepsEditing", "Please save or cancel all step edits before saving the routine");
const incompleteSteps: string[] = [];
steps.forEach((step, index) => {
if (!step.name?.trim()) incompleteSteps.push(t("schedule.errorStepNameRequired", "Step {{n}}: Name is required", { n: index + 1 }));
if (step.type === "command" && !step.command?.trim()) incompleteSteps.push(t("schedule.errorStepCommandRequired", "Step {{n}}: Command is required", { n: index + 1 }));
if (step.type === "ai-prompt" && !step.prompt?.trim()) incompleteSteps.push(t("schedule.errorStepPromptRequired", "Step {{n}}: Prompt is required", { n: index + 1 }));
if (step.type === "create-task" && !step.taskDescription?.trim()) incompleteSteps.push(t("schedule.errorStepTaskDescRequired", "Step {{n}}: Task description is required", { n: index + 1 }));
});
if (incompleteSteps.length > 0) e.steps = incompleteSteps.join("; ");
}
if (timeoutMs < 1000) e.timeoutMs = t("schedule.errorTimeoutMin", "Timeout must be at least 1 second (1000ms)");
setErrors(e);
return Object.keys(e).length === 0;
}, [name, triggerType, cronExpression, cronPreset, webhookPath, endpoint, localScope, projectId, actionMode, simpleActionType, command, prompt, taskDescription, modelProvider, modelId, thinkingLevel, steps, hasEditingSteps, timeoutMs]);
const handleSubmit = useCallback(
async (e: React.FormEvent) => {
e.preventDefault();
if (!validate()) return;
setSubmitting(true);
try {
// Determine scope: use edit mode's existing scope, otherwise use localScope
// When localScope is "project" but no projectId provided, fall back to "global"
let effectiveScope = routine?.scope ?? localScope ?? (projectId ? "project" : "global");
if (effectiveScope === "project" && !projectId) {
effectiveScope = "global";
}
const trigger = buildTrigger(triggerType, cronExpression, webhookPath, webhookSecret, endpoint);
let actionCommand: string | undefined;
let actionSteps: AutomationStep[] | undefined;
if (actionMode === "simple") {
if (simpleActionType === "command") {
actionCommand = command.trim() || undefined;
} else if (simpleActionType === "ai-prompt") {
actionSteps = [{
id: generateStepId(),
type: "ai-prompt",
name: name.trim(),
prompt: prompt.trim(),
modelProvider: modelProvider.trim() || undefined,
modelId: modelId.trim() || undefined,
thinkingLevel: normalizeThinkingLevel(thinkingLevel),
}];
} else {
actionSteps = [{
id: generateStepId(),
type: "create-task",
name: name.trim(),
taskTitle: taskTitle.trim() || undefined,
taskDescription: taskDescription.trim(),
// Empty means "let the workflow decide" — an explicit column overrides entry resolution.
taskColumn: taskColumn || undefined,
modelProvider: modelProvider.trim() || undefined,
modelId: modelId.trim() || undefined,
thinkingLevel: normalizeThinkingLevel(thinkingLevel),
}];
}
} else {
actionSteps = steps;
}
const input: RoutineCreateInput = {
name: name.trim(),
agentId: routine?.agentId ?? "",
description: description.trim() || undefined,
trigger,
command: actionCommand,
steps: actionSteps,
timeoutMs,
executionPolicy,
catchUpPolicy,
enabled,
scope: effectiveScope,
};
await onSubmit(input);
} finally {
if (isMountedRef.current) {
setSubmitting(false);
}
}
},
[validate, onSubmit, name, description, triggerType, cronExpression, webhookPath, webhookSecret, endpoint, actionMode, simpleActionType, command, prompt, modelProvider, modelId, thinkingLevel, taskTitle, taskDescription, taskColumn, steps, timeoutMs, executionPolicy, catchUpPolicy, enabled, localScope, projectId, routine?.scope, routine?.agentId],
);
const nameErrorId = "routine-name-error";
const cronErrorId = "routine-cron-error";
const webhookErrorId = "routine-webhook-error";
const endpointErrorId = "routine-endpoint-error";
const commandErrorId = "routine-command-error";
const promptErrorId = "routine-prompt-error";
const taskDescriptionErrorId = "routine-task-description-error";
const modelErrorId = "routine-model-error";
const timeoutErrorId = "routine-timeout-error";
const handleCronPresetChange = useCallback((preset: CronPresetType) => {
setCronPreset(preset);
if (preset !== "custom") {
setCronExpression(CRON_PRESETS[preset]);
}
}, []);
return (
<form className="routine-form" onSubmit={handleSubmit} noValidate>
<h4 className="settings-section-heading">
{isEditing ? t("schedule.editRoutineHeading", "Edit Routine") : t("schedule.newRoutineHeading", "New Routine")}
</h4>
{/* Basic Info */}
<div className="form-group">
<label htmlFor="routine-name">{t("schedule.nameLabel", "Name")}</label>
<input
id="routine-name"
type="text"
placeholder={t("schedule.namePlaceholder", "e.g. Daily standup reminder")}
value={name}
onChange={(e) => setName(e.target.value)}
aria-invalid={!!errors.name}
aria-describedby={errors.name ? nameErrorId : undefined}
/>
{errors.name && (
<small id={nameErrorId} className="field-error">{errors.name}</small>
)}
</div>
<div className="form-group">
<label htmlFor="routine-description">{t("schedule.descriptionLabel", "Description (optional)")}</label>
<textarea
id="routine-description"
placeholder={t("schedule.descriptionPlaceholder", "What does this routine do?")}
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={2}
/>
</div>
{/* Scope selector */}
<div className="form-group">
<label>{t("schedule.scopeLabel", "Scope")}</label>
<div className="routine-scope-toggle" role="radiogroup" aria-label={t("schedule.scopeAriaLabel", "Routine scope")}>
<button
type="button"
className={`routine-scope-btn${localScope === "global" ? " active" : ""}`}
onClick={() => { setLocalScope("global"); onScopeChange?.("global"); }}
role="radio"
aria-checked={localScope === "global" ? "true" : "false"}
disabled={!!routine?.scope}
title={routine?.scope ? t("schedule.scopeLockedTitle", "Scope is locked to {{scope}} for existing routines", { scope: routine.scope }) : t("schedule.globalScopeTitle", "Global scope")}
>
<Globe size={12} />
{t("schedule.globalScope", "Global")}
</button>
<button
type="button"
className={`routine-scope-btn${localScope === "project" ? " active" : ""}`}
onClick={() => { setLocalScope("project"); onScopeChange?.("project"); }}
role="radio"
aria-checked={localScope === "project" ? "true" : "false"}
disabled={!!routine?.scope || !projectId}
title={routine?.scope ? t("schedule.scopeLockedTitle", "Scope is locked to {{scope}} for existing routines", { scope: routine.scope }) : !projectId ? t("schedule.selectProjectTitle", "Select a project to enable project scope") : t("schedule.projectScopeTitle", "Project scope")}
>
<Folder size={12} />
{t("schedule.projectScope", "Project")}
</button>
</div>
<small>
{!projectId && !routine?.scope
? t("schedule.scopeHintNoProject", "No active project. Routines will be created at global scope.")
: localScope === "project" && projectId
? t("schedule.scopeHintProject", "This routine will be scoped to the current project.")
: t("schedule.scopeHintGlobal", "This routine will be created at global scope.")}
</small>
{errors.scope && (
<small className="field-error">{errors.scope}</small>
)}
</div>
{/* Trigger Type */}
<div className="form-group">
<label>{t("schedule.triggerTypeLabel", "Trigger Type")}</label>
<div className="routine-trigger-type-selector" role="radiogroup" aria-label={t("schedule.triggerTypeAriaLabel", "Trigger type")}>
<button
type="button"
className={`routine-trigger-btn${triggerType === "cron" ? " active" : ""}`}
onClick={() => setTriggerType("cron")}
role="radio"
aria-checked={triggerType === "cron"}
>
<Calendar size={14} />
{t("schedule.triggerCron", "Cron")}
</button>
<button
type="button"
className={`routine-trigger-btn${triggerType === "webhook" ? " active" : ""}`}
onClick={() => setTriggerType("webhook")}
role="radio"
aria-checked={triggerType === "webhook"}
>
<Webhook size={14} />
{t("schedule.triggerWebhook", "Webhook")}
</button>
<button
type="button"
className={`routine-trigger-btn${triggerType === "api" ? " active" : ""}`}
onClick={() => setTriggerType("api")}
role="radio"
aria-checked={triggerType === "api"}
>
<Code size={14} />
{t("schedule.triggerApi", "API")}
</button>
<button
type="button"
className={`routine-trigger-btn${triggerType === "manual" ? " active" : ""}`}
onClick={() => setTriggerType("manual")}
role="radio"
aria-checked={triggerType === "manual"}
>
<Zap size={14} />
{t("schedule.triggerManual", "Manual")}
</button>
</div>
</div>
{/* Cron Expression */}
{triggerType === "cron" && (
<div className="form-group">
<label htmlFor="routine-frequency">{t("schedule.frequencyLabel", "Frequency")}</label>
<select
id="routine-frequency"
value={cronPreset}
onChange={(e) => handleCronPresetChange(e.target.value as CronPresetType)}
>
{Object.entries(CRON_PRESET_LABELS).map(([value, label]) => (
<option key={value} value={value}>{label}</option>
))}
</select>
<label htmlFor="routine-cron">{t("schedule.cronExpressionLabel", "Cron Expression")}</label>
<input
id="routine-cron"
type="text"
placeholder="* * * * *"
value={cronExpression}
onChange={(e) => setCronExpression(e.target.value)}
disabled={cronPreset !== "custom"}
aria-invalid={!!errors.cronExpression}
aria-describedby={errors.cronExpression ? cronErrorId : undefined}
/>
{errors.cronExpression ? (
<small id={cronErrorId} className="field-error">{errors.cronExpression}</small>
) : (
<small>
{cronPreset === "custom" ? (
<>{t("schedule.cronCustomHint", "min hour day month weekday")} — <a href="https://crontab.guru" target="_blank" rel="noopener noreferrer">{t("schedule.crontabGuru", "crontab.guru")}</a></>
) : (
t("schedule.cronAutoFilledHint", "Auto-filled from preset: {{expression}}", { expression: cronExpression })
)}
</small>
)}
</div>
)}
{/* Webhook Configuration */}
{triggerType === "webhook" && (
<>
<div className="form-group">
<label htmlFor="routine-webhook-path">{t("schedule.webhookPathLabel", "Webhook Path")}</label>
<input
id="routine-webhook-path"
type="text"
placeholder={t("schedule.webhookPathPlaceholder", "/trigger/my-routine")}
value={webhookPath}
onChange={(e) => setWebhookPath(e.target.value)}
aria-invalid={!!errors.webhookPath}
aria-describedby={errors.webhookPath ? webhookErrorId : undefined}
/>
{errors.webhookPath ? (
<small id={webhookErrorId} className="field-error">{errors.webhookPath}</small>
) : (
<small>{t("schedule.webhookPathHint", "URL path for the webhook endpoint")}</small>
)}
</div>
<div className="form-group">
<label htmlFor="routine-webhook-secret">{t("schedule.webhookSecretLabel", "Webhook Secret (optional)")}</label>
<input
id="routine-webhook-secret"
type="password"
placeholder={t("schedule.webhookSecretPlaceholder", "Optional — leave empty for unauthenticated webhooks")}
value={webhookSecret}
onChange={(e) => setWebhookSecret(e.target.value)}
/>
<small>{t("schedule.webhookSecretHint", "HMAC secret for signature verification. Leave empty for unauthenticated webhooks.")}</small>
</div>
</>
)}
{/* API Configuration */}
{triggerType === "api" && (
<div className="form-group">
<label htmlFor="routine-endpoint">{t("schedule.apiEndpointLabel", "API Endpoint")}</label>
<input
id="routine-endpoint"
type="text"
placeholder={t("schedule.apiEndpointPlaceholder", "/api/routine/my-routine")}
value={endpoint}
onChange={(e) => setEndpoint(e.target.value)}
aria-invalid={!!errors.endpoint}
aria-describedby={errors.endpoint ? endpointErrorId : undefined}
/>
{errors.endpoint ? (
<small id={endpointErrorId} className="field-error">{errors.endpoint}</small>
) : (
<small>{t("schedule.apiEndpointHint", "API endpoint path that triggers this routine")}</small>
)}
</div>
)}
{/* Manual trigger info */}
{triggerType === "manual" && (
<div className="form-group">
<small className="routine-trigger-info">
{t("schedule.manualTriggerInfo", "This routine will be triggered manually via the dashboard or API.")}
</small>
</div>
)}
<div className="form-group">
<label>{t("schedule.actionModeLabel", "Action Mode")}</label>
<div className="schedule-mode-toggle" role="radiogroup" aria-label={t("schedule.actionModeAriaLabel", "Action mode")}>
<button
type="button"
className={`schedule-mode-btn${actionMode === "simple" ? " active" : ""}`}
onClick={() => setActionMode("simple")}
role="radio"
aria-checked={actionMode === "simple"}
>
{t("schedule.actionModeSimple", "Simple")}
</button>
<button
type="button"
className={`schedule-mode-btn${actionMode === "advanced" ? " active" : ""}`}
onClick={() => setActionMode("advanced")}
role="radio"
aria-checked={actionMode === "advanced"}
>
{t("schedule.actionModeAdvanced", "Multi-Step")}
</button>
</div>
<small>{actionMode === "simple" ? t("schedule.actionModeSimpleHint", "Run one command, prompt, or task creation action") : t("schedule.actionModeAdvancedHint", "Run multiple actions sequentially")}</small>
</div>
{actionMode === "simple" ? (
<>
<div className="form-group">
<label>{t("schedule.actionTypeLabel", "Action Type")}</label>
<div className="schedule-mode-toggle" role="radiogroup" aria-label={t("schedule.actionTypeAriaLabel", "Action type")}>
<button type="button" className={`schedule-mode-btn${simpleActionType === "command" ? " active" : ""}`} onClick={() => setSimpleActionType("command")} role="radio" aria-checked={simpleActionType === "command"}>{t("schedule.actionTypeCommand", "Command")}</button>
<button type="button" className={`schedule-mode-btn${simpleActionType === "ai-prompt" ? " active" : ""}`} onClick={() => setSimpleActionType("ai-prompt")} role="radio" aria-checked={simpleActionType === "ai-prompt"}>{t("schedule.actionTypeAiPrompt", "AI Prompt")}</button>
<button type="button" className={`schedule-mode-btn${simpleActionType === "create-task" ? " active" : ""}`} onClick={() => setSimpleActionType("create-task")} role="radio" aria-checked={simpleActionType === "create-task"}>{t("schedule.actionTypeCreateTask", "Create Task")}</button>
</div>
</div>
{simpleActionType === "command" ? (
<div className="form-group">
<label htmlFor="routine-command">{t("schedule.commandLabel", "Command")}</label>
<input id="routine-command" type="text" placeholder={t("schedule.commandPlaceholder", "e.g. npx runfusion.ai backup --create")} value={command} onChange={(e) => setCommand(e.target.value)} aria-invalid={!!errors.command} aria-describedby={errors.command ? commandErrorId : undefined} />
{errors.command ? <small id={commandErrorId} className="field-error">{errors.command}</small> : <small>{t("schedule.commandHint", "Shell command to execute.")}</small>}
</div>
) : simpleActionType === "ai-prompt" ? (
<>
<div className="form-group">
<label htmlFor="routine-prompt">{t("schedule.promptLabel", "Prompt")}</label>
<textarea id="routine-prompt" placeholder={t("schedule.promptPlaceholder", "e.g. Summarize recent activity and create action items")} value={prompt} onChange={(e) => setPrompt(e.target.value)} rows={3} aria-invalid={!!errors.prompt} aria-describedby={errors.prompt ? promptErrorId : undefined} />
{errors.prompt ? <small id={promptErrorId} className="field-error">{errors.prompt}</small> : <small>{t("schedule.promptHint", "AI prompt to execute.")}</small>}
</div>
<div className="form-group">
<label htmlFor="routine-model">{t("schedule.modelLabel", "Model (optional)")}</label>
<CustomModelDropdown id="routine-model" label={t("schedule.modelDropdownLabel", "Model")} models={models} value={modelValue} onChange={handleModelChange} placeholder={t("schedule.modelPlaceholder", "Use default")} disabled={modelsLoading} thinkingLevel={thinkingLevel} onThinkingLevelChange={setThinkingLevel} defaultThinkingLevel="off" showThinkingLevel />
{modelsError && <small className="field-error">{modelsError}</small>}
{errors.model && <small id={modelErrorId} className="field-error">{errors.model}</small>}
</div>
</>
) : (
<>
<div className="form-group">
<label htmlFor="routine-task-title">{t("schedule.taskTitleLabel", "Task Title (optional)")}</label>
<input id="routine-task-title" type="text" placeholder={t("schedule.taskTitlePlaceholder", "e.g. Review weekly dependencies")} value={taskTitle} onChange={(e) => setTaskTitle(e.target.value)} />
</div>
<div className="form-group">
<label htmlFor="routine-task-description">{t("schedule.taskDescriptionLabel", "Task Description")}</label>
<textarea id="routine-task-description" placeholder={t("schedule.taskDescriptionPlaceholder", "e.g. Check npm dependencies for security vulnerabilities")} value={taskDescription} onChange={(e) => setTaskDescription(e.target.value)} rows={4} aria-invalid={!!errors.taskDescription} aria-describedby={errors.taskDescription ? taskDescriptionErrorId : undefined} />
{errors.taskDescription ? <small id={taskDescriptionErrorId} className="field-error">{errors.taskDescription}</small> : <small>{t("schedule.taskDescriptionHint", "Describes the task that will be created.")}</small>}
</div>
<div className="form-group">
<label htmlFor="routine-task-column">{t("schedule.taskColumnLabel", "Target Column")}</label>
<select id="routine-task-column" value={taskColumn} onChange={(e) => setTaskColumn(e.target.value)}>
{/*
The `triage` option is REMOVED, not merely un-defaulted: fixing only the initializer
left the operator able to pick a column the default workflow no longer declares — and
it was the option labelled "Planning", which is the name the merged `todo` column now
displays, so it was the natural choice. Removing it also retires that label inversion.
A persisted `triage` is coerced to Automatic on load (see above), so no routine keeps it.
*/}
<option value="">{t("schedule.taskColumnAuto", "Automatic (workflow intake)")}</option>
<option value="todo">{t("schedule.taskColumnPlanning", "Planning")}</option>
</select>
</div>
<div className="form-group">
<label htmlFor="routine-task-model">{t("schedule.executorModelLabel", "Executor Model (optional)")}</label>
<CustomModelDropdown id="routine-task-model" label={t("schedule.executorModelDropdownLabel", "Executor Model")} models={models} value={modelValue} onChange={handleModelChange} placeholder={t("schedule.modelPlaceholder", "Use default")} disabled={modelsLoading} thinkingLevel={thinkingLevel} onThinkingLevelChange={setThinkingLevel} defaultThinkingLevel="off" showThinkingLevel />
{modelsError && <small className="field-error">{modelsError}</small>}
{errors.model && <small id={modelErrorId} className="field-error">{errors.model}</small>}
</div>
</>
)}
</>
) : (
<>
<ScheduleStepsEditor steps={steps} onChange={setSteps} onEditingChange={setHasEditingSteps} />
{errors.steps && <small className="field-error">{errors.steps}</small>}
{errors.stepsEditing && <small className="field-error">{errors.stepsEditing}</small>}
</>
)}
<div className="form-group">
<label htmlFor="routine-timeout">{t("schedule.timeoutLabel", "Timeout (ms)")}</label>
<input id="routine-timeout" type="number" min={1000} step={1000} value={timeoutMs} onChange={(e) => setTimeoutMs(Number(e.target.value))} aria-invalid={!!errors.timeoutMs} aria-describedby={errors.timeoutMs ? timeoutErrorId : undefined} />
{errors.timeoutMs ? <small id={timeoutErrorId} className="field-error">{errors.timeoutMs}</small> : <small>{t("schedule.timeoutHint", "Maximum execution time in milliseconds.")}</small>}
</div>
{/* Execution Policy */}
<div className="form-group">
<label htmlFor="routine-execution-policy">{t("schedule.executionPolicyLabel", "Execution Policy")}</label>
<select
id="routine-execution-policy"
value={executionPolicy}
onChange={(e) => setExecutionPolicy(e.target.value as RoutineExecutionPolicy)}
>
{EXECUTION_POLICY_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>{opt.label}</option>
))}
</select>
<small>{t("schedule.executionPolicyHint", "How to handle concurrent executions of this routine")}</small>
</div>
{/* Catch-up Policy */}
<div className="form-group">
<label htmlFor="routine-catchup-policy">{t("schedule.catchUpPolicyLabel", "Catch-up Policy")}</label>
<select
id="routine-catchup-policy"
value={catchUpPolicy}
onChange={(e) => setCatchUpPolicy(e.target.value as RoutineCatchUpPolicy)}
>
{CATCH_UP_POLICY_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>{opt.label}</option>
))}
</select>
<small>{t("schedule.catchUpPolicyHint", "What to do when a scheduled run is missed")}</small>
</div>
{/* Enabled */}
<div className="form-group">
<label htmlFor="routine-enabled" className="checkbox-label">
<input
id="routine-enabled"
type="checkbox"
checked={enabled}
onChange={(e) => setEnabled(e.target.checked)}
/>
{t("schedule.enabledLabel", "Enabled")}
</label>
<small>{t("schedule.enabledHint", "When disabled, the routine will not run automatically")}</small>
</div>
<div className="modal-actions">
<button
type="button"
className="btn btn-sm"
onClick={onCancel}
disabled={submitting}
>
{t("common.cancel", "Cancel")}
</button>
<button
type="submit"
className="btn btn-primary btn-sm"
disabled={submitting}
>
{submitting ? t("common.saving", "Saving…") : isEditing ? t("schedule.saveChanges", "Save Changes") : t("schedule.createRoutine", "Create Routine")}
</button>
</div>
</form>
);
}