diff --git a/packages/api/test/encrypted-integration-repository.postgres.test.ts b/packages/api/test/encrypted-integration-repository.postgres.test.ts index 1d8c8331..ee0531c3 100644 --- a/packages/api/test/encrypted-integration-repository.postgres.test.ts +++ b/packages/api/test/encrypted-integration-repository.postgres.test.ts @@ -21,6 +21,8 @@ describe.skipIf(!url)("encrypted integration persistence (PostgreSQL)", () => { let db: Database; let admin: pg.Client; let databaseName: string; + let tearingDown = false; + let unexpectedPoolError: Error | undefined; beforeAll(async () => { admin = new pg.Client({ connectionString: url }); await admin.connect(); @@ -28,12 +30,22 @@ describe.skipIf(!url)("encrypted integration persistence (PostgreSQL)", () => { await admin.query(`CREATE DATABASE ${databaseName}`); const databaseUrl = new URL(url!); databaseUrl.pathname = `/${databaseName}`; db = new Database({ connectionString: databaseUrl.toString() }); + db.pool.on("error", error => { + if (tearingDown && (error as NodeJS.ErrnoException).code === "57P01") return; + unexpectedPoolError = error; + }); const migrations = new URL("../migrations/", import.meta.url); for (const file of (await readdir(migrations)).filter(file => /^\d+.*\.sql$/.test(file)).sort()) await db.pool.query(await readFile(new URL(file, migrations), "utf8")); const migration = await db.pool.query("SELECT to_regclass('app.integration_collections') AS collection, to_regclass('app.integration_changes') AS changes"); expect(migration.rows[0]).toEqual({ collection: "app.integration_collections", changes: "app.integration_changes" }); }, 30_000); - afterAll(async () => { await db?.close(); await admin?.query(`DROP DATABASE IF EXISTS ${databaseName} WITH (FORCE)`); await admin?.end(); }); + afterAll(async () => { + await db?.close(); + tearingDown = true; + await admin?.query(`DROP DATABASE IF EXISTS ${databaseName} WITH (FORCE)`); + await admin?.end(); + if (unexpectedPoolError) throw unexpectedPoolError; + }); async function freshRepository() { const tenantId = crypto.randomUUID(); diff --git a/packages/api/test/static-slice.e2e.test.ts b/packages/api/test/static-slice.e2e.test.ts index 561909c3..403d7c7b 100644 --- a/packages/api/test/static-slice.e2e.test.ts +++ b/packages/api/test/static-slice.e2e.test.ts @@ -122,23 +122,22 @@ describe.skipIf(!url)("compiled React + actual Worker API + PostgreSQL", () => { return route.fulfill({ status: response.status, headers, body: Buffer.from(await response.arrayBuffer()) }); }); const page = await context.newPage(); page.setDefaultTimeout(10000); - await page.goto(`https://factorize.test/jobs/${job.id}/edit`); - await page.waitForURL(`**/jobs/${job.id}/settings`); + await page.goto(`https://factorize.test/jobs/${job.id}/settings/context`); await page.getByLabel("Prompt template", { exact: true }).fill("My edited prompt"); await browserWriteRequest; await service.updateJob(job.id, { name: "Concurrent name", slug: job.slug, promptTemplate: job.promptTemplate, executionConfigId: job.executionConfigId, concurrencyLimit: 1, triggers: [{ id: job.triggers[0].id, slug: job.triggers[0].slug, kind: "manual", enabled: true, config: {} }], expectedUpdatedAt: job.updatedAt }); releaseBrowserWrite(); await page.getByRole("button", { name: "Reconcile my changes" }).waitFor(); await page.getByRole("button", { name: "Reconcile my changes" }).click(); - expect(await page.getByLabel("Name", { exact: true }).inputValue()).toBe("Concurrent name"); await page.getByRole("status").filter({ hasText: "Job settings saved." }).waitFor(); - expect(new URL(page.url()).pathname).toBe(`/jobs/${job.id}/settings`); + expect(new URL(page.url()).pathname).toBe(`/jobs/${job.id}/settings/context`); const saved = await service.getJob(job.id); expect(saved.name).toBe("Concurrent name"); expect(saved.promptTemplate).toBe("My edited prompt"); expect(saved.triggers[0].id).toBe(job.triggers[0].id); const row = (await f.db.pool.query("SELECT encrypted_prompt_template FROM app.jobs WHERE tenant_id=$1 AND id=$2", [f.tenantId, job.id])).rows[0]; expect(await decrypt(row.encrypted_prompt_template, f.env.CREDENTIAL_ENCRYPTION_KEY)).toBe("My edited prompt"); await page.reload(); await page.getByLabel("Prompt template", { exact: true }).waitFor(); - expect(await page.getByLabel("Name", { exact: true }).inputValue()).toBe("Concurrent name"); expect(await page.getByLabel("Prompt template", { exact: true }).inputValue()).toBe("My edited prompt"); + await page.goto(`https://factorize.test/jobs/${job.id}/settings/general`); + expect(await page.getByLabel("Name", { exact: true }).inputValue()).toBe("Concurrent name"); await page.goto("https://factorize.test/settings/api-keys"); await page.getByRole("button", { name: "Create API Key" }).click(); await page.waitForURL("**/settings/api-keys/new"); await page.getByLabel("Key name").fill("Real key"); await page.getByRole("button", { name: "Create key" }).click(); await page.getByText("Copy this key now. It will only be displayed once.", { exact: true }).waitFor(); await page.getByRole("button", { name: "Dismiss key" }).click(); await page.reload(); await page.getByText("Real key", { exact: true }).waitFor(); page.once("dialog", dialog => dialog.accept()); await page.getByRole("button", { name: "Revoke key" }).click(); await page.getByText("Revoked", { exact: true }).waitFor(); diff --git a/packages/app/src/features/jobs/editor.tsx b/packages/app/src/features/jobs/editor.tsx index c1f4f250..e0a7a1ff 100644 --- a/packages/app/src/features/jobs/editor.tsx +++ b/packages/app/src/features/jobs/editor.tsx @@ -1,7 +1,6 @@ import { RunPermissions, defaultRunScopes } from "./run-permissions"; import { Disclosure, Summary, Button, Input, Select, Label, Page, Card, Textarea } from "../../shared/ui"; import { Dialog } from "../../shared/dialog"; -import { JobHeader } from "./header"; import { DeleteJob } from "./delete"; import { validationMessage } from "./validation-message"; import { useEffect, useState, useRef } from "react"; @@ -15,18 +14,18 @@ import { TemplateField } from "./template-field"; import { TriggerEditor } from "./trigger-editor"; import { InvocationPermissionEditor } from "./invocation-permission-editor"; import { messageOf } from "../auth/session"; -import { projectQuery, projectsQuery } from "../projects/queries"; +import { projectsQuery } from "../projects/queries"; import { AutosaveStatus, useDebouncedAutosave } from "../../shared/use-debounced-autosave"; import { skillsQuery } from "../skills/queries"; import { JobNav } from "./job-nav"; export function JobEditor() { - const { jobId } = useParams({ strict: false }); + const { jobId, section } = useParams({ strict: false }); const job = useQuery({ ...jobQuery(jobId ?? ""), enabled: !!jobId }); if (jobId && job.isPending) return

Loading job configuration…

; if (jobId && job.error) return

{job.error.message}

; - return <>{job.data?.projectId && }; + return <>{job.data?.projectId && }; } -function EditorForm({ initial }: { initial?: Job }) { +function EditorForm({ initial, section }: { initial?: Job; section?: string }) { const location = useLocation(), navigate = useNavigate(), cache = useQueryClient(); const [base, setBase] = useState(initial ? editableJob(initial) : emptyJob); const [draft, setDraft] = useState(base), [revision, setRevision] = useState(initial?.updatedAt); @@ -34,10 +33,9 @@ function EditorForm({ initial }: { initial?: Job }) { const [reconciling, setReconciling] = useState(false), [saved, setSaved] = useState(false), [invalidForm, setInvalidForm] = useState(false); const savingNavigation = useRef(false); const dirty = JSON.stringify(base) !== JSON.stringify(draft); - useBlocker({ shouldBlockFn: () => dirty && !savingNavigation.current && !window.confirm("Discard unsaved job changes?"), enableBeforeUnload: dirty }); + useBlocker({ shouldBlockFn: ({ next }) => dirty && !(initial && next.pathname.startsWith(`/jobs/${initial.id}/settings/`)) && !savingNavigation.current && !window.confirm("Discard unsaved job changes?"), enableBeforeUnload: dirty }); useEffect(() => { const handler = (event: BeforeUnloadEvent) => { if (dirty) { event.preventDefault(); event.returnValue = ""; } }; window.addEventListener("beforeunload", handler); return () => window.removeEventListener("beforeunload", handler); }, [dirty]); const targets = useQuery(targetsQuery), metadata = useQuery(metadataQuery), skills = useQuery(skillsQuery()); - const project = useQuery({ ...projectQuery(initial?.projectId ?? ""), enabled: !!initial?.projectId }); const projects = useQuery({ ...projectsQuery, enabled: !initial }); const target = targets.data?.find(t => t.id === draft.executionConfigId); const verificationFingerprint = JSON.stringify([draft.executionConfigId, canonicalizeVmImage(draft.vmImage ?? ""), draft.tags ?? [], target?.agentKind ?? ""]); @@ -90,18 +88,21 @@ function EditorForm({ initial }: { initial?: Job }) { if (conflicts.length === 1) setRemote(undefined); }; const [localConflictDraft, setLocalConflictDraft] = useState(draft); - return {initial && } + const selectedSection = initial && ["general", "execution", "context", "permissions", "triggers"].includes(section ?? "") ? section : initial ? "general" : "all"; + const show = (name: string) => selectedSection === "all" || selectedSection === name; + const settingsSection = (name: "general" | "execution" | "context" | "permissions" | "triggers") => {name[0].toUpperCase() + name.slice(1)}; + return {(remote || reconciling || refreshConflict.error) &&

This job changed while you were editing

Your unsaved draft is retained. Review the latest configuration before retrying.

{refreshConflict.isPending &&

Loading latest configuration…

}{refreshConflict.error && <>

{refreshConflict.error.message}

} {remote && !conflicts.length && <>
{JSON.stringify(editableJob(remote), null, 2)}
} {conflicts.map(field =>
Both versions changed {field}
Mine: {JSON.stringify(localConflictDraft[field], null, 2)}
Latest: {JSON.stringify(base[field], null, 2)}
)}
}
{ e.preventDefault(); save.mutate(draft); }}> - +
-

General

Set the job name, description, and stable identifier.

{!initial &&
{projects.isPending &&

Loading projects…

}{projects.error &&

{projects.error.message}

}
} + {show("general") &&

General

Set the job name, description, and stable identifier.

{!initial &&
{projects.isPending &&

Loading projects…

}{projects.error &&

{projects.error.message}

}
}