From 1ad5506e9f6d581cd0c6f1afbc2202eed10b1672 Mon Sep 17 00:00:00 2001 From: Brendan Date: Thu, 17 Sep 2026 23:30:13 +0000 Subject: [PATCH] Refine exe.dev VM integrations --- packages/app/src/exe-vm-backend.ts | 37 ++++++++++-- packages/app/src/exe.ts | 5 +- packages/app/src/index.ts | 8 ++- packages/app/src/tenant.ts | 63 +++++++++++++-------- packages/app/src/types.ts | 7 --- packages/app/src/ui.ts | 19 ++++--- packages/app/test/execution-backend.test.ts | 17 +++++- packages/app/test/ui.test.ts | 21 +++++-- 8 files changed, 125 insertions(+), 52 deletions(-) diff --git a/packages/app/src/exe-vm-backend.ts b/packages/app/src/exe-vm-backend.ts index ca53caef..16eb0e81 100644 --- a/packages/app/src/exe-vm-backend.ts +++ b/packages/app/src/exe-vm-backend.ts @@ -1,6 +1,6 @@ import type { BackendCommandResult, ExecutionBackend, ExecutionObservation, LaunchReceipt, LaunchRequest, RunHandle } from "./execution"; import { base64 } from "./crypto"; -import { defaultAgentCommand, shellAtom, type ExeConnection } from "./exe"; +import { defaultAgentCommand, shellAtom, type ExeConnection, type ExeRunConnection } from "./exe"; const API = "https://exe.dev/exec"; const capabilities = ["output", "recovery", "stop"] as const; @@ -20,18 +20,32 @@ function shellWords(value: string): string[] { return words; } -function agentCommand(connection: ExeConnection): string { +function agentCommand(connection: ExeRunConnection): string { const args = shellWords(connection.agentCommand?.trim() || defaultAgentCommand(connection.agentKind)); if (connection.model?.trim()) args.push("--model", connection.model.trim()); if (connection.effort?.trim() && connection.agentKind === "codex") args.push("-c", `model_reasoning_effort=${connection.effort.trim()}`); return args.map(shellAtom).join(" "); } +export interface ExePermissionTest { ok: boolean; missingPermissions: string[]; tags: string[]; checks: BackendCommandResult[] } + +export function tagsFromInventory(inventory: unknown): string[] { + const tags = new Set(); + const visit = (value: unknown, key?: string): void => { + if (typeof value === "string" && value.startsWith("tag:") && value.length > 4) { tags.add(value.slice(4)); return; } + if (Array.isArray(value)) { if (key === "tags") value.forEach(tag => typeof tag === "string" && tags.add(tag)); else value.forEach(item => visit(item)); return; } + if (!value || typeof value !== "object") return; + Object.entries(value as Record).forEach(([name, item]) => visit(item, name)); + }; + visit(inventory); + return [...tags].sort((a, b) => a.localeCompare(b)); +} + export class ExeVmBackend implements ExecutionBackend { readonly kind = "exe-vm"; readonly capabilities = capabilities; - constructor(private readonly connection: ExeConnection) {} + constructor(private readonly connection: ExeConnection | ExeRunConnection) {} private async api(command: string): Promise { const response = await fetch(API, { method: "POST", headers: { Authorization: `Bearer ${this.connection.apiToken}`, "Content-Type": "text/plain" }, body: command }); @@ -40,9 +54,20 @@ export class ExeVmBackend implements ExecutionBackend { return { body, status: response.status, exitCode, ok: response.ok && (exitCode === null || exitCode === 0), requestBody: command }; } + async testPermissions(): Promise { + const commands = ["ls --json", "integrations list --json", "new --help", "ssh --help", "rm --help"]; + const checks = await Promise.all(commands.map(command => this.api(command))); + let tags: string[] = []; + for (const check of checks.slice(0, 2)) if (check.ok) try { tags.push(...tagsFromInventory(JSON.parse(check.body))); } catch { /* use the remaining tag source */ } + tags = [...new Set(tags)].sort((a, b) => a.localeCompare(b)); + return { ok: checks.every(check => check.ok), missingPermissions: checks.filter(check => !check.ok).map(check => String(check.requestBody).split(" ")[0]), tags, checks }; + } + async test(): Promise { return this.api("ls --json"); } async launch(request: LaunchRequest): Promise { + const connection = this.connection as ExeRunConnection; + if (!connection.agentKind || !connection.repositoryUrl) throw new Error("The job is missing its agent or repository configuration"); const vm = vmNameFor(request.runId); const tags = [...new Set(this.connection.tags)].map(tag => `--tag=${shellAtom(tag)}`).join(" "); const created = await this.api(`new --name=${shellAtom(vm)} --no-email --comment=${shellAtom(`Factorize VM ${vm}`)} ${tags}`.trim()); @@ -52,15 +77,15 @@ export class ExeVmBackend implements ExecutionBackend { } const prompt = base64(request.prompt), output = "/tmp/factorize.log", status = "/tmp/factorize.status"; - const checkout = this.connection.checkoutRef ? ` && git checkout --detach ${shellAtom(this.connection.checkoutRef)}` : ""; + const checkout = connection.checkoutRef ? ` && git checkout --detach ${shellAtom(connection.checkoutRef)}` : ""; const work = [ "set -eu", "mkdir -p /workspace", "cd /workspace", - `git clone -- ${shellAtom(this.connection.repositoryUrl)} repo`, + `git clone -- ${shellAtom(connection.repositoryUrl)} repo`, `cd repo${checkout}`, `printf '%s' ${shellAtom(prompt)} | base64 -d > /tmp/factorize-prompt.md`, - `setsid nohup sh -c ${shellAtom(`set +e; ${agentCommand(this.connection)} < /tmp/factorize-prompt.md > ${output} 2>&1; code=$?; printf '%s' "$code" > ${status}`)} >/dev/null 2>&1 &`, + `setsid nohup sh -c ${shellAtom(`set +e; ${agentCommand(connection)} < /tmp/factorize-prompt.md > ${output} 2>&1; code=$?; printf '%s' "$code" > ${status}`)} >/dev/null 2>&1 &`, "echo started", ].join(" && "); let started = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(work)}`); diff --git a/packages/app/src/exe.ts b/packages/app/src/exe.ts index d978530d..c0550729 100644 --- a/packages/app/src/exe.ts +++ b/packages/app/src/exe.ts @@ -1,7 +1,10 @@ export interface ExeConnection { apiToken: string; - agentKind: string; tags: string[]; +} + +export interface ExeRunConnection extends ExeConnection { + agentKind: string; repositoryUrl: string; checkoutRef?: string; agentCommand?: string; diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 1d310332..3e532f63 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -276,9 +276,9 @@ app.post("/api/connections/exe/test", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); return tenant(c, session.tenantId).fetch("https://tenant/connections/exe/test", { method: "POST", headers: { "Content-Type": "application/json" }, body: await c.req.text() }); }); -app.post("/api/connections/exe/:id/models", async (c) => { +app.delete("/api/connections/exe/:id", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return tenant(c, session.tenantId).fetch(`https://tenant/connections/exe/${encodeURIComponent(c.req.param("id"))}/models`, { method: "POST" }); + return tenant(c, session.tenantId).fetch(`https://tenant/connections/exe/${encodeURIComponent(c.req.param("id"))}`, { method: "DELETE" }); }); app.put("/api/connections/amp", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); @@ -288,6 +288,10 @@ app.post("/api/connections/amp/test", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); return tenant(c, session.tenantId).fetch("https://tenant/connections/amp/test", { method: "POST", headers: { "Content-Type": "application/json" }, body: await c.req.text() }); }); +app.delete("/api/connections/amp/:id", async (c) => { + const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); + return tenant(c, session.tenantId).fetch(`https://tenant/connections/amp/${encodeURIComponent(c.req.param("id"))}`, { method: "DELETE" }); +}); app.post("/webhooks/cloudflare/:tenantId/:jobId", async (c) => { const raw = await c.req.text(); if (new TextEncoder().encode(raw).byteLength > 262_144) return c.text("Payload too large", 413); diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index 374b51f7..6a294eb4 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -1,7 +1,7 @@ import { DurableObject } from "cloudflare:workers"; import Mustache from "mustache"; import { decrypt, encrypt, equalHmac } from "./crypto"; -import { defaultAgentCommand, type ExeConnection } from "./exe"; +import { defaultAgentCommand, type ExeConnection, type ExeRunConnection } from "./exe"; import { LINEAR_ISSUE_PROJECT_QUERY, LINEAR_OPTION_QUERIES, LINEAR_PROJECTS_QUERY, isLinearAuthenticationError, refreshLinearToken } from "./linear"; import { matchingIssue } from "./matcher"; import type { AmpConnectionInput, Env, ExeConnectionInput, FilterType, MatchRule, RunState, TailIntegrationInput } from "./types"; @@ -245,9 +245,13 @@ export class TenantV2 extends DurableObject { if (request.method === "PUT" && url.pathname === "/connections/clickup") return await this.saveClickUp(await request.json()); if (request.method === "PUT" && url.pathname === "/connections/exe") return await this.saveExe(await request.json()); if (request.method === "POST" && url.pathname === "/connections/exe/test") return await this.testExe(await request.json()); + const exeConnectionMatch = url.pathname.match(/^\/connections\/exe\/([^/]+)$/); + if (request.method === "DELETE" && exeConnectionMatch) return await this.removeExecutionConnection("exe", decodeURIComponent(exeConnectionMatch[1])); if (request.method === "POST" && url.pathname === "/authorize") return this.authorize(await request.json()); if (request.method === "PUT" && url.pathname === "/connections/amp") return await this.saveAmp(await request.json()); if (request.method === "POST" && url.pathname === "/connections/amp/test") return await this.testAmp(await request.json()); + const ampConnectionMatch = url.pathname.match(/^\/connections\/amp\/([^/]+)$/); + if (request.method === "DELETE" && ampConnectionMatch) return await this.removeExecutionConnection("amp", decodeURIComponent(ampConnectionMatch[1])); if (request.method === "GET" && url.pathname === "/connections/cloudflare-tail") return json(await this.tailIntegrationStatus()); if (request.method === "POST" && url.pathname === "/connections/cloudflare-tail") return await this.saveTailIntegration(await request.json()); const tailConnectionMatch = url.pathname.match(/^\/connections\/cloudflare-tail\/([^/]+)$/); @@ -327,14 +331,12 @@ export class TenantV2 extends DurableObject { private async saveExe(input: unknown): Promise { const value = input as ExeConnectionInput; - if (!value.apiToken || !value.agentKind || !value.repositoryUrl) throw new Error("An account-level exe.dev token, repository URL, and agent are required"); + if (!value.apiToken) throw new Error("An account-level exe.dev HTTPS token is required"); const tags = Array.isArray(value.tags) ? value.tags.map(tag => String(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 may contain only letters, numbers, dot, underscore, colon, and hyphen"); - if (!/^https:\/\//i.test(value.repositoryUrl) || value.repositoryUrl.length > 2000) throw new Error("Repository URL must be an HTTPS URL"); - if (value.checkoutRef && (value.checkoutRef.length > 255 || /[\0\r\n]/.test(value.checkoutRef))) throw new Error("Checkout ref is invalid"); - const saved: ExeConnection = { ...value, tags, models: value.models ?? [] }; - const verification = await new ExeVmBackend(saved).test(); - if (!verification.ok) throw new Error(`exe.dev account verification failed (${verification.status}): ${verification.body.slice(0, 300)}`); + const saved: ExeConnection = { apiToken: value.apiToken, tags }; + const verification = await new ExeVmBackend(saved).testPermissions(); + if (!verification.ok) throw new Error(`exe.dev token is missing required permissions: ${verification.missingPermissions.join(", ")}`); const connectionId = value.connectionId || id(); await this.putConnection(`exe:${connectionId}`, saved); // Preserve the most recently saved connection for existing flows created @@ -347,9 +349,21 @@ export class TenantV2 extends DurableObject { const supplied = input as Partial; const saved = supplied.connectionId ? await this.exeConnection(supplied.connectionId) : await this.connection("exe"); const connection = supplied.apiToken ? supplied as ExeConnection : saved; - if (!connection?.apiToken || !connection.repositoryUrl) throw new Error("Account token and repository URL are required"); - const result = await new ExeVmBackend(connection).test(); - return json({ ok: result.ok && (result.exitCode === null || result.exitCode === 0), httpStatus: result.status, exitCode: result.exitCode, command: result.requestBody, output: result.body }); + if (!connection?.apiToken) throw new Error("Account-level exe.dev HTTPS token is required"); + const result = await new ExeVmBackend(connection).testPermissions(); + return json({ 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 })) }); + } + + private async removeExecutionConnection(kind: "exe" | "amp", connectionId: string): Promise { + const referenced = this.rows("SELECT id,execution_target FROM jobs").some(row => { + try { const target = JSON.parse(String(row.execution_target)); return target.backendKind === (kind === "exe" ? "exe-vm" : "amp") && String(target.connectionId) === connectionId; } catch { return false; } + }); + if (referenced) return Response.json({ error: "This integration is used by one or more jobs. Change or remove those jobs first." }, { status: 409 }); + if (kind === "exe" && this.one("SELECT id FROM pipes WHERE exe_connection_id=?", connectionId)) return Response.json({ error: "This integration is used by a legacy flow. Remove that flow first." }, { status: 409 }); + const result = this.ctx.storage.sql.exec("DELETE FROM connections WHERE kind=?", `${kind}:${connectionId}`); + if (!Number(result.rowsWritten)) return new Response("Not found", { status: 404 }); + if (kind === "exe" && !this.one("SELECT kind FROM connections WHERE kind LIKE 'exe:%'")) this.ctx.storage.sql.exec("DELETE FROM connections WHERE kind='exe'"); + return new Response(null, { status: 204 }); } private async saveAmp(input: unknown): Promise { @@ -429,7 +443,7 @@ export class TenantV2 extends DurableObject { // App-wide webhook verification is performed at the Worker edge before reaching this object. this.ctx.storage.sql.exec( "INSERT INTO pipes (id,name,project_id,team_id,filter_type,filter_target_id,max_concurrency,capability,webhook_id,signing_secret,workspace_name,agent_kind,context_template,match_rules,exe_connection_id,cwd,source_kind,source_config,trigger_kind,trigger_config,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", - pipeId, input.name, source.kind === "linear" ? source.projectId : "", "", rules[0].type, rules[0].targetId, maxConcurrency, "app-webhook", null, "app-webhook", workspaceName, exe.agentKind, source.kind !== "github" ? this.contextTemplate(input.contextTemplate) : "", JSON.stringify(rules), input.exeConnectionId || "default", cwd, source.kind, JSON.stringify(source), source.kind === "github" ? source.trigger : source.kind === "custom" ? "custom_handler" : "linear_match", "{}", now(), + pipeId, input.name, source.kind === "linear" ? source.projectId : "", "", rules[0].type, rules[0].targetId, maxConcurrency, "app-webhook", null, "app-webhook", workspaceName, "codex", source.kind !== "github" ? this.contextTemplate(input.contextTemplate) : "", JSON.stringify(rules), input.exeConnectionId || "default", cwd, source.kind, JSON.stringify(source), source.kind === "github" ? source.trigger : source.kind === "custom" ? "custom_handler" : "linear_match", "{}", now(), ); return Response.json({ id: pipeId }, { status: 201 }); } @@ -448,7 +462,7 @@ export class TenantV2 extends DurableObject { const cwd = this.cwdTemplate(input.cwd ?? "/workspace/repo", flowId); this.ctx.storage.sql.exec( "UPDATE pipes SET name=?, project_id=?, filter_type=?, filter_target_id=?, max_concurrency=?, workspace_name=?, agent_kind=?, context_template=?, match_rules=?, exe_connection_id=?, cwd=?, source_kind=?, source_config=?, trigger_kind=?, trigger_config=? WHERE id=?", - input.name, source.kind === "linear" ? source.projectId : "", rules[0].type, rules[0].targetId, maxConcurrency, workspaceName, exe.agentKind, source.kind !== "github" ? this.contextTemplate(input.contextTemplate) : "", JSON.stringify(rules), input.exeConnectionId || "default", cwd, source.kind, JSON.stringify(source), source.kind === "github" ? source.trigger : source.kind === "custom" ? "custom_handler" : "linear_match", "{}", pipeId, + input.name, source.kind === "linear" ? source.projectId : "", rules[0].type, rules[0].targetId, maxConcurrency, workspaceName, "codex", source.kind !== "github" ? this.contextTemplate(input.contextTemplate) : "", JSON.stringify(rules), input.exeConnectionId || "default", cwd, source.kind, JSON.stringify(source), source.kind === "github" ? source.trigger : source.kind === "custom" ? "custom_handler" : "linear_match", "{}", pipeId, ); return json({ id: pipeId, ok: true }); } @@ -463,7 +477,7 @@ export class TenantV2 extends DurableObject { return json({ linear: linear ? { organizationName: linear.organizationName ?? null, viewerEmail: linear.viewerEmail ?? null } : null, clickup: clickup ? { teamName: clickup.teamName ?? null } : null, - exe: exe ? { agentKind: exe.agentKind, repositoryUrl: exe.repositoryUrl, checkoutRef: exe.checkoutRef ?? null, tags: exe.tags ?? [] } : null, + exe: exe ? { tags: exe.tags ?? [] } : null, exeConnections: connections.map(({ apiToken, ...connection }) => connection), ampConnections: ampConnections.map(({ accessToken, ...connection }) => connection), cloudflareTail: { count: tailInstallations.length, installations: await this.tailIntegrationStatus(tailInstallations) }, @@ -479,10 +493,7 @@ export class TenantV2 extends DurableObject { name: "Ephemeral exe.dev VMs", workspace: "ephemeral", cwd: "/workspace/repo", - agentKind: connection.agentKind, - models: connection.models ?? [], - modelsRefreshedAt: connection.modelsRefreshedAt ?? null, - efforts: connection.efforts ?? (connection.agentKind === "codex" ? ["minimal", "low", "medium", "high", "xhigh"] : []), + agents: ["codex", "claude"], capabilities: ["output", "recovery", "stop"], })), ...ampConnections.map(connection => ({ id: `amp:${connection.connectionId}`, kind: "amp", name: `Amp · ${connection.project}`, workspace: connection.project, cwd: "Cloud orb", agentKind: "Amp", capabilities: ["stop"] }))]); } @@ -494,7 +505,7 @@ export class TenantV2 extends DurableObject { if (!job) return undefined; let target: Record = {}; try { target = JSON.parse(String(job.execution_target)); } catch { return undefined; } - return { id: job.id, name: job.name, max_concurrency: job.concurrency_limit, workspace_name: job.slug, agent_kind: target.agentKind, model: target.model ?? "", effort: target.effort ?? "", cwd: target.cwd, execution_backend_kind: target.backendKind ?? "exe-vm", execution_connection_id: target.connectionId, exe_connection_id: target.connectionId, enabled: job.enabled }; + return { id: job.id, name: job.name, max_concurrency: job.concurrency_limit, workspace_name: job.slug, agent_kind: target.agentKind, model: target.model ?? "", effort: target.effort ?? "", cwd: target.cwd, repository_url: target.repositoryUrl, checkout_ref: target.checkoutRef, execution_backend_kind: target.backendKind ?? "exe-vm", execution_connection_id: target.connectionId, exe_connection_id: target.connectionId, enabled: job.enabled }; } private async publicJobs(rows: Row[]): Promise[]> { @@ -560,6 +571,9 @@ export class TenantV2 extends DurableObject { runNameTemplate: row.encrypted_run_name_template ? await decrypt(String(row.encrypted_run_name_template), this.env.CREDENTIAL_ENCRYPTION_KEY) : "", model: String(executionTarget.model ?? ""), effort: String(executionTarget.effort ?? ""), + agentKind: String(executionTarget.agentKind ?? ""), + repositoryUrl: String(executionTarget.repositoryUrl ?? ""), + checkoutRef: String(executionTarget.checkoutRef ?? ""), concurrencyLimit: Number(row.concurrency_limit), runningCount: Number(runSummary?.running_count ?? 0), maxConcurrency: Number(row.concurrency_limit), @@ -580,7 +594,7 @@ export class TenantV2 extends DurableObject { } const target = (await this.exeConnections()).find(item => item.connectionId === targetId); if (!target) throw new Error("Execution target not found"); - return { connectionId: target.connectionId, backendKind: "exe-vm", workspace: "ephemeral", cwd: "/workspace/repo", agentKind: target.agentKind }; + return { connectionId: target.connectionId, backendKind: "exe-vm", workspace: "ephemeral", cwd: "/workspace/repo" }; } private validateJobInput(input: any): void { @@ -588,6 +602,9 @@ export class TenantV2 extends DurableObject { if (!JOB_SLUG.test(String(input.slug ?? ""))) throw new Error("Job slug must start with a lowercase letter and contain only lowercase letters, digits, hyphens, or underscores (30 characters maximum)."); if (input.model !== undefined && (typeof input.model !== "string" || input.model.trim().length > 120)) throw new Error("Job model must be a string of 120 characters or fewer"); if (input.effort !== undefined && (typeof input.effort !== "string" || input.effort.trim().length > 40)) throw new Error("Job effort must be a string of 40 characters or fewer"); + if (!input.executionTargetId?.startsWith?.("amp:") && !["codex", "claude"].includes(input.agentKind)) throw new Error("Choose a supported agent"); + if (!input.executionTargetId?.startsWith?.("amp:") && (!/^https:\/\//i.test(input.repositoryUrl) || input.repositoryUrl.length > 2000)) throw new Error("Repository URL must be an HTTPS URL"); + if (input.checkoutRef && (String(input.checkoutRef).length > 255 || /[\0\r\n]/.test(String(input.checkoutRef)))) throw new Error("Checkout ref is invalid"); if (!Array.isArray(input.triggers) || input.triggers.some((trigger: any) => !["manual", "schedule", "webhook", "jobLifecycle"].includes(trigger?.kind))) throw new Error("Job triggers are invalid"); Mustache.parse(input.promptTemplate); if (input.runNameTemplate !== undefined) Mustache.parse(String(input.runNameTemplate)); @@ -675,7 +692,7 @@ export class TenantV2 extends DurableObject { this.validateJobInput(input); if (this.one("SELECT id FROM jobs WHERE slug=?", input.slug)) throw new Error("Job slug is already in use"); await this.validateProviderIntegrations(input.triggers); - const target = { ...await this.jobTarget(input.executionTargetId), model: text(input.model).trim(), effort: text(input.effort).trim() }, jobId = id(), timestamp = now(); + const target = { ...await this.jobTarget(input.executionTargetId), agentKind: text(input.agentKind).trim(), repositoryUrl: text(input.repositoryUrl).trim(), checkoutRef: text(input.checkoutRef).trim(), model: text(input.model).trim(), effort: text(input.effort).trim() }, jobId = id(), timestamp = now(); const triggers = this.normalizedTriggers(input.triggers); this.validateLifecycleGraph(jobId, triggers); this.ctx.storage.sql.exec("INSERT INTO jobs (id,name,slug,encrypted_prompt_template,encrypted_run_name_template,execution_target,concurrency_limit,enabled,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?)", jobId, input.name, input.slug, await encrypt(input.promptTemplate, this.env.CREDENTIAL_ENCRYPTION_KEY), await encrypt(String(input.runNameTemplate ?? ""), this.env.CREDENTIAL_ENCRYPTION_KEY), JSON.stringify(target), input.concurrencyLimit, 1, timestamp, timestamp); @@ -697,7 +714,7 @@ export class TenantV2 extends DurableObject { await this.validateProviderIntegrations(input.triggers, existing); const triggers = this.normalizedTriggers(input.triggers, existing); this.validateLifecycleGraph(jobId, triggers); - const target = { ...await this.jobTarget(input.executionTargetId), model: text(input.model).trim(), effort: text(input.effort).trim() }, timestamp = now(); + const target = { ...await this.jobTarget(input.executionTargetId), agentKind: text(input.agentKind).trim(), repositoryUrl: text(input.repositoryUrl).trim(), checkoutRef: text(input.checkoutRef).trim(), model: text(input.model).trim(), effort: text(input.effort).trim() }, timestamp = now(); this.ctx.storage.sql.exec("UPDATE jobs SET name=?,slug=?,encrypted_prompt_template=?,encrypted_run_name_template=?,execution_target=?,concurrency_limit=?,updated_at=? WHERE id=?", input.name, input.slug, await encrypt(input.promptTemplate, this.env.CREDENTIAL_ENCRYPTION_KEY), await encrypt(String(input.runNameTemplate ?? ""), this.env.CREDENTIAL_ENCRYPTION_KEY), JSON.stringify(target), input.concurrencyLimit, timestamp, jobId); const retained = new Set(); for (const trigger of triggers) { @@ -1624,10 +1641,10 @@ export class TenantV2 extends DurableObject { return Promise.all(rows.map(async row => ({ ...(JSON.parse(await decrypt(String(row.value), this.env.CREDENTIAL_ENCRYPTION_KEY)) as AmpConnection), connectionId: String(row.kind).slice(4) }))); } - private async connectionForPipe(pipe: Row): Promise { + private async connectionForPipe(pipe: Row): Promise { const connection = await this.exeConnection(String(pipe.exe_connection_id || "default")); if (!connection) return null; - return { ...connection, model: String(pipe.model ?? ""), effort: String(pipe.effort ?? "") }; + return { ...connection, agentKind: String(pipe.agent_kind ?? ""), repositoryUrl: String(pipe.repository_url ?? ""), checkoutRef: String(pipe.checkout_ref ?? "") || undefined, model: String(pipe.model ?? ""), effort: String(pipe.effort ?? "") }; } private async upsertMember(input: unknown): Promise { diff --git a/packages/app/src/types.ts b/packages/app/src/types.ts index dddf34f2..5e542ac2 100644 --- a/packages/app/src/types.ts +++ b/packages/app/src/types.ts @@ -52,14 +52,7 @@ export interface WorkItem { export interface ExeConnectionInput { connectionId?: string; apiToken: string; - agentKind: "claude" | "codex" | "pi" | string; tags?: string[]; - repositoryUrl: string; - checkoutRef?: string; - agentCommand?: string; - models?: string[]; - modelsRefreshedAt?: string; - efforts?: string[]; } export interface AmpConnectionInput { connectionId?: string; accessToken: string; project: string; apiBaseUrl?: string; } diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index 5f63a3d2..474e84a5 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -95,7 +95,7 @@ export const jobPage = (viewer: { email: string }, jobId?: string) => shell(`${j

Step 1

Job details

Name this job and set how many runs it can process at once.

Step 2

Triggers

Choose the events that start this job and expose prompt context.

Context slugTypeConfigurationEnabledActions

Step 3

Prompt and context

Write the instructions for each run using context supplied by your triggers.

-

Step 4

Execution target

Select the connected environment, model, and effort that will run this job.

+

Step 4

Execution target

Select the VM connection and configure the agent and repository for this job.

Add trigger

Provider credentials stay managed by Factorize.

@@ -136,7 +136,7 @@ $('#context-paths').addEventListener('click',e=>{const hint=e.target.closest('[d function nextSlug(){let n=1;while(reservedSlugs.has('trigger-'+n))n++;const slug='trigger-'+n;reservedSlugs.add(slug);return slug} async function repositories(installationId){const key=String(installationId);if(resources.repositories.has(key))return resources.repositories.get(key);const response=await fetch('/api/github/installations/'+encodeURIComponent(key)+'/repositories');const items=response.ok?await response.json():[];resources.repositories.set(key,items);return items} function options(select,items,label,value='id'){select.replaceChildren(...items.map(x=>new Option(x[label]||x.name,String(x[value]))))} -function syncModels(selected=form.model.value,selectedEffort=form.effort.value){const target=resources.targets.find(x=>String(x.id)===form.executionTargetId.value),models=target?.models||[],efforts=target?.efforts||[];form.model.replaceChildren(new Option('Harness default',''),...models.map(value=>new Option(value,value)));form.model.disabled=target?.kind==='amp';form.model.value=form.model.disabled?'':selected;if(selected&&!form.model.value){form.model.append(new Option(selected+' (unavailable)',selected));form.model.value=selected}form.effort.replaceChildren(new Option('Harness default',''),...efforts.map(value=>new Option(value,value)));form.effort.disabled=form.model.disabled||!efforts.length;form.effort.value=form.effort.disabled?'':selectedEffort;$('#model-help').textContent=form.model.disabled?'This target manages its model in Amp.':models.length?'Models cached from this connection. Refresh them in Settings → Integrations.':'No models are cached for this connection. Refresh them in Settings → Integrations.';$('#effort-help').textContent=efforts.length?'Select the harness reasoning effort.':'This harness does not expose effort selection.'} +function syncModels(selected=form.model.value,selectedEffort=form.effort.value){const amp=resources.targets.find(x=>String(x.id)===form.executionTargetId.value)?.kind==='amp';for(const name of ['agentKind','repositoryUrl','checkoutRef','model','effort'])form.elements[name].disabled=amp;form.repositoryUrl.required=!amp;form.model.value=amp?'':selected;form.effort.value=amp?'':selectedEffort;$('#model-help').textContent=amp?'This target manages its agent and model in Amp.':'Leave blank to let the selected harness choose.';$('#effort-help').textContent=amp?'This target manages effort in Amp.':'Codex reasoning effort.'} // Select the connected environment and model that will run this job. syncModels(current?.model||'') async function syncRepositories(selected){const install=triggerForm.elements.installationId.value,repos=await repositories(install);options(triggerForm.elements.repositoryId,repos,'fullName');if(selected)triggerForm.elements.repositoryId.value=String(selected)} function linearRuleRows(){return [...$('#linear-rules').querySelectorAll('[data-linear-rule]')]} @@ -160,10 +160,10 @@ $('#trigger-rows').onchange=e=>{if(e.target.dataset.enable===undefined)return;tr 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/v1/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,clickupLists,installResponse,tails,jobs,current]=await Promise.all([request('/api/v1/execution-targets'),request('/api/linear/projects').catch(()=>[]),request('/api/linear/options').catch(()=>({statuses:[]})),request('/api/clickup/lists').catch(()=>[]),fetch('/api/github/installations'),request('/api/connections/cloudflare-tail').catch(()=>[]),request('/api/v1/jobs'),jobId?request('/api/v1/jobs/'+encodeURIComponent(jobId)):null]);resources.targets=targets;resources.projects=projects;resources.options=linearOptions;resources.clickupLists=clickupLists;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.slug.value=current.slug;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:{}}];syncModels(current?.model||'',current?.effort||'');highlightPrompt();reservedSlugs=new Set(triggers.map(t=>t.slug));await refreshAvailability();render()} +async function init(){const [targets,projects,linearOptions,clickupLists,installResponse,tails,jobs,current]=await Promise.all([request('/api/v1/execution-targets'),request('/api/linear/projects').catch(()=>[]),request('/api/linear/options').catch(()=>({statuses:[]})),request('/api/clickup/lists').catch(()=>[]),fetch('/api/github/installations'),request('/api/connections/cloudflare-tail').catch(()=>[]),request('/api/v1/jobs'),jobId?request('/api/v1/jobs/'+encodeURIComponent(jobId)):null]);resources.targets=targets;resources.projects=projects;resources.options=linearOptions;resources.clickupLists=clickupLists;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.slug.value=current.slug;form.promptTemplate.value=current.promptTemplate;form.concurrencyLimit.value=current.concurrencyLimit;form.executionTargetId.value=current.executionTargetId;form.agentKind.value=current.agentKind||'codex';form.repositoryUrl.value=current.repositoryUrl||'';form.checkoutRef.value=current.checkoutRef||'';triggers=current.triggers.map(t=>({...t,config:{...t.config}}))}else triggers=[{kind:'manual',slug:'trigger-1',enabled:true,config:{}}];syncModels(current?.model||'',current?.effort||'');highlightPrompt();reservedSlugs=new Set(triggers.map(t=>t.slug));await refreshAvailability();render()} form.executionTargetId.addEventListener('change',()=>syncModels('','')); window.addEventListener('focus',()=>refreshAvailability().catch(()=>{}));window.addEventListener('pageshow',()=>refreshAvailability().catch(()=>{})); -form.onsubmit=async e=>{e.preventDefault();const error=$('#error');error.classList.add('hidden');try{if(!triggers.length)throw new Error('Add at least one trigger.');const body={name:form.name.value,slug:form.slug.value,promptTemplate:form.promptTemplate.value,model:form.model.value.trim(),effort:form.effort.value.trim(),concurrencyLimit:Number(form.concurrencyLimit.value),executionTargetId:form.executionTargetId.value,triggers:triggers.map(({id,slug,kind,enabled,config})=>({id,slug,kind,enabled,config}))};const result=await request('/api/v1/jobs'+(jobId?'/'+encodeURIComponent(jobId):''),{method:jobId?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});location.href='/jobs/'+encodeURIComponent(result.id)}catch(e){error.textContent=e.message;error.classList.remove('hidden');error.scrollIntoView({block:'center'})}};init().catch(e=>{const error=$('#error');error.textContent=e.message;error.classList.remove('hidden')});`); +form.onsubmit=async e=>{e.preventDefault();const error=$('#error');error.classList.add('hidden');try{if(!triggers.length)throw new Error('Add at least one trigger.');const body={name:form.name.value,slug:form.slug.value,promptTemplate:form.promptTemplate.value,agentKind:form.agentKind.value,repositoryUrl:form.repositoryUrl.value.trim(),checkoutRef:form.checkoutRef.value.trim(),model:form.model.value.trim(),effort:form.effort.value.trim(),concurrencyLimit:Number(form.concurrencyLimit.value),executionTargetId:form.executionTargetId.value,triggers:triggers.map(({id,slug,kind,enabled,config})=>({id,slug,kind,enabled,config}))};const result=await request('/api/v1/jobs'+(jobId?'/'+encodeURIComponent(jobId):''),{method:jobId?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});location.href='/jobs/'+encodeURIComponent(result.id)}catch(e){error.textContent=e.message;error.classList.remove('hidden');error.scrollIntoView({block:'center'})}};init().catch(e=>{const error=$('#error');error.textContent=e.message;error.classList.remove('hidden')});`); export const jobDetailPage = (viewer: { email: string }, jobId: string) => shell("Job — Factorize", viewer, `

Loading job…

Run job manually

Add an optional prompt for this run.

`, `${uiHelpers} @@ -209,23 +209,26 @@ ${[["linear","Linear","Issues and projects"],["clickup","ClickUp","Tasks and lis

Connect Linear

You’ll leave Factorize to authorize access to your Linear workspace, then return here.

Connect ClickUp

Authorize a ClickUp workspace. Factorize will register the task webhook automatically.

Install the GitHub App

You’ll choose an account and repositories on GitHub, then return to Factorize.

-

Connect Exe.dev

Each run creates and then deletes an isolated VM. The token must allow ls, new, ssh, and rm.

+

Connect Exe.dev

Each run creates and then deletes an isolated VM. The token must allow ls, integrations list, new, ssh, and rm.

Connect Amp

This verifies and stores a write-only token for an Amp cloud project.

Install Cloudflare Tail

Name the installation and paste a secret, or have Factorize generate one.

Installed integrations

Check status and manage providers already connected to Factorize.

Loading installed integrations…
`), `${uiHelpers} const badge=(id,label,tone)=>{const el=$(id);el.textContent=label;el.className='text-xs font-medium '+(tone==='warn'?'text-amber-700 dark:text-amber-300':'text-slate-500 dark:text-slate-400')}; const integrationIcons=${JSON.stringify(integrationIcons)}; -const testButton=(kind,id)=>''; +const testButton=(kind,id)=>''; const installedRow=(name,description,status,tone,actions)=>'
'+integrationIcons[name==='Cloudflare Tail'?'tail':name==='Exe.dev'?'exe':name.toLowerCase()]+'

'+esc(name)+'

Actions
'+actions+'

'+description+'

'+esc(status)+'
'; async function disconnectGitHub(id){if(!confirm('Disconnect this GitHub installation from Factorize?'))return;await request('/api/github/installations/'+encodeURIComponent(id),{method:'DELETE'});await load()} -async function load(){const loading=$('#installed-loading'),list=$('#installed-integrations'),table=$('#installed-table'),empty=$('#installed-empty');loading.classList.remove('hidden');table.classList.add('hidden');empty.classList.add('hidden');$('#integration-error').classList.add('hidden');try{const [s,gh,tails]=await Promise.all([request('/api/connections/status'),fetch('/api/github/installations'),request('/api/connections/cloudflare-tail')]),rows=[];const exe=s.exeConnections||[],amps=s.ampConnections||[];badge('#linear-available-status',(s.linear?1:0)+' installed','neutral');badge('#clickup-available-status',(s.clickup?1:0)+' installed','neutral');badge('#exe-available-status',exe.length+' installed','neutral');badge('#amp-available-status',amps.length+' installed','neutral');badge('#tail-available-status',tails.length+' installed','neutral');$('#linear-action').textContent=s.linear?'Reconnect Linear':'Continue to Linear';if(s.linear)rows.push(installedRow('Linear',esc(s.linear.organizationName||'Linear workspace')+(s.linear.viewerEmail?' · '+esc(s.linear.viewerEmail):''),'Connected','ok',''));if(s.clickup)rows.push(installedRow('ClickUp',esc(s.clickup.teamName||'ClickUp workspace'),'Connected','ok',''));exe.forEach(c=>rows.push(installedRow('Exe.dev',esc(c.repositoryUrl)+' · '+esc(c.agentKind)+(c.tags?.length?' · '+esc(c.tags.join(', ')):''),'Connected','ok',testButton('exe',c.connectionId)+'')));amps.forEach(c=>rows.push(installedRow('Amp',esc(c.project),'Connected','ok',testButton('amp',c.connectionId)+'')));tails.forEach(c=>rows.push(installedRow('Cloudflare Tail',esc(c.name)+(c.referencedJobCount?' · '+c.referencedJobCount+' jobs':''),'Connected','ok','')));if(gh.status===404){badge('#github-available-status','Unavailable','neutral');$('#github-install').classList.add('hidden')}else if(!gh.ok){badge('#github-available-status','Action required','warn');rows.push(installedRow('GitHub','Installation status could not be loaded.','Action required','warn',''))}else{const installs=await gh.json(),active=installs.filter(x=>x.state==='active');badge('#github-available-status',active.length+' installed',installs.length&&!active.length?'warn':'neutral');$('#github-install').textContent=active.length?'Add another installation':'Continue to GitHub';installs.forEach(x=>rows.push(installedRow('GitHub',esc(x.accountLogin||'Installation '+x.installationId)+' · '+esc(x.accountType||'GitHub'),x.state==='active'?'Connected':x.state,'active'===x.state?'ok':'warn','Configure ↗')))}list.innerHTML=rows.join('');loading.classList.add('hidden');table.classList.toggle('hidden',!rows.length);empty.classList.toggle('hidden',rows.length>0);bindActions()}catch(e){loading.classList.add('hidden');empty.classList.remove('hidden');const error=$('#integration-error');error.textContent=e.message||'Could not load integration status. Try again.';error.classList.remove('hidden');['linear','clickup','github','exe','amp','tail'].forEach(id=>badge('#'+id+'-available-status','Unavailable','neutral'))}} +async function load(){const loading=$('#installed-loading'),list=$('#installed-integrations'),table=$('#installed-table'),empty=$('#installed-empty');loading.classList.remove('hidden');table.classList.add('hidden');empty.classList.add('hidden');$('#integration-error').classList.add('hidden');try{const [s,gh,tails]=await Promise.all([request('/api/connections/status'),fetch('/api/github/installations'),request('/api/connections/cloudflare-tail')]),rows=[];const exe=s.exeConnections||[],amps=s.ampConnections||[];badge('#linear-available-status',(s.linear?1:0)+' installed','neutral');badge('#clickup-available-status',(s.clickup?1:0)+' installed','neutral');badge('#exe-available-status',exe.length+' installed','neutral');badge('#amp-available-status',amps.length+' installed','neutral');badge('#tail-available-status',tails.length+' installed','neutral');$('#linear-action').textContent=s.linear?'Reconnect Linear':'Continue to Linear';if(s.linear)rows.push(installedRow('Linear',esc(s.linear.organizationName||'Linear workspace')+(s.linear.viewerEmail?' · '+esc(s.linear.viewerEmail):''),'Connected','ok',''));if(s.clickup)rows.push(installedRow('ClickUp',esc(s.clickup.teamName||'ClickUp workspace'),'Connected','ok',''));exe.forEach(c=>rows.push(installedRow('Exe.dev',c.tags?.length?'VM tags · '+esc(c.tags.join(', ')):'No VM tags','Connected','ok',testButton('exe',c.connectionId)+'')));amps.forEach(c=>rows.push(installedRow('Amp',esc(c.project),'Connected','ok',testButton('amp',c.connectionId)+'')));tails.forEach(c=>rows.push(installedRow('Cloudflare Tail',esc(c.name)+(c.referencedJobCount?' · '+c.referencedJobCount+' jobs':''),'Connected','ok','')));if(gh.status===404){badge('#github-available-status','Unavailable','neutral');$('#github-install').classList.add('hidden')}else if(!gh.ok){badge('#github-available-status','Action required','warn');rows.push(installedRow('GitHub','Installation status could not be loaded.','Action required','warn',''))}else{const installs=await gh.json(),active=installs.filter(x=>x.state==='active');badge('#github-available-status',active.length+' installed',installs.length&&!active.length?'warn':'neutral');$('#github-install').textContent=active.length?'Add another installation':'Continue to GitHub';installs.forEach(x=>rows.push(installedRow('GitHub',esc(x.accountLogin||'Installation '+x.installationId)+' · '+esc(x.accountType||'GitHub'),x.state==='active'?'Connected':x.state,'active'===x.state?'ok':'warn','Configure ↗')))}list.innerHTML=rows.join('');loading.classList.add('hidden');table.classList.toggle('hidden',!rows.length);empty.classList.toggle('hidden',rows.length>0);bindActions()}catch(e){loading.classList.add('hidden');empty.classList.remove('hidden');const error=$('#integration-error');error.textContent=e.message||'Could not load integration status. Try again.';error.classList.remove('hidden');['linear','clickup','github','exe','amp','tail'].forEach(id=>badge('#'+id+'-available-status','Unavailable','neutral'))}} function openSetup(kind){const dialog=$('#'+kind+'-setup');if(!dialog.open)dialog.showModal()} function closeSetup(kind){const dialog=$('#'+kind+'-setup');if(dialog.open)dialog.close()} async function tailAction(id,method){await request('/api/connections/cloudflare-tail/'+encodeURIComponent(id),{method});await load()} function bindActions(){bindTests();document.querySelectorAll('[data-open-setup]').forEach(button=>button.onclick=()=>{if(button.dataset.openSetup==='tail'){delete $('#tail-connection').dataset.id;$('#tail-connection').reset()}openSetup(button.dataset.openSetup)});document.querySelectorAll('[data-close-setup]').forEach(button=>button.onclick=()=>closeSetup(button.dataset.closeSetup));document.querySelectorAll('dialog').forEach(dialog=>dialog.onclick=e=>{if(e.target===dialog)dialog.close()});document.querySelectorAll('[data-disconnect-github]').forEach(button=>button.onclick=()=>disconnectGitHub(button.dataset.disconnectGithub).catch(showError));document.querySelectorAll('[data-disconnect-tail]').forEach(button=>button.onclick=()=>{if(confirm('Disconnect this Tail installation? Jobs using it will need another installation.'))tailAction(button.dataset.disconnectTail,'DELETE').catch(showError)});document.querySelectorAll('[data-test-tail]').forEach(button=>button.onclick=async()=>{button.disabled=true;try{await request('/api/connections/cloudflare-tail/'+encodeURIComponent(button.dataset.testTail)+'/test',{method:'POST'});button.textContent='Connected'}catch(e){button.textContent='Action required'}finally{button.disabled=false}});document.querySelectorAll('[data-configure-tail]').forEach(button=>button.onclick=()=>{const form=$('#tail-connection');form.dataset.id=button.dataset.configureTail;form.elements.name.value=button.dataset.name;openSetup('tail')})} function showError(e){const error=$('#integration-error');error.textContent=e.message||'The integration action failed.';error.classList.remove('hidden')} function bindTests(){document.querySelectorAll('[data-test]').forEach(button=>button.onclick=async()=>{const original=button.textContent;button.disabled=true;button.textContent='Testing…';try{const kind=button.dataset.test,result=await request('/api/connections/'+kind+'/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({connectionId:button.dataset.id})});button.textContent=result.ok?'Connected':'Action required'}catch(e){button.textContent='Action required'}finally{setTimeout(()=>{button.disabled=false;button.textContent=original},1500)}})} -$('#connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,d=new FormData(form),m=$('#settings-message');try{await request('/api/connections/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({apiToken:d.get('apiToken'),repositoryUrl:d.get('repositoryUrl'),checkoutRef:d.get('checkoutRef')||undefined,agentKind:d.get('agentKind'),tags:String(d.get('tags')||'').split(',').map(x=>x.trim()).filter(Boolean)})});form.reset();m.textContent='Connection saved. Each run will receive an isolated VM.';await load()}catch(x){m.textContent=x.message}}; +document.addEventListener('click',async event=>{const button=event.target.closest('[data-remove-integration]');if(!button||!confirm('Remove this integration?'))return;button.disabled=true;try{await request('/api/connections/'+button.dataset.removeIntegration+'/'+encodeURIComponent(button.dataset.id),{method:'DELETE'});await load()}catch(error){button.disabled=false;showError(error)}}); +const exePayload=()=>{const form=$('#connection');return {apiToken:form.elements.apiToken.value,tags:[...form.elements.tags.selectedOptions].map(option=>option.value)}}; +$('#test-exe-token').onclick=async()=>{const form=$('#connection'),m=$('#settings-message'),button=$('#test-exe-token');button.disabled=true;try{const result=await request('/api/connections/exe/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({apiToken:form.elements.apiToken.value})});if(!result.ok){m.textContent='Missing required permissions: '+result.missingPermissions.join(', ');return}form.elements.tags.replaceChildren(...result.tags.map(tag=>new Option(tag,tag)));form.elements.tags.disabled=false;m.textContent=result.tags.length?'Token works. Select the VM tags to attach.':'Token works. No tags were found on existing VMs.'}catch(error){m.textContent=error.message}finally{button.disabled=false}}; +$('#connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,m=$('#settings-message');try{await request('/api/connections/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(exePayload())});form.reset();form.elements.tags.disabled=true;m.textContent='VM connection saved.';await load()}catch(x){m.textContent=x.message}}; const ampPayload=()=>{const d=new FormData($('#amp-connection'));return {project:d.get('project'),accessToken:d.get('accessToken'),apiBaseUrl:d.get('apiBaseUrl')}};$('#test-amp').onclick=async()=>{const m=$('#amp-message');try{const x=await request('/api/connections/amp/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});m.textContent=x.ok?'Amp connection succeeded.':'Amp connection needs attention.'}catch(x){m.textContent=x.message}};$('#amp-connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,m=$('#amp-message');try{await request('/api/connections/amp',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});form.reset();m.textContent='Amp connection saved. The token remains write-only.';await load()}catch(x){m.textContent=x.message}}; $('#tail-connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,d=new FormData(form),m=$('#tail-message'),id=form.dataset.id,url='/api/connections/cloudflare-tail'+(id?'/'+encodeURIComponent(id):'');try{const x=await request(url,{method:id?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:d.get('name'),signingSecret:d.get('signingSecret')||undefined,generateSecret:d.get('generateSecret')==='on'})});if(x.generatedSecret){$('#tail-generated-value').textContent=x.generatedSecret;$('#tail-generated').classList.remove('hidden')}form.reset();delete form.dataset.id;m.textContent='Tail installation saved. Its secret remains write-only.';await load()}catch(x){m.textContent=x.message}};$('#copy-tail-secret').onclick=async()=>{await navigator.clipboard.writeText($('#tail-generated-value').textContent);$('#copy-tail-secret').textContent='Copied'};bindActions();load();`); diff --git a/packages/app/test/execution-backend.test.ts b/packages/app/test/execution-backend.test.ts index 3a7be909..4170996f 100644 --- a/packages/app/test/execution-backend.test.ts +++ b/packages/app/test/execution-backend.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { ExeVmBackend, isOwnedVmName, vmNameFor } from "../src/exe-vm-backend"; +import { ExeVmBackend, isOwnedVmName, tagsFromInventory, vmNameFor } from "../src/exe-vm-backend"; import type { ExecutionBackend, ExecutionObservation, LaunchRequest, RunHandle } from "../src/execution"; afterEach(() => vi.unstubAllGlobals()); @@ -7,6 +7,21 @@ afterEach(() => vi.unstubAllGlobals()); const connection = { apiToken: "secret", agentKind: "codex", repositoryUrl: "https://github.int.exe.xyz/acme/repo.git", checkoutRef: "main", tags: ["github", "llm"], model: "gpt-5.5", effort: "high" }; describe("ExeVmBackend", () => { + it("tests every required permission and discovers sorted unique VM tags", async () => { + vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => String(init.body) === "ssh --help" + ? new Response("forbidden", { status: 403 }) + : new Response(String(init.body) === "ls --json" ? '{"vms":[{"tags":["github","llm"]},{"tags":["github"]}]}' : "help", { headers: { "X-Exe-Exit": "0" } }))); + const result = await new ExeVmBackend({ apiToken: "secret", tags: [] }).testPermissions(); + expect(result.ok).toBe(false); + expect(result.missingPermissions).toEqual(["ssh"]); + expect(result.tags).toEqual(["github", "llm"]); + expect(result.checks.map(check => check.requestBody)).toEqual(["ls --json", "integrations list --json", "new --help", "ssh --help", "rm --help"]); + }); + + it("extracts tags only from tag arrays", () => { + expect(tagsFromInventory({ tags: ["one"], nested: { name: "ignored", attachments: ["tag:three"], tags: ["two", "one"] } })).toEqual(["one", "three", "two"]); + }); + it("creates a tagged VM, clones the repository, and launches Codex directly", async () => { const requests: string[] = []; vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { diff --git a/packages/app/test/ui.test.ts b/packages/app/test/ui.test.ts index fd1a6f87..f4acea59 100644 --- a/packages/app/test/ui.test.ts +++ b/packages/app/test/ui.test.ts @@ -176,13 +176,26 @@ describe("pages", () => { expect(html).not.toContain('min-w-[48rem]'); }); - it("selects a per-job model with harness-aware suggestions", () => { + it("configures agent and repository per job", () => { const html = jobPage({ email: "owner@example.com" }, "job-1"); expect(html).toContain('name="model"'); - expect(html).toContain("new Option('Harness default','')"); - expect(html).toContain("target?.models||[]"); + expect(html).toContain('name="agentKind"'); + expect(html).toContain('name="repositoryUrl"'); + expect(html).toContain('name="checkoutRef"'); expect(html).toContain("model:form.model.value.trim()"); - expect(html).toContain("syncModels(current?.model||'')"); + expect(html).toContain("repositoryUrl:form.repositoryUrl.value.trim()"); + expectInlineScriptsToParse(html); + }); + + it("keeps exe.dev settings VM-only and supports testing, tags, and removal", () => { + const html = settingsPage({ email: "owner@example.com" }); + const dialog = html.match(//)?.[0] ?? ""; + expect(dialog).toContain('id="test-exe-token"'); + expect(dialog).toContain('name="tags" multiple'); + expect(dialog).not.toContain('name="repositoryUrl"'); + expect(dialog).not.toContain('name="checkoutRef"'); + expect(html).toContain('data-remove-integration='); + expect(html).toContain('missingPermissions'); expectInlineScriptsToParse(html); });