Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions packages/app/src/schedule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,24 @@ export interface ScheduleConfig {
timezone: string;
}

export type SimpleScheduleInterval = { unit: "minutes" | "hours"; value: number };

export function simpleIntervalToCron(interval: SimpleScheduleInterval): string {
const maximum = interval.unit === "minutes" ? 59 : 23;
if (!Number.isInteger(interval.value) || interval.value < 1 || interval.value > maximum) throw new Error(`Schedule interval must be between 1 and ${maximum} ${interval.unit}`);
return interval.unit === "minutes" ? `*/${interval.value} * * * *` : `0 */${interval.value} * * *`;
}

export function simpleIntervalFromSchedule(config: ScheduleConfig): SimpleScheduleInterval | null {
if (config.timezone !== "UTC") return null;
const cron = config.cron.trim(), minutes = cron.match(/^\*\/(\d+) \* \* \* \*$/), hours = cron.match(/^0 \*\/(\d+) \* \* \*$/);
if (cron === "* * * * *") return { unit: "minutes", value: 1 };
if (cron === "0 * * * *") return { unit: "hours", value: 1 };
if (minutes && Number(minutes[1]) >= 1 && Number(minutes[1]) <= 59) return { unit: "minutes", value: Number(minutes[1]) };
if (hours && Number(hours[1]) >= 1 && Number(hours[1]) <= 23) return { unit: "hours", value: Number(hours[1]) };
return null;
}

export function validateScheduleConfig(value: unknown): ScheduleConfig {
const config = value as ScheduleConfig;
if (!config || typeof config.cron !== "string" || typeof config.timezone !== "string") throw new Error("Schedule cron and timezone are required");
Expand Down
7 changes: 6 additions & 1 deletion packages/app/src/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export const jobPage = (viewer: { email: string }, jobId?: string) => shell(`${j
<section class="${card} p-6" aria-labelledby="job-prompt-title"><div class="border-b border-stone-200 pb-5 dark:border-slate-800"><p class="text-xs font-semibold uppercase tracking-[.18em] text-factorize-700 dark:text-factorize-100">Step 3</p><h2 id="job-prompt-title" class="mt-2 text-xl font-semibold">Prompt and context</h2><p class="mt-1 text-sm text-slate-500 dark:text-slate-400">Write the instructions for each run using context supplied by your triggers.</p></div><label class="label mt-5 relative">Mustache prompt template<textarea class="field mt-2 min-h-44 font-mono text-sm" name="promptTemplate" required placeholder="Review {{trigger-2.issue.title}}" aria-autocomplete="list" aria-controls="context-suggestions" aria-expanded="false"></textarea><div id="context-suggestions" class="absolute z-20 hidden max-h-56 w-[min(32rem,calc(100vw-4rem))] overflow-y-auto rounded-lg border border-stone-300 bg-white py-1 text-sm font-normal shadow-xl dark:border-slate-700 dark:bg-slate-900" role="listbox"></div><div id="context-announcement" class="sr-only" aria-live="polite"></div><div id="context-paths" class="mt-2 text-sm font-normal text-slate-500 dark:text-slate-400" aria-live="polite"></div></label></section>
<section class="${card} p-6" aria-labelledby="job-target-title"><div class="border-b border-stone-200 pb-5 dark:border-slate-800"><p class="text-xs font-semibold uppercase tracking-[.18em] text-factorize-700 dark:text-factorize-100">Step 4</p><h2 id="job-target-title" class="mt-2 text-xl font-semibold">Execution target</h2><p class="mt-1 text-sm text-slate-500 dark:text-slate-400">Select the connected environment that will run this job.</p></div><label class="label mt-5">Execution target<select class="field" name="executionTargetId" required><option value="">Loading saved targets…</option></select><span class="mt-2 block font-normal text-slate-500 dark:text-slate-400">Credentials are managed only in <a class="underline" href="/settings">Settings</a>.</span></label></section>
<p id="error" class="hidden rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700" role="alert"></p><button id="save" class="rounded-xl bg-slate-950 px-6 py-3 text-sm font-semibold text-white dark:bg-white dark:text-slate-950">${jobId ? "Save changes" : "Create job"}</button></form>
<dialog id="trigger-dialog" class="m-auto w-[min(44rem,calc(100%-2rem))] rounded-2xl bg-white p-0 text-slate-950 shadow-2xl backdrop:bg-slate-950/60 dark:bg-slate-900 dark:text-white"><form id="trigger-form" method="dialog"><div class="border-b border-stone-200 p-6 dark:border-slate-700"><h2 id="dialog-title" class="text-xl font-semibold">Add trigger</h2><p class="mt-1 text-sm text-slate-500">Provider credentials stay managed by Factorize.</p></div><div class="grid max-h-[70vh] gap-5 overflow-y-auto p-6 sm:grid-cols-2"><div data-panel="schedule" class="hidden contents"><label class="label">Cron<input class="field font-mono" name="cron" value="0 9 * * *"></label><label class="label">Timezone<select class="field" name="timezone"><option>UTC</option><option>America/New_York</option><option>America/Chicago</option><option>America/Denver</option><option>America/Los_Angeles</option><option>Europe/London</option><option>Europe/Berlin</option><option>Asia/Tokyo</option><option>Australia/Sydney</option></select></label><p id="schedule-preview" class="sm:col-span-2 text-sm text-slate-500"></p></div>
<dialog id="trigger-dialog" class="m-auto w-[min(44rem,calc(100%-2rem))] rounded-2xl bg-white p-0 text-slate-950 shadow-2xl backdrop:bg-slate-950/60 dark:bg-slate-900 dark:text-white"><form id="trigger-form" method="dialog"><div class="border-b border-stone-200 p-6 dark:border-slate-700"><h2 id="dialog-title" class="text-xl font-semibold">Add trigger</h2><p class="mt-1 text-sm text-slate-500">Provider credentials stay managed by Factorize.</p></div><div class="grid max-h-[70vh] gap-5 overflow-y-auto p-6 sm:grid-cols-2"><div data-panel="schedule" class="hidden sm:col-span-2"><fieldset><legend class="label">Schedule setup</legend><div class="mt-2 flex gap-5"><label class="font-medium"><input type="radio" name="scheduleMode" value="simple" checked> Simple</label><label class="font-medium"><input type="radio" name="scheduleMode" value="advanced"> Advanced</label></div></fieldset><div id="schedule-simple" class="mt-5"><div class="flex items-end gap-3"><label class="label flex-1">Every<input class="field" type="number" name="intervalValue" value="5" min="1" max="59" required></label><label class="label flex-1">Interval<select class="field" name="intervalUnit"><option value="minutes">minutes</option><option value="hours">hours</option></select></label></div><p id="schedule-semantics" class="mt-3 text-sm text-slate-500">Runs every 5 minutes, aligned to UTC clock boundaries.</p></div><div id="schedule-advanced" class="mt-5 hidden grid gap-5 sm:grid-cols-2"><label class="label">Cron expression<input class="field font-mono" name="cron" value="0 9 * * *"></label><label class="label">Timezone<select class="field" name="timezone"><option>UTC</option><option>America/New_York</option><option>America/Chicago</option><option>America/Denver</option><option>America/Los_Angeles</option><option>Europe/London</option><option>Europe/Berlin</option><option>Asia/Tokyo</option><option>Australia/Sydney</option></select></label></div><p id="schedule-preview" class="mt-4 text-sm text-slate-500" aria-live="polite"></p></div>
<div data-panel="linear" class="hidden sm:col-span-2"><label class="label">Project<select class="field" name="projectId"></select></label><div class="mt-5 flex items-start justify-between gap-4"><div><p class="label">Issue matching rules</p><p class="mt-1 text-sm text-slate-500">The issue must match every rule. A run starts when it enters the matching set.</p></div><button id="add-linear-rule" type="button" class="shrink-0 rounded-lg border border-stone-300 px-3 py-2 text-sm font-semibold hover:bg-stone-50 dark:border-slate-700 dark:hover:bg-slate-800">Add rule</button></div><div id="linear-rules" class="mt-4 space-y-3"></div></div>
<div data-panel="github" class="hidden contents"><label class="label">Installation<select class="field" name="installationId"></select></label><label class="label">Repository<select class="field" name="repositoryId"></select></label><label class="label">Event<input class="field" name="event" value="pull_request"></label><label class="label">Action<input class="field" name="action" value="dequeued"></label></div>
<div data-panel="jobLifecycle" class="hidden contents"><label class="label">Source jobs<select class="field" name="sourceJobId" multiple size="4"></select></label><fieldset class="label"><legend>Final states</legend><label class="mt-2 block font-normal"><input type="checkbox" name="lifecycleState" value="succeeded" checked> Succeeded</label><label class="mt-2 block font-normal"><input type="checkbox" name="lifecycleState" value="failed" checked> Failed</label><label class="mt-2 block font-normal"><input type="checkbox" name="lifecycleState" value="stopped"> Stopped</label></fieldset></div>
Expand All @@ -78,6 +78,10 @@ const reflection=t=>t.reflection?.paths||contextCatalog[providerKind(t)]||[];
const triggerHints=()=>triggers.map(t=>({path:t.slug+'.*',type:'context',description:kinds[providerKind(t)]+' trigger context'}));
const contextPaths=()=>triggers.flatMap(t=>[{path:t.slug+'.*',type:'context',description:kinds[providerKind(t)]+' trigger context'},...reflection(t).filter(x=>x.path!=='*').map(x=>({path:t.slug+'.'+x.path,type:x.type,description:x.description}))]);
const nameOf=(items,id)=>items.find(x=>String(x.id)===String(id))?.name||String(id||'Not selected');
const simpleSchedule=c=>{if(c.timezone!=='UTC')return null;const cron=(c.cron||'').trim(),minutes=cron.match(/^\\*\\/(\\d+) \\* \\* \\* \\*$/),hours=cron.match(/^0 \\*\\/(\\d+) \\* \\* \\*$/);if(cron==='* * * * *')return {unit:'minutes',value:1};if(cron==='0 * * * *')return {unit:'hours',value:1};if(minutes&&Number(minutes[1])>=1&&Number(minutes[1])<=59)return {unit:'minutes',value:Number(minutes[1])};if(hours&&Number(hours[1])>=1&&Number(hours[1])<=23)return {unit:'hours',value:Number(hours[1])};return null};
function simpleCron(){const unit=triggerForm.elements.intervalUnit.value,value=Number(triggerForm.elements.intervalValue.value),max=unit==='minutes'?59:23;if(!Number.isInteger(value)||value<1||value>max)throw new Error('Enter an interval from 1 to '+max+' '+unit+'.');return unit==='minutes'?'*/'+value+' * * * *':'0 */'+value+' * * *'}
function syncScheduleEditor(){const simple=triggerForm.elements.scheduleMode.value==='simple',unit=triggerForm.elements.intervalUnit.value,max=unit==='minutes'?59:23,value=triggerForm.elements.intervalValue;$('#schedule-simple').classList.toggle('hidden',!simple);$('#schedule-advanced').classList.toggle('hidden',simple);value.required=simple;value.max=String(max);$('#schedule-semantics').textContent='Runs every '+(value.value||'X')+' '+unit+', aligned to UTC clock boundaries.';if(simple){try{triggerForm.elements.cron.value=simpleCron();triggerForm.elements.timezone.value='UTC'}catch{}}previewSchedule()}
const showTriggerDialog=dialog.showModal.bind(dialog);dialog.showModal=()=>{if(triggerForm.dataset.kind==='schedule'){const c=editing>=0?triggers[editing].config:null,simple=c?simpleSchedule(c):{unit:'minutes',value:5};triggerForm.elements.scheduleMode.value=simple?'simple':'advanced';if(simple){triggerForm.elements.intervalUnit.value=simple.unit;triggerForm.elements.intervalValue.value=String(simple.value)}syncScheduleEditor()}showTriggerDialog()};
async function refreshAvailability(){availability=await request('/api/job-trigger-availability');const select=$('#add-trigger'),selected=select.value;select.replaceChildren(new Option('Add trigger…',''),...Object.entries(kinds).filter(([kind])=>availability[kind]).map(([kind,label])=>new Option(label,kind)));select.value=selected;select.disabled=false}
const ruleLabels={status:'Status',label:'Label',assignee:'Assignee',creator:'Creator',owner:'Owner'};
const ruleOptions=type=>type==='status'?resources.options.statuses:type==='label'?resources.options.labels:resources.options.users;
Expand Down Expand Up @@ -106,6 +110,7 @@ function configFromForm(){const k=triggerForm.dataset.kind,h=triggerForm.element
function validate(candidate){const k=providerKind(candidate);if(k==='manual'&&triggers.some((t,i)=>i!==editing&&providerKind(t)==='manual'))throw new Error('Only one Manual trigger can be configured.');if(k==='linear'&&(!candidate.config.projectId||!candidate.config.matchRules.length||candidate.config.matchRules.some(rule=>!rule.targetId)))throw new Error('Choose a Linear project and a value for every matching rule.');if(k==='github'&&(!candidate.config.installationId||!candidate.config.repositoryId))throw new Error('Choose a GitHub installation and repository.');if(k==='jobLifecycle'&&(!candidate.config.sourceJobIds[0]||!candidate.config.states.length))throw new Error('Choose a source job and at least one final state.');if(triggers.some((t,i)=>i!==editing&&JSON.stringify(t.config)===JSON.stringify(candidate.config)&&t.kind===candidate.kind))throw new Error('An identical trigger is already configured.')}
$('#trigger-rows').onclick=e=>{const b=e.target.closest('button');if(!b)return;const key=['edit','remove'].find(x=>b.dataset[x]!==undefined),i=Number(b.dataset[key]);if(key==='edit')openEditor(providerKind(triggers[i]),i);if(key==='remove'){if(providerKind(triggers[i])==='manual'){const error=$('#error');error.textContent='A Job must keep its Manual trigger. Disable it if manual runs should be unavailable.';error.classList.remove('hidden');return}triggers.splice(i,1);render()}};
$('#trigger-rows').onchange=e=>{if(e.target.dataset.enable===undefined)return;triggers[Number(e.target.dataset.enable)].enabled=e.target.checked;render()};$('#add-trigger').onchange=e=>{const kind=e.target.value;e.target.value='';if(kind)openEditor(kind)};$('#add-linear-rule').onclick=()=>addLinearRule();$('#cancel-trigger').onclick=()=>dialog.close();triggerForm.elements.installationId.onchange=()=>syncRepositories();triggerForm.elements.cron.oninput=previewSchedule;triggerForm.elements.timezone.onchange=previewSchedule;
triggerForm.querySelectorAll('[name=scheduleMode]').forEach(input=>input.onchange=syncScheduleEditor);triggerForm.elements.intervalUnit.onchange=syncScheduleEditor;triggerForm.elements.intervalValue.oninput=syncScheduleEditor;
triggerForm.onsubmit=e=>{e.preventDefault();try{const value=configFromForm();validate(value);if(editing>=0)triggers[editing]={...triggers[editing],...value};else triggers.push({...value,id:undefined,slug:nextSlug(),enabled:true,_clientId:++clientId});dialog.close();render()}catch(error){$('#dialog-error').textContent=error.message;$('#dialog-error').classList.remove('hidden')}};
$('#test-handler').onclick=async()=>{const output=$('#handler-result');try{const handlerCode=triggerForm.elements.handlerCode.value;if(!handlerCode)throw new Error('Enter handler code first.');const payload=JSON.parse(triggerForm.elements.testPayload.value);const result=await request('/api/job-handlers/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({handlerCode,payload})});output.textContent=result.ok?'Accepted: '+JSON.stringify(result.decision):'Rejected: '+result.category}catch(e){output.textContent=e.message}};
async function init(){const [targets,projects,linearOptions,installResponse,tails,jobs,current]=await Promise.all([request('/api/execution-targets'),request('/api/linear/projects').catch(()=>[]),request('/api/linear/options').catch(()=>({statuses:[]})),fetch('/api/github/installations'),request('/api/connections/cloudflare-tail').catch(()=>[]),request('/api/jobs'),jobId?request('/api/jobs/'+encodeURIComponent(jobId)):null]);resources.projects=projects;resources.options=linearOptions;resources.installations=installResponse.ok?(await installResponse.json()).filter(x=>x.state==='active'):[];resources.tailInstallations=tails;resources.jobs=jobs;options(triggerForm.elements.tailIntegrationId,tails,'name','integrationId');options(form.executionTargetId,targets,'name');if(current){form.name.value=current.name;form.promptTemplate.value=current.promptTemplate;form.concurrencyLimit.value=current.concurrencyLimit;form.executionTargetId.value=current.executionTargetId;triggers=current.triggers.map(t=>({...t,config:{...t.config}}))}else triggers=[{kind:'manual',slug:'trigger-1',enabled:true,config:{}}];reservedSlugs=new Set(triggers.map(t=>t.slug));await refreshAvailability();render()}
Expand Down
23 changes: 22 additions & 1 deletion packages/app/test/schedule.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { catchUpOccurrence, nextOccurrence, validateScheduleConfig } from "../src/schedule";
import { catchUpOccurrence, nextOccurrence, simpleIntervalFromSchedule, simpleIntervalToCron, validateScheduleConfig } from "../src/schedule";

describe("durable schedules", () => {
it("calculates occurrences in the configured IANA timezone", () => {
Expand All @@ -25,4 +25,25 @@ describe("durable schedules", () => {
expect(result?.occurredAt.toISOString()).toBe("2026-09-16T10:00:00.000Z");
expect(result?.nextRunAt.toISOString()).toBe("2026-09-16T11:05:00.000Z");
});

it("converts simple interval boundaries to UTC cron forms", () => {
expect(simpleIntervalToCron({ unit: "minutes", value: 1 })).toBe("*/1 * * * *");
expect(simpleIntervalToCron({ unit: "minutes", value: 59 })).toBe("*/59 * * * *");
expect(simpleIntervalToCron({ unit: "hours", value: 1 })).toBe("0 */1 * * *");
expect(simpleIntervalToCron({ unit: "hours", value: 23 })).toBe("0 */23 * * *");
expect(() => simpleIntervalToCron({ unit: "minutes", value: 60 })).toThrow(/1 and 59/);
expect(() => simpleIntervalToCron({ unit: "hours", value: 24 })).toThrow(/1 and 23/);
});

it("recognizes only supported UTC interval schedules", () => {
expect(simpleIntervalFromSchedule({ cron: "*/15 * * * *", timezone: "UTC" })).toEqual({ unit: "minutes", value: 15 });
expect(simpleIntervalFromSchedule({ cron: "0 */6 * * *", timezone: "UTC" })).toEqual({ unit: "hours", value: 6 });
expect(simpleIntervalFromSchedule({ cron: "0 9 * * *", timezone: "UTC" })).toBeNull();
expect(simpleIntervalFromSchedule({ cron: "*/15 * * * *", timezone: "America/New_York" })).toBeNull();
});

it("previews converted simple intervals with existing occurrence logic", () => {
const config = { cron: simpleIntervalToCron({ unit: "hours", value: 3 }), timezone: "UTC" };
expect(nextOccurrence(config, new Date("2026-09-16T10:01:00Z")).toISOString()).toBe("2026-09-16T12:00:00.000Z");
});
});
14 changes: 14 additions & 0 deletions packages/app/test/ui.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,20 @@ describe("pages", () => {
expectInlineScriptsToParse(html);
});

it("offers simple UTC schedule intervals while preserving advanced schedules", () => {
const html = jobPage({ email: "owner@example.com" });
expect(html).toContain('name="scheduleMode" value="simple" checked');
expect(html).toContain('name="intervalValue" value="5" min="1" max="59"');
expect(html).toContain('value="minutes">minutes');
expect(html).toContain('value="hours">hours');
expect(html).toContain("simple=c?simpleSchedule(c):{unit:'minutes',value:5}");
expect(html).toContain("triggerForm.elements.scheduleMode.value=simple?'simple':'advanced'");
expect(html).toContain("triggerForm.elements.timezone.value='UTC'");
expect(html).toContain("aligned to UTC clock boundaries");
expect(html).toContain("previewSchedule()");
expectInlineScriptsToParse(html);
});

it("organizes create and edit job fields into the same four-step sequence", () => {
for (const html of [jobPage({ email: "owner@example.com" }), jobPage({ email: "owner@example.com" }, "job-1")]) {
const basics = html.indexOf('id="job-basics-title"');
Expand Down