diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index e0bac789..d7b02883 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -2911,12 +2911,6 @@ export interface operations { /** @default [] */ tags?: string[]; agentKind: string; - /** @default */ - model?: string; - /** @default */ - effort?: string; - /** Format: date-time */ - expectedUpdatedAt?: string; }; }; }; @@ -2978,12 +2972,6 @@ export interface operations { /** @default [] */ tags?: string[]; agentKind: string; - /** @default */ - model?: string; - /** @default */ - effort?: string; - /** Format: date-time */ - expectedUpdatedAt?: string; }; }; }; @@ -3344,7 +3332,7 @@ export interface operations { content: { "application/json": { connectionId?: string; - apiToken: string; + apiToken?: string; /** @enum {string} */ agentKind?: "codex" | "claude" | "pi"; tags?: string[]; @@ -3437,8 +3425,8 @@ export interface operations { content: { "application/json": { connectionId?: string; - accessToken: string; - project: string; + accessToken?: string; + project?: string; /** Format: uri */ apiBaseUrl?: string; }; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 0afe060e..9367ee01 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -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}$/)) @@ -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 @@ -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(), diff --git a/packages/api/src/postgres/integration-service.ts b/packages/api/src/postgres/integration-service.ts index a86cae14..d488663c 100644 --- a/packages/api/src/postgres/integration-service.ts +++ b/packages/api/src/postgres/integration-service.ts @@ -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(`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(`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) { const saved = input.connectionId ? await this.connections.get(`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(`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(`exe:${connectionId}`); if (!connection) return null; @@ -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(`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) { const saved = input.connectionId ? await this.connections.get(`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) { @@ -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 } }; } diff --git a/packages/api/src/types.ts b/packages/api/src/types.ts index a52497bb..1199c961 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -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; } diff --git a/packages/api/test/static-slice.e2e.test.ts b/packages/api/test/static-slice.e2e.test.ts index 2d3cc1f3..33ac525f 100644 --- a/packages/api/test/static-slice.e2e.test.ts +++ b/packages/api/test/static-slice.e2e.test.ts @@ -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); diff --git a/packages/app/src/features/jobs/conditions-editor.tsx b/packages/app/src/features/jobs/conditions-editor.tsx index bfcd9530..c2ee1497 100644 --- a/packages/app/src/features/jobs/conditions-editor.tsx +++ b/packages/app/src/features/jobs/conditions-editor.tsx @@ -5,13 +5,13 @@ import { api } from "factorize-api-client"; import { validationMessage } from "./validation-message"; import type { Trigger } from "./editor-state"; type Conditions = Extract["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); @@ -21,8 +21,8 @@ export function ConditionsEditor({ conditions, onChange }: { conditions: Conditi } }); return