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: 3 additions & 15 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2911,12 +2911,6 @@ export interface operations {
/** @default [] */
tags?: string[];
agentKind: string;
/** @default */
model?: string;
/** @default */
effort?: string;
/** Format: date-time */
expectedUpdatedAt?: string;
};
};
};
Expand Down Expand Up @@ -2978,12 +2972,6 @@ export interface operations {
/** @default [] */
tags?: string[];
agentKind: string;
/** @default */
model?: string;
/** @default */
effort?: string;
/** Format: date-time */
expectedUpdatedAt?: string;
};
};
};
Expand Down Expand Up @@ -3344,7 +3332,7 @@ export interface operations {
content: {
"application/json": {
connectionId?: string;
apiToken: string;
apiToken?: string;
/** @enum {string} */
agentKind?: "codex" | "claude" | "pi";
tags?: string[];
Expand Down Expand Up @@ -3437,8 +3425,8 @@ export interface operations {
content: {
"application/json": {
connectionId?: string;
accessToken: string;
project: string;
accessToken?: string;
project?: string;
/** Format: uri */
apiBaseUrl?: string;
};
Expand Down
8 changes: 4 additions & 4 deletions packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export interface RouteContract {

const exeBody = z.object({
connectionId: z.string().min(1).optional(),
apiToken: z.string().min(1).meta({ writeOnly: true }),
apiToken: z.string().min(1).meta({ writeOnly: true }).optional(),
agentKind: z.enum(["codex", "claude", "pi"]).optional(),
tags: z
.array(z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/))
Expand All @@ -54,8 +54,8 @@ const exeTestBody = exeBody
});
const ampBody = z.object({
connectionId: z.string().min(1).optional(),
accessToken: z.string().min(1).meta({ writeOnly: true }),
project: z.string().min(1),
accessToken: z.string().min(1).meta({ writeOnly: true }).optional(),
project: z.string().min(1).optional(),
apiBaseUrl: z.url().optional(),
});
const ampTestBody = ampBody
Expand All @@ -74,7 +74,7 @@ const tailBody = z.object({
.meta({ writeOnly: true }),
generateSecret: z.boolean().optional(),
});
const executionTargetBody = z.object({ name: z.string().trim().min(1).max(120), integrationKind: z.enum(["exe", "amp"]), integrationId: z.string().min(1), tags: z.array(z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/)).max(20).default([]), agentKind: z.string().min(1).max(40), model: z.string().max(200).default(""), effort: z.string().max(40).default(""), expectedUpdatedAt: z.string().datetime().optional() });
const executionTargetBody = z.object({ name: z.string().trim().min(1).max(120), integrationKind: z.enum(["exe", "amp"]), integrationId: z.string().min(1), tags: z.array(z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/)).max(20).default([]), agentKind: z.string().min(1).max(40) });
const executionTargetUpdateBody = executionTargetBody;
const deliveryQuery = z.object({
provider: z.string().optional(),
Expand Down
28 changes: 17 additions & 11 deletions packages/api/src/postgres/integration-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,32 @@ export class IntegrationService {
constructor(private database: Database, private tenantId: string, encryptionKey: string) { this.connections = new ConnectionRepository(database, tenantId, encryptionKey); }

async saveExe(value: ExeConnectionInput) {
if (!value.apiToken) throw new Error("An exe.dev HTTPS token is required");
const candidate: ExeConnection = { apiToken: value.apiToken };
const existing = value.connectionId ? await this.connections.get<ExeConnection>(`exe:${value.connectionId}`) : null;
const apiToken = value.apiToken || existing?.apiToken;
if (!apiToken) throw new Error("An exe.dev HTTPS token is required");
const tags = Array.isArray(value.tags) ? value.tags.map(String).map(tag => tag.trim()).filter(Boolean) : [];
if (tags.length > 20 || tags.some(tag => !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(tag))) throw new Error("VM tags are invalid");
const candidate: ExeConnection = { apiToken, tags, ...(value.agentKind ? { agentKind: value.agentKind } : {}) };
const backend = new ExeVmBackend(candidate), permissions = await backend.testPermissions();
if (!permissions.ok) throw new Error(`exe.dev token is missing required permissions: ${permissions.missingPermissions.join(", ")}`);
const connectionId = value.connectionId || crypto.randomUUID();
const existing = value.connectionId ? await this.connections.get<ExeConnection>(`exe:${connectionId}`) : null;
await this.connections.put(`exe:${connectionId}`, { ...(existing ?? {}), apiToken: value.apiToken });
return { ok: true, connectionId };
const validation = value.agentKind ? await backend.validateAgentAndModels(value.agentKind) : undefined, connectionId = value.connectionId || crypto.randomUUID();
const saved = { ...candidate, ...(validation ? { models: validation.models, modelsRefreshedAt: timestamp() } : {}) };
await this.connections.put(`exe:${connectionId}`, saved);
await this.database.pool.query("INSERT INTO app.execution_targets(tenant_id,id,name,integration_kind,integration_id,tags,agent_kind) VALUES ($1,gen_random_uuid(),$2,'exe',$3,$4,$5) ON CONFLICT (tenant_id,integration_kind,integration_id,name) DO NOTHING", [this.tenantId, `exe.dev · ${connectionId.slice(0, 8)}`, connectionId, JSON.stringify(tags), value.agentKind]);
return { ok: true, connectionId, ...(validation ? { models: validation.models } : {}) };
}
async testExe(input: Partial<ExeConnectionInput>) {
const saved = input.connectionId ? await this.connections.get<ExeConnection>(`exe:${input.connectionId}`) : null;
const connection = input.apiToken ? input as ExeConnection : saved; if (!connection?.apiToken) throw new Error("Account-level exe.dev HTTPS token is required");
const result = await new ExeVmBackend({ ...connection, tags: [] }).testPermissions();
const result = await new ExeVmBackend(connection).testPermissions();
return { ok: result.ok, missingPermissions: result.missingPermissions, tags: result.tags, checks: result.checks.map(check => ({ command: check.requestBody, ok: check.ok, httpStatus: check.status, exitCode: check.exitCode, output: check.body })) };
}
async diagnoseExe(connectionId: string) {
const connection = await this.connections.get<ExeConnection>(`exe:${connectionId}`); if (!connection) return null;
const backend = new ExeVmBackend({ ...connection, tags: [] }), permissions = await backend.testPermissions();
const backend = new ExeVmBackend(connection), permissions = await backend.testPermissions();
if (!permissions.ok) return { ok: false, connectionId, agentKind: connection.agentKind, permissions: { ok: false, missing: permissions.missingPermissions, tags: permissions.tags }, agent: null };
return { ok: true, connectionId, permissions: { ok: true, missing: [], tags: permissions.tags }, agent: null };
try { const validation = connection.agentKind ? await backend.validateAgentAndModels(connection.agentKind) : undefined; return { ok: true, connectionId, agentKind: connection.agentKind, permissions: { ok: true, missing: [], tags: permissions.tags }, agent: validation ? { ok: true, models: validation.models } : null }; }
catch (error) { return { ok: false, connectionId, agentKind: connection.agentKind, permissions: { ok: true, missing: [], tags: permissions.tags }, agent: { ok: false, error: error instanceof Error ? error.message.slice(0, 500) : "Agent validation failed" } }; }
}
async diagnoseExeTarget(targetId: string, connectionId: string, tags: string[], agentKind: "codex" | "claude" | "pi") {
const connection = await this.connections.get<ExeConnection>(`exe:${connectionId}`); if (!connection) return null;
Expand All @@ -43,7 +49,7 @@ export class IntegrationService {
try { const validation = await backend.validateAgentAndModels(agentKind); return { ok: true, targetId, integrationId: connectionId, agentKind, tags, permissions: { ok: true, missing: [], tags: permissions.tags }, agent: { ok: true, models: validation.models } }; }
catch (error) { return { ok: false, targetId, integrationId: connectionId, agentKind, tags, permissions: { ok: true, missing: [], tags: permissions.tags }, agent: { ok: false, error: error instanceof Error ? error.message.slice(0, 500) : "Agent validation failed" } }; }
}
async saveAmp(value: AmpConnectionInput) { if (!value.accessToken || !value.project) throw new Error("Amp access token and project are required"); if (!await new AmpBackend(value).test()) throw new Error("Amp connection verification failed"); const connectionId = value.connectionId || crypto.randomUUID(); await this.connections.put(`amp:${connectionId}`, value); await this.database.pool.query("INSERT INTO app.execution_targets(tenant_id,id,name,integration_kind,integration_id,tags,agent_kind) VALUES ($1,gen_random_uuid(),$2,'amp',$3,'[]','Amp') ON CONFLICT (tenant_id,integration_kind,integration_id,name) DO NOTHING", [this.tenantId, `Amp · ${value.project}`, connectionId]); return { ok: true, connectionId }; }
async saveAmp(value: AmpConnectionInput) { const existing = value.connectionId ? await this.connections.get<AmpConnection>(`amp:${value.connectionId}`) : null, accessToken = value.accessToken || existing?.accessToken, project = value.project || existing?.project; if (!accessToken || !project) throw new Error("Amp access token and project are required"); const connection = { ...existing, ...value, accessToken, project }; if (!await new AmpBackend(connection).test()) throw new Error("Amp connection verification failed"); const connectionId = value.connectionId || crypto.randomUUID(); await this.connections.put(`amp:${connectionId}`, connection); await this.database.pool.query("INSERT INTO app.execution_targets(tenant_id,id,name,integration_kind,integration_id,tags,agent_kind) VALUES ($1,gen_random_uuid(),$2,'amp',$3,'[]','Amp') ON CONFLICT (tenant_id,integration_kind,integration_id,name) DO NOTHING", [this.tenantId, `Amp · ${project}`, connectionId]); return { ok: true, connectionId }; }
async testAmp(input: Partial<AmpConnectionInput>) { const saved = input.connectionId ? await this.connections.get<AmpConnection>(`amp:${input.connectionId}`) : null, connection = input.accessToken ? input as AmpConnection : saved; if (!connection?.accessToken || !connection.project) throw new Error("Amp connection is required"); return { ok: await new AmpBackend(connection).test() }; }

async remove(kind: "exe" | "amp", id: string) {
Expand Down Expand Up @@ -79,7 +85,7 @@ export class IntegrationService {
const connectionsPromise = this.connections.all(["linear", "clickup", "exe:", "amp:", "cloudflare-tail:"]);
const [connections, tails] = await Promise.all([connectionsPromise, this.tails(connectionsPromise)]);
const linear = connections.get("linear"), clickup = connections.get("clickup");
const exeConnections = [...connections].filter(([kind]) => kind.startsWith("exe:")).map(([kind, value]) => ({ connectionId: kind.slice(4), credentialStatus: "connected" as const, accountTags: value.accountTags ?? [] }));
const exeConnections = [...connections].filter(([kind]) => kind.startsWith("exe:")).map(([kind, value]) => { const { apiToken: _, ...safe } = value; return { ...safe, connectionId: kind.slice(4) }; });
const ampConnections = [...connections].filter(([kind]) => kind.startsWith("amp:")).map(([kind, value]) => { const { accessToken: _, ...safe } = value; return { ...safe, connectionId: kind.slice(4) }; });
return { linear: linear ? { organizationName: linear.organizationName ?? null, viewerEmail: linear.viewerEmail ?? null } : null, clickup: clickup ? { teamName: clickup.teamName ?? null } : null, exe: exeConnections[0] ?? null, exeConnections, ampConnections, cloudflareTail: { count: tails.length, installations: tails } };
}
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,10 @@ export interface WorkItem {

export interface ExeConnectionInput {
connectionId?: string;
apiToken: string;
apiToken?: string;
tags?: string[];
agentKind?: "codex" | "claude" | "pi";
}

export interface AmpConnectionInput { connectionId?: string; accessToken: string; project: string; apiBaseUrl?: string; }
export interface AmpConnectionInput { connectionId?: string; accessToken?: string; project?: string; apiBaseUrl?: string; }
export interface TailIntegrationInput { integrationId?: string; name: string; signingSecret?: string; generateSecret?: boolean; }
3 changes: 1 addition & 2 deletions packages/api/test/static-slice.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,9 @@ describe.skipIf(!url)("compiled React + actual Worker API + PostgreSQL", () => {
await page.waitForURL(`**/jobs/${job.id}/settings`);
await page.getByLabel("Prompt template", { exact: true }).fill("My edited prompt");
await service.updateJob(job.id, { name: "Concurrent name", slug: job.slug, promptTemplate: job.promptTemplate, executionTargetId: job.executionTargetId, concurrencyLimit: 1, triggers: [{ id: job.triggers[0].id, slug: job.triggers[0].slug, kind: "manual", enabled: true, config: {} }], expectedUpdatedAt: job.updatedAt });
await page.getByRole("button", { name: "Save job", exact: true }).click();
await page.getByRole("button", { name: "Reconcile my changes" }).waitFor();
await page.getByRole("button", { name: "Reconcile my changes" }).click();
expect(await page.getByLabel("Name", { exact: true }).inputValue()).toBe("Concurrent name");
await page.getByRole("button", { name: "Save job", exact: true }).click();
await page.getByRole("status").filter({ hasText: "Job settings saved." }).waitFor();
expect(new URL(page.url()).pathname).toBe(`/jobs/${job.id}/settings`);
const saved = await service.getJob(job.id); expect(saved.name).toBe("Concurrent name"); expect(saved.promptTemplate).toBe("My edited prompt"); expect(saved.triggers[0].id).toBe(job.triggers[0].id);
Expand Down
8 changes: 4 additions & 4 deletions packages/app/src/features/jobs/conditions-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import { api } from "factorize-api-client";
import { validationMessage } from "./validation-message";
import type { Trigger } from "./editor-state";
type Conditions = Extract<Trigger, { kind: "webhook" }>["config"]["conditions"];
export function ConditionsEditor({ conditions, onChange }: { conditions: Conditions; onChange: (value: Conditions) => void }) {
export function ConditionsEditor({ conditions, onChange, onValidityChange }: { conditions: Conditions; onChange: (value: Conditions) => void; onValidityChange?: (invalid: boolean) => void }) {
const [text, setText] = useState(() => conditions === undefined ? "" : JSON.stringify(conditions, null, 2));
const [webhook, setWebhook] = useState("{}"), [invalid, setInvalid] = useState("");
const accepted = useRef(JSON.stringify(conditions));
useEffect(() => {
const value = JSON.stringify(conditions);
if (value !== accepted.current) { accepted.current = value; setText(conditions === undefined ? "" : JSON.stringify(conditions, null, 2)); setInvalid(""); }
if (value !== accepted.current) { accepted.current = value; setText(conditions === undefined ? "" : JSON.stringify(conditions, null, 2)); setInvalid(""); onValidityChange?.(false); }
}, [conditions]);
const test = useMutation({ retry: false, mutationFn: async () => {
const example: unknown = JSON.parse(webhook);
Expand All @@ -21,8 +21,8 @@ export function ConditionsEditor({ conditions, onChange }: { conditions: Conditi
} });
return <div className="grid gap-3"><Label>Conditions JSON (optional) <Textarea maxLength={16_384} rows={8} value={text} onChange={e => {
const value = e.target.value; setText(value); test.reset();
try { const parsed = value.trim() ? JSON.parse(value) : undefined; setInvalid(""); accepted.current = JSON.stringify(parsed); onChange(parsed); }
catch { setInvalid("Conditions must be valid JSON before saving."); }
try { const parsed = value.trim() ? JSON.parse(value) : undefined; setInvalid(""); onValidityChange?.(false); accepted.current = JSON.stringify(parsed); onChange(parsed); }
catch { setInvalid("Conditions must be valid JSON before saving."); onValidityChange?.(true); }
}} ref={element => element?.setCustomValidity(invalid)} /></Label>
{invalid && <p role="alert">{invalid}</p>}<p>Empty conditions add no filtering. Conditions only decide whether to invoke; prompt context stays intact.</p>
<Disclosure><Summary>Test webhook conditions</Summary><p>Supply the prepared context the job would receive. This preview does not authenticate, route events, verify live GitHub state, or invoke jobs.</p>
Expand Down
16 changes: 16 additions & 0 deletions packages/app/src/features/jobs/editor-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,19 @@ export function reconcile(base: JobInput, local: JobInput, remote: JobInput) {
export function writeInput(draft: JobInput): JobInput {
return { ...draft, triggers: draft.triggers.map(trigger => ({ ...trigger, slug: trigger.slug && /^trigger-[1-9][0-9]*$/.test(trigger.slug) ? trigger.slug : undefined })) };
}

export function validateJobInput(input: JobInput): string | undefined {
if (!input.name.trim() || input.name.length > 120) return "Enter a job name between 1 and 120 characters.";
if (!/^[a-z][a-z0-9_-]{0,29}$/.test(input.slug)) return "Slug must start with a lowercase letter and contain at most 30 characters.";
if (!input.promptTemplate || input.promptTemplate.length > 50_000) return "Enter a prompt template between 1 and 50,000 characters.";
if (!Number.isInteger(input.concurrencyLimit) || input.concurrencyLimit < 1 || input.concurrencyLimit > 50) return "Concurrency limit must be between 1 and 50.";
if (!input.executionTargetId) return "Choose an execution target.";
if (input.triggers.length > 50) return "A job can have at most 50 triggers.";
for (const trigger of input.triggers) {
if (!trigger.slug || !/^trigger-[1-9][0-9]*$/.test(trigger.slug)) return "Each trigger needs a valid stable identifier.";
if (trigger.kind === "schedule" && (!trigger.config.cron.trim() || !trigger.config.timezone.trim())) return "Schedule triggers require a cron expression and timezone.";
if (trigger.kind === "jobLifecycle" && (!trigger.config.sourceJobIds.length || !trigger.config.states.length)) return "Lifecycle triggers require a source job and state.";
if (trigger.kind === "webhook" && (trigger.config.provider === "linear" || trigger.config.provider === "clickup") && !trigger.config.matchRules?.length) return "Provider triggers require at least one matching rule.";
}
return undefined;
}
Loading
Loading