From 2718c10b1df16d04e90e6a1ae776ca6961c6d18c Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Wed, 14 Oct 2026 20:04:34 +0000 Subject: [PATCH 01/10] feat: introduce tenant projects for jobs --- packages/api-client/src/schema.d.ts | 272 ++++++++++++ packages/api/migrations/0016_projects.sql | 16 + packages/api/src/api-contract.ts | 12 + packages/api/src/flow-schemas.ts | 1 + packages/api/src/flow-service.ts | 12 +- packages/api/src/job-contracts.ts | 4 +- packages/api/src/job-domain.ts | 1 + packages/api/src/postgres/job-repository.ts | 6 +- .../src/postgres/job-summary-repository.ts | 11 +- .../api/src/postgres/project-repository.ts | 13 + packages/api/src/postgres/schema.ts | 7 +- packages/api/src/project-contracts.ts | 3 + packages/api/src/protected-api.ts | 5 + .../app/src/features/auth/account-bar.tsx | 2 +- packages/app/src/features/jobs/queries.ts | 6 +- packages/app/src/features/projects/create.tsx | 7 + packages/app/src/features/projects/detail.tsx | 6 + packages/app/src/features/projects/list.tsx | 5 + packages/app/src/features/projects/queries.ts | 5 + packages/app/src/features/projects/routes.tsx | 3 + packages/app/src/main.tsx | 3 +- packages/docs/openapi.yaml | 387 ++++++++++++++++++ 22 files changed, 768 insertions(+), 19 deletions(-) create mode 100644 packages/api/migrations/0016_projects.sql create mode 100644 packages/api/src/postgres/project-repository.ts create mode 100644 packages/api/src/project-contracts.ts create mode 100644 packages/app/src/features/projects/create.tsx create mode 100644 packages/app/src/features/projects/detail.tsx create mode 100644 packages/app/src/features/projects/list.tsx create mode 100644 packages/app/src/features/projects/queries.ts create mode 100644 packages/app/src/features/projects/routes.tsx diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index fe2aa880..8f099089 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -990,6 +990,68 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/projects": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List projects + * @description Requires the flows:read scope. + * + * Accepts a scoped bearer token or interactive owner session. + */ + get: operations["get_api_v1_projects"]; + put?: never; + /** + * Create project + * @description Requires the flows:write scope. + * + * Accepts a scoped bearer token or interactive owner session. + */ + post: operations["post_api_v1_projects"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/projects/{projectId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Get project + * @description Requires the flows:read scope. + * + * Accepts a scoped bearer token or interactive owner session. + */ + get: operations["get_api_v1_projects_projectId"]; + /** + * Update project + * @description Requires the flows:write scope. + * + * Accepts a scoped bearer token or interactive owner session. + */ + put: operations["put_api_v1_projects_projectId"]; + post?: never; + /** + * Delete empty project + * @description Requires the flows:write scope. + * + * Accepts a scoped bearer token or interactive owner session. + */ + delete: operations["delete_api_v1_projects_projectId"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/jobs": { parameters: { query?: never; @@ -1711,6 +1773,8 @@ export interface components { updatedAt?: string; }; JobInput: { + /** Format: uuid */ + projectId?: string; name: string; slug: string; promptTemplate: string; @@ -3833,6 +3897,7 @@ export interface operations { get_api_v1_job_summaries: { parameters: { query?: { + projectId?: string; limit?: number; cursor?: string; q?: string; @@ -3857,6 +3922,8 @@ export interface operations { name: string; slug: string; enabled: boolean; + /** Format: uuid */ + projectId: string; model: string; effort: string; agentKind: string; @@ -3883,6 +3950,7 @@ export interface operations { get_api_v1_job_selector: { parameters: { query?: { + projectId?: string; limit?: number; cursor?: string; q?: string; @@ -3922,6 +3990,200 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_projects: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Projects */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + name: string; + description?: string; + createdAt: string; + updatedAt: string; + jobCount: number; + }[]; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + post_api_v1_projects: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + name: string; + description?: string; + }; + }; + }; + responses: { + /** @description Created */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + name: string; + description?: string; + createdAt: string; + updatedAt: string; + jobCount: number; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + get_api_v1_projects_projectId: { + parameters: { + query?: never; + header?: never; + path: { + projectId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Project */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + name: string; + description?: string; + createdAt: string; + updatedAt: string; + jobCount: number; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + put_api_v1_projects_projectId: { + parameters: { + query?: never; + header?: never; + path: { + projectId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + name: string; + description?: string; + }; + }; + }; + responses: { + /** @description Updated */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + name: string; + description?: string; + createdAt: string; + updatedAt: string; + jobCount: number; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + delete_api_v1_projects_projectId: { + parameters: { + query?: never; + header?: never; + path: { + projectId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Deleted */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": Record; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; get_api_v1_jobs: { parameters: { query?: never; @@ -3940,6 +4202,8 @@ export interface operations { "application/json": { /** Format: uuid */ id: string; + /** Format: uuid */ + projectId?: string; name: string; slug: string; enabled: boolean; @@ -4108,6 +4372,8 @@ export interface operations { "application/json": { /** Format: uuid */ id: string; + /** Format: uuid */ + projectId?: string; name: string; slug: string; enabled: boolean; @@ -4448,6 +4714,8 @@ export interface operations { "application/json": { /** Format: uuid */ id: string; + /** Format: uuid */ + projectId?: string; name: string; slug: string; enabled: boolean; @@ -4606,6 +4874,8 @@ export interface operations { requestBody: { content: { "application/json": { + /** Format: uuid */ + projectId?: string; name: string; slug: string; promptTemplate: string; @@ -4717,6 +4987,8 @@ export interface operations { "application/json": { /** Format: uuid */ id: string; + /** Format: uuid */ + projectId?: string; name: string; slug: string; enabled: boolean; diff --git a/packages/api/migrations/0016_projects.sql b/packages/api/migrations/0016_projects.sql new file mode 100644 index 00000000..57476254 --- /dev/null +++ b/packages/api/migrations/0016_projects.sql @@ -0,0 +1,16 @@ +CREATE TABLE app.projects ( + tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, + id uuid NOT NULL, name text NOT NULL, description text, + created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (tenant_id, id), UNIQUE (tenant_id, name) +); +CREATE INDEX projects_tenant_updated ON app.projects(tenant_id, updated_at); +INSERT INTO app.projects(tenant_id,id,name,description) +SELECT t.id, md5(t.id::text || ':default')::uuid, 'Default', 'Jobs migrated from the legacy jobs collection.' +FROM app.tenants t WHERE EXISTS (SELECT 1 FROM app.jobs j WHERE j.tenant_id=t.id) +ON CONFLICT (tenant_id,name) DO NOTHING; +ALTER TABLE app.jobs ADD COLUMN project_id uuid; +UPDATE app.jobs j SET project_id=p.id FROM app.projects p WHERE p.tenant_id=j.tenant_id AND p.name='Default' AND j.project_id IS NULL; +ALTER TABLE app.jobs ALTER COLUMN project_id SET NOT NULL; +ALTER TABLE app.jobs ADD CONSTRAINT jobs_project_fk FOREIGN KEY (tenant_id,project_id) REFERENCES app.projects(tenant_id,id) ON DELETE RESTRICT; +CREATE INDEX jobs_tenant_project_updated ON app.jobs(tenant_id,project_id,updated_at); diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 89fa9f7b..87957140 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -5,6 +5,7 @@ import { exeConnection, integrationStatus, authorizedClient, accessToken, create import { executionTargetResponse, triggerAvailabilityResponse, namedOption, providerOptions, githubInstallation, githubRepository, tailIntegration } from "./editor-contracts"; import { runSummaryResponse, runPageResponse, runStatusResponse, revisionTracePage, revisionTraceQuery } from "./run-read-contracts"; import { jobPageQuery, jobSummaryPage, jobSelectorPage, jobResponse, jobUpdateInput } from "./job-contracts"; +import { projectInput, projectResponse } from "./project-contracts"; import { z } from "zod"; import type { ApiService } from "./flow-service"; import { @@ -635,6 +636,17 @@ export const API_ROUTES: RouteContract[] = [ summary: "Search bounded lifecycle job options", responses: { "200": { description: "Selector page; same ordering/filter semantics as job-summaries", content: { "application/json": { schema: jsonSchema(jobSelectorPage, "output") } } } }, }, (service, { query }) => service.listJobSummaries(query, true), { query: jobPageQuery }), + route( + "GET", + "/api/v1/projects", + "flows:read", + { summary: "List projects", responses: { "200": { description: "Projects", content: { "application/json": { schema: jsonSchema(z.array(projectResponse), "output") } } } } }, + (service) => service.listProjects(), + ), + route("POST", "/api/v1/projects", "flows:write", { summary: "Create project", responses: { "201": { description: "Created", content: { "application/json": { schema: jsonSchema(projectResponse, "output") } } } } }, (service, { body }) => service.createProject(body), { body: projectInput }), + route("GET", "/api/v1/projects/{projectId}", "flows:read", { summary: "Get project", responses: { "200": { description: "Project", content: { "application/json": { schema: jsonSchema(projectResponse, "output") } } } } }, (service, { params }) => service.getProject(params.projectId)), + route("PUT", "/api/v1/projects/{projectId}", "flows:write", { summary: "Update project", responses: { "200": { description: "Updated", content: { "application/json": { schema: jsonSchema(projectResponse, "output") } } } } }, (service, { params, body }) => service.updateProject(params.projectId, body), { body: projectInput }), + route("DELETE", "/api/v1/projects/{projectId}", "flows:write", { summary: "Delete empty project", responses: { "200": { description: "Deleted" } } }, (service, { params }) => service.deleteProject(params.projectId)), route( "GET", "/api/v1/jobs", diff --git a/packages/api/src/flow-schemas.ts b/packages/api/src/flow-schemas.ts index f63db805..706e35b9 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/flow-schemas.ts @@ -34,6 +34,7 @@ export const triggerSchema = z.discriminatedUnion("kind", [ }).strict() }).strict(), ]); export const jobInputSchema = z.object({ + projectId: z.guid().optional(), name: z.string().trim().min(1).max(120), slug: z.string().regex(/^[a-z][a-z0-9_-]{0,29}$/), promptTemplate: z.string().min(1).max(50_000), diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 8ecf2a02..5bf9757c 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -31,6 +31,7 @@ import { ACCESS_SCOPES, accessTokenDigest, issueAccessToken } from "./access-tok import { TraceProjectionRepository } from "./postgres/trace-projection-repository"; import { replayTrace, traceReplaySchema, traceReplayRunIdSchema, TraceReplayError } from "./trace-replay"; +import { ProjectRepository } from "./postgres/project-repository"; export class ServiceError extends Error { constructor(public status: number, public code: string, message: string) { super(message); } @@ -54,6 +55,7 @@ export class ApiService { private jobs() { return new PostgresJobRepository(databaseFor(this.env), this.auth.tenantId, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY), value => decrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)); } private connections() { return new ConnectionRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } + private projects() { return new ProjectRepository(databaseFor(this.env), this.auth.tenantId); } private async executionTarget(id: string) { if (id.startsWith("amp:")) { @@ -182,6 +184,11 @@ export class ApiService { async listJobSummaries(input: JobPageQuery, selector = false) { await this.authorize("flows:read"); return new JobSummaryRepository(databaseFor(this.env), this.auth.tenantId).page(input, selector); } async listJobs() { await this.authorize("flows:read"); const jobs = await this.jobs().list(), stats = await this.jobStatistics(jobs.map(job => job.id)); return Promise.all(jobs.map(job => this.presentJob(job, stats.get(job.id) ?? { running_count: "0", last_run_state: null }))); } async getJob(jobId: string) { await this.authorize("flows:read"); const job = await this.jobs().getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); return this.presentJob(job); } + async listProjects() { await this.authorize("flows:read"); return this.projects().list(); } + async getProject(projectId: string) { await this.authorize("flows:read"); const project = await this.projects().get(projectId); if (!project) throw new ServiceError(404, "not_found", "Project not found"); return project; } + async createProject(input: { name: string; description?: string }) { await this.authorize("flows:write"); try { return await this.projects().create(input.name, input.description); } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "A project with this name already exists"); throw error; } } + async updateProject(projectId: string, input: { name: string; description?: string }) { await this.authorize("flows:write"); const result = await this.projects().update(projectId, input.name, input.description); if (!result) throw new ServiceError(404, "not_found", "Project not found"); return result; } + async deleteProject(projectId: string) { await this.authorize("flows:write"); const result = await this.projects().remove(projectId); if (result === "missing") throw new ServiceError(404, "not_found", "Project not found"); if (result === "nonempty") throw new ServiceError(409, "conflict", "Move or delete the project's jobs before deleting it"); return { id: projectId, deleted: true }; } async listJobEvents(jobId: string, limit = 50) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).jobEvents(jobId, limit); } async listWebhookDeliveries(query: URLSearchParams) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).deliveries(query); } async getWebhookDelivery(deliveryId: string) { await this.authorize("runs:read"); const value = await new OperationsRepository(databaseFor(this.env), this.auth.tenantId).delivery(deliveryId); if (!value) throw new ServiceError(404,"not_found","Webhook delivery not found"); return value; } @@ -189,13 +196,14 @@ export class ApiService { async createJob(input: JobInput) { await this.authorize("flows:write"); const timestamp = new Date().toISOString(), id = crypto.randomUUID(); const triggers = this.normalizedTriggers(input.triggers).map(trigger => ({ ...trigger, jobId: id })); - const job: Job = { id, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", model: input.model ?? "", ...(input.effort ? { effort: input.effort } : {}), executionTarget: await this.executionTarget(input.executionTargetId), concurrencyLimit: input.concurrencyLimit, enabled: true, triggers, createdAt: timestamp, updatedAt: timestamp }; + const projectId = input.projectId ?? await this.projects().defaultProjectId(); + const job: Job = { id, projectId, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", model: input.model ?? "", ...(input.effort ? { effort: input.effort } : {}), executionTarget: await this.executionTarget(input.executionTargetId), concurrencyLimit: input.concurrencyLimit, enabled: true, triggers, createdAt: timestamp, updatedAt: timestamp }; try { return this.presentJob(await this.jobs().create(job)); } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "Job slug is already in use"); throw error; } } async updateJob(jobId: string, input: JobInput & { expectedUpdatedAt?: string }) { await this.authorize("flows:write"); const repository = this.jobs(), current = await repository.getJob(jobId); if (!current) throw new ServiceError(404, "not_found", "Job not found"); const triggers = this.normalizedTriggers(input.triggers, current.triggers).map(trigger => ({ ...trigger, jobId })); - const updated = await repository.update({ ...current, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", model: input.model ?? "", effort: input.effort, executionTarget: await this.executionTarget(input.executionTargetId), concurrencyLimit: input.concurrencyLimit, triggers, updatedAt: new Date().toISOString() }, input.expectedUpdatedAt).catch(error => { if (error instanceof StaleJobEdit) throw new ServiceError(409, "stale_job", "This job changed. Reload its configuration before saving."); throw error; }); + const updated = await repository.update({ ...current, projectId: input.projectId ?? current.projectId, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", model: input.model ?? "", effort: input.effort, executionTarget: await this.executionTarget(input.executionTargetId), concurrencyLimit: input.concurrencyLimit, triggers, updatedAt: new Date().toISOString() }, input.expectedUpdatedAt).catch(error => { if (error instanceof StaleJobEdit) throw new ServiceError(409, "stale_job", "This job changed. Reload its configuration before saving."); throw error; }); await this.wakeScheduler(); return this.presentJob(updated); } diff --git a/packages/api/src/job-contracts.ts b/packages/api/src/job-contracts.ts index 4e04401c..30dd831c 100644 --- a/packages/api/src/job-contracts.ts +++ b/packages/api/src/job-contracts.ts @@ -2,6 +2,7 @@ import { z } from "zod"; import { jobInputSchema, triggerSchema, webhookTriggerConfigSchema } from "./flow-schemas"; export const jobPageQuery = z.object({ + projectId: z.guid().optional(), limit: z.coerce.number().int().min(1).max(100).default(30), cursor: z.guid().optional(), q: z.string().trim().max(120).default(""), @@ -10,6 +11,7 @@ export const jobPageQuery = z.object({ export type JobPageQuery = z.infer; export const jobSelectorItem = z.object({ id: z.guid(), name: z.string(), slug: z.string(), enabled: z.boolean() }); export const jobSummary = jobSelectorItem.extend({ + projectId: z.guid(), model: z.string(), effort: z.string(), agentKind: z.string(), concurrencyLimit: z.number().int(), runningCount: z.number().int(), lastRunState: z.enum(["queued", "reserved", "starting", "running", "blocked", "stopping", "succeeded", "failed", "stopped", "done", "ignored"]).nullable(), createdAt: z.string(), updatedAt: z.string(), @@ -30,7 +32,7 @@ export const triggerResponse = z.discriminatedUnion("kind", [ triggerSchema.options[3].extend(triggerIdentity), ]); export const jobResponse = z.object({ - id: z.guid(), name: z.string(), slug: z.string(), enabled: z.boolean(), + id: z.guid(), projectId: z.guid().optional(), name: z.string(), slug: z.string(), enabled: z.boolean(), promptTemplate: z.string(), runNameTemplate: z.string(), model: z.string(), effort: z.string().optional(), executionTarget: z.object({ connectionId: z.string(), workspace: z.string().optional(), cwd: z.string().optional(), agentKind: z.string() }), executionTargetId: z.string(), agentKind: z.string(), concurrencyLimit: z.number().int(), diff --git a/packages/api/src/job-domain.ts b/packages/api/src/job-domain.ts index 0dda2739..49bd8517 100644 --- a/packages/api/src/job-domain.ts +++ b/packages/api/src/job-domain.ts @@ -25,6 +25,7 @@ export interface Trigger { export interface Job { id: string; + projectId?: string; name: string; slug: string; promptTemplate: string; diff --git a/packages/api/src/postgres/job-repository.ts b/packages/api/src/postgres/job-repository.ts index b6a13b87..ef5ee23d 100644 --- a/packages/api/src/postgres/job-repository.ts +++ b/packages/api/src/postgres/job-repository.ts @@ -19,7 +19,7 @@ export class PostgresJobRepository implements JobRepository { private trigger(row: TriggerRow): Trigger { return { id: row.id, jobId: row.jobId, kind: row.kind, slug: row.slug, enabled: row.enabled, config: row.config, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; } private async mapped(row: JobRow, db: any = this.database.orm, loadedTriggers?: TriggerRow[]): Promise { const triggerRows: TriggerRow[] = loadedTriggers ?? await db.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, row.id), isNull(triggers.removedAt))).orderBy(triggers.position, triggers.createdAt, triggers.id); - return { id: row.id, name: row.name, slug: row.slug, promptTemplate: await this.decrypt(row.encryptedPromptTemplate), runNameTemplate: row.encryptedRunNameTemplate ? await this.decrypt(row.encryptedRunNameTemplate) : "", model: row.model, ...(row.effort ? { effort: row.effort } : {}), executionTarget: row.executionTarget, concurrencyLimit: row.concurrencyLimit, enabled: row.enabled, triggers: triggerRows.map(value => this.trigger(value)), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; + return { id: row.id, projectId: row.projectId, name: row.name, slug: row.slug, promptTemplate: await this.decrypt(row.encryptedPromptTemplate), runNameTemplate: row.encryptedRunNameTemplate ? await this.decrypt(row.encryptedRunNameTemplate) : "", model: row.model, ...(row.effort ? { effort: row.effort } : {}), executionTarget: row.executionTarget, concurrencyLimit: row.concurrencyLimit, enabled: row.enabled, triggers: triggerRows.map(value => this.trigger(value)), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; } async getJob(id: string): Promise { @@ -42,7 +42,7 @@ export class PostgresJobRepository implements JobRepository { async create(job: Job): Promise { return this.database.orm.transaction(async tx => { - const [row] = await tx.insert(jobs).values({ tenantId: this.tenantId, id: job.id, name: job.name, slug: job.slug, encryptedPromptTemplate: await this.encrypt(job.promptTemplate), encryptedRunNameTemplate: job.runNameTemplate ? await this.encrypt(job.runNameTemplate) : "", executionTarget: job.executionTarget, model: job.model, effort: job.effort ?? "", concurrencyLimit: job.concurrencyLimit, enabled: job.enabled, createdAt: new Date(job.createdAt), updatedAt: new Date(job.updatedAt) }).returning(); + const [row] = await tx.insert(jobs).values({ tenantId: this.tenantId, id: job.id, projectId: job.projectId ?? crypto.randomUUID(), name: job.name, slug: job.slug, encryptedPromptTemplate: await this.encrypt(job.promptTemplate), encryptedRunNameTemplate: job.runNameTemplate ? await this.encrypt(job.runNameTemplate) : "", executionTarget: job.executionTarget, model: job.model, effort: job.effort ?? "", concurrencyLimit: job.concurrencyLimit, enabled: job.enabled, createdAt: new Date(job.createdAt), updatedAt: new Date(job.updatedAt) }).returning(); await this.reconcileTriggers(tx, job, []); return this.mapped(row!, tx); }); @@ -55,7 +55,7 @@ export class PostgresJobRepository implements JobRepository { if (expectedUpdatedAt && current.updatedAt.toISOString() !== expectedUpdatedAt) throw new StaleJobEdit("Job changed since it was loaded"); job = { ...job, updatedAt: new Date(Math.max(Date.parse(job.updatedAt), current.updatedAt.getTime() + 1)).toISOString() }; const existing: TriggerRow[] = await tx.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, job.id), isNull(triggers.removedAt))).orderBy(triggers.position); - const [row] = await tx.update(jobs).set({ name: job.name, slug: job.slug, encryptedPromptTemplate: await this.encrypt(job.promptTemplate), encryptedRunNameTemplate: job.runNameTemplate ? await this.encrypt(job.runNameTemplate) : "", executionTarget: job.executionTarget, model: job.model, effort: job.effort ?? "", concurrencyLimit: job.concurrencyLimit, enabled: job.enabled, updatedAt: new Date(job.updatedAt) }).where(and(eq(jobs.tenantId, this.tenantId), eq(jobs.id, job.id))).returning(); + const [row] = await tx.update(jobs).set({ projectId: job.projectId, name: job.name, slug: job.slug, encryptedPromptTemplate: await this.encrypt(job.promptTemplate), encryptedRunNameTemplate: job.runNameTemplate ? await this.encrypt(job.runNameTemplate) : "", executionTarget: job.executionTarget, model: job.model, effort: job.effort ?? "", concurrencyLimit: job.concurrencyLimit, enabled: job.enabled, updatedAt: new Date(job.updatedAt) }).where(and(eq(jobs.tenantId, this.tenantId), eq(jobs.id, job.id))).returning(); await this.reconcileTriggers(tx, job, existing); await this.recordEdit(tx, job.id, job.updatedAt); return this.mapped(row!, tx); diff --git a/packages/api/src/postgres/job-summary-repository.ts b/packages/api/src/postgres/job-summary-repository.ts index 15c5af77..12c9661a 100644 --- a/packages/api/src/postgres/job-summary-repository.ts +++ b/packages/api/src/postgres/job-summary-repository.ts @@ -2,7 +2,7 @@ import type { Database } from "./database"; import type { JobPageQuery } from "../job-contracts"; interface SummaryRow { - id: string; name: string; slug: string; enabled: boolean; model: string; effort: string; + id: string; project_id: string; name: string; slug: string; enabled: boolean; model: string; effort: string; agent_kind: string; concurrency_limit: number; running_count: string; last_run_state: string | null; created_at: Date; updated_at: Date; } @@ -15,12 +15,13 @@ export class JobSummaryRepository { async page(input: JobPageQuery, selector = false) { const result = await this.database.pool.query(` WITH page AS MATERIALIZED ( - SELECT id,name,slug,enabled,model,effort,execution_target->>'agentKind' agent_kind, + SELECT id,project_id project_id,name,slug,enabled,model,effort,execution_target->>'agentKind' agent_kind, concurrency_limit,created_at,updated_at FROM app.jobs WHERE tenant_id=$1 AND ($2::uuid IS NULL OR id<$2) AND ($3='' OR strpos(lower(name),lower($3))>0 OR strpos(lower(slug),lower($3))>0) AND ($4::boolean IS NULL OR enabled=$4) - ORDER BY id DESC LIMIT $5 + AND ($5::uuid IS NULL OR project_id=$5) + ORDER BY id DESC LIMIT $6 ) SELECT p.*,s.running_count,s.last_run_state FROM page p ${selector ? "LEFT JOIN LATERAL (SELECT '0'::text running_count,NULL::text last_run_state) s ON true" : `LEFT JOIN ( @@ -28,10 +29,10 @@ export class JobSummaryRepository { (array_agg(r.state ORDER BY r.created_at DESC,r.id DESC))[1] last_run_state FROM app.job_runs r JOIN page ON page.id=r.job_id WHERE r.tenant_id=$1 GROUP BY r.job_id ) s ON s.job_id=p.id`} - ORDER BY p.id DESC`, [this.tenantId, input.cursor ?? null, input.q, input.enabled === undefined ? null : input.enabled === "true", input.limit + 1]); + ORDER BY p.id DESC`, [this.tenantId, input.cursor ?? null, input.q, input.enabled === undefined ? null : input.enabled === "true", input.projectId ?? null, input.limit + 1]); const rows = result.rows.slice(0, input.limit); return { - items: rows.map(row => ({ id: row.id, name: row.name, slug: row.slug, enabled: row.enabled, + items: rows.map(row => ({ id: row.id, projectId: row.project_id, name: row.name, slug: row.slug, enabled: row.enabled, ...(selector ? {} : { model: row.model, effort: row.effort, agentKind: row.agent_kind, concurrencyLimit: row.concurrency_limit, runningCount: Number(row.running_count ?? 0), lastRunState: row.last_run_state ?? null, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }) })), diff --git a/packages/api/src/postgres/project-repository.ts b/packages/api/src/postgres/project-repository.ts new file mode 100644 index 00000000..9d09372d --- /dev/null +++ b/packages/api/src/postgres/project-repository.ts @@ -0,0 +1,13 @@ +import type { Database } from "./database"; + +export interface Project { id: string; name: string; description?: string; createdAt: string; updatedAt: string; jobCount: number; } +export class ProjectRepository { + constructor(private database: Database, private tenantId: string) {} + private map(row: any): Project { return { id: row.id, name: row.name, ...(row.description ? { description: row.description } : {}), createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString(), jobCount: Number(row.job_count ?? 0) }; } + async list() { const result = await this.database.pool.query(`SELECT p.*,count(j.id)::int job_count FROM app.projects p LEFT JOIN app.jobs j ON j.tenant_id=p.tenant_id AND j.project_id=p.id WHERE p.tenant_id=$1 GROUP BY p.tenant_id,p.id ORDER BY p.name,p.id`, [this.tenantId]); return result.rows.map(row => this.map(row)); } + async get(id: string) { const result = await this.database.pool.query(`SELECT p.*,count(j.id)::int job_count FROM app.projects p LEFT JOIN app.jobs j ON j.tenant_id=p.tenant_id AND j.project_id=p.id WHERE p.tenant_id=$1 AND p.id=$2 GROUP BY p.tenant_id,p.id`, [this.tenantId,id]); return result.rows[0] ? this.map(result.rows[0]) : null; } + async defaultProjectId() { const result = await this.database.pool.query(`INSERT INTO app.projects(tenant_id,id,name,description) VALUES ($1,md5($1::text || ':default')::uuid,'Default','Jobs created by legacy clients') ON CONFLICT (tenant_id,name) DO UPDATE SET updated_at=app.projects.updated_at RETURNING id`, [this.tenantId]); return result.rows[0].id as string; } + async create(name: string, description?: string) { const result = await this.database.pool.query(`INSERT INTO app.projects(tenant_id,id,name,description) VALUES ($1,gen_random_uuid(),$2,$3) RETURNING *`, [this.tenantId,name.trim(),description?.trim() || null]); return this.map({ ...result.rows[0], job_count: 0 }); } + async update(id: string, name: string, description?: string) { const result = await this.database.pool.query(`UPDATE app.projects SET name=$3,description=$4,updated_at=now() WHERE tenant_id=$1 AND id=$2 RETURNING *`, [this.tenantId,id,name.trim(),description?.trim() || null]); return result.rows[0] ? this.map({ ...result.rows[0], job_count: 0 }) : null; } + async remove(id: string) { return this.database.transaction(async client => { const project = await client.query(`SELECT id FROM app.projects WHERE tenant_id=$1 AND id=$2 FOR UPDATE`, [this.tenantId,id]); if (!project.rows.length) return "missing" as const; const jobs = await client.query(`SELECT 1 FROM app.jobs WHERE tenant_id=$1 AND project_id=$2 LIMIT 1`, [this.tenantId,id]); if (jobs.rows.length) return "nonempty" as const; await client.query(`DELETE FROM app.projects 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 ef870dc1..006b3087 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -43,10 +43,11 @@ export const connections = app.table("connections", { tenantId: uuid("tenant_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')`)]); export const githubSetupStates = app.table("github_setup_states", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), nonce: text("nonce").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), usedAt: timestamp("used_at", { withTimezone: true }) }, t => [primaryKey({ columns: [t.tenantId, t.nonce] })]); +export const projects = app.table("projects", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), name: text("name").notNull(), description: text("description"), createdAt: createdAt(), updatedAt: updatedAt() }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.name), index("projects_tenant_updated").on(t.tenantId, t.updatedAt)]); export const jobs = app.table("jobs", { - tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), name: text("name").notNull(), slug: text("slug").notNull(), encryptedPromptTemplate: text("encrypted_prompt_template").notNull(), encryptedRunNameTemplate: text("encrypted_run_name_template").notNull().default(""), executionTarget: jsonb("execution_target").$type().notNull(), model: text("model").notNull().default(""), effort: text("effort").notNull().default(""), concurrencyLimit: integer("concurrency_limit").notNull(), enabled: boolean("enabled").notNull().default(true), createdAt: createdAt(), updatedAt: updatedAt(), -}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.slug), check("jobs_concurrency_limit_check", sql`${t.concurrencyLimit} >= 1`)]); + tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), projectId: uuid("project_id").notNull(), name: text("name").notNull(), slug: text("slug").notNull(), encryptedPromptTemplate: text("encrypted_prompt_template").notNull(), encryptedRunNameTemplate: text("encrypted_run_name_template").notNull().default(""), executionTarget: jsonb("execution_target").$type().notNull(), model: text("model").notNull().default(""), effort: text("effort").notNull().default(""), concurrencyLimit: integer("concurrency_limit").notNull(), enabled: boolean("enabled").notNull().default(true), createdAt: createdAt(), updatedAt: updatedAt(), +}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.slug), foreignKey({ columns: [t.tenantId, t.projectId], foreignColumns: [projects.tenantId, projects.id] }).onDelete("restrict"), index("jobs_tenant_project_updated").on(t.tenantId, t.projectId, t.updatedAt), check("jobs_concurrency_limit_check", sql`${t.concurrencyLimit} >= 1`)]); export const triggers = app.table("triggers", { tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), kind: text("kind").$type().notNull(), slug: text("slug").notNull(), enabled: boolean("enabled").notNull().default(true), config: jsonb("config").$type>().notNull().default({}), position: integer("position").notNull().default(0), createdAt: createdAt(), updatedAt: updatedAt(), removedAt: timestamp("removed_at", { withTimezone: true }), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), uniqueIndex("triggers_active_slug").on(t.tenantId, t.jobId, t.slug).where(sql`${t.removedAt} is null`), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), check("no_webhook_handler_code", sql`NOT (${t.config} ? 'handlerCode')`), check("triggers_kind_check", sql`${t.kind} in ('manual','schedule','webhook','jobLifecycle')`)]); @@ -124,7 +125,7 @@ export const runRelations = relations(runs, ({ one, many }) => ({ export const databaseSchema = { schemaMigrations, tenants, oauthConnections, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens, - connections, linearWorkspaces, githubInstallations, githubSetupStates, jobs, triggers, webhookConditionsCutover, invocations, jobRuns, runs, runArtifacts, + connections, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, triggers, webhookConditionsCutover, invocations, jobRuns, runs, runArtifacts, runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, jobEditDeliveries, jobEvents, webhookDeliveries, webhookDeliveryEvents, pendingVerifications, tailFingerprints, wakeHints, runTraceCursors, runTraceChunks, runTraceProjections, traceReplayLimits, traceReplayOperations, diff --git a/packages/api/src/project-contracts.ts b/packages/api/src/project-contracts.ts new file mode 100644 index 00000000..0f3c1937 --- /dev/null +++ b/packages/api/src/project-contracts.ts @@ -0,0 +1,3 @@ +import { z } from "zod"; +export const projectResponse = z.object({ id: z.guid(), name: z.string(), description: z.string().optional(), createdAt: z.string(), updatedAt: z.string(), jobCount: z.number().int() }); +export const projectInput = z.object({ name: z.string().trim().min(1).max(120), description: z.string().trim().max(2000).optional() }).strict(); diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index 4c516397..665f4037 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -103,6 +103,11 @@ function createMcpServer(service: ApiService): McpServer { tool("stop_run", "Stop an active run", runIdSchema, ({ runId }: any) => service.stopRun(runId)); tool("kill_run", "Force a run in any non-terminal state to stop immediately, release its concurrency slot, and clean up its backend asynchronously.", runIdSchema, ({ runId }: any) => service.killRun(runId)); tool("list_jobs", "List jobs with their current run count and maximum concurrency", z.object({}), () => service.listJobs()); + tool("list_projects", "List tenant projects with job counts", z.object({}), () => service.listProjects()); + tool("get_project", "Get a tenant project", z.object({ projectId: z.string().min(1) }), ({ projectId }: any) => service.getProject(projectId)); + tool("create_project", "Create a tenant project", z.object({ name: z.string().trim().min(1).max(120), description: z.string().max(2000).optional() }), (input: any) => service.createProject(input)); + tool("update_project", "Rename or describe a tenant project", z.object({ projectId: z.string().min(1), name: z.string().trim().min(1).max(120), description: z.string().max(2000).optional() }), ({ projectId, ...input }: any) => service.updateProject(projectId, input)); + tool("delete_project", "Delete an empty tenant project", z.object({ projectId: z.string().min(1) }), ({ projectId }: any) => service.deleteProject(projectId)); tool("get_job", "Get a job with its current run count and maximum concurrency", jobIdSchema, ({ jobId }: any) => service.getJob(jobId)); tool("create_job", "Create a job using an executionTargetId returned by list_execution_targets. Credentials are never accepted or returned.", jobInputSchema, (input: any) => service.createJob(input)); tool("update_job", "Replace a job configuration. Credentials are never accepted or returned.", jobUpdateInput.extend({ jobId: z.string().min(1) }), ({ jobId, ...input }: any) => service.updateJob(jobId, input)); diff --git a/packages/app/src/features/auth/account-bar.tsx b/packages/app/src/features/auth/account-bar.tsx index 439ac764..abde715c 100644 --- a/packages/app/src/features/auth/account-bar.tsx +++ b/packages/app/src/features/auth/account-bar.tsx @@ -33,7 +33,7 @@ export function AccountBar() {