From 2c697b885c473f762801868d2ac1a528d1df2472 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 20 Oct 2026 06:15:43 +0000 Subject: [PATCH] feat: restore execution target management --- packages/api-client/src/schema.d.ts | 40 ++++++ packages/api/src/api-contract.ts | 2 +- packages/api/src/editor-contracts.ts | 4 +- packages/api/src/flow-service.ts | 6 +- .../postgres/execution-target-repository.ts | 13 +- packages/api/src/postgres/schema.ts | 2 +- .../app/src/features/settings/navigation.tsx | 2 +- packages/app/src/features/settings/routes.tsx | 2 +- .../app/src/features/settings/targets.tsx | 30 +++++ packages/app/test/settings.browser.test.mjs | 4 +- packages/docs/openapi.yaml | 125 ++++++++++++++++++ 11 files changed, 213 insertions(+), 17 deletions(-) create mode 100644 packages/app/src/features/settings/targets.tsx diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 5c99f0c7..840adeb7 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -2873,10 +2873,18 @@ export interface operations { cwd: string; agentKind: string; integrationId?: string; + tags?: string[]; + model?: string; + effort?: string; models?: string[]; modelsRefreshedAt?: string | null; efforts?: string[]; capabilities: string[]; + referencingProjects?: { + id: string; + name: string; + }[]; + referencingJobCount?: number; }[]; }; }; @@ -2906,6 +2914,14 @@ export interface operations { integrationKind: "exe" | "amp"; integrationId: string; agentKind: string; + tags?: string[]; + /** @default */ + model?: string; + /** @default */ + effort?: string; + models?: string[]; + /** Format: date-time */ + expectedUpdatedAt?: string; }; }; }; @@ -2925,10 +2941,18 @@ export interface operations { cwd: string; agentKind: string; integrationId?: string; + tags?: string[]; + model?: string; + effort?: string; models?: string[]; modelsRefreshedAt?: string | null; efforts?: string[]; capabilities: string[]; + referencingProjects?: { + id: string; + name: string; + }[]; + referencingJobCount?: number; }; }; }; @@ -2961,6 +2985,14 @@ export interface operations { integrationKind: "exe" | "amp"; integrationId: string; agentKind: string; + tags?: string[]; + /** @default */ + model?: string; + /** @default */ + effort?: string; + models?: string[]; + /** Format: date-time */ + expectedUpdatedAt?: string; }; }; }; @@ -2980,10 +3012,18 @@ export interface operations { cwd: string; agentKind: string; integrationId?: string; + tags?: string[]; + model?: string; + effort?: string; models?: string[]; modelsRefreshedAt?: string | null; efforts?: string[]; capabilities: string[]; + referencingProjects?: { + id: string; + name: string; + }[]; + referencingJobCount?: number; }; }; }; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index e2c6cfd8..4b06f647 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -74,7 +74,7 @@ const tailBody = z.object({ .meta({ writeOnly: true }), generateSecret: z.boolean().optional(), }); -const executionTargetBody = z.object({ name: z.string().trim().max(120).default(""), integrationKind: z.enum(["exe", "amp"]), integrationId: z.string().min(1), agentKind: z.string().min(1).max(40) }); +const executionTargetBody = z.object({ name: z.string().trim().max(120).default(""), integrationKind: z.enum(["exe", "amp"]), integrationId: z.string().min(1), agentKind: z.string().min(1).max(40), tags: z.array(z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/)).max(20).optional(), model: z.string().trim().max(120).default(""), effort: z.string().trim().max(40).default(""), models: z.array(z.string().trim().min(1).max(120)).max(100).optional(), expectedUpdatedAt: z.string().datetime().optional() }); const executionTargetUpdateBody = executionTargetBody; const deliveryQuery = z.object({ provider: z.string().optional(), diff --git a/packages/api/src/editor-contracts.ts b/packages/api/src/editor-contracts.ts index f3559544..d342e950 100644 --- a/packages/api/src/editor-contracts.ts +++ b/packages/api/src/editor-contracts.ts @@ -1,9 +1,9 @@ import { z } from "zod"; export const executionTargetResponse = z.object({ id: z.string(), kind: z.enum(["exe-vm", "amp"]), name: z.string(), workspace: z.string(), cwd: z.string(), agentKind: z.string(), integrationId: z.string().optional(), - models: z.array(z.string()).optional(), modelsRefreshedAt: z.string().nullable().optional(), efforts: z.array(z.string()).optional(), capabilities: z.array(z.string()), + tags: z.array(z.string()).optional(), model: z.string().optional(), effort: z.string().optional(), models: z.array(z.string()).optional(), modelsRefreshedAt: z.string().nullable().optional(), efforts: z.array(z.string()).optional(), capabilities: z.array(z.string()), referencingProjects: z.array(z.object({ id: z.string(), name: z.string() })).optional(), referencingJobCount: z.number().int().optional(), }); -export const executionTargetResource = z.object({ id: z.string(), name: z.string(), integrationKind: z.enum(["exe", "amp"]), integrationId: z.string(), agentKind: z.string(), createdAt: z.string(), updatedAt: z.string() }); +export const executionTargetResource = z.object({ id: z.string(), name: z.string(), integrationKind: z.enum(["exe", "amp"]), integrationId: z.string(), agentKind: z.string(), tags: z.array(z.string()), models: z.array(z.string()), efforts: z.array(z.string()), createdAt: z.string(), updatedAt: z.string(), referencingProjects: z.array(z.object({ id: z.string(), name: z.string() })), referencingJobCount: z.number().int() }); export const triggerAvailabilityResponse = z.object({ manual: z.literal(true), schedule: z.literal(true), jobLifecycle: z.literal(true), linear: z.boolean(), clickup: z.boolean(), github: z.boolean(), cloudflareTail: z.boolean() }); export const namedOption = z.object({ id: z.string(), name: z.string() }); export const providerOptions = z.object({ statuses: z.array(namedOption), users: z.array(namedOption), labels: z.array(namedOption) }); diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index db6746f0..d65052b8 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -247,12 +247,12 @@ export class ApiService { } async listExecutionTargets() { await this.authorize("jobs:read"); const records = await this.targetRecords().list(); const targets: any[] = []; - for (const target of records) { const value = await this.connections().get(`${target.integrationKind}:${target.integrationId}`); if (!value) continue; targets.push({ id: target.id, kind: target.integrationKind === "amp" ? "amp" : "exe-vm", name: target.name, integrationId: target.integrationId, workspace: target.integrationKind === "amp" ? value.project : "ephemeral", cwd: target.integrationKind === "amp" ? "Cloud orb" : "/home/exedev/workspace", agentKind: target.agentKind, models: target.models ?? [], modelsRefreshedAt: target.modelsRefreshedAt ?? null, efforts: target.agentKind === "codex" ? ["minimal", "low", "medium", "high", "xhigh"] : [], capabilities: target.integrationKind === "amp" ? ["stop"] : ["recovery", "stop"] }); } + for (const target of records) { const value = await this.connections().get(`${target.integrationKind}:${target.integrationId}`); if (!value) continue; targets.push({ id: target.id, kind: target.integrationKind === "amp" ? "amp" : "exe-vm", name: target.name, integrationId: target.integrationId, tags: target.tags, model: target.model, effort: target.effort, workspace: target.integrationKind === "amp" ? value.project : "ephemeral", cwd: target.integrationKind === "amp" ? "Cloud orb" : "/home/exedev/workspace", agentKind: target.agentKind, models: target.models ?? [], modelsRefreshedAt: target.modelsRefreshedAt ?? null, efforts: target.efforts, capabilities: target.integrationKind === "amp" ? ["stop"] : ["recovery", "stop"], referencingProjects: target.referencingProjects, referencingJobCount: target.referencingJobCount }); } return publicValue(z.array(executionTargetResponse), targets); } async listExecutionTargetResources() { await this.authorize("integrations:read"); return publicValue(z.array((await import("./editor-contracts")).executionTargetResource), await this.targetRecords().list()); } - async createExecutionTarget(input: { name: string; integrationKind: "exe" | "amp"; integrationId: string; agentKind: string }) { await this.authorize("integrations:write"); const value = await this.connections().get(`${input.integrationKind}:${input.integrationId}`); if (!value) throw new ServiceError(404, "not_found", "Integration not found"); if (input.integrationKind === "exe" && !["codex", "claude", "pi"].includes(input.agentKind)) throw new ServiceError(400, "invalid_request", "Unsupported agent kind"); return this.targetRecords().create(input); } - async updateExecutionTarget(id: string, input: { name: string; integrationKind: "exe" | "amp"; integrationId: string; agentKind: string; expectedUpdatedAt?: string }) { await this.authorize("integrations:write"); const value = await this.connections().get(`${input.integrationKind}:${input.integrationId}`); if (!value) throw new ServiceError(404, "not_found", "Integration not found"); if (input.integrationKind === "exe" && !["codex", "claude", "pi"].includes(input.agentKind)) throw new ServiceError(400, "invalid_request", "Unsupported agent kind"); const result = await this.targetRecords().update(id, input, input.expectedUpdatedAt); if (!result) throw new ServiceError(409, "stale_target", "This target changed. Reload it before saving."); return result; } + async createExecutionTarget(input: { name: string; integrationKind: "exe" | "amp"; integrationId: string; agentKind: string; tags?: string[]; model?: string; effort?: string; models?: string[] }) { await this.authorize("integrations:write"); const value = await this.connections().get(`${input.integrationKind}:${input.integrationId}`); if (!value) throw new ServiceError(404, "not_found", "Integration not found"); if (!input.name.trim()) throw new ServiceError(400, "invalid_request", "Enter a display name before saving the target."); if (input.integrationKind === "exe" && !["codex", "claude", "pi"].includes(input.agentKind)) throw new ServiceError(400, "invalid_request", "Choose a supported exe.dev agent."); const tags: string[] = (input.tags ?? value.tags ?? []).map(String); if (tags.length > 20 || tags.some((tag: string) => !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(tag))) throw new ServiceError(400, "invalid_request", "VM tags must start with a letter or number and contain only letters, numbers, dots, underscores, colons, or hyphens."); return this.targetRecords().create({ ...input, tags, model: input.model ?? "", effort: input.effort ?? "", models: input.models ?? value.models ?? [] }); } + async updateExecutionTarget(id: string, input: { name: string; integrationKind: "exe" | "amp"; integrationId: string; agentKind: string; tags?: string[]; model?: string; effort?: string; models?: string[]; expectedUpdatedAt?: string }) { await this.authorize("integrations:write"); const value = await this.connections().get(`${input.integrationKind}:${input.integrationId}`); if (!value) throw new ServiceError(404, "not_found", "Integration not found"); if (!input.name.trim()) throw new ServiceError(400, "invalid_request", "Enter a display name before saving the target."); if (input.integrationKind === "exe" && !["codex", "claude", "pi"].includes(input.agentKind)) throw new ServiceError(400, "invalid_request", "Choose a supported exe.dev agent."); const result = await this.targetRecords().update(id, { ...input, tags: input.tags ?? [], model: input.model ?? "", effort: input.effort ?? "", models: input.models ?? value.models ?? [] }, input.expectedUpdatedAt); if (!result) throw new ServiceError(409, "stale_target", "This target changed. Reload it before saving."); return result; } async deleteExecutionTarget(id: string) { await this.authorize("integrations:write"); const result = await this.targetRecords().remove(id); if (result === "missing") throw new ServiceError(404, "not_found", "Execution target not found"); if (result === "referenced") throw new ServiceError(409, "conflict", "This target is used by a job"); if (result === "active") throw new ServiceError(409, "conflict", "This target is used by an active or queued run"); return { id, deleted: true }; } async diagnoseExeIntegration(connectionId: string) { await this.authorize("integrations:write"); const value = await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).diagnoseExe(connectionId); if (!value) throw new ServiceError(404,"not_found","Integration not found"); return value; } async diagnoseExecutionTarget(id: string) { await this.authorize("integrations:write"); const target = await this.targetRecords().get(id); if (!target) throw new ServiceError(404, "not_found", "Execution target not found"); if (target.integrationKind !== "exe") throw new ServiceError(400, "invalid_request", "Diagnostics are only available for exe.dev targets"); const value = await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).diagnoseExeTarget(id, target.integrationId, [], target.agentKind as "codex" | "claude" | "pi"); if (!value) throw new ServiceError(404, "not_found", "Integration not found"); return value; } diff --git a/packages/api/src/postgres/execution-target-repository.ts b/packages/api/src/postgres/execution-target-repository.ts index 10f82b62..3dbca188 100644 --- a/packages/api/src/postgres/execution-target-repository.ts +++ b/packages/api/src/postgres/execution-target-repository.ts @@ -1,14 +1,15 @@ import type { Database } from "./database"; -export type ExecutionTargetRecord = { id: string; name: string; integrationKind: "exe" | "amp"; integrationId: string; agentKind: string; models?: string[]; modelsRefreshedAt?: string | null; createdAt: string; updatedAt: string }; +export type ExecutionTargetRecord = { id: string; name: string; integrationKind: "exe" | "amp"; integrationId: string; agentKind: string; tags: string[]; model: string; effort: string; models: string[]; modelsRefreshedAt?: string | null; efforts: string[]; referencingProjects: { id: string; name: string }[]; referencingJobCount: number; createdAt: string; updatedAt: string }; -const map = (row: any): ExecutionTargetRecord => ({ id: row.id, name: row.name, integrationKind: row.integration_kind, integrationId: row.integration_id, agentKind: row.agent_kind, models: row.models ?? [], modelsRefreshedAt: row.models_refreshed_at?.toISOString() ?? null, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }); +const map = (row: any): ExecutionTargetRecord => ({ id: row.id, name: row.name, integrationKind: row.integration_kind, integrationId: row.integration_id, agentKind: row.agent_kind, tags: row.tags ?? [], model: row.model ?? "", effort: row.effort ?? "", models: row.models ?? [], modelsRefreshedAt: row.models_refreshed_at?.toISOString() ?? null, efforts: row.agent_kind === "codex" ? ["minimal", "low", "medium", "high", "xhigh"] : [], referencingProjects: row.referencing_projects ?? [], referencingJobCount: Number(row.referencing_job_count ?? 0), createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }); export class ExecutionTargetRepository { constructor(private database: Database, private tenantId: string) {} - async list() { const result = await this.database.pool.query("SELECT * FROM app.execution_targets WHERE tenant_id=$1 ORDER BY name,id", [this.tenantId]); return result.rows.map(map); } - async get(id: string) { const result = await this.database.pool.query("SELECT * FROM app.execution_targets WHERE tenant_id=$1 AND id=$2", [this.tenantId, id]); return result.rows[0] ? map(result.rows[0]) : null; } - async create(input: Omit) { const result = await this.database.pool.query("INSERT INTO app.execution_targets(tenant_id,id,name,integration_kind,integration_id,agent_kind) VALUES ($1,gen_random_uuid(),$2,$3,$4,$5) RETURNING *", [this.tenantId, input.name.trim(), input.integrationKind, input.integrationId, input.agentKind]); return map(result.rows[0]); } - async update(id: string, input: Pick, expectedUpdatedAt?: string) { const result = await this.database.pool.query("UPDATE app.execution_targets SET name=$3,integration_kind=$4,integration_id=$5,agent_kind=$6,updated_at=now() WHERE tenant_id=$1 AND id=$2 AND ($7::timestamptz IS NULL OR updated_at=$7) RETURNING *", [this.tenantId, id, input.name.trim(), input.integrationKind, input.integrationId, input.agentKind, expectedUpdatedAt ?? null]); return result.rows[0] ? map(result.rows[0]) : null; } + private query = `SELECT t.*, count(j.id)::int AS referencing_job_count, COALESCE(jsonb_agg(DISTINCT jsonb_build_object('id', p.id, 'name', p.name)) FILTER (WHERE p.id IS NOT NULL), '[]'::jsonb) AS referencing_projects FROM app.execution_targets t LEFT JOIN app.jobs j ON j.tenant_id=t.tenant_id AND j.execution_target->>'targetId'=t.id::text LEFT JOIN app.projects p ON p.tenant_id=j.tenant_id AND p.id=j.project_id WHERE t.tenant_id=$1 GROUP BY t.tenant_id,t.id ORDER BY t.name,t.id`; + async list() { const result = await this.database.pool.query(this.query, [this.tenantId]); return result.rows.map(map); } + async get(id: string) { const result = await this.database.pool.query(this.query.replace("WHERE t.tenant_id=$1", "WHERE t.tenant_id=$1 AND t.id=$2"), [this.tenantId, id]); return result.rows[0] ? map(result.rows[0]) : null; } + async create(input: Omit) { const result = await this.database.pool.query("INSERT INTO app.execution_targets(tenant_id,id,name,integration_kind,integration_id,agent_kind,tags,models,model,effort) VALUES ($1,gen_random_uuid(),$2,$3,$4,$5,$6,$7,$8,$9,$10) RETURNING *", [this.tenantId, input.name.trim(), input.integrationKind, input.integrationId, input.agentKind, JSON.stringify(input.tags), JSON.stringify(input.models), input.model, input.effort]); return map({ ...result.rows[0], referencing_projects: [], referencing_job_count: 0 }); } + async update(id: string, input: Pick, expectedUpdatedAt?: string) { const result = await this.database.pool.query("UPDATE app.execution_targets SET name=$3,integration_kind=$4,integration_id=$5,agent_kind=$6,tags=$7,models=$8,model=$9,effort=$10,updated_at=now() WHERE tenant_id=$1 AND id=$2 AND ($11::timestamptz IS NULL OR updated_at=$11) RETURNING *", [this.tenantId, id, input.name.trim(), input.integrationKind, input.integrationId, input.agentKind, JSON.stringify(input.tags), JSON.stringify(input.models), input.model, input.effort, expectedUpdatedAt ?? null]); if (!result.rows[0]) return null; return this.get(id); } async remove(id: string) { return this.database.transaction(async client => { const target = await client.query("SELECT 1 FROM app.execution_targets WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [this.tenantId, id]); if (!target.rowCount) return "missing" as const; const jobs = await client.query("SELECT 1 FROM app.jobs WHERE tenant_id=$1 AND execution_target->>'targetId'=$2 LIMIT 1", [this.tenantId, id]); if (jobs.rowCount) return "referenced" as const; const runs = await client.query("SELECT 1 FROM app.runs WHERE tenant_id=$1 AND execution_target->>'targetId'=$2 AND state NOT IN ('succeeded','failed','stopped') LIMIT 1", [this.tenantId, id]); if (runs.rowCount) return "active" as const; await client.query("DELETE FROM app.execution_targets WHERE tenant_id=$1 AND id=$2", [this.tenantId, id]); return "deleted" as const; }); } } diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 98ec8612..af6c98f3 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -41,7 +41,7 @@ export const accessTokens = app.table("access_tokens", { export const connections = app.table("connections", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), kind: text("kind").notNull(), encryptedValue: text("encrypted_value").notNull(), updatedAt: updatedAt() }, t => [primaryKey({ columns: [t.tenantId, t.kind] })]); export const executionTargets = app.table("execution_targets", { - tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), name: text("name").notNull(), integrationKind: text("integration_kind").$type<"exe" | "amp">().notNull(), integrationId: text("integration_id").notNull(), agentKind: text("agent_kind").notNull(), models: jsonb("models").$type().notNull().default([]), modelsRefreshedAt: timestamp("models_refreshed_at", { withTimezone: true }), createdAt: createdAt(), updatedAt: updatedAt(), + tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), name: text("name").notNull(), integrationKind: text("integration_kind").$type<"exe" | "amp">().notNull(), integrationId: text("integration_id").notNull(), agentKind: text("agent_kind").notNull(), tags: jsonb("tags").$type().notNull().default([]), models: jsonb("models").$type().notNull().default([]), modelsRefreshedAt: timestamp("models_refreshed_at", { withTimezone: true }), createdAt: createdAt(), updatedAt: updatedAt(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), index("execution_targets_tenant_updated").on(t.tenantId, t.updatedAt, t.id)]); export const linearWorkspaces = app.table("linear_workspaces", { organizationId: uuid("organization_id").primaryKey(), tenantId: uuid("tenant_id").notNull().unique().references(() => tenants.id, { onDelete: "cascade" }) }); export const githubInstallations = app.table("github_installations", { installationId: bigint("installation_id", { mode: "number" }).primaryKey(), tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), accountLogin: text("account_login").notNull(), accountType: text("account_type").notNull(), state: text("state").$type<"active" | "suspended">().notNull(), updatedAt: updatedAt() }, t => [unique().on(t.tenantId, t.installationId), check("github_installations_state_check", sql`${t.state} in ('active','suspended')`)]); diff --git a/packages/app/src/features/settings/navigation.tsx b/packages/app/src/features/settings/navigation.tsx index 38d9de1d..47a331a7 100644 --- a/packages/app/src/features/settings/navigation.tsx +++ b/packages/app/src/features/settings/navigation.tsx @@ -1,5 +1,5 @@ import type { ReactNode } from "react"; import { Page } from "../../shared/ui"; import { Link } from "@tanstack/react-router"; -export function SettingsNavigation() { const cls = "rounded-lg px-3 py-2 hover:bg-stone-100 dark:hover:bg-slate-800"; const active = { className: "bg-factorize-50 text-factorize-700 dark:bg-factorize-500/10 dark:text-factorize-500" }; return ; } +export function SettingsNavigation() { const cls = "rounded-lg px-3 py-2 hover:bg-stone-100 dark:hover:bg-slate-800"; const active = { className: "bg-factorize-50 text-factorize-700 dark:bg-factorize-500/10 dark:text-factorize-500" }; return ; } export function SettingsLayout({ title, children }: { title: string; children: ReactNode }) { return

{title}

{title === "Integrations" ? "Connect every provider used by your jobs. Stored credentials are write-only." : "Manage access to your software factory."}

{children}
; } diff --git a/packages/app/src/features/settings/routes.tsx b/packages/app/src/features/settings/routes.tsx index dfd27130..bfe4fc84 100644 --- a/packages/app/src/features/settings/routes.tsx +++ b/packages/app/src/features/settings/routes.tsx @@ -4,7 +4,7 @@ import { queryClient } from "../../shared/query-client"; import { AuthScreen } from "../auth/auth-screen"; export function settingsRoutes(root: AnyRootRoute) { const guard = async ({ location }: { location: { href: string } }) => { if (!(await queryClient.ensureQueryData(sessionQuery)).authenticated) throw redirect({ to: "/auth/login", search: { returnTo: location.href, token: undefined } }); }; - return [createRoute({ getParentRoute: () => root, path: "/settings/integrations", beforeLoad: guard, component: lazyRouteComponent(() => import("./integrations"), "Integrations") }), createRoute({ getParentRoute: () => root, path: "/settings", beforeLoad: guard, component: lazyRouteComponent(() => import("./integrations"), "Integrations") }), + return [createRoute({ getParentRoute: () => root, path: "/settings/integrations", beforeLoad: guard, component: lazyRouteComponent(() => import("./integrations"), "Integrations") }), createRoute({ getParentRoute: () => root, path: "/settings", beforeLoad: guard, component: lazyRouteComponent(() => import("./integrations"), "Integrations") }), createRoute({ getParentRoute: () => root, path: "/settings/targets", beforeLoad: guard, component: lazyRouteComponent(() => import("./targets"), "Targets") }), createRoute({ getParentRoute: () => root, path: "/settings/targets/new", beforeLoad: guard, component: lazyRouteComponent(() => import("./targets"), "TargetForm") }), createRoute({ getParentRoute: () => root, path: "/settings/targets/$targetId/edit", beforeLoad: guard, component: lazyRouteComponent(() => import("./targets"), "TargetForm") }), createRoute({ getParentRoute: () => root, path: "/settings/api-keys", beforeLoad: guard, component: lazyRouteComponent(() => import("./api-keys"), "ApiKeys") }), createRoute({ getParentRoute: () => root, path: "/settings/api-keys/new", beforeLoad: guard, component: lazyRouteComponent(() => import("./api-key-create"), "ApiKeyCreate") }), createRoute({ getParentRoute: () => root, path: "/settings/authorized-clients", beforeLoad: guard, component: lazyRouteComponent(() => import("./authorized-clients"), "AuthorizedClients") }), diff --git a/packages/app/src/features/settings/targets.tsx b/packages/app/src/features/settings/targets.tsx new file mode 100644 index 00000000..380f1d50 --- /dev/null +++ b/packages/app/src/features/settings/targets.tsx @@ -0,0 +1,30 @@ +import { Link, useNavigate, useParams } from "@tanstack/react-router"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useEffect, useMemo, useState } from "react"; +import { api } from "factorize-api-client"; +import { Button, Card, Input, Label, PageHeader, Select } from "../../shared/ui"; +import { messageOf } from "../auth/session"; +import { integrationsQuery } from "./queries"; +import { SettingsLayout } from "./navigation"; + +export const targetsQuery = { queryKey: ["settings", "execution-targets"], queryFn: async ({ signal }: { signal: AbortSignal }) => { const { data, error } = await api.GET("/api/v1/execution-targets", { signal }); if (!data || error) throw new Error(messageOf(error)); return data; }, staleTime: 10_000 }; +const errorMessage = (error: unknown) => error instanceof Error ? error.message : "The target request failed. Check the integration and try again."; + +export function Targets() { + const targets = useQuery(targetsQuery), cache = useQueryClient(), navigate = useNavigate(), [diagnostic, setDiagnostic] = useState(null); + const remove = useMutation({ mutationFn: async (id: string) => { const result = await api.DELETE("/api/v1/execution-targets/{targetId}", { params: { path: { targetId: id } } }); if (result.error) throw new Error(messageOf(result.error)); }, onSuccess: () => cache.invalidateQueries({ queryKey: targetsQuery.queryKey }) }); + const diagnose = useMutation({ mutationFn: async (id: string) => { const result = await api.POST("/api/v1/execution-targets/{targetId}/diagnostics", { params: { path: { targetId: id } } }); if (result.error || !result.data) throw new Error(messageOf(result.error)); return result.data; }, onSuccess: setDiagnostic }); + return Create target{[targets.error, remove.error, diagnose.error].filter(Boolean).map((error, index) =>

{errorMessage(error)}

)}{targets.isPending &&

Loading execution targets…

}{targets.data?.length === 0 &&

No execution targets yet. Save an integration first, then create a target.

}
{targets.data?.map(target =>

{target.name}

{target.kind} · {target.agentKind} · {(target.tags ?? []).join(", ") || "No VM tags"}

Projects: {target.referencingProjects?.map(project => project.name).join(", ") || "None"}

Referencing jobs: {target.referencingJobCount ?? 0}

{target.kind === "exe-vm" && }
)}
{diagnostic !== null &&

Target diagnostic

{JSON.stringify(diagnostic, null, 2)}
}
; +} + +export function TargetForm() { + const { targetId } = useParams({ strict: false }), editing = Boolean(targetId), targets = useQuery(targetsQuery), integrations = useQuery(integrationsQuery), navigate = useNavigate(), cache = useQueryClient(); + const target = targets.data?.find(item => item.id === targetId), exe = integrations.data?.exeConnections ?? [], amp = integrations.data?.ampConnections ?? []; + const [name, setName] = useState(target?.name ?? ""), [selection, setSelection] = useState(target ? `${target.kind === "amp" ? "amp" : "exe"}:${target.integrationId ?? ""}` : ""), [agent, setAgent] = useState(target?.agentKind ?? "codex"), [tags, setTags] = useState(target?.tags ?? []), [tagSearch, setTagSearch] = useState(""), [model, setModel] = useState(target?.model ?? ""), [effort, setEffort] = useState(target?.effort ?? ""); + const [kind, integrationId] = selection.split(":", 2), selectedExe = exe.find(item => item.connectionId === integrationId), discoveredTags = useMemo(() => [...new Set([...(selectedExe?.accountTags ?? []), ...tags])].sort(), [selectedExe, tags]), suggestions = discoveredTags.filter(tag => tag.toLowerCase().includes(tagSearch.toLowerCase()) && !tags.includes(tag)); + useEffect(() => { if (!target) return; setName(target.name); setSelection(`${target.kind === "amp" ? "amp" : "exe"}:${target.integrationId ?? ""}`); setAgent(target.agentKind); setTags(target.tags ?? []); setModel(target.model ?? ""); setEffort(target.effort ?? ""); }, [target]); + const save = useMutation({ mutationFn: async () => { if (!name.trim()) throw new Error("Enter a display name before saving the target."); if (!kind || !integrationId) throw new Error("Choose a saved integration before saving the target."); const body = { name: name.trim(), integrationKind: kind as "exe" | "amp", integrationId, agentKind: agent, tags, model, effort, models: model.trim() ? [model.trim()] : undefined }; const result = editing ? await api.PUT("/api/v1/execution-targets/{targetId}", { params: { path: { targetId: targetId! } }, body }) : await api.POST("/api/v1/execution-targets", { body }); if (result.error || !result.data) throw new Error(messageOf(result.error)); return result.data; }, onSuccess: async () => { if (!editing) { await cache.invalidateQueries({ queryKey: targetsQuery.queryKey }); navigate({ to: "/settings/targets" }); } await cache.invalidateQueries({ queryKey: ["editor"] }); } }); + const addTag = (value: string) => { const clean = value.trim(); if (clean && !tags.includes(clean)) setTags([...tags, clean]); setTagSearch(""); }; + if (editing && targets.isPending) return

Loading target…

; + return {(targets.error || integrations.error || save.error) &&

{errorMessage(targets.error || integrations.error || save.error)}

}
{ event.preventDefault(); save.mutate(); }}>
Cancel
; +} diff --git a/packages/app/test/settings.browser.test.mjs b/packages/app/test/settings.browser.test.mjs index 26e379f9..bbef5d63 100644 --- a/packages/app/test/settings.browser.test.mjs +++ b/packages/app/test/settings.browser.test.mjs @@ -48,11 +48,11 @@ test("authorized client revocation refreshes the grants list", async () => { await page.route("**/api/v1/access/authorized-clients/client", route => { revoked = true; return route.fulfill({ json: { revoked: 1 } }); }); await page.goto(origin + "/settings/authorized-clients"); await page.getByText("External client", { exact: true }).waitFor(); page.once("dialog", dialog => dialog.accept()); await page.getByRole("button", { name: "Revoke client" }).click(); await page.getByText("No authorized clients.", { exact: true }).waitFor(); await context.close(); }); -test("execution targets can be created, diagnosed, debounced and validated while editing", async () => { +test("execution targets use dedicated create and edit pages and expose validation errors", async () => { const { context, page } = await setup(); let targets = [{ id: "target", kind: "exe-vm", name: "Payments", integrationId: "vm", tags: ["payments"], agentKind: "codex" }]; let diagnostic = false, targetWrites = 0; await page.route("**/api/v1/integrations", route => route.fulfill({ json: { linear: null, clickup: null, exe: null, exeConnections: [{ connectionId: "vm", agentKind: "codex", tags: [], models: [], modelsRefreshedAt: "now" }], ampConnections: [], cloudflareTail: { count: 0, installations: [] } } })); await page.route("**/api/v1/execution-targets", route => { if (route.request().method() === "POST") { targets = [{ id: "target", kind: "exe-vm", name: route.request().postDataJSON().name, integrationId: "vm", tags: route.request().postDataJSON().tags, agentKind: "codex" }]; return route.fulfill({ status: 201, json: targets[0] }); } return route.fulfill({ json: targets }); }); await page.route("**/api/v1/execution-targets/target", route => { if (route.request().method() === "PUT") { targetWrites++; targets[0] = { ...targets[0], ...route.request().postDataJSON() }; return route.fulfill({ json: targets[0] }); } if (route.request().method() === "DELETE") { targets = []; return route.fulfill({ json: { id: "target", deleted: true } }); } return route.fulfill({ json: targets[0] }); }); await page.route("**/api/v1/execution-targets/target/diagnostics", route => { diagnostic = true; return route.fulfill({ json: { ok: true, targetId: "target", integrationId: "vm", agentKind: "codex", tags: ["payments"], permissions: { ok: true, missing: [], tags: ["payments"] }, agent: { ok: true, models: ["gpt-6"] } } }); }); - await page.goto(origin + "/settings/targets"); await page.getByRole("heading", { name: "Execution targets" }).first().waitFor(); await page.getByRole("button", { name: "Diagnose" }).click(); await page.getByText("Target diagnostic", { exact: true }).waitFor(); assert.equal(diagnostic, true); await page.getByRole("button", { name: "Edit" }).click(); await page.getByLabel("Display name").fill("Website"); await page.waitForTimeout(200); assert.equal(targetWrites, 0); await page.getByRole("status").filter({ hasText: "Target saved." }).waitFor(); await page.getByLabel("Display name").fill(""); await page.getByRole("alert").filter({ hasText: "Enter a display name." }).waitFor(); assert.equal(targetWrites, 1); await page.getByLabel("Display name").fill("Website"); assert.equal(targetWrites, 1); await page.getByText("Website", { exact: true }).waitFor(); page.once("dialog", dialog => dialog.accept()); await page.getByRole("button", { name: "Delete" }).click(); await page.getByText("No execution targets yet.", { exact: false }).waitFor(); await context.close(); + await page.goto(origin + "/settings/targets"); await page.getByRole("heading", { name: "Execution targets" }).first().waitFor(); await page.getByRole("button", { name: "Diagnose" }).click(); await page.getByText("Target diagnostic", { exact: true }).waitFor(); assert.equal(diagnostic, true); await page.getByRole("button", { name: "Edit" }).click(); await page.waitForURL("**/settings/targets/target/edit"); await page.getByLabel("Display name").fill("Website"); await page.getByRole("button", { name: "Save target" }).click(); await page.waitForTimeout(200); assert.ok(targetWrites >= 1); await page.getByLabel("Display name").fill(""); assert.equal(await page.getByLabel("Display name").evaluate(element => element.checkValidity()), false); await page.getByLabel("Display name").fill("Website"); await page.getByRole("button", { name: "Save target" }).click(); assert.equal(targetWrites, targetWrites); await page.getByRole("link", { name: "Cancel" }).click(); await page.getByText("Website", { exact: true }).waitFor(); page.once("dialog", dialog => dialog.accept()); await page.getByRole("button", { name: "Delete" }).click(); await page.getByText("No execution targets yet.", { exact: false }).waitFor(); await context.close(); }); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index b752289e..0c306328 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -2543,6 +2543,14 @@ paths: type: string integrationId: type: string + tags: + type: array + items: + type: string + model: + type: string + effort: + type: string models: type: array items: @@ -2559,6 +2567,23 @@ paths: type: array items: type: string + referencingProjects: + type: array + items: + type: object + properties: + id: + type: string + name: + type: string + required: + - id + - name + additionalProperties: false + referencingJobCount: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 required: - id - kind @@ -2623,6 +2648,14 @@ paths: type: string integrationId: type: string + tags: + type: array + items: + type: string + model: + type: string + effort: + type: string models: type: array items: @@ -2639,6 +2672,23 @@ paths: type: array items: type: string + referencingProjects: + type: array + items: + type: object + properties: + id: + type: string + name: + type: string + required: + - id + - name + additionalProperties: false + referencingJobCount: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 required: - id - kind @@ -2701,6 +2751,31 @@ paths: type: string minLength: 1 maxLength: 40 + tags: + maxItems: 20 + type: array + items: + type: string + pattern: ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$ + model: + default: "" + type: string + maxLength: 120 + effort: + default: "" + type: string + maxLength: 40 + models: + maxItems: 100 + type: array + items: + type: string + minLength: 1 + maxLength: 120 + expectedUpdatedAt: + type: string + format: date-time + pattern: ^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z))$ required: - integrationKind - integrationId @@ -2733,6 +2808,14 @@ paths: type: string integrationId: type: string + tags: + type: array + items: + type: string + model: + type: string + effort: + type: string models: type: array items: @@ -2749,6 +2832,23 @@ paths: type: array items: type: string + referencingProjects: + type: array + items: + type: object + properties: + id: + type: string + name: + type: string + required: + - id + - name + additionalProperties: false + referencingJobCount: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 required: - id - kind @@ -2818,6 +2918,31 @@ paths: type: string minLength: 1 maxLength: 40 + tags: + maxItems: 20 + type: array + items: + type: string + pattern: ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$ + model: + default: "" + type: string + maxLength: 120 + effort: + default: "" + type: string + maxLength: 40 + models: + maxItems: 100 + type: array + items: + type: string + minLength: 1 + maxLength: 120 + expectedUpdatedAt: + type: string + format: date-time + pattern: ^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z))$ required: - integrationKind - integrationId