diff --git a/.prettierrc.json b/.prettierrc.json index 4ddc855d..d064e915 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -8,7 +8,7 @@ "trailingComma": "none", "printWidth": 160, "arrowParens": "always", - "objectWrap": "collapse", + "objectWrap": "preserve", "plugins": ["prettier-plugin-tailwindcss"], "tailwindStylesheet": "src/app/globals.css", "tailwindFunctions": ["cn", "cva"], diff --git a/GLOSSARY.md b/GLOSSARY.md index a47a3084..dd32da4e 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -67,6 +67,10 @@ _Avoid_: global Add-on configuration, runtime version cache The Cluster Add-on that installs the Agent Sandbox controller and its extension CRDs, including SandboxTemplate and SandboxWarmPool. It does not create user workload resources. _Avoid_: Agent, Agent runtime +**Node Monitoring History**: +A record of CPU, memory, and occupied node filesystem usage over time for each cluster node. Cluster totals include all nodes measured at a given time. +_Avoid_: App monitoring history, volume usage + **App**: A deployable workload managed by QuickStack. diff --git a/eslint.config.mjs b/eslint.config.mjs index e0710e9b..2a0a30bb 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -26,6 +26,7 @@ const eslintConfig = [ "unused-imports": unusedImports, }, rules: { + "curly": ["error", "all"], "no-unused-vars": "off", "@typescript-eslint/no-unused-vars": "off", "unused-imports/no-unused-imports": "error", diff --git a/prisma/migrations/20261116120000_node_monitoring_history/migration.sql b/prisma/migrations/20261116120000_node_monitoring_history/migration.sql new file mode 100644 index 00000000..b64f79fd --- /dev/null +++ b/prisma/migrations/20261116120000_node_monitoring_history/migration.sql @@ -0,0 +1,10 @@ +CREATE TABLE "NodeMonitoringSample" ( + "id" TEXT NOT NULL PRIMARY KEY, + "sampledAt" DATETIME NOT NULL, + "nodeName" TEXT NOT NULL, + "cpuCores" REAL, + "ramBytes" REAL, + "diskBytes" REAL +); +CREATE INDEX "NodeMonitoringSample_sampledAt_idx" ON "NodeMonitoringSample"("sampledAt"); +CREATE INDEX "NodeMonitoringSample_nodeName_sampledAt_idx" ON "NodeMonitoringSample"("nodeName", "sampledAt"); diff --git a/prisma/migrations/20261116130000_unify_monitoring_samples/migration.sql b/prisma/migrations/20261116130000_unify_monitoring_samples/migration.sql new file mode 100644 index 00000000..1f29d214 --- /dev/null +++ b/prisma/migrations/20261116130000_unify_monitoring_samples/migration.sql @@ -0,0 +1,20 @@ +-- Monitoring history is beta data: discard existing App and Node samples. +DROP TABLE "AppMonitoringSample"; +DROP TABLE "NodeMonitoringSample"; + +CREATE TABLE "MonitoringSample" ( + "id" TEXT NOT NULL PRIMARY KEY, + "sampledAt" DATETIME NOT NULL, + "measuredAt" DATETIME, + "appId" TEXT, + "nodeName" TEXT, + "cpuCores" REAL, + "ramBytes" REAL, + "nodeFilesystemUsedBytes" REAL, + CONSTRAINT "MonitoringSample_appId_fkey" FOREIGN KEY ("appId") REFERENCES "App" ("id") ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT "MonitoringSample_owner_check" CHECK (("appId" IS NOT NULL AND "nodeName" IS NULL) OR ("appId" IS NULL AND "nodeName" IS NOT NULL)), + CONSTRAINT "MonitoringSample_storage_check" CHECK ("appId" IS NULL OR "nodeFilesystemUsedBytes" IS NULL) +); +CREATE INDEX "MonitoringSample_appId_sampledAt_idx" ON "MonitoringSample"("appId", "sampledAt"); +CREATE INDEX "MonitoringSample_nodeName_sampledAt_idx" ON "MonitoringSample"("nodeName", "sampledAt"); +CREATE INDEX "MonitoringSample_sampledAt_idx" ON "MonitoringSample"("sampledAt"); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 80c07ca0..04a91c2c 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -466,7 +466,7 @@ model App { appPorts AppPort[] appNodePorts AppNodePort[] appVolumes AppVolume[] - monitoringSamples AppMonitoringSample[] + monitoringSamples MonitoringSample[] appFileMounts AppFileMount[] appBasicAuths AppBasicAuth[] appGitSshKey AppGitSshKey? @@ -649,17 +649,21 @@ model AppBasicAuth { updatedAt DateTime @updatedAt } -// One row per known App and Volume at each collection time. Null values are gaps. -model AppMonitoringSample { - id String @id @default(uuid()) - sampledAt DateTime - appId String - app App @relation(fields: [appId], references: [id], onDelete: Cascade) - cpuCores Float? - ramBytes Float? - measuredAt DateTime? +// One row per App or Node at each collection time. Null metric values are gaps. +// The migration enforces exactly one owner and reserves filesystem usage for Nodes. +model MonitoringSample { + id String @id @default(uuid()) + sampledAt DateTime + measuredAt DateTime? + appId String? + app App? @relation(fields: [appId], references: [id], onDelete: Cascade) + nodeName String? + cpuCores Float? + ramBytes Float? + nodeFilesystemUsedBytes Float? @@index([appId, sampledAt]) + @@index([nodeName, sampledAt]) @@index([sampledAt]) } diff --git a/src/__tests__/integration/server/mcp/mcp-eval.integration.spec.ts b/src/__tests__/integration/server/mcp/mcp-eval.integration.spec.ts index c33af21c..3ef4febe 100644 --- a/src/__tests__/integration/server/mcp/mcp-eval.integration.spec.ts +++ b/src/__tests__/integration/server/mcp/mcp-eval.integration.spec.ts @@ -7,93 +7,105 @@ import { z } from 'zod'; import { createQuickStackMcpHandler } from '@/server/mcp/mcp-handler'; function runHarness(url: string, apiKey: string): Promise<{ code: number | null; stdout: string; stderr: string }> { - return new Promise((resolve, reject) => { - const child = spawn(process.execPath, ['scripts/mcp-eval.mjs', '--url', url, '--api-key', apiKey], { - cwd: process.cwd(), - env: process.env, - }); - let stdout = ''; - let stderr = ''; - child.stdout.on('data', (chunk) => { stdout += chunk.toString(); }); - child.stderr.on('data', (chunk) => { stderr += chunk.toString(); }); - child.on('error', reject); - child.on('close', (code) => resolve({ code, stdout, stderr })); + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, ['scripts/mcp-eval.mjs', '--url', url, '--api-key', apiKey], { + cwd: process.cwd(), + env: process.env }); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (chunk) => { + stdout += chunk.toString(); + }); + child.stderr.on('data', (chunk) => { + stderr += chunk.toString(); + }); + child.on('error', reject); + child.on('close', (code) => resolve({ code, stdout, stderr })); + }); } describe('MCP evaluation harness', () => { - it('runs the scripted tasks against the real MCP handler', async () => { - const fixture = new Elysia({ prefix: '/api/v1' }) - .get('/projects', ({ query }) => { - const projects = [{ id: 'p1', name: 'Demo' }, { id: 'p2', name: 'Second' }]; - if (query.limit === undefined) return projects; - const limit = Number(query.limit); - return { - items: projects.slice(0, limit), - total: projects.length, - limit, - nextCursor: limit < projects.length ? String(limit) : null, - }; - }, { - query: z.object({ limit: z.coerce.number().optional() }), - response: { 200: z.union([z.array(z.object({ id: z.string(), name: z.string() })), z.object({ - items: z.array(z.object({ id: z.string(), name: z.string() })), - total: z.number(), - limit: z.number(), - nextCursor: z.string().nullable(), - })]) }, - detail: { operationId: 'listProjects', summary: 'List projects', tags: ['Projects'] }, - }) - .post('/apps/:appId/deploy', ({ params }) => ({ deploymentId: `deploy-${params.appId}` }), { - params: z.object({ appId: z.string() }), - query: z.object({ forceRebuild: z.coerce.boolean().optional() }), - response: { 200: z.object({ deploymentId: z.string() }) }, - detail: { operationId: 'deployApp', summary: 'Deploy app', description: 'Deploy an app.', tags: ['Apps'] }, - }); + it('runs the scripted tasks against the real MCP handler', async () => { + const fixture = new Elysia({ prefix: '/api/v1' }) + .get( + '/projects', + ({ query }) => { + const projects = [ + { id: 'p1', name: 'Demo' }, + { id: 'p2', name: 'Second' } + ]; + if (query.limit === undefined) { + return projects; + } + const limit = Number(query.limit); + return { + items: projects.slice(0, limit), + total: projects.length, + limit, + nextCursor: limit < projects.length ? String(limit) : null + }; + }, + { + query: z.object({ limit: z.coerce.number().optional() }), + response: { + 200: z.union([ + z.array(z.object({ id: z.string(), name: z.string() })), + z.object({ + items: z.array(z.object({ id: z.string(), name: z.string() })), + total: z.number(), + limit: z.number(), + nextCursor: z.string().nullable() + }) + ]) + }, + detail: { operationId: 'listProjects', summary: 'List projects', tags: ['Projects'] } + } + ) + .post('/apps/:appId/deploy', ({ params }) => ({ deploymentId: `deploy-${params.appId}` }), { + params: z.object({ appId: z.string() }), + query: z.object({ forceRebuild: z.coerce.boolean().optional() }), + response: { 200: z.object({ deploymentId: z.string() }) }, + detail: { operationId: 'deployApp', summary: 'Deploy app', description: 'Deploy an app.', tags: ['Apps'] } + }); - const handler = createQuickStackMcpHandler({ - app: fixture, - resolveAuthInfo: async () => ({ token: 'eval-token', clientId: 'eval', scopes: [] }), - }); - const server = createServer(async (request, response) => { - const chunks: Buffer[] = []; - for await (const chunk of request) { - chunks.push(Buffer.from(chunk)); - } - const method = request.method ?? 'GET'; - const body = method === 'GET' || method === 'HEAD' - ? undefined - : new Uint8Array(Buffer.concat(chunks)); - const fetchResponse = await handler.fetch(new Request( - `http://127.0.0.1${request.url ?? '/api/mcp'}`, - { - method, - headers: request.headers as Record, - body, - } - )); - response.statusCode = fetchResponse.status; - fetchResponse.headers.forEach((value, key) => response.setHeader(key, value)); - response.end(Buffer.from(await fetchResponse.arrayBuffer())); - }); - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const handler = createQuickStackMcpHandler({ + app: fixture, + resolveAuthInfo: async () => ({ token: 'eval-token', clientId: 'eval', scopes: [] }) + }); + const server = createServer(async (request, response) => { + const chunks: Buffer[] = []; + for await (const chunk of request) { + chunks.push(Buffer.from(chunk)); + } + const method = request.method ?? 'GET'; + const body = method === 'GET' || method === 'HEAD' ? undefined : new Uint8Array(Buffer.concat(chunks)); + const fetchResponse = await handler.fetch( + new Request(`http://127.0.0.1${request.url ?? '/api/mcp'}`, { + method, + headers: request.headers as Record, + body + }) + ); + response.statusCode = fetchResponse.status; + fetchResponse.headers.forEach((value, key) => response.setHeader(key, value)); + response.end(Buffer.from(await fetchResponse.arrayBuffer())); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); - try { - const address = server.address(); - if (!address || typeof address === 'string') { - throw new Error('Test server did not expose a port.'); - } - const { code, stdout, stderr } = await runHarness( - `http://127.0.0.1:${address.port}/api/mcp`, - 'eval-token' - ); + try { + const address = server.address(); + if (!address || typeof address === 'string') { + throw new Error('Test server did not expose a port.'); + } + const { code, stdout, stderr } = await runHarness(`http://127.0.0.1:${address.port}/api/mcp`, 'eval-token'); - expect(stderr).toBe(''); - expect(stdout).toContain('Success: 3/3 tasks'); - expect(code).toBe(0); - } finally { - await handler.close(); - await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve())); - } - }, 60_000); + expect(stderr).toBe(''); + expect(stdout).toContain('Success: 3/3 tasks'); + expect(code).toBe(0); + } finally { + await handler.close(); + await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))); + } + }, 60_000); }); diff --git a/src/__tests__/integration/server/services/app-monitoring-history.integration.spec.ts b/src/__tests__/integration/server/services/app-monitoring-history.integration.spec.ts index c9ff01c4..8723a944 100644 --- a/src/__tests__/integration/server/services/app-monitoring-history.integration.spec.ts +++ b/src/__tests__/integration/server/services/app-monitoring-history.integration.spec.ts @@ -2,7 +2,7 @@ vi.mock('@/server/adapter/kubernetes-api.adapter', () => ({ default: {} })); import { createPrismaTestContext } from '@/__tests__/prisma-test.utils'; -import adapter from '@/server/adapter/app-history.adapter'; +import nodeHistory from '@/server/services/standalone-services/node-monitoring-history.service'; import history from '@/server/services/standalone-services/app-monitoring-history.service'; import metrics from '@/server/services/standalone-services/app-history.service'; import filesystem from '@/server/services/standalone-services/app-volume-filesystem.service'; @@ -15,7 +15,7 @@ describe('App monitoring history persistence', () => { await db.project.create({ data: { id: 'project', name: 'Project' } }); await db.app.create({ data: { id: 'app', name: 'App', projectId: 'project' } }); const cutoff = new Date(Date.now() - 3600_000); - await adapter.save( + await history.save( [ { appId: 'app', sampledAt: new Date(cutoff.getTime() - 1), cpuCores: 1, ramBytes: 2 }, { appId: 'app', sampledAt: cutoff, cpuCores: 3, ramBytes: 4 } @@ -34,11 +34,11 @@ describe('App monitoring history persistence', () => { await db.project.create({ data: { id: 'project', name: 'Project' } }); await db.app.create({ data: { id: 'app', name: 'App', projectId: 'project' } }); const now = Date.now(); - await adapter.save([{ appId: 'app', sampledAt: new Date(now - 2 * 3600_000), cpuCores: 1, ramBytes: 2 }], [], [], new Date(now - 24 * 3600_000)); - await adapter.setRetentionHours(1); + await history.save([{ appId: 'app', sampledAt: new Date(now - 2 * 3600_000), cpuCores: 1, ramBytes: 2 }], [], [], new Date(now - 24 * 3600_000)); + await history.setRetentionHours(1); expect((await history.getHistory(['app'])).points).toEqual([]); - await adapter.save([], [], [], new Date(now - (await adapter.getRetentionHours()) * 3600_000)); - expect(await db.appMonitoringSample.count()).toBe(0); + await history.save([], [], [], new Date(now - (await history.getRetentionHours()) * 3600_000)); + expect(await db.monitoringSample.count()).toBe(0); }); it('stores shared Volume usage once and exposes it only through accessible mounts', async () => { @@ -53,7 +53,7 @@ describe('App monitoring history persistence', () => { await db.appVolume.create({ data: { id: 'base', appId: 'one', containerMountPath: '/data', size: 1 } }); await db.appVolume.create({ data: { id: 'shared', appId: 'two', containerMountPath: '/share', size: 1, sharedVolumeId: 'base' } }); const sampledAt = new Date(); - await adapter.save( + await history.save( [], [{ id: 'sample', volumeId: 'base', sampledAt, status: 'available', usedBytes: 42, measuredAt: sampledAt }], [ @@ -104,6 +104,24 @@ describe('App monitoring history persistence', () => { } }); + it('keeps App and Node histories separate in the shared table', async () => { + const db = ctx.getDataAccess().client; + await db.project.create({ data: { id: 'project', name: 'Project' } }); + await db.app.create({ data: { id: 'app', name: 'App', projectId: 'project' } }); + const sampledAt = new Date(); + const cutoff = new Date(sampledAt.getTime() - 3600_000); + await history.save([{ appId: 'app', sampledAt, cpuCores: 1, ramBytes: 2 }], [], [], cutoff); + await nodeHistory.save([{ nodeName: 'node', sampledAt, measuredAt: sampledAt, cpuCores: 3, ramBytes: 4, nodeFilesystemUsedBytes: 5 }], cutoff); + expect((await history.getRawHistory(['app'], cutoff))[0]).toHaveLength(1); + expect(await db.monitoringSample.findMany({ where: { nodeName: { not: null }, sampledAt: { gte: cutoff } } })).toMatchObject([ + { nodeName: 'node', measuredAt: sampledAt, nodeFilesystemUsedBytes: 5 } + ]); + await db.app.delete({ where: { id: 'app' } }); + expect(await db.monitoringSample.findMany({ where: { nodeName: { not: null }, sampledAt: { gte: cutoff } } })).toHaveLength(1); + await nodeHistory.save([], new Date(sampledAt.getTime() + 1)); + expect(await db.monitoringSample.findMany({ where: { nodeName: { not: null }, sampledAt: { gte: cutoff } } })).toHaveLength(0); + }); + it('reads a day of five-minute history for 100 Apps', async () => { const db = ctx.getDataAccess().client; await db.project.create({ data: { id: 'project', name: 'Project' } }); @@ -113,7 +131,7 @@ describe('App monitoring history persistence', () => { const samples = Array.from({ length: 288 }, (_, index) => appIds.map((appId) => ({ appId, sampledAt: new Date(now - index * 5 * 60_000), cpuCores: 0.25, ramBytes: 1024 })) ).flat(); - await adapter.save(samples, [], [], new Date(now - 24 * 3600_000)); + await history.save(samples, [], [], new Date(now - 24 * 3600_000)); const result = await history.getHistory(appIds); expect(result.points).toHaveLength(288); expect(result.points[0]).toMatchObject({ cpuCores: 25, ramBytes: 102400 }); diff --git a/src/__tests__/integration/server/services/monitoring-sample-migration.integration.spec.ts b/src/__tests__/integration/server/services/monitoring-sample-migration.integration.spec.ts new file mode 100644 index 00000000..5c98c12d --- /dev/null +++ b/src/__tests__/integration/server/services/monitoring-sample-migration.integration.spec.ts @@ -0,0 +1,34 @@ +// @vitest-environment node +import Database from 'better-sqlite3'; +import { readFileSync } from 'node:fs'; + +it('replaces beta samples while preserving volumes and enforcing ownership and cascade rules', () => { + const db = new Database(':memory:'); + db.pragma('foreign_keys = ON'); + try { + db.exec(` + CREATE TABLE App (id TEXT PRIMARY KEY); + CREATE TABLE AppMonitoringSample (id TEXT PRIMARY KEY); + CREATE TABLE NodeMonitoringSample (id TEXT PRIMARY KEY); + CREATE TABLE AppVolumeMonitoringSample (id TEXT PRIMARY KEY); + INSERT INTO App VALUES ('app'); + INSERT INTO AppMonitoringSample VALUES ('old-app'); + INSERT INTO NodeMonitoringSample VALUES ('old-node'); + INSERT INTO AppVolumeMonitoringSample VALUES ('volume'); + `); + db.exec(readFileSync('prisma/migrations/20261116130000_unify_monitoring_samples/migration.sql', 'utf8')); + expect(db.prepare('SELECT count(*) AS n FROM MonitoringSample').get()).toEqual({ n: 0 }); + expect(db.prepare('SELECT count(*) AS n FROM AppVolumeMonitoringSample').get()).toEqual({ n: 1 }); + const insert = db.prepare('INSERT INTO MonitoringSample (id, sampledAt, appId, nodeName, nodeFilesystemUsedBytes) VALUES (?, ?, ?, ?, ?)'); + insert.run('app-sample', 1, 'app', null, null); + insert.run('node-sample', 1, null, 'node', 5); + expect(() => insert.run('none', 1, null, null, null)).toThrow(); + expect(() => insert.run('both', 1, 'app', 'node', null)).toThrow(); + expect(() => insert.run('storage-on-app', 1, 'app', null, 5)).toThrow(); + expect(() => insert.run('missing-app', 1, 'missing', null, null)).toThrow(); + db.prepare('DELETE FROM App WHERE id = ?').run('app'); + expect(db.prepare('SELECT id FROM MonitoringSample').all()).toEqual([{ id: 'node-sample' }]); + } finally { + db.close(); + } +}); diff --git a/src/app/api/agent-sandboxes/route.ts b/src/app/api/agent-sandboxes/route.ts index cb53ea42..ab9f0e3b 100644 --- a/src/app/api/agent-sandboxes/route.ts +++ b/src/app/api/agent-sandboxes/route.ts @@ -1,111 +1,110 @@ -import k3s from "@/server/adapter/kubernetes-api.adapter"; -import { - BASE_SANDBOX_API_GROUP, - CLAIM_PLURAL, - SANDBOX_API_GROUP, - SANDBOX_API_VERSION, - SANDBOX_PLURAL, -} from "@/server/adapter/agent-sandbox.adapter"; -import agentRuntimeService from "@/server/services/agent-runtime.service"; -import agentService from "@/server/services/agent.service"; -import { isAuthorizedReadForWorkload, simpleRoute } from "@/server/utils/action-wrapper.utils"; -import { Constants } from "@/shared/utils/constants"; +import k3s from '@/server/adapter/kubernetes-api.adapter'; +import { BASE_SANDBOX_API_GROUP, CLAIM_PLURAL, SANDBOX_API_GROUP, SANDBOX_API_VERSION, SANDBOX_PLURAL } from '@/server/adapter/agent-sandbox.adapter'; +import agentRuntimeService from '@/server/services/agent-runtime.service'; +import agentService from '@/server/services/agent.service'; +import { isAuthorizedReadForWorkload, simpleRoute } from '@/server/utils/action-wrapper.utils'; +import { Constants } from '@/shared/utils/constants'; import * as k8s from '@kubernetes/client-node'; -import z from "zod"; -import { AgentSandboxUtils } from "@/server/utils/agent-sandbox.utils"; +import z from 'zod'; +import { AgentSandboxUtils } from '@/server/utils/agent-sandbox.utils'; // Prevents this route's response from being cached -export const dynamic = "force-dynamic"; +export const dynamic = 'force-dynamic'; export async function POST(request: Request) { - return simpleRoute(async () => { + return simpleRoute(async () => { + const inputParam = z + .object({ + agentId: z.string() + }) + .parse(await request.json()); - const inputParam = z.object({ - agentId: z.string(), - }).parse(await request.json()); + await isAuthorizedReadForWorkload(inputParam.agentId); + const agent = await agentService.getById(inputParam.agentId); + const namespace = agent.project.id; - await isAuthorizedReadForWorkload(inputParam.agentId); - const agent = await agentService.getById(inputParam.agentId); - const namespace = agent.project.id; + const encoder = new TextEncoder(); + let shouldStopStreaming = false; + let watchRequest: { abort: () => void } | null = null; - const encoder = new TextEncoder(); - let shouldStopStreaming = false; - let watchRequest: { abort: () => void } | null = null; + let agentSandboxes = await agentRuntimeService.listSandboxes(agent.id); - let agentSandboxes = await agentRuntimeService.listSandboxes(agent.id); + const customReadable = new ReadableStream({ + async start(controller) { + const send = (data: any) => { + if (shouldStopStreaming) { + return; + } + try { + controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`)); + } catch (e) { + console.error(`[ENQUEUE ERROR] Error while enqueueing Agent Sandbox Status data: `, e); + shouldStopStreaming = true; + controller.close(); + } + }; - const customReadable = new ReadableStream({ - async start(controller) { + // 1. Send full initial snapshot + send({ type: 'FULL', data: agentSandboxes }); - const send = (data: any) => { - if (shouldStopStreaming) return; - try { - controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`)); - } catch (e) { - console.error(`[ENQUEUE ERROR] Error while enqueueing Agent Sandbox Status data: `, e); - shouldStopStreaming = true; - controller.close(); - } - }; - - // 1. Send full initial snapshot - send({ type: 'FULL', data: agentSandboxes }); - - - // 2. Watch for changes — direct base Sandboxes for PER_CUSTOM_TAG agents, claims otherwise - const usesDirectSandbox = AgentSandboxUtils.usesPerCustomTagVolume(agent.agentVolumes); - const watchPath = usesDirectSandbox - ? `/apis/${BASE_SANDBOX_API_GROUP}/${SANDBOX_API_VERSION}/namespaces/${namespace}/${SANDBOX_PLURAL}` - : `/apis/${SANDBOX_API_GROUP}/${SANDBOX_API_VERSION}/namespaces/${namespace}/${CLAIM_PLURAL}`; - const kc = k3s.getKubeConfig(); - const watch = new k8s.Watch(kc); - console.log("[START] Starting watch for agent sandboxes in namespace", namespace); - watchRequest = await watch.watch( - watchPath, - { labelSelector: `${Constants.QS_ANNOTATION_AGENT_ID}=${inputParam.agentId}` }, - async (type, apiObj) => { - if (shouldStopStreaming) return; + // 2. Watch for changes — direct base Sandboxes for PER_CUSTOM_TAG agents, claims otherwise + const usesDirectSandbox = AgentSandboxUtils.usesPerCustomTagVolume(agent.agentVolumes); + const watchPath = usesDirectSandbox + ? `/apis/${BASE_SANDBOX_API_GROUP}/${SANDBOX_API_VERSION}/namespaces/${namespace}/${SANDBOX_PLURAL}` + : `/apis/${SANDBOX_API_GROUP}/${SANDBOX_API_VERSION}/namespaces/${namespace}/${CLAIM_PLURAL}`; + const kc = k3s.getKubeConfig(); + const watch = new k8s.Watch(kc); + console.log('[START] Starting watch for agent sandboxes in namespace', namespace); + watchRequest = await watch.watch( + watchPath, + { labelSelector: `${Constants.QS_ANNOTATION_AGENT_ID}=${inputParam.agentId}` }, + async (type, apiObj) => { + if (shouldStopStreaming) { + return; + } - // DELETED: only need the name — apiObj is the deleted object - if (type === 'DELETED') { - const name = apiObj?.metadata?.name; - if (name) { - send({ type: 'DELETED', sandbox: { name } }); - } - return; - } + // DELETED: only need the name — apiObj is the deleted object + if (type === 'DELETED') { + const name = apiObj?.metadata?.name; + if (name) { + send({ type: 'DELETED', sandbox: { name } }); + } + return; + } - // ADDED / MODIFIED: map full object to sandbox DTO - const sandbox = usesDirectSandbox - ? agentRuntimeService.mapSandboxToSandbox(apiObj, namespace) - : agentRuntimeService.mapClaimToSandbox(apiObj, namespace); - send({ type, sandbox }); - }, - (err) => { - if (err) console.error('agent sandboxes watch error', err); - console.log('agent sandboxes watch ended'); - if (!shouldStopStreaming) { - controller.close(); - } - } - ); - }, - cancel() { - console.log("[LEAVE] Cancelling informer for agent sandboxes"); - shouldStopStreaming = true; - if (watchRequest && typeof watchRequest.abort === 'function') { - watchRequest.abort(); - } + // ADDED / MODIFIED: map full object to sandbox DTO + const sandbox = usesDirectSandbox + ? agentRuntimeService.mapSandboxToSandbox(apiObj, namespace) + : agentRuntimeService.mapClaimToSandbox(apiObj, namespace); + send({ type, sandbox }); + }, + (err) => { + if (err) { + console.error('agent sandboxes watch error', err); + } + console.log('agent sandboxes watch ended'); + if (!shouldStopStreaming) { + controller.close(); } - }); + } + ); + }, + cancel() { + console.log('[LEAVE] Cancelling informer for agent sandboxes'); + shouldStopStreaming = true; + if (watchRequest && typeof watchRequest.abort === 'function') { + watchRequest.abort(); + } + } + }); - return new Response(customReadable, { - headers: { - Connection: "keep-alive", - "Content-Encoding": "none", - "Cache-Control": "no-cache, no-transform", - "Content-Type": "text/event-stream; charset=utf-8", - }, - }); + return new Response(customReadable, { + headers: { + Connection: 'keep-alive', + 'Content-Encoding': 'none', + 'Cache-Control': 'no-cache, no-transform', + 'Content-Type': 'text/event-stream; charset=utf-8' + } }); + }); } diff --git a/src/app/api/build-status/route.ts b/src/app/api/build-status/route.ts index 24e02a2c..fc203e47 100644 --- a/src/app/api/build-status/route.ts +++ b/src/app/api/build-status/route.ts @@ -1,103 +1,111 @@ -import buildLiveStatusService from "@/server/services/build-live-status.service"; -import buildStatusService from "@/server/services/standalone-services/build-status-pub-sub.service"; -import buildWatchService from "@/server/services/standalone-services/build-watch.service"; -import { getAuthUserSession, simpleRoute } from "@/server/utils/action-wrapper.utils"; -import { StreamUtils } from "@/shared/utils/stream.utils"; +import buildLiveStatusService from '@/server/services/build-live-status.service'; +import buildStatusService from '@/server/services/standalone-services/build-status-pub-sub.service'; +import buildWatchService from '@/server/services/standalone-services/build-watch.service'; +import { getAuthUserSession, simpleRoute } from '@/server/utils/action-wrapper.utils'; +import { StreamUtils } from '@/shared/utils/stream.utils'; // Prevents this route's response from being cached -export const dynamic = "force-dynamic"; +export const dynamic = 'force-dynamic'; export async function POST() { - return simpleRoute(async () => { - const session = await getAuthUserSession(); + return simpleRoute(async () => { + const session = await getAuthUserSession(); - void buildWatchService.startWatch(); - await buildStatusService.ensureSeeded(); + void buildWatchService.startWatch(); + await buildStatusService.ensureSeeded(); - let appLookup = await buildLiveStatusService.getBuildableAppLookup(session); + let appLookup = await buildLiveStatusService.getBuildableAppLookup(session); - const encoder = new TextEncoder(); - let shouldStopStreaming = false; - let unsubscribe: (() => void) | null = null; - let heartbeat: ReturnType | null = null; + const encoder = new TextEncoder(); + let shouldStopStreaming = false; + let unsubscribe: (() => void) | null = null; + let heartbeat: ReturnType | null = null; - const customReadable = new ReadableStream({ - async start(controller) { - const sendData = (data: unknown) => { - if (shouldStopStreaming) { - return; - } - try { - controller.enqueue(encoder.encode(StreamUtils.encodeSseData(data))); - } catch (e) { - console.error(`[BUILD STATUS] Error while enqueueing build status data: `, e); - shouldStopStreaming = true; - unsubscribe?.(); - unsubscribe = null; - if (heartbeat) clearInterval(heartbeat); - heartbeat = null; - controller.close(); - } - }; + const customReadable = new ReadableStream({ + async start(controller) { + const sendData = (data: unknown) => { + if (shouldStopStreaming) { + return; + } + try { + controller.enqueue(encoder.encode(StreamUtils.encodeSseData(data))); + } catch (e) { + console.error(`[BUILD STATUS] Error while enqueueing build status data: `, e); + shouldStopStreaming = true; + unsubscribe?.(); + unsubscribe = null; + if (heartbeat) { + clearInterval(heartbeat); + } + heartbeat = null; + controller.close(); + } + }; - unsubscribe = buildStatusService.subscribe(async (status) => { - if (shouldStopStreaming || status.workloadType !== 'app') { - return; - } + unsubscribe = buildStatusService.subscribe(async (status) => { + if (shouldStopStreaming || status.workloadType !== 'app') { + return; + } - let appInfo = appLookup.get(status.workloadId); - if (!appInfo) { - // A new app might have been created while streaming, refresh the lookup. - appLookup = await buildLiveStatusService.getBuildableAppLookup(session); - appInfo = appLookup.get(status.workloadId); - } - if (!appInfo) { - return; - } + let appInfo = appLookup.get(status.workloadId); + if (!appInfo) { + // A new app might have been created while streaming, refresh the lookup. + appLookup = await buildLiveStatusService.getBuildableAppLookup(session); + appInfo = appLookup.get(status.workloadId); + } + if (!appInfo) { + return; + } - sendData(buildLiveStatusService.mapBuildToStatus(status, appInfo)); - }); + sendData(buildLiveStatusService.mapBuildToStatus(status, appInfo)); + }); - try { - sendData(buildLiveStatusService.getInitialStatus(appLookup)); - } catch (e) { - console.error("Error fetching initial build status", e); - } + try { + sendData(buildLiveStatusService.getInitialStatus(appLookup)); + } catch (e) { + console.error('Error fetching initial build status', e); + } - heartbeat = setInterval(() => { - if (shouldStopStreaming) return; - try { - controller.enqueue(encoder.encode(': ping\n\n')); - } catch (error) { - console.error('[BUILD STATUS] Error while sending heartbeat:', error); - shouldStopStreaming = true; - unsubscribe?.(); - unsubscribe = null; - if (heartbeat) clearInterval(heartbeat); - heartbeat = null; - controller.close(); - } - }, 25_000); - }, - cancel() { - console.log("[BUILD STATUS] Client left, cancelling build status stream"); - shouldStopStreaming = true; - if (unsubscribe) { - unsubscribe(); - unsubscribe = null; - } - if (heartbeat) clearInterval(heartbeat); - heartbeat = null; - }, - }); + heartbeat = setInterval(() => { + if (shouldStopStreaming) { + return; + } + try { + controller.enqueue(encoder.encode(': ping\n\n')); + } catch (error) { + console.error('[BUILD STATUS] Error while sending heartbeat:', error); + shouldStopStreaming = true; + unsubscribe?.(); + unsubscribe = null; + if (heartbeat) { + clearInterval(heartbeat); + } + heartbeat = null; + controller.close(); + } + }, 25_000); + }, + cancel() { + console.log('[BUILD STATUS] Client left, cancelling build status stream'); + shouldStopStreaming = true; + if (unsubscribe) { + unsubscribe(); + unsubscribe = null; + } + if (heartbeat) { + clearInterval(heartbeat); + } + heartbeat = null; + } + }); - return new Response(customReadable, { - headers: { - Connection: "keep-alive", - "Content-Encoding": "none", - "Cache-Control": "no-cache, no-transform", - "Content-Type": "text/event-stream; charset=utf-8", - }, - }); + return new Response(customReadable, { + headers: { + Connection: 'keep-alive', + 'Content-Encoding': 'none', + 'Cache-Control': 'no-cache, no-transform', + 'Content-Type': 'text/event-stream; charset=utf-8' + } }); + }); } diff --git a/src/app/api/deployment-status/route.ts b/src/app/api/deployment-status/route.ts index fbbb4a44..ab43cefe 100644 --- a/src/app/api/deployment-status/route.ts +++ b/src/app/api/deployment-status/route.ts @@ -1,130 +1,146 @@ -import deploymentLiveStatusService from "@/server/services/deployment-live-status.service"; -import buildPodLogWatchService from "@/server/services/standalone-services/build-pod-log-watch.service"; -import buildWatchService from "@/server/services/standalone-services/build-watch.service"; -import deploymentEventWatchService from "@/server/services/standalone-services/deployment-event-watch.service"; -import deploymentWatchService from "@/server/services/standalone-services/deployment-watch.service"; -import { getAuthUserSession, simpleRoute } from "@/server/utils/action-wrapper.utils"; -import { V1Deployment } from "@kubernetes/client-node"; +import deploymentLiveStatusService from '@/server/services/deployment-live-status.service'; +import buildPodLogWatchService from '@/server/services/standalone-services/build-pod-log-watch.service'; +import buildWatchService from '@/server/services/standalone-services/build-watch.service'; +import deploymentEventWatchService from '@/server/services/standalone-services/deployment-event-watch.service'; +import deploymentWatchService from '@/server/services/standalone-services/deployment-watch.service'; +import { getAuthUserSession, simpleRoute } from '@/server/utils/action-wrapper.utils'; +import { V1Deployment } from '@kubernetes/client-node'; // Prevents this route's response from being cached -export const dynamic = "force-dynamic"; +export const dynamic = 'force-dynamic'; const IGNORED_NAMESPACES = ['default', 'longhorn-system', 'kube-public', 'kube-system', 'cert-manager']; export async function POST() { - return simpleRoute(async () => { - - const session = await getAuthUserSession(); - - buildPodLogWatchService.startWatch(); - buildWatchService.startWatch(); - deploymentEventWatchService.startWatch(); - - const encoder = new TextEncoder(); - let shouldStopStreaming = false; - let unsubscribe: (() => void) | null = null; - let heartbeat: ReturnType | null = null; - - // Fetch all projects and apps to build a lookup map - let appLookup = await deploymentLiveStatusService.getAppLookup(session); - - const customReadable = new ReadableStream({ - async start(controller) { - - const sendData = (data: any) => { - if (shouldStopStreaming) return; - try { - controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`)); - } catch (e) { - console.error(`[ENQUEUE ERROR] Error while enqueueing Deployment Status data: `, e); - shouldStopStreaming = true; - unsubscribe?.(); - unsubscribe = null; - if (heartbeat) clearInterval(heartbeat); - heartbeat = null; - controller.close(); - } - }; - - // 1. Send initial state - try { - const initialStatus = await deploymentLiveStatusService.getInitialStatus(appLookup); - sendData(initialStatus); - } catch (e) { - console.error("Error fetching initial status", e); - } - - // 2. Subscribe to the shared watch for changes - unsubscribe = deploymentWatchService.subscribe(async (type, deployment: V1Deployment) => { - if (shouldStopStreaming) { return; } - - const appId = deployment.metadata?.name; - const projectId = deployment.metadata?.namespace; - - if (!appId || !projectId) { return; } - - // ignore system namespaces - if (IGNORED_NAMESPACES.includes(projectId)) { return; } - - // If a new deployment is detected (ADDED) and we don't know about it, - // it might be a newly created app. Refresh the lookup. - if (type === 'ADDED' && !appLookup.has(appId)) { - console.log(`[LiveStatus] New unknown deployment detected for ${appId}, refreshing app lookup`); - appLookup = await deploymentLiveStatusService.getAppLookup(session); - } - - const appInfo = appLookup.get(appId); - if (!appInfo) { - return; - } - - // Verify namespace matches project ID - if (appInfo.projectId !== projectId) { return; } - - let status; - if (type === 'DELETED') { - status = deploymentLiveStatusService.mapDeploymentToStatus(appId, appInfo, undefined); - } else { - status = deploymentLiveStatusService.mapDeploymentToStatus(appId, appInfo, deployment); - } - - sendData(status); - }); - - heartbeat = setInterval(() => { - if (shouldStopStreaming) return; - try { - controller.enqueue(encoder.encode(': ping\n\n')); - } catch (error) { - console.error('[ENQUEUE ERROR] Error while sending deployment status heartbeat:', error); - shouldStopStreaming = true; - unsubscribe?.(); - unsubscribe = null; - if (heartbeat) clearInterval(heartbeat); - heartbeat = null; - controller.close(); - } - }, 25_000); - }, - cancel() { - console.log("[LEAVE] Cancelling deployment status stream"); - shouldStopStreaming = true; - if (unsubscribe) { - unsubscribe(); - unsubscribe = null; - } - if (heartbeat) clearInterval(heartbeat); - heartbeat = null; + return simpleRoute(async () => { + const session = await getAuthUserSession(); + + buildPodLogWatchService.startWatch(); + buildWatchService.startWatch(); + deploymentEventWatchService.startWatch(); + + const encoder = new TextEncoder(); + let shouldStopStreaming = false; + let unsubscribe: (() => void) | null = null; + let heartbeat: ReturnType | null = null; + + // Fetch all projects and apps to build a lookup map + let appLookup = await deploymentLiveStatusService.getAppLookup(session); + + const customReadable = new ReadableStream({ + async start(controller) { + const sendData = (data: any) => { + if (shouldStopStreaming) { + return; + } + try { + controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`)); + } catch (e) { + console.error(`[ENQUEUE ERROR] Error while enqueueing Deployment Status data: `, e); + shouldStopStreaming = true; + unsubscribe?.(); + unsubscribe = null; + if (heartbeat) { + clearInterval(heartbeat); } + heartbeat = null; + controller.close(); + } + }; + + // 1. Send initial state + try { + const initialStatus = await deploymentLiveStatusService.getInitialStatus(appLookup); + sendData(initialStatus); + } catch (e) { + console.error('Error fetching initial status', e); + } + + // 2. Subscribe to the shared watch for changes + unsubscribe = deploymentWatchService.subscribe(async (type, deployment: V1Deployment) => { + if (shouldStopStreaming) { + return; + } + + const appId = deployment.metadata?.name; + const projectId = deployment.metadata?.namespace; + + if (!appId || !projectId) { + return; + } + + // ignore system namespaces + if (IGNORED_NAMESPACES.includes(projectId)) { + return; + } + + // If a new deployment is detected (ADDED) and we don't know about it, + // it might be a newly created app. Refresh the lookup. + if (type === 'ADDED' && !appLookup.has(appId)) { + console.log(`[LiveStatus] New unknown deployment detected for ${appId}, refreshing app lookup`); + appLookup = await deploymentLiveStatusService.getAppLookup(session); + } + + const appInfo = appLookup.get(appId); + if (!appInfo) { + return; + } + + // Verify namespace matches project ID + if (appInfo.projectId !== projectId) { + return; + } + + let status; + if (type === 'DELETED') { + status = deploymentLiveStatusService.mapDeploymentToStatus(appId, appInfo, undefined); + } else { + status = deploymentLiveStatusService.mapDeploymentToStatus(appId, appInfo, deployment); + } + + sendData(status); }); - return new Response(customReadable, { - headers: { - Connection: "keep-alive", - "Content-Encoding": "none", - "Cache-Control": "no-cache, no-transform", - "Content-Type": "text/event-stream; charset=utf-8", - }, - }); + heartbeat = setInterval(() => { + if (shouldStopStreaming) { + return; + } + try { + controller.enqueue(encoder.encode(': ping\n\n')); + } catch (error) { + console.error('[ENQUEUE ERROR] Error while sending deployment status heartbeat:', error); + shouldStopStreaming = true; + unsubscribe?.(); + unsubscribe = null; + if (heartbeat) { + clearInterval(heartbeat); + } + heartbeat = null; + controller.close(); + } + }, 25_000); + }, + cancel() { + console.log('[LEAVE] Cancelling deployment status stream'); + shouldStopStreaming = true; + if (unsubscribe) { + unsubscribe(); + unsubscribe = null; + } + if (heartbeat) { + clearInterval(heartbeat); + } + heartbeat = null; + } + }); + + return new Response(customReadable, { + headers: { + Connection: 'keep-alive', + 'Content-Encoding': 'none', + 'Cache-Control': 'no-cache, no-transform', + 'Content-Type': 'text/event-stream; charset=utf-8' + } }); + }); } diff --git a/src/app/monitoring/actions.ts b/src/app/monitoring/actions.ts index 8a403f02..b76e745a 100644 --- a/src/app/monitoring/actions.ts +++ b/src/app/monitoring/actions.ts @@ -1,5 +1,7 @@ 'use server'; +import nodeMonitoringHistoryService from '@/server/services/standalone-services/node-monitoring-history.service'; + import monitoringService from '@/server/services/monitoring.service'; import clusterService from '@/server/services/cluster.service'; import { getAuthUserSession, simpleAction } from '@/server/utils/action-wrapper.utils'; @@ -36,3 +38,9 @@ export const getReservedVolumeStorage = async () => await getAuthUserSession(); return await clusterService.getReservedVolumeStorage(); }) as Promise>; + +export const getNodeMonitoringHistory = async () => + simpleAction(async () => { + await getAuthUserSession(); + return nodeMonitoringHistoryService.getHistory(); + }); diff --git a/src/app/monitoring/app-volumes-monitoring.tsx b/src/app/monitoring/app-volumes-monitoring.tsx index 26fbe4a1..be6695d1 100644 --- a/src/app/monitoring/app-volumes-monitoring.tsx +++ b/src/app/monitoring/app-volumes-monitoring.tsx @@ -17,7 +17,9 @@ export default function AppVolumeMonitoring({ volumesUsage }: { volumesUsage?: A const updatedVolumeUsage = volumesUsage; const totals = useMemo(() => { const unique = new Map(); - for (const volume of volumesUsage ?? []) unique.set(AppVolumeIdentityUtils.observationKey(volume.projectId, volume.pvcName), volume); + for (const volume of volumesUsage ?? []) { + unique.set(AppVolumeIdentityUtils.observationKey(volume.projectId, volume.pvcName), volume); + } const values = [...unique.values()]; return { used: values.reduce((sum, value) => sum + (value.usedBytes ?? 0), 0), diff --git a/src/app/monitoring/monitoring-client.tsx b/src/app/monitoring/monitoring-client.tsx index 7285479e..d617457c 100644 --- a/src/app/monitoring/monitoring-client.tsx +++ b/src/app/monitoring/monitoring-client.tsx @@ -11,6 +11,7 @@ import { getMonitoringForAllApps, getNodeResourceUsage, getReservedVolumeStorage import AppRessourceMonitoring from './app-monitoring'; import AppVolumeMonitoring from './app-volumes-monitoring'; import ResourcesNodes from './monitoring-nodes'; +import NodeMonitoringHistory from './node-monitoring-history'; const MONITORING_POLL_INTERVAL_MS = 10000; @@ -58,6 +59,7 @@ export default function MonitoringClient({ return (
+
diff --git a/src/app/monitoring/monitoring-nodes.tsx b/src/app/monitoring/monitoring-nodes.tsx index afa2b74b..f036c79c 100644 --- a/src/app/monitoring/monitoring-nodes.tsx +++ b/src/app/monitoring/monitoring-nodes.tsx @@ -22,14 +22,14 @@ export default function ResourcesNodes({ resourcesNodes, reservedVolumeStorage } useEffect(() => setBreadcrumbs([{ name: 'Monitoring', url: '/monitoring' }]), [setBreadcrumbs]); const clusterStats = useMemo(() => { - if (!updatedNodeRessources) return { cpuUsage: 0, cpuCapacity: 1, ramUsage: 0, ramCapacity: 1, diskUsageAbsolut: 0, diskCapacity: 1 }; + if (!updatedNodeRessources) { return { cpuUsage: 0, cpuCapacity: 1, ramUsage: 0, ramCapacity: 1, diskUsageAbsolut: 0, diskCapacity: 1 }; } return updatedNodeRessources.reduce( (acc, node) => ({ - cpuUsage: acc.cpuUsage + node.cpuUsage, - cpuCapacity: acc.cpuCapacity + node.cpuCapacity, - ramUsage: acc.ramUsage + node.ramUsage, - ramCapacity: acc.ramCapacity + node.ramCapacity, + cpuUsage: acc.cpuUsage + (node.cpuUsage ?? 0), + cpuCapacity: acc.cpuCapacity + (node.cpuUsage === null ? 0 : node.cpuCapacity), + ramUsage: acc.ramUsage + (node.ramUsage ?? 0), + ramCapacity: acc.ramCapacity + (node.ramUsage === null ? 0 : node.ramCapacity), diskUsageAbsolut: acc.diskUsageAbsolut + getDiskUsageAbsolut(node), diskCapacity: acc.diskCapacity + getDiskUsageCapacity(node) }), @@ -38,8 +38,8 @@ export default function ResourcesNodes({ resourcesNodes, reservedVolumeStorage } }, [updatedNodeRessources]); const getUsageColor = (percentage: number) => { - if (percentage >= 90) return 'var(--chart-1)'; - if (percentage >= 80) return 'var(--chart-4)'; + if (percentage >= 90) { return 'var(--chart-1)'; } + if (percentage >= 80) { return 'var(--chart-4)'; } return 'var(--chart-2)'; }; @@ -64,32 +64,39 @@ export default function ResourcesNodes({ resourcesNodes, reservedVolumeStorage } Cluster CPU - Total Cores Usage + Usage of reporting nodes - - - } /> - - - - + {updatedNodeRessources.some((node) => node.cpuUsage === null) && ( +

Incomplete: some node CPU metrics are unavailable.

+ )} + {clusterStats.cpuCapacity <= 0 ? ( +

Metrics unavailable

+ ) : ( + + + } /> + + + + + )}
@@ -97,35 +104,42 @@ export default function ResourcesNodes({ resourcesNodes, reservedVolumeStorage } Cluster RAM - Total Memory Usage + Usage of reporting nodes - - - KubeSizeConverter.convertBytesToReadableSize(value as number)} />} - /> - - - - + + + + + )} @@ -244,26 +258,34 @@ export default function ResourcesNodes({ resourcesNodes, reservedVolumeStorage } {node.name} -
-
- {((node.cpuUsage / node.cpuCapacity) * 100).toFixed(0)}% - - {node.cpuUsage.toFixed(2)} / {node.cpuCapacity} Cores - + {node.cpuUsage === null ? ( + Unavailable + ) : ( +
+
+ {((node.cpuUsage / node.cpuCapacity) * 100).toFixed(0)}% + + {node.cpuUsage.toFixed(2)} / {node.cpuCapacity} Cores + +
+
- -
+ )} -
-
- {((node.ramUsage / node.ramCapacity) * 100).toFixed(0)}% - - {KubeSizeConverter.convertBytesToReadableSize(node.ramUsage)} / {KubeSizeConverter.convertBytesToReadableSize(node.ramCapacity)} - + {node.ramUsage === null ? ( + Unavailable + ) : ( +
+
+ {((node.ramUsage / node.ramCapacity) * 100).toFixed(0)}% + + {KubeSizeConverter.convertBytesToReadableSize(node.ramUsage)} / {KubeSizeConverter.convertBytesToReadableSize(node.ramCapacity)} + +
+
- -
+ )}
@@ -272,7 +294,7 @@ export default function ResourcesNodes({ resourcesNodes, reservedVolumeStorage } const diskCapacity = getDiskUsageCapacity(node); const diskUsedAndReserved = diskUsed; const diskPercent = toPercent(diskUsedAndReserved, diskCapacity); - if (node.diskUsageCapacity === undefined) return Unavailable; + if (node.diskUsageCapacity === undefined) { return Unavailable; } return ( <>
diff --git a/src/app/monitoring/node-monitoring-history.tsx b/src/app/monitoring/node-monitoring-history.tsx new file mode 100644 index 00000000..21e0cfe1 --- /dev/null +++ b/src/app/monitoring/node-monitoring-history.tsx @@ -0,0 +1,64 @@ +'use client'; + +import { useCallback, useState } from 'react'; +import { HistoryChart, getMonitoringRangeOptions, getMonitoringRangeStart } from '@/components/custom/app-monitoring-history'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; +import { usePolling } from '@/frontend/hooks/use-polling'; +import { getNodeMonitoringHistory } from './actions'; + +type History = NonNullable>['data']>; + +export default function NodeMonitoringHistory() { + const [history, setHistory] = useState(); + const [error, setError] = useState(false); + const [range, setRange] = useState('1h'); + const refresh = useCallback(async () => { + try { + const result = await getNodeMonitoringHistory(); + if (result.status !== 'success' || !result.data) { throw new Error('Unable to load monitoring history'); } + setHistory(result.data); + setError(false); + } catch { + setError(true); + } + }, []); + usePolling(refresh, { intervalMs: 60_000, runImmediately: true }); + const options = getMonitoringRangeOptions(history?.retentionHours ?? 1); + const selected = options.find((option) => option.value === range) ?? options[0]; + const points = history?.points.filter((point) => point.time >= getMonitoringRangeStart(selected.value, selected.hours)) ?? []; + return ( +
+
+

Cluster history

+ +
+

Totals include only nodes reporting each metric. Missing nodes or metrics are excluded.

+ {error &&

Unable to load monitoring history.

} + {history && history.points.length === 0 &&

No measurements yet. History is collected every five minutes.

} + {history?.points.at(-1)?.isGap &&

Collection has stopped or is delayed. The chart shows a gap after the last sample.

} + {history && ( +
+ + + +
+ )} +
+ ); +} diff --git a/src/app/project/[projectId]/actions.unit.spec.ts b/src/app/project/[projectId]/actions.unit.spec.ts index 995b0319..90382480 100644 --- a/src/app/project/[projectId]/actions.unit.spec.ts +++ b/src/app/project/[projectId]/actions.unit.spec.ts @@ -1,22 +1,24 @@ import { z } from 'zod'; vi.mock('@/server/utils/action-wrapper.utils', () => ({ - getAuthUserSession: vi.fn().mockResolvedValue({}), - isAuthorizedDeleteForProject: vi.fn(), - saveFormAction: async (input: unknown, schema: z.ZodType, action: (data: unknown) => unknown) => { - const result = schema.safeParse(input); - if (!result.success) throw result.error; - return action(result.data); - }, - simpleAction: (action: () => unknown) => action(), + getAuthUserSession: vi.fn().mockResolvedValue({}), + isAuthorizedDeleteForProject: vi.fn(), + saveFormAction: async (input: unknown, schema: z.ZodType, action: (data: unknown) => unknown) => { + const result = schema.safeParse(input); + if (!result.success) { + throw result.error; + } + return action(result.data); + }, + simpleAction: (action: () => unknown) => action() })); vi.mock('@/server/utils/shared-authorization.utils', () => ({ - ensureCreateProjectWorkloadInProject: vi.fn(), - ensureDeleteProjectWorkloadInProject: vi.fn(), - ensureWriteProject: vi.fn(), + ensureCreateProjectWorkloadInProject: vi.fn(), + ensureDeleteProjectWorkloadInProject: vi.fn(), + ensureWriteProject: vi.fn() })); vi.mock('@/server/services/addons/agent-sandbox-addon.service', () => ({ - default: { isAvailable: vi.fn() }, + default: { isAvailable: vi.fn() } })); vi.mock('@/server/services/agent.service', () => ({ default: { saveAgent: vi.fn() } })); vi.mock('@/server/services/agent-template.service', () => ({ default: { createAgentFromTemplate: vi.fn() } })); @@ -29,14 +31,14 @@ vi.mock('@/server/services/db-tool-services/pgadmin.service', () => ({ default: vi.mock('@/server/services/llm-gateway.service', () => ({ default: {} })); vi.mock('@/server/services/project-network-graph-layout.service', () => ({ default: {} })); vi.mock('@/server/services/param.service', () => ({ - default: {}, - ParamService: { FEATURE_NEW_NETWORK_POLICY_EXPLENATION: 'feature' }, + default: {}, + ParamService: { FEATURE_NEW_NETWORK_POLICY_EXPLENATION: 'feature' } })); vi.mock('@/shared/model/app-template.model', () => ({ appTemplateZodModel: z.unknown() })); vi.mock('@/shared/model/agent-template.model', () => ({ agentTemplateZodModel: z.unknown() })); vi.mock('@/shared/model/rename-agent.model', () => ({ renameAgentZodModel: z.unknown() })); vi.mock('@/shared/model/project-network-graph-layout.model', () => ({ - projectNetworkGraphPositionSchema: z.unknown(), + projectNetworkGraphPositionSchema: z.unknown() })); import agentSandboxAddonService from '@/server/services/addons/agent-sandbox-addon.service'; @@ -45,21 +47,19 @@ import agentTemplateService from '@/server/services/agent-template.service'; import { createAgent, createAgentFromTemplate } from './actions'; describe('agent creation actions', () => { - beforeEach(() => { - vi.mocked(agentSandboxAddonService.isAvailable).mockResolvedValue(false); - }); + beforeEach(() => { + vi.mocked(agentSandboxAddonService.isAvailable).mockResolvedValue(false); + }); - it('rejects direct single-agent creation when the add-on is unavailable', async () => { - await expect(createAgent('Agent', 'project-1', 'gateway-1', ['model-1'])) - .rejects.toThrow('The Agent Sandbox Add-on is not available.'); + it('rejects direct single-agent creation when the add-on is unavailable', async () => { + await expect(createAgent('Agent', 'project-1', 'gateway-1', ['model-1'])).rejects.toThrow('The Agent Sandbox Add-on is not available.'); - expect(agentService.saveAgent).not.toHaveBeenCalled(); - }); + expect(agentService.saveAgent).not.toHaveBeenCalled(); + }); - it('rejects direct template-based agent creation when the add-on is unavailable', async () => { - await expect(createAgentFromTemplate(null, {}, 'project-1')) - .rejects.toThrow('The Agent Sandbox Add-on is not available.'); + it('rejects direct template-based agent creation when the add-on is unavailable', async () => { + await expect(createAgentFromTemplate(null, {}, 'project-1')).rejects.toThrow('The Agent Sandbox Add-on is not available.'); - expect(agentTemplateService.createAgentFromTemplate).not.toHaveBeenCalled(); - }); + expect(agentTemplateService.createAgentFromTemplate).not.toHaveBeenCalled(); + }); }); diff --git a/src/app/project/[projectId]/agents/details/agent-drawer.tsx b/src/app/project/[projectId]/agents/details/agent-drawer.tsx index 7f262d20..691e3f7b 100644 --- a/src/app/project/[projectId]/agents/details/agent-drawer.tsx +++ b/src/app/project/[projectId]/agents/details/agent-drawer.tsx @@ -1,29 +1,11 @@ 'use client'; import { type Ref } from 'react'; -import { - Bot, - Hammer, - Pencil, - Settings, - X, -} from 'lucide-react'; +import { Bot, Hammer, Pencil, Settings, X } from 'lucide-react'; import { Button } from '@/components/ui/button'; -import { - Drawer, - DrawerContent, - DrawerDescription, - DrawerHeader, - DrawerTitle, -} from '@/components/ui/drawer'; +import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from '@/components/ui/drawer'; import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; -import { - Empty, - EmptyDescription, - EmptyHeader, - EmptyMedia, - EmptyTitle, -} from '@/components/ui/empty'; +import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty'; import { ScrollArea } from '@/components/ui/scroll-area'; import { useDialog } from '@/frontend/states/zustand.states'; import { DrawerTabScrollArea } from '@/app/project/workload-components/drawer/drawer-tab-scroll-area'; @@ -36,188 +18,158 @@ import AgentSandboxDrawerSettings from './agent-sandbox-drawer-settings'; import type { AgentExtendedModel } from '@/shared/model/agent-extended.model'; import { RolePermissionEnum } from '@/shared/model/role-extended.model'; import type { AgentSandboxTemplateInfo } from '@/shared/model/agent-sandbox-template-info.model'; -import { - AgentDrawerNavigationUtils, - type AgentDrawerTab, -} from '@/shared/utils/agent-drawer-navigation.utils'; +import { AgentDrawerNavigationUtils, type AgentDrawerTab } from '@/shared/utils/agent-drawer-navigation.utils'; import { formatDateTime } from '@/frontend/utils/format.utils'; export function AgentSandboxDrawer({ - contentRef, - agent, - role, - templateInfo, - storageClasses, - runtimeClasses, - open, - onOpenChange, - onOpenChangeComplete, - requestedTab, - onTabChange, + contentRef, + agent, + role, + templateInfo, + storageClasses, + runtimeClasses, + open, + onOpenChange, + onOpenChangeComplete, + requestedTab, + onTabChange }: { - contentRef?: Ref; - agent?: AgentExtendedModel; - role?: RolePermissionEnum; - templateInfo?: AgentSandboxTemplateInfo; - storageClasses: string[]; - runtimeClasses: string[]; - open: boolean; - onOpenChange: (open: boolean) => void; - onOpenChangeComplete: (open: boolean) => void; - requestedTab?: string | null; - onTabChange: (tab: AgentDrawerTab) => void; + contentRef?: Ref; + agent?: AgentExtendedModel; + role?: RolePermissionEnum; + templateInfo?: AgentSandboxTemplateInfo; + storageClasses: string[]; + runtimeClasses: string[]; + open: boolean; + onOpenChange: (open: boolean) => void; + onOpenChangeComplete: (open: boolean) => void; + requestedTab?: string | null; + onTabChange: (tab: AgentDrawerTab) => void; }) { - const { openDialog } = useDialog(); - const readonly = role !== RolePermissionEnum.READWRITE; - const hasGitSource = agent?.sourceType === 'GIT' || agent?.sourceType === 'GIT_SSH'; - const activeTab = AgentDrawerNavigationUtils.resolveTab(requestedTab, { readonly, hasGitSource: !!hasGitSource }); + const { openDialog } = useDialog(); + const readonly = role !== RolePermissionEnum.READWRITE; + const hasGitSource = agent?.sourceType === 'GIT' || agent?.sourceType === 'GIT_SSH'; + const activeTab = AgentDrawerNavigationUtils.resolveTab(requestedTab, { readonly, hasGitSource: !!hasGitSource }); - const handleTabChange = (tab: string) => { - onTabChange(AgentDrawerNavigationUtils.resolveTab(tab, { readonly, hasGitSource: !!hasGitSource })); - }; + const handleTabChange = (tab: string) => { + onTabChange(AgentDrawerNavigationUtils.resolveTab(tab, { readonly, hasGitSource: !!hasGitSource })); + }; - const openRenameDialog = () => { - if (!agent) return; - openDialog(, { maxWidth: 'max-w-md' }); - }; + const openRenameDialog = () => { + if (!agent) { + return; + } + openDialog(, { maxWidth: 'max-w-md' }); + }; - return ( - - - - + + +
+
+ +
+
+ + {agent?.name ?? 'Agent Sandbox'} + {agent && role === RolePermissionEnum.READWRITE && ( + - - -
-
- -
-
- - {agent?.name ?? 'Agent Sandbox'} - {agent && role === RolePermissionEnum.READWRITE && ( - - )} - - - Agent Sandbox{agent ? ` · ${agent.project.name}` : ''} - {templateInfo?.lastDeployedAt - ? ` · Last deployed ${formatDateTime(templateInfo.lastDeployedAt)}` - : ''} - -
- {agent && ( -
- -
- )} -
- {agent && role ? ( - - - - - Sandboxes - - {!readonly && hasGitSource && ( - - - Builds - - )} - {!readonly && ( - - - Configuration - - )} - - - ) : ( -
- )} -
- {agent && role ? ( - <> - - - - - - {!readonly && hasGitSource && ( - - - - - - )} - {!readonly && ( - - - - - - )} - - ) : ( - - - - - - Agent Sandbox unavailable - - This Agent Sandbox could not be loaded. It may have been deleted. - - - - )} -
- - - - ); + size="icon-sm" + className="shrink-0 opacity-0 transition-opacity group-hover/title:opacity-100 focus-visible:opacity-100" + onClick={openRenameDialog} + > + + Rename Agent Sandbox + + )} +
+ + Agent Sandbox{agent ? ` · ${agent.project.name}` : ''} + {templateInfo?.lastDeployedAt ? ` · Last deployed ${formatDateTime(templateInfo.lastDeployedAt)}` : ''} + +
+ {agent && ( +
+ +
+ )} +
+ {agent && role ? ( + + + + + Sandboxes + + {!readonly && hasGitSource && ( + + + Builds + + )} + {!readonly && ( + + + Configuration + + )} + + + ) : ( +
+ )} +
+ {agent && role ? ( + <> + + + + + + {!readonly && hasGitSource && ( + + + + + + )} + {!readonly && ( + + + + + + )} + + ) : ( + + + + + + Agent Sandbox unavailable + This Agent Sandbox could not be loaded. It may have been deleted. + + + )} +
+
+
+
+ ); } diff --git a/src/app/project/[projectId]/agents/details/builds/agent-builds-grid.tsx b/src/app/project/[projectId]/agents/details/builds/agent-builds-grid.tsx index c92e7b84..72133d3d 100644 --- a/src/app/project/[projectId]/agents/details/builds/agent-builds-grid.tsx +++ b/src/app/project/[projectId]/agents/details/builds/agent-builds-grid.tsx @@ -1,28 +1,10 @@ 'use client'; import { useCallback, useState } from 'react'; -import { - Boxes, - EllipsisVertical, - File, - GitCommit, - Hammer, - LucideTerminal, -} from 'lucide-react'; +import { Boxes, EllipsisVertical, File, GitCommit, Hammer, LucideTerminal } from 'lucide-react'; import { Button } from '@/components/ui/button'; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from '@/components/ui/dropdown-menu'; -import { - Empty, - EmptyDescription, - EmptyHeader, - EmptyMedia, - EmptyTitle, -} from '@/components/ui/empty'; +import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; +import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty'; import { Item, ItemContent, ItemTitle } from '@/components/ui/item'; import FullLoadingSpinner from '@/components/ui/full-loading-spinnter'; import ShortCommitHash from '@/components/custom/short-commit-hash'; @@ -38,162 +20,155 @@ import { appBuildMethodLabels } from '@/shared/model/app-source-info.model'; import type { BuildJobModel } from '@/shared/model/build-job'; export function AgentBuildsGrid({ agentId }: { agentId: string }) { - const { openConfirmDialog } = useConfirmDialog(); - const { openNestedDrawer } = useNestedDrawer(); - const [builds, setBuilds] = useState(); + const { openConfirmDialog } = useConfirmDialog(); + const { openNestedDrawer } = useNestedDrawer(); + const [builds, setBuilds] = useState(); - const updateBuilds = useCallback(async () => { - const response = await getWorkloadBuildsAction({ - workloadId: agentId, - workloadType: 'agent', - }); - if (response.status === 'success') { - setBuilds(response.data ?? []); - } - }, [agentId]); - - usePolling(updateBuilds, { - intervalMs: 10000, - runImmediately: true, + const updateBuilds = useCallback(async () => { + const response = await getWorkloadBuildsAction({ + workloadId: agentId, + workloadType: 'agent' }); + if (response.status === 'success') { + setBuilds(response.data ?? []); + } + }, [agentId]); - const stopBuild = async (build: BuildJobModel) => { - const confirmed = await openConfirmDialog({ - title: 'Stop Build', - description: 'The build will be stopped and removed. Are you sure you want to stop this build?', - okButton: 'Stop & Remove Build', - }); - if (!confirmed) return; + usePolling(updateBuilds, { + intervalMs: 10000, + runImmediately: true + }); - await Toast.fromAction(() => deleteWorkloadBuildAction(build.name, { - workloadId: agentId, - workloadType: 'agent', - })); - await updateBuilds(); - }; + const stopBuild = async (build: BuildJobModel) => { + const confirmed = await openConfirmDialog({ + title: 'Stop Build', + description: 'The build will be stopped and removed. Are you sure you want to stop this build?', + okButton: 'Stop & Remove Build' + }); + if (!confirmed) { + return; + } - const showLogs = (build: BuildJobModel) => { - openNestedDrawer({ - title: 'Build Logs', - description: `View the logs for the build started ${formatDateTime(build.startTime)}.`, - content: ( - - ), - }); - }; + await Toast.fromAction(() => + deleteWorkloadBuildAction(build.name, { + workloadId: agentId, + workloadType: 'agent' + }) + ); + await updateBuilds(); + }; - if (!builds) { - return ( -
-
Latest Builds
- -
- ); - } + const showLogs = (build: BuildJobModel) => { + openNestedDrawer({ + title: 'Build Logs', + description: `View the logs for the build started ${formatDateTime(build.startTime)}.`, + content: ( + + ) + }); + }; - if (builds.length === 0) { - return ( -
-
Latest Builds
- - - - - - No builds available - - This Agent Sandbox has no builds yet. - - - -
- ); - } + if (!builds) { + return ( +
+
Latest Builds
+ +
+ ); + } + if (builds.length === 0) { return ( -
-
Latest Builds
-
- {builds.map(build => ( - -
- - - {build.status} - - {build.gitCommitMessage && ( -
- {build.gitCommitMessage.length > 200 - ? `${build.gitCommitMessage.slice(0, 200)}…` - : build.gitCommitMessage} -
- )} -
- - {(build.status === 'RUNNING' || build.status === 'PENDING') && ( - - - - Build actions - } /> - - void stopBuild(build)} - > - Stop Build - - - - )} -
-
- {build.gitCommit &&
- - {build.gitCommit} -
} - {build.gitCommit && } - {build.buildMethod && <> - - {build.buildMethod === 'DOCKERFILE' && } - {build.buildMethod === 'FRAMEWORK' && } - {appBuildMethodLabels[build.buildMethod] ?? '-'} - - - } - {formatDateTime(build.startTime)} -
-
- ))} -
-
+
+
Latest Builds
+ + + + + + No builds available + This Agent Sandbox has no builds yet. + + +
); + } + + return ( +
+
Latest Builds
+
+ {builds.map((build) => ( + +
+ + + {build.status} + + {build.gitCommitMessage && ( +
+ {build.gitCommitMessage.length > 200 ? `${build.gitCommitMessage.slice(0, 200)}…` : build.gitCommitMessage} +
+ )} +
+ + {(build.status === 'RUNNING' || build.status === 'PENDING') && ( + + + + Build actions + + } + /> + + void stopBuild(build)}> + Stop Build + + + + )} +
+
+ {build.gitCommit && ( +
+ + {build.gitCommit} +
+ )} + {build.gitCommit && } + {build.buildMethod && ( + <> + + {build.buildMethod === 'DOCKERFILE' && } + {build.buildMethod === 'FRAMEWORK' && } + {appBuildMethodLabels[build.buildMethod] ?? '-'} + + + + )} + {formatDateTime(build.startTime)} +
+
+ ))} +
+
+ ); } diff --git a/src/app/project/[projectId]/agents/details/environment/agent-env-vars-card.tsx b/src/app/project/[projectId]/agents/details/environment/agent-env-vars-card.tsx index a7906e57..dc8c80f8 100644 --- a/src/app/project/[projectId]/agents/details/environment/agent-env-vars-card.tsx +++ b/src/app/project/[projectId]/agents/details/environment/agent-env-vars-card.tsx @@ -1,72 +1,94 @@ 'use client'; -import { Button } from "@/components/ui/button"; -import { DrawerCard, DrawerCardContent, DrawerCardDescription, DrawerCardFooter, DrawerCardHeader, DrawerCardTitle } from "@/components/custom/drawer-card"; -import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; -import { useConfirmDialog, useDialog } from "@/frontend/states/zustand.states"; -import { Toast } from "@/frontend/utils/toast.utils"; -import { AgentExtendedModel } from "@/shared/model/agent-extended.model"; -import { EditIcon, Plus, TrashIcon } from "lucide-react"; -import { deleteAgentEnvVar } from "../configuration/actions"; -import AgentEnvVarEditOverlay from "./agent-env-var-edit-overlay"; +import { Button } from '@/components/ui/button'; +import { DrawerCard, DrawerCardContent, DrawerCardDescription, DrawerCardFooter, DrawerCardHeader, DrawerCardTitle } from '@/components/custom/drawer-card'; +import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'; +import { useConfirmDialog, useDialog } from '@/frontend/states/zustand.states'; +import { Toast } from '@/frontend/utils/toast.utils'; +import { AgentExtendedModel } from '@/shared/model/agent-extended.model'; +import { EditIcon, Plus, TrashIcon } from 'lucide-react'; +import { deleteAgentEnvVar } from '../configuration/actions'; +import AgentEnvVarEditOverlay from './agent-env-var-edit-overlay'; function getEnvironmentVariableNames(encryptedEnvVars: string | null | undefined): string[] { - if (!encryptedEnvVars) return []; - try { - const parsed = JSON.parse(encryptedEnvVars) as Array<{ name?: unknown }>; - return parsed.flatMap((envVar) => typeof envVar.name === 'string' ? [envVar.name] : []); - } catch { - return []; - } + if (!encryptedEnvVars) { + return []; + } + try { + const parsed = JSON.parse(encryptedEnvVars) as Array<{ name?: unknown }>; + return parsed.flatMap((envVar) => (typeof envVar.name === 'string' ? [envVar.name] : [])); + } catch { + return []; + } } export default function AgentEnvVarsCard({ agent, readonly }: { agent: AgentExtendedModel; readonly: boolean }) { - const { openConfirmDialog } = useConfirmDialog(); - const { openDialog } = useDialog(); - const environmentVariableNames = getEnvironmentVariableNames(agent.encryptedEnvVars); + const { openConfirmDialog } = useConfirmDialog(); + const { openDialog } = useDialog(); + const environmentVariableNames = getEnvironmentVariableNames(agent.encryptedEnvVars); - const openEditDialog = async (name?: string) => { - await openDialog(, { maxWidth: 'max-w-md' }); - }; - const deleteEnvironmentVariable = async (name: string) => { - const confirmed = await openConfirmDialog({ - title: 'Delete Environment Variable', - description: `Remove ${name}? This takes effect after deploying the agent.`, - okButton: 'Delete Environment Variable', - }); - if (confirmed) await Toast.fromAction(() => deleteAgentEnvVar(agent.id, name), 'Deleted Env Variable Successfully'); - }; + const openEditDialog = async (name?: string) => { + await openDialog(, { maxWidth: 'max-w-md' }); + }; + const deleteEnvironmentVariable = async (name: string) => { + const confirmed = await openConfirmDialog({ + title: 'Delete Environment Variable', + description: `Remove ${name}? This takes effect after deploying the agent.`, + okButton: 'Delete Environment Variable' + }); + if (confirmed) { + await Toast.fromAction(() => deleteAgentEnvVar(agent.id, name), 'Deleted Env Variable Successfully'); + } + }; - return ( - - - Environment Variables - - Values are encrypted at rest and never shown. Names starting with QS_ are reserved by QuickStack. - - - {environmentVariableNames.length > 0 && - - - {environmentVariableNames.length} Environment Variables - - Key - {!readonly && } - - - {environmentVariableNames.map((name) => - {name} - {!readonly && -
- - -
-
} -
)} -
-
-
} - {!readonly && } -
- ); + return ( + + + Environment Variables + + Values are encrypted at rest and never shown. Names starting with QS_ are reserved by + QuickStack. + + + {environmentVariableNames.length > 0 && ( + + + {environmentVariableNames.length} Environment Variables + + + Key + {!readonly && } + + + + {environmentVariableNames.map((name) => ( + + {name} + {!readonly && ( + +
+ + +
+
+ )} +
+ ))} +
+
+
+ )} + {!readonly && ( + + + + )} +
+ ); } diff --git a/src/app/project/[projectId]/agents/details/model/agent-model-configuration-editor.tsx b/src/app/project/[projectId]/agents/details/model/agent-model-configuration-editor.tsx index c12dda29..273bbf0c 100644 --- a/src/app/project/[projectId]/agents/details/model/agent-model-configuration-editor.tsx +++ b/src/app/project/[projectId]/agents/details/model/agent-model-configuration-editor.tsx @@ -1,172 +1,168 @@ 'use client'; -import type { z } from "zod"; -import { useActionState, useEffect, useState } from "react"; -import { SubmitButton } from "@/components/custom/submit-button"; -import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"; -import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; -import SelectBox from "@/components/custom/multiselect-field"; -import { FormUtils } from "@/frontend/utils/form.utilts"; -import { agentModelConfigurationZodModel, AgentModelConfigurationModel } from "@/shared/model/agent-config.model"; -import { ServerActionResult } from "@/shared/model/server-action-error-return.model"; -import { zodResolver } from "@hookform/resolvers/zod"; -import { useForm } from "react-hook-form"; -import { useRouter } from "next/navigation"; -import { toast } from "sonner"; -import { saveAgentModelConfiguration } from "../configuration/actions"; -import { getLlmGateways, getModelAliasesForGateway } from "@/app/project/[projectId]/actions"; -import { AgentExtendedModel } from "@/shared/model/agent-extended.model"; -import { LlmGatewayModel } from "@/shared/model/llm-gateway.model"; -import { Loader2 } from "lucide-react"; +import type { z } from 'zod'; +import { useActionState, useEffect, useState } from 'react'; +import { SubmitButton } from '@/components/custom/submit-button'; +import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; +import SelectBox from '@/components/custom/multiselect-field'; +import { FormUtils } from '@/frontend/utils/form.utilts'; +import { agentModelConfigurationZodModel, AgentModelConfigurationModel } from '@/shared/model/agent-config.model'; +import { ServerActionResult } from '@/shared/model/server-action-error-return.model'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { useForm } from 'react-hook-form'; +import { useRouter } from 'next/navigation'; +import { toast } from 'sonner'; +import { saveAgentModelConfiguration } from '../configuration/actions'; +import { getLlmGateways, getModelAliasesForGateway } from '@/app/project/[projectId]/actions'; +import { AgentExtendedModel } from '@/shared/model/agent-extended.model'; +import { LlmGatewayModel } from '@/shared/model/llm-gateway.model'; +import { Loader2 } from 'lucide-react'; -export function AgentModelConfigurationEditor({ agent, readonly }: { - agent: AgentExtendedModel; - readonly: boolean; -}) { - const router = useRouter(); - const [gateways, setGateways] = useState([]); - const [modelAliases, setModelAliases] = useState([]); - const [loadingAliases, setLoadingAliases] = useState(false); - const [selectedGatewayId, setSelectedGatewayId] = useState(agent.llmGatewayId || ''); +export function AgentModelConfigurationEditor({ agent, readonly }: { agent: AgentExtendedModel; readonly: boolean }) { + const router = useRouter(); + const [gateways, setGateways] = useState([]); + const [modelAliases, setModelAliases] = useState([]); + const [loadingAliases, setLoadingAliases] = useState(false); + const [selectedGatewayId, setSelectedGatewayId] = useState(agent.llmGatewayId || ''); - useEffect(() => { - getLlmGateways().then((r: any) => { - if (r?.data) setGateways(r.data); - }); - }, []); - - const form = useForm, unknown, z.output>({ - resolver: zodResolver(agentModelConfigurationZodModel), - defaultValues: { - llmGatewayId: agent.llmGatewayId || '', - modelAlias: agent.modelAlias || [], - }, - disabled: readonly, + useEffect(() => { + getLlmGateways().then((r: any) => { + if (r?.data) { + setGateways(r.data); + } }); + }, []); + + const form = useForm, unknown, z.output>({ + resolver: zodResolver(agentModelConfigurationZodModel), + defaultValues: { + llmGatewayId: agent.llmGatewayId || '', + modelAlias: agent.modelAlias || [] + }, + disabled: readonly + }); - useEffect(() => { - if (!selectedGatewayId) { - setModelAliases([]); - return; - } - loadModelAliases(selectedGatewayId); - }, [selectedGatewayId]); + useEffect(() => { + if (!selectedGatewayId) { + setModelAliases([]); + return; + } + loadModelAliases(selectedGatewayId); + }, [selectedGatewayId]); - const loadModelAliases = async (gatewayId: string) => { - setLoadingAliases(true); - try { - const result = await getModelAliasesForGateway(gatewayId); - if (result?.data) { - setModelAliases(result.data as string[]); - } else if (Array.isArray(result)) { - setModelAliases(result as string[]); - } else { - setModelAliases([]); - } - } catch { - setModelAliases([]); - } finally { - setLoadingAliases(false); - } - }; + const loadModelAliases = async (gatewayId: string) => { + setLoadingAliases(true); + try { + const result = await getModelAliasesForGateway(gatewayId); + if (result?.data) { + setModelAliases(result.data as string[]); + } else if (Array.isArray(result)) { + setModelAliases(result as string[]); + } else { + setModelAliases([]); + } + } catch { + setModelAliases([]); + } finally { + setLoadingAliases(false); + } + }; - const [state, formAction] = useActionState( - (state: ServerActionResult, payload: AgentModelConfigurationModel) => - saveAgentModelConfiguration(state, payload, agent.id), - FormUtils.getInitialFormState(), - ); + const [state, formAction] = useActionState( + (state: ServerActionResult, payload: AgentModelConfigurationModel) => saveAgentModelConfiguration(state, payload, agent.id), + FormUtils.getInitialFormState() + ); - useEffect(() => { - if (state.status === 'success') { - toast.success('Model configuration saved. Click "Deploy" to apply changes.'); - router.refresh(); - } - FormUtils.mapValidationErrorsToForm(state, form); - }, [form, router, state]); + useEffect(() => { + if (state.status === 'success') { + toast.success('Model configuration saved. Click "Deploy" to apply changes.'); + router.refresh(); + } + FormUtils.mapValidationErrorsToForm(state, form); + }, [form, router, state]); - return ( -
- form.handleSubmit((data) => formAction(data))()}> -
-
- ( - - LLM Gateway - - - - )} - /> + return ( + + form.handleSubmit((data) => formAction(data))()}> +
+
+ ( + + LLM Gateway + + + + )} + /> - ( - - Model Alias - {!selectedGatewayId ? ( -

Select a gateway first

- ) : loadingAliases ? ( -
- Loading model aliases... -
- ) : modelAliases.length === 0 ? ( -

No model aliases available

- ) : ( - - field.onChange(Array.isArray(value) ? value : [])} - options={modelAliases.map((alias) => ({ value: alias, label: alias }))} - placeholder="Select model aliases" - inputPlaceholder="Search model aliases..." - emptyPlaceholder="No model aliases found." - className={readonly ? "pointer-events-none opacity-50" : undefined} - /> - - )} - -
- )} - /> + ( + + Model Alias + {!selectedGatewayId ? ( +

Select a gateway first

+ ) : loadingAliases ? ( +
+ Loading model aliases...
- {!readonly && ( -
- Save Model Configuration - {state?.status === 'error' && !state?.errors && ( -

{state.message}

- )} -
- )} -
- - - ); + ) : modelAliases.length === 0 ? ( +

No model aliases available

+ ) : ( + + field.onChange(Array.isArray(value) ? value : [])} + options={modelAliases.map((alias) => ({ value: alias, label: alias }))} + placeholder="Select model aliases" + inputPlaceholder="Search model aliases..." + emptyPlaceholder="No model aliases found." + className={readonly ? 'pointer-events-none opacity-50' : undefined} + /> + + )} + + + )} + /> +
+ {!readonly && ( +
+ Save Model Configuration + {state?.status === 'error' && !state?.errors &&

{state.message}

} +
+ )} +
+ + + ); } diff --git a/src/app/project/[projectId]/agents/details/sandboxes/agent-access-dialog.tsx b/src/app/project/[projectId]/agents/details/sandboxes/agent-access-dialog.tsx index f6b46eaa..d63b7038 100644 --- a/src/app/project/[projectId]/agents/details/sandboxes/agent-access-dialog.tsx +++ b/src/app/project/[projectId]/agents/details/sandboxes/agent-access-dialog.tsx @@ -1,96 +1,95 @@ 'use client'; - -import { useEffect, useState } from "react"; -import { DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; -import { Button } from "@/components/ui/button"; -import { useDialogContext } from "@/frontend/states/dialog-context"; -import { ExternalLink } from "lucide-react"; -import { createAgentAccessUrl } from "./actions"; -import { Spinner } from "@/components/ui/spinner"; -import { Actions } from "@/frontend/utils/nextjs-actions.utils"; +import { useEffect, useState } from 'react'; +import { DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { Button } from '@/components/ui/button'; +import { useDialogContext } from '@/frontend/states/dialog-context'; +import { ExternalLink } from 'lucide-react'; +import { createAgentAccessUrl } from './actions'; +import { Spinner } from '@/components/ui/spinner'; +import { Actions } from '@/frontend/utils/nextjs-actions.utils'; export default function AgentAccessDialogContent({ - agentId, - sandboxName, - view, - domainId, + agentId, + sandboxName, + view, + domainId }: { - agentId: string; - sandboxName: string; - view: 'agent' | 'files'; - domainId: string; + agentId: string; + sandboxName: string; + view: 'agent' | 'files'; + domainId: string; }) { - const { closeDialog } = useDialogContext(); - const [url, setUrl] = useState(); - const [error, setError] = useState(); - const viewLabel = view === 'agent' ? 'Agent UI' : 'File Browser'; + const { closeDialog } = useDialogContext(); + const [url, setUrl] = useState(); + const [error, setError] = useState(); + const viewLabel = view === 'agent' ? 'Agent UI' : 'File Browser'; - useEffect(() => { - let active = true; + useEffect(() => { + let active = true; - const createUrl = async () => { - setUrl(undefined); - setError(undefined); + const createUrl = async () => { + setUrl(undefined); + setError(undefined); - try { - const result = await Actions.run(() => createAgentAccessUrl(agentId, sandboxName, view, domainId)); - if (active) { - setUrl(result.url); - } - } catch (err: any) { - if (active) { - setError(err?.message || 'Could not open Agent access.'); - } - } - }; + try { + const result = await Actions.run(() => createAgentAccessUrl(agentId, sandboxName, view, domainId)); + if (active) { + setUrl(result.url); + } + } catch (err: any) { + if (active) { + setError(err?.message || 'Could not open Agent access.'); + } + } + }; - createUrl(); + createUrl(); - return () => { - active = false; - }; - }, [agentId, sandboxName, domainId, view]); + return () => { + active = false; + }; + }, [agentId, sandboxName, domainId, view]); - return ( - <> - - Open {viewLabel} - + return ( + <> + + Open {viewLabel} + -
- {!url && !error && ( -
- - Generating access link... -
- )} - {url && ( -

- The link is ready. Open the {viewLabel} in a new tab by clicking the button below. This link is valid for 20 seconds. -

- )} - {error && ( -

{error}

- )} -
+
+ {!url && !error && ( +
+ + Generating access link... +
+ )} + {url && ( +

+ The link is ready. Open the {viewLabel} in a new tab by clicking the button below. This link is valid for 20 seconds. +

+ )} + {error &&

{error}

} +
- - - - - - ); -} \ No newline at end of file + + + + + + ); +} diff --git a/src/app/project/[projectId]/agents/details/sandboxes/agent-sandboxes-card.tsx b/src/app/project/[projectId]/agents/details/sandboxes/agent-sandboxes-card.tsx index 95bc3c20..371a938d 100644 --- a/src/app/project/[projectId]/agents/details/sandboxes/agent-sandboxes-card.tsx +++ b/src/app/project/[projectId]/agents/details/sandboxes/agent-sandboxes-card.tsx @@ -1,41 +1,43 @@ 'use client'; -import { useEffect, useState } from "react"; -import { Button } from "@/components/ui/button"; -import { useConfirmDialog, useDialog, useInputDialog } from "@/frontend/states/zustand.states"; -import { Toast } from "@/frontend/utils/toast.utils"; -import { DeploymentStatus } from "@/shared/model/deployment-info.model"; -import { Bot, ChevronDown, ExternalLink, Files, Filter, Logs, Pause, Play, PlayIcon, Search, Square, TagPlus, TagX, Terminal } from "lucide-react"; -import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; -import { startSandbox, stopSandbox, suspendSandbox, resumeSandbox, deleteAgentTag } from "./actions"; -import { ListUtils } from "@/shared/utils/list.utils"; -import { StreamUtils } from "@/shared/utils/stream.utils"; -import FullLoadingSpinner from "@/components/ui/full-loading-spinnter"; -import { LogsDialogContent } from "@/components/custom/logs-overlay"; +import { useEffect, useState } from 'react'; +import { Button } from '@/components/ui/button'; +import { useConfirmDialog, useDialog, useInputDialog } from '@/frontend/states/zustand.states'; +import { Toast } from '@/frontend/utils/toast.utils'; +import { DeploymentStatus } from '@/shared/model/deployment-info.model'; +import { Bot, ChevronDown, ExternalLink, Files, Filter, Logs, Pause, Play, PlayIcon, Search, Square, TagPlus, TagX, Terminal } from 'lucide-react'; +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; +import { startSandbox, stopSandbox, suspendSandbox, resumeSandbox, deleteAgentTag } from './actions'; +import { ListUtils } from '@/shared/utils/list.utils'; +import { StreamUtils } from '@/shared/utils/stream.utils'; +import FullLoadingSpinner from '@/components/ui/full-loading-spinnter'; +import { LogsDialogContent } from '@/components/custom/logs-overlay'; +import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty'; +import DeploymentStatusBadge from '@/app/project/workload-components/deployment-status-badge'; +import type { AgentExtendedModel } from '@/shared/model/agent-extended.model'; +import { toast } from 'sonner'; import { - Empty, - EmptyContent, - EmptyDescription, - EmptyHeader, - EmptyMedia, - EmptyTitle, -} from "@/components/ui/empty" -import DeploymentStatusBadge from "@/app/project/workload-components/deployment-status-badge"; -import type { AgentExtendedModel } from "@/shared/model/agent-extended.model"; -import { toast } from "sonner"; -import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; -import AgentAccessDialogContent from "./agent-access-dialog"; -import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; -import { DrawerCard, DrawerCardDescription, DrawerCardHeader, DrawerCardTitle } from "@/components/custom/drawer-card"; -import { Input } from "@/components/ui/input"; -import { SplitButton } from "@/components/custom/split-button"; + DropdownMenu, + DropdownMenuCheckboxItem, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu'; +import AgentAccessDialogContent from './agent-access-dialog'; +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'; +import { DrawerCard, DrawerCardDescription, DrawerCardHeader, DrawerCardTitle } from '@/components/custom/drawer-card'; +import { Input } from '@/components/ui/input'; +import { SplitButton } from '@/components/custom/split-button'; interface SandboxInfo { - name: string; - status: DeploymentStatus; - statusText: string; - createdAt: string | null; - customTag?: string; + name: string; + status: DeploymentStatus; + statusText: string; + createdAt: string | null; + customTag?: string; } const SSE_RETRY_BASE_DELAY_MS = 1_000; @@ -43,469 +45,451 @@ const SSE_RETRY_MAX_DELAY_MS = 30_000; const SANDBOX_STATUSES: DeploymentStatus[] = ['DEPLOYED', 'DEPLOYING', 'BUILDING', 'PENDING', 'SUSPENDED', 'SHUTTING_DOWN', 'SHUTDOWN', 'ERROR', 'UNKNOWN']; const SANDBOX_STATUS_LABELS: Record = { - DEPLOYED: 'Deployed', - DEPLOYING: 'Deploying', - BUILDING: 'Building', - PENDING: 'Pending', - SUSPENDED: 'Suspended', - SHUTTING_DOWN: 'Stopping', - SHUTDOWN: 'Shutdown', - ERROR: 'Error', - UNKNOWN: 'Unknown', + DEPLOYED: 'Deployed', + DEPLOYING: 'Deploying', + BUILDING: 'Building', + PENDING: 'Pending', + SUSPENDED: 'Suspended', + SHUTTING_DOWN: 'Stopping', + SHUTDOWN: 'Shutdown', + ERROR: 'Error', + UNKNOWN: 'Unknown' }; -export default function AgentSandboxesCard({ - agent, - readonly, -}: { - agent: AgentExtendedModel; - readonly: boolean; -}) { - const { id: agentId, projectId: namespace, agentDomains, deployFileBrowser } = agent; - const { openDialog } = useDialog(); - const { openInputDialog } = useInputDialog(); - const { openConfirmDialog } = useConfirmDialog(); - const [sandboxes, setSandboxes] = useState([]); - const [loading, setLoading] = useState(false); - const [isConnected, setIsConnected] = useState(false); - const [expandedSandboxNames, setExpandedSandboxNames] = useState([]); - const [searchQuery, setSearchQuery] = useState(''); - const [statusFilter, setStatusFilter] = useState([]); - - // SSE stream for live sandbox updates - useEffect(() => { - const controller = new AbortController(); - let stopped = false; - let reader: ReadableStreamDefaultReader | null = null; - let retryTimeout: ReturnType | null = null; - let resolveRetry: (() => void) | null = null; - let retryAttempt = 0; - - const waitForRetry = (delayMs: number) => new Promise(resolve => { - resolveRetry = resolve; - retryTimeout = setTimeout(() => { - retryTimeout = null; - resolveRetry = null; - resolve(); - }, delayMs); - }); - - const connectSse = async () => { - while (!stopped) { - try { - const response = await fetch('/api/agent-sandboxes', { - method: 'POST', - headers: { 'Content-Type': 'text/event-stream' }, - body: JSON.stringify({ agentId }), - signal: controller.signal, - }); - - if (!response.ok || !response.body) { - throw new Error(`SSE request failed with status ${response.status}`); - } +export default function AgentSandboxesCard({ agent, readonly }: { agent: AgentExtendedModel; readonly: boolean }) { + const { id: agentId, projectId: namespace, agentDomains, deployFileBrowser } = agent; + const { openDialog } = useDialog(); + const { openInputDialog } = useInputDialog(); + const { openConfirmDialog } = useConfirmDialog(); + const [sandboxes, setSandboxes] = useState([]); + const [loading, setLoading] = useState(false); + const [isConnected, setIsConnected] = useState(false); + const [expandedSandboxNames, setExpandedSandboxNames] = useState([]); + const [searchQuery, setSearchQuery] = useState(''); + const [statusFilter, setStatusFilter] = useState([]); + + // SSE stream for live sandbox updates + useEffect(() => { + const controller = new AbortController(); + let stopped = false; + let reader: ReadableStreamDefaultReader | null = null; + let retryTimeout: ReturnType | null = null; + let resolveRetry: (() => void) | null = null; + let retryAttempt = 0; + + const waitForRetry = (delayMs: number) => + new Promise((resolve) => { + resolveRetry = resolve; + retryTimeout = setTimeout(() => { + retryTimeout = null; + resolveRetry = null; + resolve(); + }, delayMs); + }); + + const connectSse = async () => { + while (!stopped) { + try { + const response = await fetch('/api/agent-sandboxes', { + method: 'POST', + headers: { 'Content-Type': 'text/event-stream' }, + body: JSON.stringify({ agentId }), + signal: controller.signal + }); + + if (!response.ok || !response.body) { + throw new Error(`SSE request failed with status ${response.status}`); + } + + setIsConnected(true); + reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); + + let buffer = ''; + while (!stopped) { + const { value, done } = await reader.read(); + if (done) { + break; + } - setIsConnected(true); - reader = response.body - .pipeThrough(new TextDecoderStream()) - .getReader(); - - let buffer = ''; - while (!stopped) { - const { value, done } = await reader.read(); - if (done) break; - - const parsed = StreamUtils.parseSseFrames(buffer, value); - buffer = parsed.buffer; - - for (const frame of parsed.frames) { - try { - const msg = JSON.parse(frame); - if (msg.type === 'FULL' && Array.isArray(msg.data)) { - setSandboxes(ListUtils.dedupByName(msg.data, 'name')); - } else if (msg.type === 'ADDED' && msg.sandbox) { - setSandboxes(prev => { - if (prev.some(i => i.name === msg.sandbox.name)) return prev; - return [...prev, msg.sandbox]; - }); - } else if (msg.type === 'MODIFIED' && msg.sandbox) { - setSandboxes(prev => prev.map(i => - i.name === msg.sandbox.name ? msg.sandbox : i - )); - } else if (msg.type === 'DELETED' && msg.sandbox?.name) { - setSandboxes(prev => prev.filter(i => - i.name !== msg.sandbox.name - )); - } - } catch { - // Ignore malformed SSE payloads and keep the stream alive. - } - } - } - } catch (err: any) { - if (err?.name !== 'AbortError' && !stopped) { - console.error('Agent sandboxes SSE error:', err); - } - } finally { - reader = null; - if (!stopped) { - setIsConnected(false); + const parsed = StreamUtils.parseSseFrames(buffer, value); + buffer = parsed.buffer; + + for (const frame of parsed.frames) { + try { + const msg = JSON.parse(frame); + if (msg.type === 'FULL' && Array.isArray(msg.data)) { + setSandboxes(ListUtils.dedupByName(msg.data, 'name')); + } else if (msg.type === 'ADDED' && msg.sandbox) { + setSandboxes((prev) => { + if (prev.some((i) => i.name === msg.sandbox.name)) { + return prev; } + return [...prev, msg.sandbox]; + }); + } else if (msg.type === 'MODIFIED' && msg.sandbox) { + setSandboxes((prev) => prev.map((i) => (i.name === msg.sandbox.name ? msg.sandbox : i))); + } else if (msg.type === 'DELETED' && msg.sandbox?.name) { + setSandboxes((prev) => prev.filter((i) => i.name !== msg.sandbox.name)); } - - if (stopped) break; - - const exponentialDelay = Math.min( - SSE_RETRY_BASE_DELAY_MS * 2 ** retryAttempt, - SSE_RETRY_MAX_DELAY_MS, - ); - const jitteredDelay = exponentialDelay * (0.8 + Math.random() * 0.4); - retryAttempt += 1; - await waitForRetry(jitteredDelay); + } catch { + // Ignore malformed SSE payloads and keep the stream alive. + } } - }; - - void connectSse(); - - return () => { - stopped = true; - controller.abort(); - if (retryTimeout) { - clearTimeout(retryTimeout); - retryTimeout = null; - } - resolveRetry?.(); - void reader?.cancel(); - }; - }, [agentId]); - - const handleStartSandbox = async () => { - setLoading(true); - try { - await Toast.fromAction( - () => startSandbox(agentId), - 'Sandbox started', - 'Starting sandbox...', - ); - } finally { - setLoading(false); - // SSE will push updated list automatically - } - }; - - const handleStartSandboxWithCustomTag = async () => { - const customTag = await openInputDialog({ - title: 'Start sandbox with custom tag', - description: 'The tag identifies this sandbox and must be unique for this Sandbox Instance (1–63 characters).', - fieldName: 'Custom tag', - okButton: 'Start sandbox', - }); - if (!customTag) { - return; - } - - setLoading(true); - try { - await Toast.fromAction( - () => startSandbox(agentId, customTag), - 'Sandbox started', - 'Starting sandbox...', - ); + } + } catch (err: any) { + if (err?.name !== 'AbortError' && !stopped) { + console.error('Agent sandboxes SSE error:', err); + } } finally { - setLoading(false); - } - }; - - const handleDeleteTagData = async () => { - const customTag = await openInputDialog({ - title: 'Delete Custom Tag data', - description: 'Deletes all stored data of this Custom Tag. The tag must not have a running sandbox. 1–63 characters.', - fieldName: 'Custom tag', - okButton: 'Continue', - }); - if (!customTag) { - return; + reader = null; + if (!stopped) { + setIsConnected(false); + } } - const confirmed = await openConfirmDialog({ - title: 'Delete Custom Tag data', - description: `All stored data of Custom Tag "${customTag}" will be deleted permanently. This cannot be undone.`, - okButton: 'Delete data', - }); - if (!confirmed) { - return; + if (stopped) { + break; } - await Toast.fromAction( - () => deleteAgentTag(agentId, customTag), - 'Custom Tag data deleted', - 'Deleting Custom Tag data...', - ); - }; - - const renderStartSandboxActions = () => ( - - void handleStartSandboxWithCustomTag()}> - Start with custom tag - - void handleDeleteTagData()}> - Delete custom tag data - - } - > - - Start sandbox - - ); - - const handleStopSandbox = async (sandboxName: string) => { - try { - await Toast.fromAction( - () => stopSandbox(agentId, sandboxName), - 'Sandbox stopped', - 'Stopping sandbox...', - ); - // SSE will push updated list automatically - } finally { - // nothing to fetch — SSE handles it - } + const exponentialDelay = Math.min(SSE_RETRY_BASE_DELAY_MS * 2 ** retryAttempt, SSE_RETRY_MAX_DELAY_MS); + const jitteredDelay = exponentialDelay * (0.8 + Math.random() * 0.4); + retryAttempt += 1; + await waitForRetry(jitteredDelay); + } }; - const handleSuspendSandbox = async (sandboxName: string) => { - await Toast.fromAction( - () => suspendSandbox(agentId, sandboxName), - 'Sandbox suspended', - 'Suspending sandbox...', - ); + void connectSse(); + + return () => { + stopped = true; + controller.abort(); + if (retryTimeout) { + clearTimeout(retryTimeout); + retryTimeout = null; + } + resolveRetry?.(); + void reader?.cancel(); }; - - const handleResumeSandbox = async (sandboxName: string) => { - await Toast.fromAction( - () => resumeSandbox(agentId, sandboxName), - 'Sandbox resumed', - 'Resuming sandbox...', - ); - }; - - const handleOpenTerminal = async () => { - // Terminal opening is delegated to parent component via callback - // For now, this is a placeholder — terminal per sandbox needs pod discovery - }; - - const toggleSandboxExpanded = (sandboxName: string, open: boolean) => { - setExpandedSandboxNames(current => open - ? [...new Set([...current, sandboxName])] - : current.filter(name => name !== sandboxName), - ); - }; - - const toggleStatusFilter = (status: DeploymentStatus, checked: boolean) => { - setStatusFilter(current => checked - ? [...current, status] - : current.filter(value => value !== status), - ); - }; - - const normalizedSearchQuery = searchQuery.trim().toLowerCase(); - const filteredSandboxes = sandboxes.filter(sandbox => { - const matchesSearch = normalizedSearchQuery.length === 0 - || sandbox.name.toLowerCase().includes(normalizedSearchQuery) - || sandbox.customTag?.toLowerCase().includes(normalizedSearchQuery); - const matchesStatus = statusFilter.length === 0 || statusFilter.includes(sandbox.status); - - return matchesSearch && matchesStatus; + }, [agentId]); + + const handleStartSandbox = async () => { + setLoading(true); + try { + await Toast.fromAction(() => startSandbox(agentId), 'Sandbox started', 'Starting sandbox...'); + } finally { + setLoading(false); + // SSE will push updated list automatically + } + }; + + const handleStartSandboxWithCustomTag = async () => { + const customTag = await openInputDialog({ + title: 'Start sandbox with custom tag', + description: 'The tag identifies this sandbox and must be unique for this Sandbox Instance (1–63 characters).', + fieldName: 'Custom tag', + okButton: 'Start sandbox' }); + if (!customTag) { + return; + } + + setLoading(true); + try { + await Toast.fromAction(() => startSandbox(agentId, customTag), 'Sandbox started', 'Starting sandbox...'); + } finally { + setLoading(false); + } + }; + + const handleDeleteTagData = async () => { + const customTag = await openInputDialog({ + title: 'Delete Custom Tag data', + description: 'Deletes all stored data of this Custom Tag. The tag must not have a running sandbox. 1–63 characters.', + fieldName: 'Custom tag', + okButton: 'Continue' + }); + if (!customTag) { + return; + } + + const confirmed = await openConfirmDialog({ + title: 'Delete Custom Tag data', + description: `All stored data of Custom Tag "${customTag}" will be deleted permanently. This cannot be undone.`, + okButton: 'Delete data' + }); + if (!confirmed) { + return; + } + + await Toast.fromAction(() => deleteAgentTag(agentId, customTag), 'Custom Tag data deleted', 'Deleting Custom Tag data...'); + }; + + const renderStartSandboxActions = () => ( + + void handleStartSandboxWithCustomTag()}> + Start with custom tag + + void handleDeleteTagData()}> + Delete custom tag data + + + } + > + + Start sandbox + + ); + + const handleStopSandbox = async (sandboxName: string) => { + try { + await Toast.fromAction(() => stopSandbox(agentId, sandboxName), 'Sandbox stopped', 'Stopping sandbox...'); + // SSE will push updated list automatically + } finally { + // nothing to fetch — SSE handles it + } + }; + + const handleSuspendSandbox = async (sandboxName: string) => { + await Toast.fromAction(() => suspendSandbox(agentId, sandboxName), 'Sandbox suspended', 'Suspending sandbox...'); + }; + + const handleResumeSandbox = async (sandboxName: string) => { + await Toast.fromAction(() => resumeSandbox(agentId, sandboxName), 'Sandbox resumed', 'Resuming sandbox...'); + }; + + const handleOpenTerminal = async () => { + // Terminal opening is delegated to parent component via callback + // For now, this is a placeholder — terminal per sandbox needs pod discovery + }; + + const toggleSandboxExpanded = (sandboxName: string, open: boolean) => { + setExpandedSandboxNames((current) => (open ? [...new Set([...current, sandboxName])] : current.filter((name) => name !== sandboxName))); + }; + + const toggleStatusFilter = (status: DeploymentStatus, checked: boolean) => { + setStatusFilter((current) => (checked ? [...current, status] : current.filter((value) => value !== status))); + }; + + const normalizedSearchQuery = searchQuery.trim().toLowerCase(); + const filteredSandboxes = sandboxes.filter((sandbox) => { + const matchesSearch = + normalizedSearchQuery.length === 0 || + sandbox.name.toLowerCase().includes(normalizedSearchQuery) || + sandbox.customTag?.toLowerCase().includes(normalizedSearchQuery); + const matchesStatus = statusFilter.length === 0 || statusFilter.includes(sandbox.status); + + return matchesSearch && matchesStatus; + }); + + const handleOpenLogs = (sandboxName: string) => { + openDialog(, { maxWidth: '1300px' }); + }; + + const handleOpenAgentAccess = (sandboxName: string, view: 'agent' | 'files', domainId: string) => { + if (agentDomains.length === 0) { + toast.error('Configure an Agent access domain first.'); + return; + } + + openDialog(, { maxWidth: '440px' }); + }; + + const renderAccessButton = (sandboxName: string, view: 'agent' | 'files', showLabel = false) => { + const icon = view === 'agent' ? : ; + const label = view === 'agent' ? 'Open agent' : 'Files'; + const disabled = agentDomains.length === 0; + + if (agentDomains.length <= 1) { + return ( + + ); + } - const handleOpenLogs = (sandboxName: string) => { - openDialog(, { maxWidth: '1300px' }); - }; - - const handleOpenAgentAccess = (sandboxName: string, view: 'agent' | 'files', domainId: string) => { - if (agentDomains.length === 0) { - toast.error('Configure an Agent access domain first.'); - return; - } - - openDialog( - , - { maxWidth: '440px' } - ); - }; - - const renderAccessButton = (sandboxName: string, view: 'agent' | 'files', showLabel = false) => { - const icon = view === 'agent' - ? - : ; - const label = view === 'agent' ? 'Open agent' : 'Files'; - const disabled = agentDomains.length === 0; - - if (agentDomains.length <= 1) { - return ( - - ); - } - - return ( - - - {icon} - {showLabel && {label}} - } /> - - {agentDomains.map((domain) => ( - handleOpenAgentAccess(sandboxName, view, domain.id)}> - {domain.hostname} - + return ( + + + {icon} + {showLabel && {label}} + + } + /> + + {agentDomains.map((domain) => ( + handleOpenAgentAccess(sandboxName, view, domain.id)}> + {domain.hostname} + + ))} + + + ); + }; + + return ( + +
+ + Sandboxes + + {sandboxes.length === 0 + ? 'Start a sandbox to open an agent workspace.' + : `${sandboxes.length} sandbox${sandboxes.length === 1 ? '' : 'es'} · ${sandboxes.filter((sandbox) => sandbox.status === 'DEPLOYED').length} running`} + + + {!readonly && renderStartSandboxActions()} +
+ + {!isConnected ? ( + + ) : sandboxes.length === 0 ? ( + + + + + + No sandboxes yet + Start a sandbox to create an agent workspace. + + {!readonly && {renderStartSandboxActions()}} + + ) : ( + +
+
+
+ + setSearchQuery(event.target.value)} placeholder="Search name or tag" className="pl-9" /> +
+ + }> + + Filter{statusFilter.length > 0 && ` (${statusFilter.length})`} + + + + Status + + {SANDBOX_STATUSES.map((status) => ( + toggleStatusFilter(status, checked)} + > + {SANDBOX_STATUS_LABELS[status]} + ))} + - - ); - }; - - return ( - -
- - Sandboxes - - {sandboxes.length === 0 - ? 'Start a sandbox to open an agent workspace.' - : `${sandboxes.length} sandbox${sandboxes.length === 1 ? '' : 'es'} · ${sandboxes.filter(sandbox => sandbox.status === 'DEPLOYED').length} running`} - - - {!readonly && ( - renderStartSandboxActions() - )} +
- {!isConnected ? : ( - sandboxes.length === 0 ? ( - - - - No sandboxes yet - Start a sandbox to create an agent workspace. - - {!readonly && - {renderStartSandboxActions()} - } - - ) : ( - -
-
-
- - setSearchQuery(event.target.value)} - placeholder="Search name or tag" - className="pl-9" - /> -
- - }> - - Filter{statusFilter.length > 0 && ` (${statusFilter.length})`} - - - - Status - - {SANDBOX_STATUSES.map((status) => ( - toggleStatusFilter(status, checked)} - > - {SANDBOX_STATUS_LABELS[status]} - - ))} - - - -
- - {filteredSandboxes.length === 0 && ( -
- No sandboxes match the current search or filter. -
- )} - - {filteredSandboxes.map((sandbox) => ( - toggleSandboxExpanded(sandbox.name, open)} - className="overflow-hidden rounded-lg border bg-card" - > - }> - -
- {sandbox.name} -
- Tag: {sandbox.customTag ?? '—'} - · - Created {sandbox.createdAt ? new Date(sandbox.createdAt).toLocaleString() : '—'} -
-
- {sandbox.status} -
- -
- {sandbox.status === 'DEPLOYED' && <> - - - Open Agent UI - - {deployFileBrowser && - - Open Files - } - - - {!readonly && } - } - {sandbox.status === 'SUSPENDED' && !readonly && } - {!readonly && } -
-
-
- ))} -
-
- ) + {filteredSandboxes.length === 0 && ( +
+ No sandboxes match the current search or filter. +
)} -
- ); + + {filteredSandboxes.map((sandbox) => ( + toggleSandboxExpanded(sandbox.name, open)} + className="overflow-hidden rounded-lg border bg-card" + > + }> + +
+ {sandbox.name} +
+ + Tag: {sandbox.customTag ?? '—'} + + · + Created {sandbox.createdAt ? new Date(sandbox.createdAt).toLocaleString() : '—'} +
+
+ + {sandbox.status} + +
+ +
+ {sandbox.status === 'DEPLOYED' && ( + <> + + + Open Agent UI + + {deployFileBrowser && ( + + + Open Files + + )} + + + {!readonly && ( + + )} + + )} + {sandbox.status === 'SUSPENDED' && !readonly && ( + + )} + {!readonly && ( + + )} +
+
+
+ ))} +
+ + )} + + ); } diff --git a/src/app/project/[projectId]/agents/details/source/agent-source-wizard-dialog.tsx b/src/app/project/[projectId]/agents/details/source/agent-source-wizard-dialog.tsx index 302585a5..b932ed6f 100644 --- a/src/app/project/[projectId]/agents/details/source/agent-source-wizard-dialog.tsx +++ b/src/app/project/[projectId]/agents/details/source/agent-source-wizard-dialog.tsx @@ -1,400 +1,432 @@ 'use client'; -import { Button } from "@/components/ui/button"; -import { DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; -import { useDialogContext } from "@/frontend/states/dialog-context"; -import { useConfirmDialog } from "@/frontend/states/zustand.states"; -import { Actions } from "@/frontend/utils/nextjs-actions.utils"; -import { Toast } from "@/frontend/utils/toast.utils"; -import { AgentExtendedModel } from "@/shared/model/agent-extended.model"; -import { AgentDockerfileDetectionModel, AgentGitBranchesLookupModel, AgentSourceInfoInputModel } from "@/shared/model/agent-config.model"; -import { ChevronLeft, Loader2, Rocket, Save } from "lucide-react"; -import { useRouter } from "next/navigation"; -import { useEffect, useState } from "react"; -import { toast } from "sonner"; +import { Button } from '@/components/ui/button'; +import { DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { useDialogContext } from '@/frontend/states/dialog-context'; +import { useConfirmDialog } from '@/frontend/states/zustand.states'; +import { Actions } from '@/frontend/utils/nextjs-actions.utils'; +import { Toast } from '@/frontend/utils/toast.utils'; +import { AgentExtendedModel } from '@/shared/model/agent-extended.model'; +import { AgentDockerfileDetectionModel, AgentGitBranchesLookupModel, AgentSourceInfoInputModel } from '@/shared/model/agent-config.model'; +import { ChevronLeft, Loader2, Rocket, Save } from 'lucide-react'; +import { useRouter } from 'next/navigation'; +import { useEffect, useState } from 'react'; +import { toast } from 'sonner'; import { - detectAgentDockerfilePath, - ensureAgentGitSshPublicKey, - generateOrRegenerateAgentGitSshKey, - getAgentGitBranches, - saveAgentSource, -} from "../configuration/actions"; -import { deployAgent } from "../agent-actions"; -import { PathBuilderUtils } from "@/shared/utils/path-builder.utils"; -import { ContainerImageStep } from "@/app/project/workload-components/source-wizard/container-image-step"; -import { DockerfilePathStep } from "@/app/project/workload-components/source-wizard/dockerfile-path-step"; -import { GitBranchStep } from "@/app/project/workload-components/source-wizard/git-branch-step"; -import { GitHttpsUrlStep } from "@/app/project/workload-components/source-wizard/git-https-url-step"; -import { GitSshUrlStep } from "@/app/project/workload-components/source-wizard/git-ssh-url-step"; -import { SourceSummaryStep } from "@/app/project/workload-components/source-wizard/source-summary-step"; -import { SourceTypeStep } from "@/app/project/workload-components/source-wizard/source-type-step"; -import { defaultDockerfilePath, SourceFormPatch, sourceTypeLabels, SourceType, StepId } from "@/app/project/workload-components/source-wizard/types"; -import { WizardProgress } from "@/app/project/workload-components/source-wizard/wizard-progress"; + detectAgentDockerfilePath, + ensureAgentGitSshPublicKey, + generateOrRegenerateAgentGitSshKey, + getAgentGitBranches, + saveAgentSource +} from '../configuration/actions'; +import { deployAgent } from '../agent-actions'; +import { PathBuilderUtils } from '@/shared/utils/path-builder.utils'; +import { ContainerImageStep } from '@/app/project/workload-components/source-wizard/container-image-step'; +import { DockerfilePathStep } from '@/app/project/workload-components/source-wizard/dockerfile-path-step'; +import { GitBranchStep } from '@/app/project/workload-components/source-wizard/git-branch-step'; +import { GitHttpsUrlStep } from '@/app/project/workload-components/source-wizard/git-https-url-step'; +import { GitSshUrlStep } from '@/app/project/workload-components/source-wizard/git-ssh-url-step'; +import { SourceSummaryStep } from '@/app/project/workload-components/source-wizard/source-summary-step'; +import { SourceTypeStep } from '@/app/project/workload-components/source-wizard/source-type-step'; +import { defaultDockerfilePath, SourceFormPatch, sourceTypeLabels, SourceType, StepId } from '@/app/project/workload-components/source-wizard/types'; +import { WizardProgress } from '@/app/project/workload-components/source-wizard/wizard-progress'; -export function AgentSourceWizardDialog({ agent, gitSshPublicKey }: { - agent: AgentExtendedModel; - gitSshPublicKey?: string; -}) { - const router = useRouter(); - const { closeDialog } = useDialogContext(); - const { openConfirmDialog } = useConfirmDialog(); - const [step, setStep] = useState('source'); - const [history, setHistory] = useState([]); - const [formData, setFormData] = useState(() => toSourceInput(agent)); - const [publicKey, setPublicKey] = useState(gitSshPublicKey); - const [branches, setBranches] = useState([]); - const [isLoadingBranches, setIsLoadingBranches] = useState(false); - const [branchError, setBranchError] = useState(null); - const [isEnsuringKey, setIsEnsuringKey] = useState(false); - const [isDetectingDockerfile, setIsDetectingDockerfile] = useState(false); - const [dockerfileDetectionResult, setDockerfileDetectionResult] = useState<'detected' | 'not-found' | null>(null); - const [showGitToken, setShowGitToken] = useState(false); - const [showRegistryPassword, setShowRegistryPassword] = useState(false); +export function AgentSourceWizardDialog({ agent, gitSshPublicKey }: { agent: AgentExtendedModel; gitSshPublicKey?: string }) { + const router = useRouter(); + const { closeDialog } = useDialogContext(); + const { openConfirmDialog } = useConfirmDialog(); + const [step, setStep] = useState('source'); + const [history, setHistory] = useState([]); + const [formData, setFormData] = useState(() => toSourceInput(agent)); + const [publicKey, setPublicKey] = useState(gitSshPublicKey); + const [branches, setBranches] = useState([]); + const [isLoadingBranches, setIsLoadingBranches] = useState(false); + const [branchError, setBranchError] = useState(null); + const [isEnsuringKey, setIsEnsuringKey] = useState(false); + const [isDetectingDockerfile, setIsDetectingDockerfile] = useState(false); + const [dockerfileDetectionResult, setDockerfileDetectionResult] = useState<'detected' | 'not-found' | null>(null); + const [showGitToken, setShowGitToken] = useState(false); + const [showRegistryPassword, setShowRegistryPassword] = useState(false); - const isGitSource = formData.sourceType === 'GIT' || formData.sourceType === 'GIT_SSH'; - const showGitCredentials = formData.sourceType === 'GIT' && !!formData.gitUrl?.trim(); - const showRegistryCredentials = formData.sourceType === 'CONTAINER' && !!formData.containerImageSource?.trim(); - const currentTitle = getStepTitle(step, formData.sourceType); + const isGitSource = formData.sourceType === 'GIT' || formData.sourceType === 'GIT_SSH'; + const showGitCredentials = formData.sourceType === 'GIT' && !!formData.gitUrl?.trim(); + const showRegistryCredentials = formData.sourceType === 'CONTAINER' && !!formData.containerImageSource?.trim(); + const currentTitle = getStepTitle(step, formData.sourceType); - const goTo = (nextStep: StepId) => { - setHistory((items) => [...items, step]); - setStep(nextStep); - }; + const goTo = (nextStep: StepId) => { + setHistory((items) => [...items, step]); + setStep(nextStep); + }; - const goBack = () => { - const previous = history[history.length - 1]; - if (!previous) return; - setHistory((items) => items.slice(0, -1)); - setStep(previous); - }; + const goBack = () => { + const previous = history[history.length - 1]; + if (!previous) { + return; + } + setHistory((items) => items.slice(0, -1)); + setStep(previous); + }; - const updateFormData = (patch: SourceFormPatch) => { - setFormData((current) => ({ ...current, ...patch, buildMethod: 'DOCKERFILE' })); - }; + const updateFormData = (patch: SourceFormPatch) => { + setFormData((current) => ({ ...current, ...patch, buildMethod: 'DOCKERFILE' })); + }; - const chooseSourceType = (sourceType: SourceType) => { - setBranches([]); - setBranchError(null); - setDockerfileDetectionResult(null); - setFormData((current) => resetForSourceType(current, sourceType)); - }; + const chooseSourceType = (sourceType: SourceType) => { + setBranches([]); + setBranchError(null); + setDockerfileDetectionResult(null); + setFormData((current) => resetForSourceType(current, sourceType)); + }; - const loadBranches = async () => { - if (!formData.gitUrl?.trim()) { - setBranchError('Enter a Git repository URL first.'); - return false; - } + const loadBranches = async () => { + if (!formData.gitUrl?.trim()) { + setBranchError('Enter a Git repository URL first.'); + return false; + } - const inputData: AgentGitBranchesLookupModel = formData.sourceType === 'GIT' - ? { - sourceType: 'GIT', - gitUrl: formData.gitUrl, - gitUsername: formData.gitUsername, - gitToken: formData.gitToken, - } - : { - sourceType: 'GIT_SSH', - gitUrl: formData.gitUrl, - }; + const inputData: AgentGitBranchesLookupModel = + formData.sourceType === 'GIT' + ? { + sourceType: 'GIT', + gitUrl: formData.gitUrl, + gitUsername: formData.gitUsername, + gitToken: formData.gitToken + } + : { + sourceType: 'GIT_SSH', + gitUrl: formData.gitUrl + }; - setIsLoadingBranches(true); - setBranchError(null); - try { - const result = await Actions.run(() => getAgentGitBranches(agent.id, inputData)); - setBranches(result ?? []); - if (formData.gitBranch && !result?.includes(formData.gitBranch)) { - updateFormData({ gitBranch: '' }); - } - return true; - } catch (error) { - setBranches([]); - setBranchError(error instanceof Error ? error.message : 'Branches could not be loaded.'); - return false; - } finally { - setIsLoadingBranches(false); - } - }; + setIsLoadingBranches(true); + setBranchError(null); + try { + const result = await Actions.run(() => getAgentGitBranches(agent.id, inputData)); + setBranches(result ?? []); + if (formData.gitBranch && !result?.includes(formData.gitBranch)) { + updateFormData({ gitBranch: '' }); + } + return true; + } catch (error) { + setBranches([]); + setBranchError(error instanceof Error ? error.message : 'Branches could not be loaded.'); + return false; + } finally { + setIsLoadingBranches(false); + } + }; - const ensureSshKey = async () => { - if (publicKey || isEnsuringKey) return; - setIsEnsuringKey(true); - try { - const key = await Actions.run(() => ensureAgentGitSshPublicKey(agent.id)); - setPublicKey(key); - } finally { - setIsEnsuringKey(false); - } - }; + const ensureSshKey = async () => { + if (publicKey || isEnsuringKey) { + return; + } + setIsEnsuringKey(true); + try { + const key = await Actions.run(() => ensureAgentGitSshPublicKey(agent.id)); + setPublicKey(key); + } finally { + setIsEnsuringKey(false); + } + }; - useEffect(() => { - if (step === 'ssh-url') { - ensureSshKey(); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [step, formData.gitUrl, publicKey]); + useEffect(() => { + if (step === 'ssh-url') { + ensureSshKey(); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [step, formData.gitUrl, publicKey]); - const regenerateKey = async () => { - const confirmed = await openConfirmDialog({ - title: "Regenerate Deploy Key", - description: "This replaces the current agent SSH key. Update the deploy key in your Git provider before deploying again.", - okButton: "Regenerate", - }); - if (!confirmed) return; - const key = await Actions.run(() => generateOrRegenerateAgentGitSshKey(agent.id)); - setPublicKey(key); - toast.success('Deploy key regenerated.'); - }; + const regenerateKey = async () => { + const confirmed = await openConfirmDialog({ + title: 'Regenerate Deploy Key', + description: 'This replaces the current agent SSH key. Update the deploy key in your Git provider before deploying again.', + okButton: 'Regenerate' + }); + if (!confirmed) { + return; + } + const key = await Actions.run(() => generateOrRegenerateAgentGitSshKey(agent.id)); + setPublicKey(key); + toast.success('Deploy key regenerated.'); + }; - const copyPublicKey = () => { - if (!publicKey) return; - navigator.clipboard.writeText(publicKey); - toast.success('Copied to clipboard.'); - }; + const copyPublicKey = () => { + if (!publicKey) { + return; + } + navigator.clipboard.writeText(publicKey); + toast.success('Copied to clipboard.'); + }; - const runDockerfileDetection = async (selectedBranch = formData.gitBranch) => { - if (!isGitSource || !formData.gitUrl || !selectedBranch) return; + const runDockerfileDetection = async (selectedBranch = formData.gitBranch) => { + if (!isGitSource || !formData.gitUrl || !selectedBranch) { + return; + } - const inputData: AgentDockerfileDetectionModel = formData.sourceType === 'GIT' - ? { - sourceType: 'GIT', - gitUrl: formData.gitUrl, - gitBranch: selectedBranch, - gitUsername: formData.gitUsername, - gitToken: formData.gitToken, - } - : { - sourceType: 'GIT_SSH', - gitUrl: formData.gitUrl, - gitBranch: selectedBranch, - }; + const inputData: AgentDockerfileDetectionModel = + formData.sourceType === 'GIT' + ? { + sourceType: 'GIT', + gitUrl: formData.gitUrl, + gitBranch: selectedBranch, + gitUsername: formData.gitUsername, + gitToken: formData.gitToken + } + : { + sourceType: 'GIT_SSH', + gitUrl: formData.gitUrl, + gitBranch: selectedBranch + }; - setIsDetectingDockerfile(true); - try { - const dockerfilePath = await Actions.run(() => detectAgentDockerfilePath(agent.id, inputData)); - updateFormData({ dockerfilePath: dockerfilePath || defaultDockerfilePath }); - setDockerfileDetectionResult(dockerfilePath ? 'detected' : 'not-found'); - } finally { - setIsDetectingDockerfile(false); - } - }; + setIsDetectingDockerfile(true); + try { + const dockerfilePath = await Actions.run(() => detectAgentDockerfilePath(agent.id, inputData)); + updateFormData({ dockerfilePath: dockerfilePath || defaultDockerfilePath }); + setDockerfileDetectionResult(dockerfilePath ? 'detected' : 'not-found'); + } finally { + setIsDetectingDockerfile(false); + } + }; - const selectGitBranch = async (gitBranch: string) => { - updateFormData({ gitBranch, buildMethod: 'DOCKERFILE' }); - setDockerfileDetectionResult(null); - goTo('dockerfile'); - await runDockerfileDetection(gitBranch); - }; + const selectGitBranch = async (gitBranch: string) => { + updateFormData({ gitBranch, buildMethod: 'DOCKERFILE' }); + setDockerfileDetectionResult(null); + goTo('dockerfile'); + await runDockerfileDetection(gitBranch); + }; - const next = async () => { - if (step === 'source') { - goTo(formData.sourceType === 'GIT' ? 'git-url' : formData.sourceType === 'GIT_SSH' ? 'ssh-url' : 'container-image'); - return; - } - if (step === 'git-url' || step === 'ssh-url') { - if (await loadBranches()) { - goTo('branch'); - } - return; - } - if (step === 'dockerfile' || step === 'container-image') { - goTo('summary'); - } - }; + const next = async () => { + if (step === 'source') { + goTo(formData.sourceType === 'GIT' ? 'git-url' : formData.sourceType === 'GIT_SSH' ? 'ssh-url' : 'container-image'); + return; + } + if (step === 'git-url' || step === 'ssh-url') { + if (await loadBranches()) { + goTo('branch'); + } + return; + } + if (step === 'dockerfile' || step === 'container-image') { + goTo('summary'); + } + }; - const save = async (deployAfterSave: boolean) => { - await Toast.fromAction(() => saveAgentSource(null, formData, agent.id), 'Source saved', 'Saving source...'); - if (deployAfterSave) { - await Toast.fromAction(() => deployAgent(agent.id, true), 'Deployment started', 'Starting deployment...'); - closeDialog(true); - router.refresh(); - router.push(PathBuilderUtils.projectAgentDrawer(agent.projectId, agent.id, 'configuration')); - return; - } - closeDialog(true); - router.refresh(); - }; + const save = async (deployAfterSave: boolean) => { + await Toast.fromAction(() => saveAgentSource(null, formData, agent.id), 'Source saved', 'Saving source...'); + if (deployAfterSave) { + await Toast.fromAction(() => deployAgent(agent.id, true), 'Deployment started', 'Starting deployment...'); + closeDialog(true); + router.refresh(); + router.push(PathBuilderUtils.projectAgentDrawer(agent.projectId, agent.id, 'configuration')); + return; + } + closeDialog(true); + router.refresh(); + }; - const nextDisabled = getNextDisabled(step, formData, publicKey, isLoadingBranches, isEnsuringKey, isDetectingDockerfile); + const nextDisabled = getNextDisabled(step, formData, publicKey, isLoadingBranches, isEnsuringKey, isDetectingDockerfile); - return ( - <> - - {currentTitle} - - {step === 'summary' ? 'Review the agent source before saving.' : 'Connect a source with the details QuickStack needs to run this agent.'} - - + return ( + <> + + {currentTitle} + + {step === 'summary' ? 'Review the agent source before saving.' : 'Connect a source with the details QuickStack needs to run this agent.'} + + -
- - {step === 'source' && ( - - )} - {step === 'git-url' && ( - - )} - {step === 'ssh-url' && ( - - )} - {step === 'branch' && ( - - )} - {step === 'dockerfile' && ( - updateFormData({ dockerfilePath })} - onRetry={() => void runDockerfileDetection()} - /> - )} - {step === 'container-image' && ( - - )} - {step === 'summary' && ( - - )} -
+
+ + {step === 'source' && } + {step === 'git-url' && ( + + )} + {step === 'ssh-url' && ( + + )} + {step === 'branch' && } + {step === 'dockerfile' && ( + updateFormData({ dockerfilePath })} + onRetry={() => void runDockerfileDetection()} + /> + )} + {step === 'container-image' && ( + + )} + {step === 'summary' && ( + + )} +
- -
-
- {history.length > 0 && ( - - )} -
-
- {step === 'summary' ? ( - <> - - - - ) : step === 'branch' ? null : ( - - )} -
-
-
- - ); + +
+
+ {history.length > 0 && ( + + )} +
+
+ {step === 'summary' ? ( + <> + + + + ) : step === 'branch' ? null : ( + + )} +
+
+
+ + ); } function getStepTitle(step: StepId, sourceType: AgentSourceInfoInputModel['sourceType']) { - if (step === 'source') return 'Choose source'; - if (step === 'git-url') return 'Connect Git HTTPS'; - if (step === 'ssh-url') return 'Connect Git SSH'; - if (step === 'branch') return 'Choose Git Branch'; - if (step === 'dockerfile') return 'Confirm Dockerfile Path'; - if (step === 'container-image') return 'Connect Docker Container Image'; - if (step === 'summary') return `${sourceTypeLabels[sourceType as SourceType]} Summary`; - return 'Connect Agent Source'; + if (step === 'source') { + return 'Choose source'; + } + if (step === 'git-url') { + return 'Connect Git HTTPS'; + } + if (step === 'ssh-url') { + return 'Connect Git SSH'; + } + if (step === 'branch') { + return 'Choose Git Branch'; + } + if (step === 'dockerfile') { + return 'Confirm Dockerfile Path'; + } + if (step === 'container-image') { + return 'Connect Docker Container Image'; + } + if (step === 'summary') { + return `${sourceTypeLabels[sourceType as SourceType]} Summary`; + } + return 'Connect Agent Source'; } -function getNextDisabled(step: StepId, formData: AgentSourceInfoInputModel, publicKey: string | undefined, isLoadingBranches: boolean, isEnsuringKey: boolean, isDetectingDockerfile: boolean) { - if (isLoadingBranches || isEnsuringKey || isDetectingDockerfile) return true; - if (step === 'git-url') return !formData.gitUrl?.trim(); - if (step === 'ssh-url') return !formData.gitUrl?.trim() || !publicKey; - if (step === 'branch') return !formData.gitBranch; - if (step === 'dockerfile') return !formData.dockerfilePath?.trim(); - if (step === 'container-image') return !formData.containerImageSource?.trim(); - return false; +function getNextDisabled( + step: StepId, + formData: AgentSourceInfoInputModel, + publicKey: string | undefined, + isLoadingBranches: boolean, + isEnsuringKey: boolean, + isDetectingDockerfile: boolean +) { + if (isLoadingBranches || isEnsuringKey || isDetectingDockerfile) { + return true; + } + if (step === 'git-url') { + return !formData.gitUrl?.trim(); + } + if (step === 'ssh-url') { + return !formData.gitUrl?.trim() || !publicKey; + } + if (step === 'branch') { + return !formData.gitBranch; + } + if (step === 'dockerfile') { + return !formData.dockerfilePath?.trim(); + } + if (step === 'container-image') { + return !formData.containerImageSource?.trim(); + } + return false; } function resetForSourceType(current: AgentSourceInfoInputModel, sourceType: SourceType): AgentSourceInfoInputModel { - if (sourceType === current.sourceType) return current; - if (sourceType === 'GIT') { - return { - sourceType, - buildMethod: 'DOCKERFILE', - gitUrl: '', - gitBranch: '', - gitUsername: '', - gitToken: '', - dockerfilePath: defaultDockerfilePath, - }; - } - if (sourceType === 'GIT_SSH') { - return { - sourceType, - buildMethod: 'DOCKERFILE', - gitUrl: '', - gitBranch: '', - dockerfilePath: defaultDockerfilePath, - }; - } + if (sourceType === current.sourceType) { + return current; + } + if (sourceType === 'GIT') { return { - sourceType, - buildMethod: 'DOCKERFILE', - containerImageSource: '', - containerRegistryUsername: '', - containerRegistryPassword: '', - dockerfilePath: defaultDockerfilePath, + sourceType, + buildMethod: 'DOCKERFILE', + gitUrl: '', + gitBranch: '', + gitUsername: '', + gitToken: '', + dockerfilePath: defaultDockerfilePath }; + } + if (sourceType === 'GIT_SSH') { + return { + sourceType, + buildMethod: 'DOCKERFILE', + gitUrl: '', + gitBranch: '', + dockerfilePath: defaultDockerfilePath + }; + } + return { + sourceType, + buildMethod: 'DOCKERFILE', + containerImageSource: '', + containerRegistryUsername: '', + containerRegistryPassword: '', + dockerfilePath: defaultDockerfilePath + }; } function toSourceInput(agent: AgentExtendedModel): AgentSourceInfoInputModel { - return { - sourceType: agent.sourceType as SourceType, - buildMethod: 'DOCKERFILE', - containerImageSource: agent.containerImageSource ?? '', - containerRegistryUsername: agent.containerRegistryUsername ?? '', - containerRegistryPassword: agent.containerRegistryPassword ?? '', - gitUrl: agent.gitUrl ?? '', - gitBranch: agent.gitBranch ?? '', - gitUsername: agent.gitUsername ?? '', - gitToken: agent.gitToken ?? '', - dockerfilePath: agent.dockerfilePath ?? defaultDockerfilePath, - }; + return { + sourceType: agent.sourceType as SourceType, + buildMethod: 'DOCKERFILE', + containerImageSource: agent.containerImageSource ?? '', + containerRegistryUsername: agent.containerRegistryUsername ?? '', + containerRegistryPassword: agent.containerRegistryPassword ?? '', + gitUrl: agent.gitUrl ?? '', + gitBranch: agent.gitBranch ?? '', + gitUsername: agent.gitUsername ?? '', + gitToken: agent.gitToken ?? '', + dockerfilePath: agent.dockerfilePath ?? defaultDockerfilePath + }; } diff --git a/src/app/project/[projectId]/agents/details/volumes/agent-volumes-card.tsx b/src/app/project/[projectId]/agents/details/volumes/agent-volumes-card.tsx index 26f7717a..ee099399 100644 --- a/src/app/project/[projectId]/agents/details/volumes/agent-volumes-card.tsx +++ b/src/app/project/[projectId]/agents/details/volumes/agent-volumes-card.tsx @@ -13,7 +13,9 @@ import { deleteAgentVolume } from '../configuration/actions'; import { Constants } from '@/shared/utils/constants'; function formatSize(mb: number): string { - if (mb >= 1024) return `${(mb / 1024).toFixed(1)} GiB`; + if (mb >= 1024) { + return `${(mb / 1024).toFixed(1)} GiB`; + } return `${mb} MiB`; } diff --git a/src/app/project/[projectId]/apps/create/edit-app-dialog.tsx b/src/app/project/[projectId]/apps/create/edit-app-dialog.tsx index daaf7b8f..672c2824 100644 --- a/src/app/project/[projectId]/apps/create/edit-app-dialog.tsx +++ b/src/app/project/[projectId]/apps/create/edit-app-dialog.tsx @@ -1,48 +1,51 @@ -'use client' +'use client'; -import { Toast } from "@/frontend/utils/toast.utils"; -import { createApp } from "../../actions"; -import { useRouter } from "next/navigation"; -import { cloneElement, type MouseEvent, type ReactElement } from "react"; -import type { App } from "@prisma/client"; -import { useInputDialog } from "@/frontend/states/zustand.states"; -import { PathBuilderUtils } from "@/shared/utils/path-builder.utils"; +import { Toast } from '@/frontend/utils/toast.utils'; +import { createApp } from '../../actions'; +import { useRouter } from 'next/navigation'; +import { cloneElement, type MouseEvent, type ReactElement } from 'react'; +import type { App } from '@prisma/client'; +import { useInputDialog } from '@/frontend/states/zustand.states'; +import { PathBuilderUtils } from '@/shared/utils/path-builder.utils'; export function EditAppDialog({ - children, - projectId, - existingItem, - openAppAfterCreate = true + children, + projectId, + existingItem, + openAppAfterCreate = true }: { - children?: ReactElement<{ onClick?: (event: MouseEvent) => void }>; - projectId: string; - existingItem?: Pick; - openAppAfterCreate?: boolean; + children?: ReactElement<{ onClick?: (event: MouseEvent) => void }>; + projectId: string; + existingItem?: Pick; + openAppAfterCreate?: boolean; }) { + const router = useRouter(); + const { openInputDialog } = useInputDialog(); - const router = useRouter(); - const { openInputDialog } = useInputDialog(); - - const createAppFunc = async () => { - const name = await openInputDialog({ - title: "Create App", - description: "Name your new App.", - fieldName: "Name", - inputValue: existingItem?.name ?? '' - }) - if (!name) { return; } - const result = await Toast.fromAction(() => createApp(name, projectId, existingItem?.id)); - if (result.status === "success" && !existingItem && openAppAfterCreate) { - router.push(PathBuilderUtils.projectAppDrawer(projectId, result.data!.id, 'settings')); - } - }; + const createAppFunc = async () => { + const name = await openInputDialog({ + title: 'Create App', + description: 'Name your new App.', + fieldName: 'Name', + inputValue: existingItem?.name ?? '' + }); + if (!name) { + return; + } + const result = await Toast.fromAction(() => createApp(name, projectId, existingItem?.id)); + if (result.status === 'success' && !existingItem && openAppAfterCreate) { + router.push(PathBuilderUtils.projectAppDrawer(projectId, result.data!.id, 'settings')); + } + }; - if (!children) return null; + if (!children) { + return null; + } - return cloneElement(children, { - onClick: (event) => { - children.props.onClick?.(event); - void createAppFunc(); - }, - }); + return cloneElement(children, { + onClick: (event) => { + children.props.onClick?.(event); + void createAppFunc(); + } + }); } diff --git a/src/app/project/[projectId]/apps/details/app-details-settings.tsx b/src/app/project/[projectId]/apps/details/app-details-settings.tsx index b4334913..32b73ffc 100644 --- a/src/app/project/[projectId]/apps/details/app-details-settings.tsx +++ b/src/app/project/[projectId]/apps/details/app-details-settings.tsx @@ -1,13 +1,6 @@ 'use client'; -import { - Boxes, - Globe2, - HardDrive, - Network, - SlidersHorizontal, - Zap, -} from 'lucide-react'; +import { Boxes, Globe2, HardDrive, Network, SlidersHorizontal, Zap } from 'lucide-react'; import { useCallback, useContext, useEffect } from 'react'; import { Button } from '@/components/ui/button'; import BasicAuth from '@/app/project/[projectId]/apps/details/network/policy/basic-auth'; @@ -31,208 +24,166 @@ import { AppDrawerAppContext } from './app-drawer-app-context'; import { DrawerCard, DrawerCardDescription, DrawerCardFooter, DrawerCardHeader, DrawerCardTitle } from '@/components/custom/drawer-card'; export function DrawerSettings({ - app, - role, - storageClasses, - gitSshPublicKey, - openEnvironment = false, - onEnvironmentOpened, + app, + role, + storageClasses, + gitSshPublicKey, + openEnvironment = false, + onEnvironmentOpened }: { - app: AppExtendedModel; - role: RolePermissionEnum; - storageClasses: string[]; - gitSshPublicKey?: string; - openEnvironment?: boolean; - onEnvironmentOpened?: () => void; + app: AppExtendedModel; + role: RolePermissionEnum; + storageClasses: string[]; + gitSshPublicKey?: string; + openEnvironment?: boolean; + onEnvironmentOpened?: () => void; }) { - const readonly = role !== RolePermissionEnum.READWRITE; - const { openNestedDrawer } = useNestedDrawer(); - const openEnvironmentEditor = useCallback(() => { - openNestedDrawer({ - title: 'Environment variables', - description: <>Values are encrypted at rest and never shown. Names starting with QS_ are reserved by QuickStack., - content: , - }); - }, [app, openNestedDrawer, readonly]); + const readonly = role !== RolePermissionEnum.READWRITE; + const { openNestedDrawer } = useNestedDrawer(); + const openEnvironmentEditor = useCallback(() => { + openNestedDrawer({ + title: 'Environment variables', + description: ( + <> + Values are encrypted at rest and never shown. Names starting with QS_ are reserved by + QuickStack. + + ), + content: + }); + }, [app, openNestedDrawer, readonly]); - useEffect(() => { - if (!openEnvironment) return; - openEnvironmentEditor(); - onEnvironmentOpened?.(); - }, [onEnvironmentOpened, openEnvironment, openEnvironmentEditor]); + useEffect(() => { + if (!openEnvironment) { + return; + } + openEnvironmentEditor(); + onEnvironmentOpened?.(); + }, [onEnvironmentOpened, openEnvironment, openEnvironmentEditor]); - return ( -
-
- - - - - + return ( +
+
+ + + + + - - - Advanced Container Configuration - Configure the container command, arguments, isolation and other advanced settings. - - - - - - - - - - - - - - Network Policies - Configure network policies to control the traffic flow. - - - - - - - - Advanced Network Settings - Configure node ports and basic authentication. - - - - - - - - - - - - - - Health Checks - - Configure healthchecks so that k3s can automatically monitor when your application is fully started up and ready to receive traffic. - - - - - - - -
-
- ); + + + Advanced Container Configuration + Configure the container command, arguments, isolation and other advanced settings. + + + + + +
+ + + + + + + + Network Policies + Configure network policies to control the traffic flow. + + + + + + + + Advanced Network Settings + Configure node ports and basic authentication. + + + + + + + + + + + + + + Health Checks + + Configure healthchecks so that k3s can automatically monitor when your application is fully started up and ready to receive traffic. + + + + + + + +
+
+ ); } function AdvancedNetworkSettings({ readonly }: { readonly: boolean }) { - const app = useContext(AppDrawerAppContext); - if (!app) return null; + const app = useContext(AppDrawerAppContext); + if (!app) { + return null; + } - return
- - -
; + return ( +
+ + +
+ ); } diff --git a/src/app/project/[projectId]/apps/details/deployments/deployments.tsx b/src/app/project/[projectId]/apps/details/deployments/deployments.tsx index 30fdc19f..48dc43ad 100644 --- a/src/app/project/[projectId]/apps/details/deployments/deployments.tsx +++ b/src/app/project/[projectId]/apps/details/deployments/deployments.tsx @@ -7,103 +7,103 @@ import type { AppExtendedModel } from '@/shared/model/app-extended.model'; import type { DeploymentInfoModel } from '@/shared/model/deployment-info.model'; import { RolePermissionEnum } from '@/shared/model/role-extended.model'; import { GitHashUtils } from '@/shared/utils/git-hash.utils'; -import { - deleteBuild, - getDeploymentsAndBuildsForApp, - rollbackToDeployment, -} from './actions'; +import { deleteBuild, getDeploymentsAndBuildsForApp, rollbackToDeployment } from './actions'; import { DeploymentsGridView } from './deployments-grid-view'; export default function BuildsTab({ - app, - role, - onShowLogs, + app, + role, + onShowLogs }: { - app: AppExtendedModel; - role: RolePermissionEnum; - onShowLogs: (deployment: DeploymentInfoModel) => void; + app: AppExtendedModel; + role: RolePermissionEnum; + onShowLogs: (deployment: DeploymentInfoModel) => void; }) { - const { openConfirmDialog } = useConfirmDialog(); - const [appBuilds, setAppBuilds] = useState(); - const [, setError] = useState(); + const { openConfirmDialog } = useConfirmDialog(); + const [appBuilds, setAppBuilds] = useState(); + const [, setError] = useState(); - const updateBuilds = useCallback(async () => { - setError(undefined); - try { - const response = await getDeploymentsAndBuildsForApp(app.id); - if (response.status === 'success' && response.data) { - setAppBuilds(response.data); - } else { - console.error(response); - setError(response.message ?? 'An unknown error occurred.'); - } - } catch (error) { - console.error(error); - setError('An unknown error occurred.'); - } - }, [app.id]); + const updateBuilds = useCallback(async () => { + setError(undefined); + try { + const response = await getDeploymentsAndBuildsForApp(app.id); + if (response.status === 'success' && response.data) { + setAppBuilds(response.data); + } else { + console.error(response); + setError(response.message ?? 'An unknown error occurred.'); + } + } catch (error) { + console.error(error); + setError('An unknown error occurred.'); + } + }, [app.id]); - const stopBuild = async (deployment: DeploymentInfoModel) => { - if (!deployment.buildJobName) return; - const confirmed = await openConfirmDialog({ - title: 'Delete Build', - description: 'The build will be stopped and removed. Are you sure you want to stop this build?', - okButton: 'Stop & Remove Build', - }); - if (!confirmed) return; - await Toast.fromAction(() => deleteBuild(deployment.buildJobName!)); - await updateBuilds(); - }; + const stopBuild = async (deployment: DeploymentInfoModel) => { + if (!deployment.buildJobName) { + return; + } + const confirmed = await openConfirmDialog({ + title: 'Delete Build', + description: 'The build will be stopped and removed. Are you sure you want to stop this build?', + okButton: 'Stop & Remove Build' + }); + if (!confirmed) { + return; + } + await Toast.fromAction(() => deleteBuild(deployment.buildJobName!)); + await updateBuilds(); + }; - const rollback = async (deployment: DeploymentInfoModel) => { - const confirmed = await openConfirmDialog({ - title: 'Rollback Deployment', - description: `Roll back to git commit ${GitHashUtils.shortGitHash(deployment.gitCommit)}? The App will be redeployed with the code from this commit.`, - okButton: 'Rollback', - }); - if (!confirmed) return; - await Toast.fromAction(() => rollbackToDeployment(app.id, deployment.deploymentId)); - await updateBuilds(); - }; + const rollback = async (deployment: DeploymentInfoModel) => { + const confirmed = await openConfirmDialog({ + title: 'Rollback Deployment', + description: `Roll back to git commit ${GitHashUtils.shortGitHash(deployment.gitCommit)}? The App will be redeployed with the code from this commit.`, + okButton: 'Rollback' + }); + if (!confirmed) { + return; + } + await Toast.fromAction(() => rollbackToDeployment(app.id, deployment.deploymentId)); + await updateBuilds(); + }; - const canStopBuild = (deployment: DeploymentInfoModel) => - role === RolePermissionEnum.READWRITE - && !!deployment.buildJobName - && deployment.status === 'BUILDING'; - const canRollback = (deployment: DeploymentInfoModel) => - role === RolePermissionEnum.READWRITE - && !!deployment.replicasetName - && !!deployment.gitCommit - && deployment.status !== 'DEPLOYING' - && deployment.status !== 'DEPLOYED'; + const canStopBuild = (deployment: DeploymentInfoModel) => + role === RolePermissionEnum.READWRITE && !!deployment.buildJobName && deployment.status === 'BUILDING'; + const canRollback = (deployment: DeploymentInfoModel) => + role === RolePermissionEnum.READWRITE && + !!deployment.replicasetName && + !!deployment.gitCommit && + deployment.status !== 'DEPLOYING' && + deployment.status !== 'DEPLOYED'; - const currentBuildStatus = useBuildStatus(state => state.buildStatus.get(app.id)?.status); + const currentBuildStatus = useBuildStatus((state) => state.buildStatus.get(app.id)?.status); - useEffect(() => { - if (currentBuildStatus === undefined) { - return; - } - void updateBuilds(); - }, [currentBuildStatus, updateBuilds]); + useEffect(() => { + if (currentBuildStatus === undefined) { + return; + } + void updateBuilds(); + }, [currentBuildStatus, updateBuilds]); - usePolling(updateBuilds, { - intervalMs: 10000, - enabled: app.sourceType !== 'container', - runImmediately: true, - }); + usePolling(updateBuilds, { + intervalMs: 10000, + enabled: app.sourceType !== 'container', + runImmediately: true + }); - if (app.sourceType === 'container') return null; + if (app.sourceType === 'container') { + return null; + } - const viewProps = { - deployments: appBuilds ?? [], - canStopBuild, - canRollback, - onShowLogs, - onStopBuild: (deployment: DeploymentInfoModel) => void stopBuild(deployment), - onRollback: (deployment: DeploymentInfoModel) => void rollback(deployment), - }; + const viewProps = { + deployments: appBuilds ?? [], + canStopBuild, + canRollback, + onShowLogs, + onStopBuild: (deployment: DeploymentInfoModel) => void stopBuild(deployment), + onRollback: (deployment: DeploymentInfoModel) => void rollback(deployment) + }; - return !appBuilds - ? - : ; + return !appBuilds ? : ; } diff --git a/src/app/project/[projectId]/apps/details/network/policy/app-network-policy-rule-dialog.tsx b/src/app/project/[projectId]/apps/details/network/policy/app-network-policy-rule-dialog.tsx index aaab0239..4e3f2f34 100644 --- a/src/app/project/[projectId]/apps/details/network/policy/app-network-policy-rule-dialog.tsx +++ b/src/app/project/[projectId]/apps/details/network/policy/app-network-policy-rule-dialog.tsx @@ -11,148 +11,225 @@ import { Input } from '@/components/ui/input'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { SubmitButton } from '@/components/custom/submit-button'; import { useDialogContext } from '@/frontend/states/dialog-context'; -import { AppNetworkPolicyRuleEditModel, appNetworkPolicyRuleEditZodModel, NetworkPolicyDirection, NetworkPolicySelectableTarget, NetworkPolicyTargetProject } from '@/shared/model/app-network-policy-edit.model'; +import { + AppNetworkPolicyRuleEditModel, + appNetworkPolicyRuleEditZodModel, + NetworkPolicyDirection, + NetworkPolicySelectableTarget, + NetworkPolicyTargetProject +} from '@/shared/model/app-network-policy-edit.model'; import { Constants } from '@/shared/utils/constants'; const appNetworkPolicyRuleFormZodModel = appNetworkPolicyRuleEditZodModel.extend({ - projectId: z.string().optional(), + projectId: z.string().optional() }); type AppNetworkPolicyRuleDialogProps = { - direction: NetworkPolicyDirection; - targets: NetworkPolicySelectableTarget[]; - currentProject: NetworkPolicyTargetProject; - initialTarget?: NetworkPolicySelectableTarget; - isDuplicate: (rule: AppNetworkPolicyRuleEditModel) => boolean; - onAdd: (rule: AppNetworkPolicyRuleEditModel) => void; + direction: NetworkPolicyDirection; + targets: NetworkPolicySelectableTarget[]; + currentProject: NetworkPolicyTargetProject; + initialTarget?: NetworkPolicySelectableTarget; + isDuplicate: (rule: AppNetworkPolicyRuleEditModel) => boolean; + onAdd: (rule: AppNetworkPolicyRuleEditModel) => void; }; export default function AppNetworkPolicyRuleDialog({ direction, targets, currentProject, initialTarget, isDuplicate, onAdd }: AppNetworkPolicyRuleDialogProps) { - const { closeDialog } = useDialogContext(); - const [errorMessage, setErrorMessage] = useState(null); - const ingress = direction === 'INGRESS'; - const form = useForm, unknown, z.output>({ - resolver: zodResolver(appNetworkPolicyRuleFormZodModel), - defaultValues: { - type: direction, - projectId: initialTarget?.project.id ?? currentProject.id, - targetType: initialTarget?.type ?? 'APP', - targetId: initialTarget?.id ?? '', - port: getSuggestedPort(initialTarget) ?? '', - protocol: 'TCP', - }, - }); + const { closeDialog } = useDialogContext(); + const [errorMessage, setErrorMessage] = useState(null); + const ingress = direction === 'INGRESS'; + const form = useForm, unknown, z.output>({ + resolver: zodResolver(appNetworkPolicyRuleFormZodModel), + defaultValues: { + type: direction, + projectId: initialTarget?.project.id ?? currentProject.id, + targetType: initialTarget?.type ?? 'APP', + targetId: initialTarget?.id ?? '', + port: getSuggestedPort(initialTarget) ?? '', + protocol: 'TCP' + } + }); - const submit = (data: z.output) => { - const { projectId: _projectId, ...rule } = data; - if (isDuplicate(rule)) { - setErrorMessage('A matching network policy rule already exists.'); - return; - } - onAdd(rule); - closeDialog(); - }; + const submit = (data: z.output) => { + const { projectId: _projectId, ...rule } = data; + if (isDuplicate(rule)) { + setErrorMessage('A matching network policy rule already exists.'); + return; + } + onAdd(rule); + closeDialog(); + }; - const projects = Array.from(new Map([ - [currentProject.id, currentProject], - ...targets.map(target => [target.project.id, target.project] as const), - ]).values()); - const selectedProjectId = form.watch('projectId') ?? ''; - const targetsForSelectedProject = targets.filter(target => target.project.id === selectedProjectId); - const selectedTargetId = form.watch('targetId'); - const selectedTargetType = form.watch('targetType'); - const selectedTarget = targetsForSelectedProject.find(target => target.id === selectedTargetId && target.type === selectedTargetType); - const suggestedPort = getSuggestedPort(selectedTarget); + const projects = Array.from( + new Map([[currentProject.id, currentProject], ...targets.map((target) => [target.project.id, target.project] as const)]).values() + ); + const selectedProjectId = form.watch('projectId') ?? ''; + const targetsForSelectedProject = targets.filter((target) => target.project.id === selectedProjectId); + const selectedTargetId = form.watch('targetId'); + const selectedTargetType = form.watch('targetType'); + const selectedTarget = targetsForSelectedProject.find((target) => target.id === selectedTargetId && target.type === selectedTargetType); + const suggestedPort = getSuggestedPort(selectedTarget); - return <> - - Add {ingress ? 'ingress' : 'egress'} rule - {ingress ? 'Allow a source app or agent sandbox to access this app.' : 'Allow this app to access a target app or agent sandbox.'} - -
- - - Project - - - } - /> - - {ingress ? 'Source' : 'Target'} - - - } - /> - -
- Port - {suggestedPort !== undefined && Recommended: {suggestedPort}} -
- { - field.onChange(event); - setErrorMessage(null); - }} /> - -
} - /> - - Protocol - - - } - /> - {errorMessage &&

{errorMessage}

} -
- Add rule - + return ( + <> + + Add {ingress ? 'ingress' : 'egress'} rule + + {ingress ? 'Allow a source app or agent sandbox to access this app.' : 'Allow this app to access a target app or agent sandbox.'} + + + + + ( + + Project + + + + )} + /> + ( + + {ingress ? 'Source' : 'Target'} + + + + )} + /> + ( + +
+ Port + {suggestedPort !== undefined && ( + + Recommended: {suggestedPort} + + )}
- - - ; + + { + field.onChange(event); + setErrorMessage(null); + }} + /> + + +
+ )} + /> + ( + + Protocol + + + + )} + /> + {errorMessage &&

{errorMessage}

} +
+ Add rule + +
+ + + + ); } function getSuggestedPort(target?: NetworkPolicySelectableTarget): number | undefined { - if (!target?.appType || !(target.appType in Constants.DATABASE_TEMPLATE_PORTS)) return undefined; - return Constants.DATABASE_TEMPLATE_PORTS[target.appType as keyof typeof Constants.DATABASE_TEMPLATE_PORTS]; + if (!target?.appType || !(target.appType in Constants.DATABASE_TEMPLATE_PORTS)) { + return undefined; + } + return Constants.DATABASE_TEMPLATE_PORTS[target.appType as keyof typeof Constants.DATABASE_TEMPLATE_PORTS]; } diff --git a/src/app/project/[projectId]/apps/details/network/policy/app-network-policy-rule-section.tsx b/src/app/project/[projectId]/apps/details/network/policy/app-network-policy-rule-section.tsx index 7f8393c6..24febf72 100644 --- a/src/app/project/[projectId]/apps/details/network/policy/app-network-policy-rule-section.tsx +++ b/src/app/project/[projectId]/apps/details/network/policy/app-network-policy-rule-section.tsx @@ -16,167 +16,189 @@ import { PathBuilderUtils } from '@/shared/utils/path-builder.utils'; export type AppNetworkPolicyDirection = NetworkPolicyDirection; export type AppNetworkPolicyRuleDraft = { - key: string; - persistedId?: string; - type: AppNetworkPolicyDirection; - targetType: 'APP' | 'AGENT'; - targetId: string; - targetName: string; - targetProjectId: string; - port: number; - protocol: 'TCP' | 'UDP'; + key: string; + persistedId?: string; + type: AppNetworkPolicyDirection; + targetType: 'APP' | 'AGENT'; + targetId: string; + targetName: string; + targetProjectId: string; + port: number; + protocol: 'TCP' | 'UDP'; }; type AppNetworkPolicyRuleSectionProps = { - direction: AppNetworkPolicyDirection; - rules: AppNetworkPolicyRuleDraft[]; - readonly: boolean; - onAdd: () => void; - onDeleteRule: (key: string) => void; - currentProjectId: string; - projects: NetworkPolicyTargetProject[]; - internetAccess?: boolean; - onInternetAccessChange?: (checked: boolean) => void; - traefikAccess?: boolean; - onTraefikAccessChange?: (checked: boolean) => void; + direction: AppNetworkPolicyDirection; + rules: AppNetworkPolicyRuleDraft[]; + readonly: boolean; + onAdd: () => void; + onDeleteRule: (key: string) => void; + currentProjectId: string; + projects: NetworkPolicyTargetProject[]; + internetAccess?: boolean; + onInternetAccessChange?: (checked: boolean) => void; + traefikAccess?: boolean; + onTraefikAccessChange?: (checked: boolean) => void; }; export default function AppNetworkPolicyRuleSection({ - direction, - rules, - readonly, - onAdd, - onDeleteRule, - currentProjectId, - projects, - internetAccess, - onInternetAccessChange, - traefikAccess, - onTraefikAccessChange, + direction, + rules, + readonly, + onAdd, + onDeleteRule, + currentProjectId, + projects, + internetAccess, + onInternetAccessChange, + traefikAccess, + onTraefikAccessChange }: AppNetworkPolicyRuleSectionProps) { - const ingress = direction === 'INGRESS'; - const title = ingress ? 'Ingress rules' : 'Egress rules'; - const description = ingress ? 'Who can access this app?' : 'Which apps or agent sandboxes can this app access?'; + const ingress = direction === 'INGRESS'; + const title = ingress ? 'Ingress rules' : 'Egress rules'; + const description = ingress ? 'Who can access this app?' : 'Which apps or agent sandboxes can this app access?'; - return ( -
- - -
-
- {ingress ? : } -
-
-

{title}

-

{description}

-
-
+ return ( +
+ + +
+
+ {ingress ? : } +
+
+

{title}

+

{description}

+
+
- {!ingress && internetAccess !== undefined && onInternetAccessChange && ( - - -
- -

Allow outgoing connections to the public internet.

-
- -
-
- )} + {!ingress && internetAccess !== undefined && onInternetAccessChange && ( + + +
+ +

Allow outgoing connections to the public internet.

+
+ +
+
+ )} - {!ingress && traefikAccess !== undefined && onTraefikAccessChange && ( - - -
- -

Allow outgoing connections to apps and agents exposed through this cluster's Traefik ingress.

-
- -
-
- )} + {!ingress && traefikAccess !== undefined && onTraefikAccessChange && ( + + +
+ +

+ Allow outgoing connections to apps and agents exposed through this cluster's Traefik ingress. +

+
+ +
+
+ )} - - - - {ingress ? 'Source' : 'Target'} - Port - Protocol - Actions - - - - {rules.length > 0 ? rules.map(rule => ) : ( - - No rules configured. - - )} - -
+ + + + {ingress ? 'Source' : 'Target'} + Port + Protocol + + Actions + + + + + {rules.length > 0 ? ( + rules.map((rule) => ( + + )) + ) : ( + + + No rules configured. + + + )} + +
- {!readonly && } -
-
-
- ); + {!readonly && ( + + )} +
+
+
+ ); } -function RuleRow({ rule, readonly, onDelete, currentProjectId, projects }: { - rule: AppNetworkPolicyRuleDraft; - readonly: boolean; - onDelete: (key: string) => void; - currentProjectId: string; - projects: NetworkPolicyTargetProject[]; +function RuleRow({ + rule, + readonly, + onDelete, + currentProjectId, + projects +}: { + rule: AppNetworkPolicyRuleDraft; + readonly: boolean; + onDelete: (key: string) => void; + currentProjectId: string; + projects: NetworkPolicyTargetProject[]; }) { - const projectName = rule.targetProjectId === currentProjectId - ? 'This project' - : projects.find(project => project.id === rule.targetProjectId)?.name ?? 'Unknown project'; - const targetTypeLabel = rule.targetType === 'AGENT' ? 'Agent sandbox' : 'App'; - const copyInternalHostname = () => { - if (rule.targetType !== 'APP') return; - navigator.clipboard.writeText(InternalHostnameUtils.getInternalBaseUrlForApp({ id: rule.targetId, projectId: rule.targetProjectId }, rule.port)); - toast.success('Copied internal hostname to clipboard'); - }; - - return ( - - + const projectName = + rule.targetProjectId === currentProjectId ? 'This project' : (projects.find((project) => project.id === rule.targetProjectId)?.name ?? 'Unknown project'); + const targetTypeLabel = rule.targetType === 'AGENT' ? 'Agent sandbox' : 'App'; + const copyInternalHostname = () => { + if (rule.targetType !== 'APP') { + return; + } + navigator.clipboard.writeText(InternalHostnameUtils.getInternalBaseUrlForApp({ id: rule.targetId, projectId: rule.targetProjectId }, rule.port)); + toast.success('Copied internal hostname to clipboard'); + }; - {rule.targetType === 'APP' - ? {rule.targetName} - : rule.targetName} - - {projectName} · {targetTypeLabel} - - - {rule.port} - {rule.protocol} - - {!readonly && ( - - - - Rule actions - } /> - - {rule.targetType === 'APP' && - Copy internal hostname - } - onDelete(rule.key)}> - Delete - - - - )} - - - ); + return ( + + + {rule.targetType === 'APP' ? ( + + {rule.targetName} + + ) : ( + rule.targetName + )} + + {projectName} · {targetTypeLabel} + + + {rule.port} + {rule.protocol} + + {!readonly && ( + + + + Rule actions + + } + /> + + {rule.targetType === 'APP' && ( + + Copy internal hostname + + )} + onDelete(rule.key)}> + Delete + + + + )} + + + ); } diff --git a/src/app/project/[projectId]/apps/details/network/policy/network-policy-graph.tsx b/src/app/project/[projectId]/apps/details/network/policy/network-policy-graph.tsx index 2208963a..33d61177 100644 --- a/src/app/project/[projectId]/apps/details/network/policy/network-policy-graph.tsx +++ b/src/app/project/[projectId]/apps/details/network/policy/network-policy-graph.tsx @@ -3,17 +3,17 @@ import { useMemo, type CSSProperties } from 'react'; import { useRouter } from 'next/navigation'; import { - Background, - BackgroundVariant, - Controls, - Handle, - MarkerType, - Position, - ReactFlow, - type Edge, - type Node, - type NodeProps, - type NodeTypes, + Background, + BackgroundVariant, + Controls, + Handle, + MarkerType, + Position, + ReactFlow, + type Edge, + type Node, + type NodeProps, + type NodeTypes } from '@xyflow/react'; import '@xyflow/react/dist/style.css'; import { Bot, Boxes, Cloud, MoveRight } from 'lucide-react'; @@ -25,12 +25,12 @@ import { PathBuilderUtils } from '@/shared/utils/path-builder.utils'; type WorkloadType = 'APP' | 'AGENT'; type Neighbor = { - type: WorkloadType; - id: string; - name: string; - projectId: string; - ingress: string[]; - egress: string[]; + type: WorkloadType; + id: string; + name: string; + projectId: string; + ingress: string[]; + egress: string[]; }; const CENTER_WIDTH = 224; @@ -41,344 +41,390 @@ const COLUMN_X_RIGHT = 360; const INTERNET_Y = -320; const EDGE_COLORS = { - ingress: '#10b981', - egress: '#0ea5e9', - internet: '#8b5cf6', + ingress: '#10b981', + egress: '#0ea5e9', + internet: '#8b5cf6' } as const; const handleClassName = 'h-1.5! w-1.5! border-0! bg-transparent! opacity-0!'; function formatRuleLabel(port: number, protocol: string) { - return `${port}/${protocol.toUpperCase()}`; + return `${port}/${protocol.toUpperCase()}`; } function aggregateLabels(labels: string[]) { - return Array.from(new Set(labels)).sort((a, b) => { - const portA = parseInt(a, 10); - const portB = parseInt(b, 10); - if (!Number.isNaN(portA) && !Number.isNaN(portB)) return portA - portB; - return a.localeCompare(b); - }).join(' · '); + return Array.from(new Set(labels)) + .sort((a, b) => { + const portA = parseInt(a, 10); + const portB = parseInt(b, 10); + if (!Number.isNaN(portA) && !Number.isNaN(portB)) { + return portA - portB; + } + return a.localeCompare(b); + }) + .join(' · '); } function collectNeighbors(rules: AppNetworkPolicyRuleWithTargetAppModel[], appId: string) { - const map = new Map(); - for (const rule of rules) { - const target = rule.targetAgent ?? rule.targetApp; - if (!target) continue; - if (rule.targetAppId === appId || rule.targetAgentId === appId) continue; - const type: WorkloadType = rule.targetApp ? 'APP' : 'AGENT'; - const key = `${type}:${target.id}`; - let neighbor = map.get(key); - if (!neighbor) { - neighbor = { type, id: target.id, name: target.name, projectId: target.projectId, ingress: [], egress: [] }; - map.set(key, neighbor); - } - const label = formatRuleLabel(rule.port, rule.protocol); - if (rule.type === 'INGRESS') neighbor.ingress.push(label); - else if (rule.type === 'EGRESS') neighbor.egress.push(label); + const map = new Map(); + for (const rule of rules) { + const target = rule.targetAgent ?? rule.targetApp; + if (!target) { + continue; + } + if (rule.targetAppId === appId || rule.targetAgentId === appId) { + continue; + } + const type: WorkloadType = rule.targetApp ? 'APP' : 'AGENT'; + const key = `${type}:${target.id}`; + let neighbor = map.get(key); + if (!neighbor) { + neighbor = { type, id: target.id, name: target.name, projectId: target.projectId, ingress: [], egress: [] }; + map.set(key, neighbor); + } + const label = formatRuleLabel(rule.port, rule.protocol); + if (rule.type === 'INGRESS') { + neighbor.ingress.push(label); + } else if (rule.type === 'EGRESS') { + neighbor.egress.push(label); } - return Array.from(map.values()).map(neighbor => ({ - ...neighbor, - ingress: aggregateLabels(neighbor.ingress).split(' · ').filter(Boolean), - egress: aggregateLabels(neighbor.egress).split(' · ').filter(Boolean), - })); + } + return Array.from(map.values()).map((neighbor) => ({ + ...neighbor, + ingress: aggregateLabels(neighbor.ingress).split(' · ').filter(Boolean), + egress: aggregateLabels(neighbor.egress).split(' · ').filter(Boolean) + })); } type PeerNodeData = { - type: WorkloadType; - projectId: string; - name: string; - side: 'left' | 'right'; - both: boolean; - externalProject: boolean; - caption?: string; + type: WorkloadType; + projectId: string; + name: string; + side: 'left' | 'right'; + both: boolean; + externalProject: boolean; + caption?: string; }; type CenterNodeData = { - name: string; + name: string; }; type InternetNodeData = Record; const CenterNode = ({ data }: NodeProps>) => ( -
- This app -
- -
-

{data.name}

- - - - - +
+ This app +
+
+

+ {data.name} +

+ + + + + +
); const PeerNode = ({ data }: NodeProps>) => { - const AgentIcon = data.type === 'AGENT' ? Bot : Boxes; - const iconClasses = data.type === 'AGENT' - ? 'bg-violet-500/15 text-violet-600 ring-violet-500/30' - : 'bg-qs-500/10 text-qs-600 ring-qs-500/30'; - return ( -
-
- -
-
-

{data.name}

- {data.caption &&

{data.caption}

} -
- {data.side === 'left' && } - {data.side === 'right' && ( - <> - - {data.both && } - - )} -
- ); + const AgentIcon = data.type === 'AGENT' ? Bot : Boxes; + const iconClasses = data.type === 'AGENT' ? 'bg-violet-500/15 text-violet-600 ring-violet-500/30' : 'bg-qs-500/10 text-qs-600 ring-qs-500/30'; + return ( +
+
+ +
+
+

+ {data.name} +

+ {data.caption &&

{data.caption}

} +
+ {data.side === 'left' && } + {data.side === 'right' && ( + <> + + {data.both && } + + )} +
+ ); }; const InternetNode = () => ( -
-
- -
- Internet - - +
+
+
+ Internet + + +
); const nodeTypes = { peer: PeerNode, center: CenterNode, internet: InternetNode } satisfies NodeTypes; function getLegendItem(label: string, children: React.ReactNode) { - return ( - - {children} - {label} - - ); + return ( + + {children} + {label} + + ); } function Legend() { - return ( -
- {getLegendItem('Ingress rule', )} - {getLegendItem('Egress rule', )} - {getLegendItem('Internet access', )} - {getLegendItem('Other project', )} - {getLegendItem('App', )} - {getLegendItem('Agent sandbox', )} - Arrows point in the direction of allowed traffic -
- ); + return ( +
+ {getLegendItem('Ingress rule', )} + {getLegendItem('Egress rule', )} + {getLegendItem('Internet access', )} + {getLegendItem('Other project', )} + {getLegendItem('App', )} + {getLegendItem('Agent sandbox', )} + + + Arrows point in the direction of allowed traffic + +
+ ); } function edgeLabelStyle() { - return { - labelStyle: { fill: 'var(--muted-foreground)', fontSize: 10, fontWeight: 600 }, - labelBgStyle: { fill: 'var(--card)', fillOpacity: 0.9, stroke: 'var(--border)', strokeWidth: 1 }, - labelBgPadding: [6, 3] as [number, number], - labelBgBorderRadius: 6, - }; + return { + labelStyle: { fill: 'var(--muted-foreground)', fontSize: 10, fontWeight: 600 }, + labelBgStyle: { fill: 'var(--card)', fillOpacity: 0.9, stroke: 'var(--border)', strokeWidth: 1 }, + labelBgPadding: [6, 3] as [number, number], + labelBgBorderRadius: 6 + }; } export default function NetworkPolicyGraph({ - appId, - appName, - appProjectId, - rules, - allowInternetAccess, - domainLabels, - projects, + appId, + appName, + appProjectId, + rules, + allowInternetAccess, + domainLabels, + projects }: { - appId: string; - appName: string; - appProjectId: string; - rules: AppNetworkPolicyRuleWithTargetAppModel[]; - allowInternetAccess: boolean; - domainLabels: string[]; - projects: NetworkPolicyTargetProject[]; + appId: string; + appName: string; + appProjectId: string; + rules: AppNetworkPolicyRuleWithTargetAppModel[]; + allowInternetAccess: boolean; + domainLabels: string[]; + projects: NetworkPolicyTargetProject[]; }) { - const router = useRouter(); - - const projectNameById = useMemo(() => { - const map = new Map(); - for (const project of projects) map.set(project.id, project.name); - return map; - }, [projects]); - - const { nodes, edges, hasContent } = useMemo(() => { - const neighbors = collectNeighbors(rules, appId); - const ingressOnly = neighbors.filter(neighbor => neighbor.ingress.length > 0 && neighbor.egress.length === 0); - const egressOnly = neighbors.filter(neighbor => neighbor.egress.length > 0 && neighbor.ingress.length === 0); - const both = neighbors.filter(neighbor => neighbor.ingress.length > 0 && neighbor.egress.length > 0); - const leftPeers = [...ingressOnly].sort((a, b) => a.name.localeCompare(b.name)); - const rightPeers = [...egressOnly, ...both].sort((a, b) => a.name.localeCompare(b.name)); - - const hasDomains = domainLabels.length > 0; - const hasContent = neighbors.length > 0 || allowInternetAccess || hasDomains; - - const nodes: (Node | Node | Node)[] = []; - const edges: Edge[] = []; - - nodes.push({ - id: 'center', - type: 'center', - position: { x: -CENTER_WIDTH / 2, y: -60 }, - data: { name: appName }, - }); - - const captionFor = (neighbor: Neighbor) => { - const parts: string[] = []; - if (neighbor.type === 'AGENT') parts.push('Agent sandbox'); - if (neighbor.projectId !== appProjectId) parts.push(projectNameById.get(neighbor.projectId) ?? 'Other project'); - return parts.join(' · '); - }; - - const yForIndex = (index: number, count: number) => (index - (count - 1) / 2) * ROW_SPACING; - - leftPeers.forEach((neighbor, index) => { - const y = yForIndex(index, leftPeers.length); - nodes.push({ - id: `${neighbor.type}:${neighbor.id}`, - type: 'peer', - position: { x: COLUMN_X_LEFT - PEER_WIDTH / 2, y: y - 28 }, - data: { type: neighbor.type, projectId: neighbor.projectId, name: neighbor.name, side: 'left', both: false, externalProject: neighbor.projectId !== appProjectId, caption: captionFor(neighbor) }, - }); - edges.push({ - ...edgeLabelStyle(), - id: `edge-ingress-${neighbor.type}-${neighbor.id}`, - source: `${neighbor.type}:${neighbor.id}`, - target: 'center', - sourceHandle: 'source', - targetHandle: 'in-left', - label: aggregateLabels(neighbor.ingress), - markerEnd: { type: MarkerType.ArrowClosed, color: EDGE_COLORS.ingress, width: 16, height: 16 }, - style: { stroke: EDGE_COLORS.ingress, strokeWidth: 1.5 }, - }); - }); + const router = useRouter(); - rightPeers.forEach((neighbor, index) => { - const y = yForIndex(index, rightPeers.length); - const hasIngress = neighbor.ingress.length > 0; - nodes.push({ - id: `${neighbor.type}:${neighbor.id}`, - type: 'peer', - position: { x: COLUMN_X_RIGHT - PEER_WIDTH / 2, y: y - 28 }, - data: { type: neighbor.type, projectId: neighbor.projectId, name: neighbor.name, side: 'right', both: hasIngress, externalProject: neighbor.projectId !== appProjectId, caption: captionFor(neighbor) }, - }); - edges.push({ - ...edgeLabelStyle(), - id: `edge-egress-${neighbor.type}-${neighbor.id}`, - source: 'center', - target: `${neighbor.type}:${neighbor.id}`, - sourceHandle: 'out-right', - targetHandle: 'egress-in', - label: aggregateLabels(neighbor.egress), - markerEnd: { type: MarkerType.ArrowClosed, color: EDGE_COLORS.egress, width: 16, height: 16 }, - style: { stroke: EDGE_COLORS.egress, strokeWidth: 1.5 }, - }); - if (hasIngress) { - edges.push({ - ...edgeLabelStyle(), - id: `edge-ingress-reverse-${neighbor.type}-${neighbor.id}`, - source: `${neighbor.type}:${neighbor.id}`, - target: 'center', - sourceHandle: 'ingress-out', - targetHandle: 'in-right', - label: aggregateLabels(neighbor.ingress), - markerEnd: { type: MarkerType.ArrowClosed, color: EDGE_COLORS.ingress, width: 16, height: 16 }, - style: { stroke: EDGE_COLORS.ingress, strokeWidth: 1.5 }, - }); - } - }); + const projectNameById = useMemo(() => { + const map = new Map(); + for (const project of projects) { + map.set(project.id, project.name); + } + return map; + }, [projects]); + + const { nodes, edges, hasContent } = useMemo(() => { + const neighbors = collectNeighbors(rules, appId); + const ingressOnly = neighbors.filter((neighbor) => neighbor.ingress.length > 0 && neighbor.egress.length === 0); + const egressOnly = neighbors.filter((neighbor) => neighbor.egress.length > 0 && neighbor.ingress.length === 0); + const both = neighbors.filter((neighbor) => neighbor.ingress.length > 0 && neighbor.egress.length > 0); + const leftPeers = [...ingressOnly].sort((a, b) => a.name.localeCompare(b.name)); + const rightPeers = [...egressOnly, ...both].sort((a, b) => a.name.localeCompare(b.name)); + + const hasDomains = domainLabels.length > 0; + const hasContent = neighbors.length > 0 || allowInternetAccess || hasDomains; + + const nodes: (Node | Node | Node)[] = []; + const edges: Edge[] = []; + + nodes.push({ + id: 'center', + type: 'center', + position: { x: -CENTER_WIDTH / 2, y: -60 }, + data: { name: appName } + }); + + const captionFor = (neighbor: Neighbor) => { + const parts: string[] = []; + if (neighbor.type === 'AGENT') { + parts.push('Agent sandbox'); + } + if (neighbor.projectId !== appProjectId) { + parts.push(projectNameById.get(neighbor.projectId) ?? 'Other project'); + } + return parts.join(' · '); + }; - if (allowInternetAccess || hasDomains) { - nodes.push({ - id: 'internet', - type: 'internet', - position: { x: -48, y: INTERNET_Y - 48 }, - data: {}, - }); - if (allowInternetAccess) { - edges.push({ - id: 'edge-internet-egress', - source: 'center', - target: 'internet', - sourceHandle: 'out-internet', - targetHandle: 'target', - markerEnd: { type: MarkerType.ArrowClosed, color: EDGE_COLORS.internet, width: 16, height: 16 }, - style: { stroke: EDGE_COLORS.internet, strokeWidth: 1.5, strokeDasharray: '5 4' }, - }); - } - if (hasDomains) { - edges.push({ - id: 'edge-internet-ingress', - source: 'internet', - target: 'center', - sourceHandle: 'source', - targetHandle: 'in-internet', - label: aggregateLabels(domainLabels), - markerEnd: { type: MarkerType.ArrowClosed, color: EDGE_COLORS.ingress, width: 16, height: 16 }, - style: { stroke: EDGE_COLORS.ingress, strokeWidth: 1.5 }, - }); - } + const yForIndex = (index: number, count: number) => (index - (count - 1) / 2) * ROW_SPACING; + + leftPeers.forEach((neighbor, index) => { + const y = yForIndex(index, leftPeers.length); + nodes.push({ + id: `${neighbor.type}:${neighbor.id}`, + type: 'peer', + position: { x: COLUMN_X_LEFT - PEER_WIDTH / 2, y: y - 28 }, + data: { + type: neighbor.type, + projectId: neighbor.projectId, + name: neighbor.name, + side: 'left', + both: false, + externalProject: neighbor.projectId !== appProjectId, + caption: captionFor(neighbor) } - - return { nodes, edges, hasContent }; - }, [allowInternetAccess, appId, appName, appProjectId, domainLabels, projectNameById, rules]); - - if (!hasContent) { - return ( -
- -

No connections yet. Network policy rules will be visualized here.

-
- ); + }); + edges.push({ + ...edgeLabelStyle(), + id: `edge-ingress-${neighbor.type}-${neighbor.id}`, + source: `${neighbor.type}:${neighbor.id}`, + target: 'center', + sourceHandle: 'source', + targetHandle: 'in-left', + label: aggregateLabels(neighbor.ingress), + markerEnd: { type: MarkerType.ArrowClosed, color: EDGE_COLORS.ingress, width: 16, height: 16 }, + style: { stroke: EDGE_COLORS.ingress, strokeWidth: 1.5 } + }); + }); + + rightPeers.forEach((neighbor, index) => { + const y = yForIndex(index, rightPeers.length); + const hasIngress = neighbor.ingress.length > 0; + nodes.push({ + id: `${neighbor.type}:${neighbor.id}`, + type: 'peer', + position: { x: COLUMN_X_RIGHT - PEER_WIDTH / 2, y: y - 28 }, + data: { + type: neighbor.type, + projectId: neighbor.projectId, + name: neighbor.name, + side: 'right', + both: hasIngress, + externalProject: neighbor.projectId !== appProjectId, + caption: captionFor(neighbor) + } + }); + edges.push({ + ...edgeLabelStyle(), + id: `edge-egress-${neighbor.type}-${neighbor.id}`, + source: 'center', + target: `${neighbor.type}:${neighbor.id}`, + sourceHandle: 'out-right', + targetHandle: 'egress-in', + label: aggregateLabels(neighbor.egress), + markerEnd: { type: MarkerType.ArrowClosed, color: EDGE_COLORS.egress, width: 16, height: 16 }, + style: { stroke: EDGE_COLORS.egress, strokeWidth: 1.5 } + }); + if (hasIngress) { + edges.push({ + ...edgeLabelStyle(), + id: `edge-ingress-reverse-${neighbor.type}-${neighbor.id}`, + source: `${neighbor.type}:${neighbor.id}`, + target: 'center', + sourceHandle: 'ingress-out', + targetHandle: 'in-right', + label: aggregateLabels(neighbor.ingress), + markerEnd: { type: MarkerType.ArrowClosed, color: EDGE_COLORS.ingress, width: 16, height: 16 }, + style: { stroke: EDGE_COLORS.ingress, strokeWidth: 1.5 } + }); + } + }); + + if (allowInternetAccess || hasDomains) { + nodes.push({ + id: 'internet', + type: 'internet', + position: { x: -48, y: INTERNET_Y - 48 }, + data: {} + }); + if (allowInternetAccess) { + edges.push({ + id: 'edge-internet-egress', + source: 'center', + target: 'internet', + sourceHandle: 'out-internet', + targetHandle: 'target', + markerEnd: { type: MarkerType.ArrowClosed, color: EDGE_COLORS.internet, width: 16, height: 16 }, + style: { stroke: EDGE_COLORS.internet, strokeWidth: 1.5, strokeDasharray: '5 4' } + }); + } + if (hasDomains) { + edges.push({ + id: 'edge-internet-ingress', + source: 'internet', + target: 'center', + sourceHandle: 'source', + targetHandle: 'in-internet', + label: aggregateLabels(domainLabels), + markerEnd: { type: MarkerType.ArrowClosed, color: EDGE_COLORS.ingress, width: 16, height: 16 }, + style: { stroke: EDGE_COLORS.ingress, strokeWidth: 1.5 } + }); + } } + return { nodes, edges, hasContent }; + }, [allowInternetAccess, appId, appName, appProjectId, domainLabels, projectNameById, rules]); + + if (!hasContent) { return ( -
-
- { - if (node.type !== 'peer') return; - const [workloadType, workloadId] = String(node.id).split(':'); - const peer = node.data as PeerNodeData; - router.push(workloadType === 'AGENT' - ? PathBuilderUtils.projectAgentDrawer(peer.projectId, workloadId) - : PathBuilderUtils.projectAppDrawer(peer.projectId, workloadId)); - }} - > - - - -
- -
+
+ +

No connections yet. Network policy rules will be visualized here.

+
); + } + + return ( +
+
+ { + if (node.type !== 'peer') { + return; + } + const [workloadType, workloadId] = String(node.id).split(':'); + const peer = node.data as PeerNodeData; + router.push( + workloadType === 'AGENT' + ? PathBuilderUtils.projectAgentDrawer(peer.projectId, workloadId) + : PathBuilderUtils.projectAppDrawer(peer.projectId, workloadId) + ); + }} + > + + + +
+ +
+ ); } diff --git a/src/app/project/[projectId]/apps/details/source/app-source-wizard/app-source-wizard-dialog.tsx b/src/app/project/[projectId]/apps/details/source/app-source-wizard/app-source-wizard-dialog.tsx index 13262228..0bcb6741 100644 --- a/src/app/project/[projectId]/apps/details/source/app-source-wizard/app-source-wizard-dialog.tsx +++ b/src/app/project/[projectId]/apps/details/source/app-source-wizard/app-source-wizard-dialog.tsx @@ -1,508 +1,529 @@ 'use client'; -import { Button } from "@/components/ui/button"; -import { DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; -import { useDialogContext } from "@/frontend/states/dialog-context"; -import { useConfirmDialog } from "@/frontend/states/zustand.states"; -import { Actions } from "@/frontend/utils/nextjs-actions.utils"; -import { Toast } from "@/frontend/utils/toast.utils"; -import { AppExtendedModel } from "@/shared/model/app-extended.model"; -import { AppBuildMethod, AppDockerfileDetectionModel, AppGitBranchesLookupModel, AppSourceInfoInputModel } from "@/shared/model/app-source-info.model"; -import { JsFramework, jsFrameworkPresets, jsFrameworkZodModel } from "@/shared/model/js-framework.model"; -import { ChevronLeft, Loader2, Rocket, Save } from "lucide-react"; -import { useRouter } from "next/navigation"; -import { useEffect, useState } from "react"; -import { toast } from "sonner"; -import { detectDockerfilePath, ensureGitSshPublicKey, generateOrRegenerateGitSshKey, getGitBranches, saveGeneralAppSourceInfo } from "../../configuration/actions"; -import { BuildMethodStep } from "../../configuration/app-source-wizard/build-method-step"; -import { ContainerImageStep } from "../../../../../workload-components/source-wizard/container-image-step"; -import { DockerfilePathStep } from "../../../../../workload-components/source-wizard/dockerfile-path-step"; -import { FrameworkConfigurationStep } from "./framework-configuration-step"; -import { FrameworkStep } from "./framework-step"; -import { GitBranchStep } from "../../../../../workload-components/source-wizard/git-branch-step"; -import { GitHttpsUrlStep } from "../../../../../workload-components/source-wizard/git-https-url-step"; -import { GitSshUrlStep } from "../../../../../workload-components/source-wizard/git-ssh-url-step"; -import { SourceSummaryStep } from "../../../../../workload-components/source-wizard/source-summary-step"; -import { SourceTypeStep } from "../../../../../workload-components/source-wizard/source-type-step"; -import { defaultDockerfilePath, sourceTypeLabels, SourceType, StepId } from "../../../../../workload-components/source-wizard/types"; -import { WizardProgress } from "../../../../../workload-components/source-wizard/wizard-progress"; -import { deploy } from "../../actions"; -import LoadingSpinner from "@/components/ui/loading-spinner"; - -export function AppSourceWizardDialog({ app, gitSshPublicKey }: { - app: AppExtendedModel; - gitSshPublicKey?: string; -}) { - const router = useRouter(); - const { closeDialog } = useDialogContext(); - const { openConfirmDialog } = useConfirmDialog(); - const [step, setStep] = useState('source'); - const [history, setHistory] = useState([]); - const [formData, setFormData] = useState(() => toSourceInput(app)); - const [publicKey, setPublicKey] = useState(gitSshPublicKey); - const [branches, setBranches] = useState([]); - const [isLoadingBranches, setIsLoadingBranches] = useState(false); - const [branchError, setBranchError] = useState(null); - const [isEnsuringKey, setIsEnsuringKey] = useState(false); - const [isDetectingDockerfile, setIsDetectingDockerfile] = useState(false); - const [dockerfileDetectionResult, setDockerfileDetectionResult] = useState<'detected' | 'not-found' | null>(null); - const [showGitToken, setShowGitToken] = useState(false); - const [showRegistryPassword, setShowRegistryPassword] = useState(false); - const [showButtonLoading, setShowButtonLoading] = useState(false); - - const canUseGitSources = app.appType === 'APP'; - const isGitSource = formData.sourceType === 'GIT' || formData.sourceType === 'GIT_SSH'; - const showGitCredentials = formData.sourceType === 'GIT' && !!formData.gitUrl?.trim(); - const showRegistryCredentials = formData.sourceType === 'CONTAINER' && !!formData.containerImageSource?.trim(); - const currentTitle = getStepTitle(step, formData.sourceType); - - const goTo = (nextStep: StepId) => { - setHistory((items) => [...items, step]); - setStep(nextStep); - }; - - const goBack = () => { - const previous = history[history.length - 1]; - if (!previous) { - return; - } - setHistory((items) => items.slice(0, -1)); - setStep(previous); - }; - - const updateFormData = (patch: Partial) => { - setFormData((current) => ({ ...current, ...patch })); - }; - - const chooseSourceType = (sourceType: SourceType) => { - setBranches([]); - setBranchError(null); - setDockerfileDetectionResult(null); - setFormData((current) => resetForSourceType(current, sourceType)); - }; - - const loadBranches = async () => { - if (!formData.gitUrl?.trim()) { - setBranchError('Enter a Git repository URL first.'); - return false; - } - - const inputData: AppGitBranchesLookupModel = formData.sourceType === 'GIT' - ? { - sourceType: 'GIT', - gitUrl: formData.gitUrl, - gitUsername: formData.gitUsername, - gitToken: formData.gitToken, - } - : { - sourceType: 'GIT_SSH', - gitUrl: formData.gitUrl, - }; - - setIsLoadingBranches(true); - setBranchError(null); - try { - const result = await Actions.run(() => getGitBranches(app.id, inputData)); - setBranches(result ?? []); - if (formData.gitBranch && !result?.includes(formData.gitBranch)) { - updateFormData({ gitBranch: '' }); - } - return true; - } catch (error) { - setBranches([]); - setBranchError(error instanceof Error ? error.message : 'Branches could not be loaded.'); - return false; - } finally { - setIsLoadingBranches(false); - } - }; - - const ensureSshKey = async () => { - if (publicKey || isEnsuringKey) { - return; - } - setIsEnsuringKey(true); - try { - const key = await Actions.run(() => ensureGitSshPublicKey(app.id)); - setPublicKey(key); - } finally { - setIsEnsuringKey(false); - } - }; - - useEffect(() => { - if (step === 'ssh-url') { - ensureSshKey(); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [step, formData.gitUrl, publicKey]); - - const regenerateKey = async () => { - const confirmed = await openConfirmDialog({ - title: "Regenerate Deploy Key", - description: "This replaces the current app SSH key. Update the deploy key in your Git provider before deploying again.", - okButton: "Regenerate", - }); - if (!confirmed) { - return; - } - const key = await Actions.run(() => generateOrRegenerateGitSshKey(app.id)); - setPublicKey(key); - toast.success('Deploy key regenerated.'); - }; - - const copyPublicKey = () => { - if (!publicKey) { - return; - } - navigator.clipboard.writeText(publicKey); - toast.success('Copied to clipboard.'); - }; - - const runDockerfileDetection = async () => { - if (!isGitSource || !formData.gitUrl || !formData.gitBranch) { - return; - } - - const inputData: AppDockerfileDetectionModel = formData.sourceType === 'GIT' - ? { - sourceType: 'GIT', - gitUrl: formData.gitUrl, - gitBranch: formData.gitBranch, - gitUsername: formData.gitUsername, - gitToken: formData.gitToken, - } - : { - sourceType: 'GIT_SSH', - gitUrl: formData.gitUrl, - gitBranch: formData.gitBranch, - }; - - setIsDetectingDockerfile(true); - try { - const dockerfilePath = await Actions.run(() => detectDockerfilePath(app.id, inputData)); - updateFormData({ dockerfilePath: dockerfilePath || defaultDockerfilePath }); - setDockerfileDetectionResult(dockerfilePath ? 'detected' : 'not-found'); - } finally { - setIsDetectingDockerfile(false); - } - }; - - const selectGitBranch = (gitBranch: string) => { - updateFormData({ gitBranch }); - setDockerfileDetectionResult(null); - goTo('build-method'); - }; +import { Button } from '@/components/ui/button'; +import { DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { useDialogContext } from '@/frontend/states/dialog-context'; +import { useConfirmDialog } from '@/frontend/states/zustand.states'; +import { Actions } from '@/frontend/utils/nextjs-actions.utils'; +import { Toast } from '@/frontend/utils/toast.utils'; +import { AppExtendedModel } from '@/shared/model/app-extended.model'; +import { AppBuildMethod, AppDockerfileDetectionModel, AppGitBranchesLookupModel, AppSourceInfoInputModel } from '@/shared/model/app-source-info.model'; +import { JsFramework, jsFrameworkPresets, jsFrameworkZodModel } from '@/shared/model/js-framework.model'; +import { ChevronLeft, Loader2, Rocket, Save } from 'lucide-react'; +import { useRouter } from 'next/navigation'; +import { useEffect, useState } from 'react'; +import { toast } from 'sonner'; +import { + detectDockerfilePath, + ensureGitSshPublicKey, + generateOrRegenerateGitSshKey, + getGitBranches, + saveGeneralAppSourceInfo +} from '../../configuration/actions'; +import { BuildMethodStep } from '../../configuration/app-source-wizard/build-method-step'; +import { ContainerImageStep } from '../../../../../workload-components/source-wizard/container-image-step'; +import { DockerfilePathStep } from '../../../../../workload-components/source-wizard/dockerfile-path-step'; +import { FrameworkConfigurationStep } from './framework-configuration-step'; +import { FrameworkStep } from './framework-step'; +import { GitBranchStep } from '../../../../../workload-components/source-wizard/git-branch-step'; +import { GitHttpsUrlStep } from '../../../../../workload-components/source-wizard/git-https-url-step'; +import { GitSshUrlStep } from '../../../../../workload-components/source-wizard/git-ssh-url-step'; +import { SourceSummaryStep } from '../../../../../workload-components/source-wizard/source-summary-step'; +import { SourceTypeStep } from '../../../../../workload-components/source-wizard/source-type-step'; +import { defaultDockerfilePath, sourceTypeLabels, SourceType, StepId } from '../../../../../workload-components/source-wizard/types'; +import { WizardProgress } from '../../../../../workload-components/source-wizard/wizard-progress'; +import { deploy } from '../../actions'; +import LoadingSpinner from '@/components/ui/loading-spinner'; + +export function AppSourceWizardDialog({ app, gitSshPublicKey }: { app: AppExtendedModel; gitSshPublicKey?: string }) { + const router = useRouter(); + const { closeDialog } = useDialogContext(); + const { openConfirmDialog } = useConfirmDialog(); + const [step, setStep] = useState('source'); + const [history, setHistory] = useState([]); + const [formData, setFormData] = useState(() => toSourceInput(app)); + const [publicKey, setPublicKey] = useState(gitSshPublicKey); + const [branches, setBranches] = useState([]); + const [isLoadingBranches, setIsLoadingBranches] = useState(false); + const [branchError, setBranchError] = useState(null); + const [isEnsuringKey, setIsEnsuringKey] = useState(false); + const [isDetectingDockerfile, setIsDetectingDockerfile] = useState(false); + const [dockerfileDetectionResult, setDockerfileDetectionResult] = useState<'detected' | 'not-found' | null>(null); + const [showGitToken, setShowGitToken] = useState(false); + const [showRegistryPassword, setShowRegistryPassword] = useState(false); + const [showButtonLoading, setShowButtonLoading] = useState(false); + + const canUseGitSources = app.appType === 'APP'; + const isGitSource = formData.sourceType === 'GIT' || formData.sourceType === 'GIT_SSH'; + const showGitCredentials = formData.sourceType === 'GIT' && !!formData.gitUrl?.trim(); + const showRegistryCredentials = formData.sourceType === 'CONTAINER' && !!formData.containerImageSource?.trim(); + const currentTitle = getStepTitle(step, formData.sourceType); + + const goTo = (nextStep: StepId) => { + setHistory((items) => [...items, step]); + setStep(nextStep); + }; + + const goBack = () => { + const previous = history[history.length - 1]; + if (!previous) { + return; + } + setHistory((items) => items.slice(0, -1)); + setStep(previous); + }; + + const updateFormData = (patch: Partial) => { + setFormData((current) => ({ ...current, ...patch })); + }; + + const chooseSourceType = (sourceType: SourceType) => { + setBranches([]); + setBranchError(null); + setDockerfileDetectionResult(null); + setFormData((current) => resetForSourceType(current, sourceType)); + }; + + const loadBranches = async () => { + if (!formData.gitUrl?.trim()) { + setBranchError('Enter a Git repository URL first.'); + return false; + } - const selectBuildMethod = async (buildMethod: AppBuildMethod) => { - updateFormData({ buildMethod }); - if (buildMethod === 'DOCKERFILE') { - goTo('dockerfile'); - await runDockerfileDetection(); - return; - } - if (buildMethod === 'FRAMEWORK') { - goTo('framework-selection'); - return; - } - goTo('summary'); - }; + const inputData: AppGitBranchesLookupModel = + formData.sourceType === 'GIT' + ? { + sourceType: 'GIT', + gitUrl: formData.gitUrl, + gitUsername: formData.gitUsername, + gitToken: formData.gitToken + } + : { + sourceType: 'GIT_SSH', + gitUrl: formData.gitUrl + }; + + setIsLoadingBranches(true); + setBranchError(null); + try { + const result = await Actions.run(() => getGitBranches(app.id, inputData)); + setBranches(result ?? []); + if (formData.gitBranch && !result?.includes(formData.gitBranch)) { + updateFormData({ gitBranch: '' }); + } + return true; + } catch (error) { + setBranches([]); + setBranchError(error instanceof Error ? error.message : 'Branches could not be loaded.'); + return false; + } finally { + setIsLoadingBranches(false); + } + }; - const selectFramework = (framework: JsFramework) => { - const preset = jsFrameworkPresets[framework]; - updateFormData({ - framework, - installCommand: preset.installCommand, - buildCommand: preset.buildCommand, - runCommand: preset.runCommand, - rootDirectory: preset.rootDirectory, - outputDirectory: preset.outputDirectory, - }); - goTo('framework-configuration'); - }; + const ensureSshKey = async () => { + if (publicKey || isEnsuringKey) { + return; + } + setIsEnsuringKey(true); + try { + const key = await Actions.run(() => ensureGitSshPublicKey(app.id)); + setPublicKey(key); + } finally { + setIsEnsuringKey(false); + } + }; - const next = async () => { - if (step === 'source') { - goTo(formData.sourceType === 'GIT' ? 'git-url' : formData.sourceType === 'GIT_SSH' ? 'ssh-url' : 'container-image'); - return; - } - if (step === 'git-url') { - if (await loadBranches()) { - goTo('branch'); - } - return; - } - if (step === 'ssh-url') { - if (await loadBranches()) { - goTo('branch'); - } - return; - } - if (step === 'dockerfile' || step === 'framework-configuration' || step === 'container-image') { - goTo('summary'); - } - }; + useEffect(() => { + if (step === 'ssh-url') { + ensureSshKey(); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [step, formData.gitUrl, publicKey]); + + const regenerateKey = async () => { + const confirmed = await openConfirmDialog({ + title: 'Regenerate Deploy Key', + description: 'This replaces the current app SSH key. Update the deploy key in your Git provider before deploying again.', + okButton: 'Regenerate' + }); + if (!confirmed) { + return; + } + const key = await Actions.run(() => generateOrRegenerateGitSshKey(app.id)); + setPublicKey(key); + toast.success('Deploy key regenerated.'); + }; + + const copyPublicKey = () => { + if (!publicKey) { + return; + } + navigator.clipboard.writeText(publicKey); + toast.success('Copied to clipboard.'); + }; - const save = async (deployAfterSave: boolean) => { - try { - setShowButtonLoading(true); - await Toast.fromAction(() => saveGeneralAppSourceInfo(null, formData, app.id), 'Source saved', 'Saving source...'); - if (deployAfterSave) { - await Toast.fromAction(() => deploy(app.id, true), 'Deployment started', 'Staring deployment...'); - closeDialog(true); - router.refresh(); - return; - } - - closeDialog(true); - router.refresh(); - } finally { - setShowButtonLoading(false); - } - }; + const runDockerfileDetection = async () => { + if (!isGitSource || !formData.gitUrl || !formData.gitBranch) { + return; + } - const nextDisabled = getNextDisabled(step, formData, publicKey, isLoadingBranches, isEnsuringKey, isDetectingDockerfile); - - return ( - <> - - {currentTitle} - - {step === 'summary' ? 'Review the app source before saving.' : ''} - - - -
- - {step === 'source' && ( - - )} - {step === 'git-url' && ( - - )} - {step === 'ssh-url' && ( - - )} - {step === 'branch' && ( - - )} - {step === 'build-method' && ( - - )} - {step === 'dockerfile' && ( - updateFormData({ dockerfilePath })} - onRetry={() => void runDockerfileDetection()} - /> - )} - {step === 'framework-selection' && ( - - )} - {step === 'framework-configuration' && formData.framework && ( - - )} - {step === 'container-image' && ( - - )} - {step === 'summary' && ( - - )} -
- - -
-
- {history.length > 0 && ( - - )} -
-
- {step === 'summary' ? ( - <> - - - - ) : step === 'branch' || step === 'build-method' || step === 'framework-selection' ? ( - null - ) : ( - - )} -
-
-
- - ); + const inputData: AppDockerfileDetectionModel = + formData.sourceType === 'GIT' + ? { + sourceType: 'GIT', + gitUrl: formData.gitUrl, + gitBranch: formData.gitBranch, + gitUsername: formData.gitUsername, + gitToken: formData.gitToken + } + : { + sourceType: 'GIT_SSH', + gitUrl: formData.gitUrl, + gitBranch: formData.gitBranch + }; + + setIsDetectingDockerfile(true); + try { + const dockerfilePath = await Actions.run(() => detectDockerfilePath(app.id, inputData)); + updateFormData({ dockerfilePath: dockerfilePath || defaultDockerfilePath }); + setDockerfileDetectionResult(dockerfilePath ? 'detected' : 'not-found'); + } finally { + setIsDetectingDockerfile(false); + } + }; + + const selectGitBranch = (gitBranch: string) => { + updateFormData({ gitBranch }); + setDockerfileDetectionResult(null); + goTo('build-method'); + }; + + const selectBuildMethod = async (buildMethod: AppBuildMethod) => { + updateFormData({ buildMethod }); + if (buildMethod === 'DOCKERFILE') { + goTo('dockerfile'); + await runDockerfileDetection(); + return; + } + if (buildMethod === 'FRAMEWORK') { + goTo('framework-selection'); + return; + } + goTo('summary'); + }; + + const selectFramework = (framework: JsFramework) => { + const preset = jsFrameworkPresets[framework]; + updateFormData({ + framework, + installCommand: preset.installCommand, + buildCommand: preset.buildCommand, + runCommand: preset.runCommand, + rootDirectory: preset.rootDirectory, + outputDirectory: preset.outputDirectory + }); + goTo('framework-configuration'); + }; + + const next = async () => { + if (step === 'source') { + goTo(formData.sourceType === 'GIT' ? 'git-url' : formData.sourceType === 'GIT_SSH' ? 'ssh-url' : 'container-image'); + return; + } + if (step === 'git-url') { + if (await loadBranches()) { + goTo('branch'); + } + return; + } + if (step === 'ssh-url') { + if (await loadBranches()) { + goTo('branch'); + } + return; + } + if (step === 'dockerfile' || step === 'framework-configuration' || step === 'container-image') { + goTo('summary'); + } + }; + + const save = async (deployAfterSave: boolean) => { + try { + setShowButtonLoading(true); + await Toast.fromAction(() => saveGeneralAppSourceInfo(null, formData, app.id), 'Source saved', 'Saving source...'); + if (deployAfterSave) { + await Toast.fromAction(() => deploy(app.id, true), 'Deployment started', 'Staring deployment...'); + closeDialog(true); + router.refresh(); + return; + } + + closeDialog(true); + router.refresh(); + } finally { + setShowButtonLoading(false); + } + }; + + const nextDisabled = getNextDisabled(step, formData, publicKey, isLoadingBranches, isEnsuringKey, isDetectingDockerfile); + + return ( + <> + + {currentTitle} + {step === 'summary' ? 'Review the app source before saving.' : ''} + + +
+ + {step === 'source' && } + {step === 'git-url' && ( + + )} + {step === 'ssh-url' && ( + + )} + {step === 'branch' && } + {step === 'build-method' && } + {step === 'dockerfile' && ( + updateFormData({ dockerfilePath })} + onRetry={() => void runDockerfileDetection()} + /> + )} + {step === 'framework-selection' && } + {step === 'framework-configuration' && formData.framework && ( + + )} + {step === 'container-image' && ( + + )} + {step === 'summary' && ( + + )} +
+ + +
+
+ {history.length > 0 && ( + + )} +
+
+ {step === 'summary' ? ( + <> + + + + ) : step === 'branch' || step === 'build-method' || step === 'framework-selection' ? null : ( + + )} +
+
+
+ + ); } function getStepTitle(step: StepId, sourceType: AppSourceInfoInputModel['sourceType']) { - if (step === 'source') return 'Choose source'; - if (step === 'git-url') return 'Connect Git HTTPS'; - if (step === 'ssh-url') return 'Connect Git SSH'; - if (step === 'branch') return 'Choose Git Branch'; - if (step === 'build-method') return 'Choose Build Method'; - if (step === 'dockerfile') return 'Confirm Dockerfile Path'; - if (step === 'framework-selection') return 'Choose Framework'; - if (step === 'framework-configuration') return 'Configure Framework'; - if (step === 'container-image') return 'Connect Docker Container Image'; - if (step === 'summary') return `${sourceTypeLabels[sourceType as SourceType]} Summary`; - return 'Connect App Source'; + if (step === 'source') { + return 'Choose source'; + } + if (step === 'git-url') { + return 'Connect Git HTTPS'; + } + if (step === 'ssh-url') { + return 'Connect Git SSH'; + } + if (step === 'branch') { + return 'Choose Git Branch'; + } + if (step === 'build-method') { + return 'Choose Build Method'; + } + if (step === 'dockerfile') { + return 'Confirm Dockerfile Path'; + } + if (step === 'framework-selection') { + return 'Choose Framework'; + } + if (step === 'framework-configuration') { + return 'Configure Framework'; + } + if (step === 'container-image') { + return 'Connect Docker Container Image'; + } + if (step === 'summary') { + return `${sourceTypeLabels[sourceType as SourceType]} Summary`; + } + return 'Connect App Source'; } -function getNextDisabled(step: StepId, formData: AppSourceInfoInputModel, publicKey: string | undefined, isLoadingBranches: boolean, isEnsuringKey: boolean, isDetectingDockerfile: boolean) { - if (isLoadingBranches || isEnsuringKey || isDetectingDockerfile) return true; - if (step === 'git-url') return !formData.gitUrl?.trim(); - if (step === 'ssh-url') return !formData.gitUrl?.trim() || !publicKey; - if (step === 'branch') return !formData.gitBranch; - if (step === 'dockerfile') return !formData.dockerfilePath?.trim(); - if (step === 'framework-configuration') return !formData.framework || !formData.buildCommand?.trim(); - if (step === 'container-image') return !formData.containerImageSource?.trim(); - return false; +function getNextDisabled( + step: StepId, + formData: AppSourceInfoInputModel, + publicKey: string | undefined, + isLoadingBranches: boolean, + isEnsuringKey: boolean, + isDetectingDockerfile: boolean +) { + if (isLoadingBranches || isEnsuringKey || isDetectingDockerfile) { + return true; + } + if (step === 'git-url') { + return !formData.gitUrl?.trim(); + } + if (step === 'ssh-url') { + return !formData.gitUrl?.trim() || !publicKey; + } + if (step === 'branch') { + return !formData.gitBranch; + } + if (step === 'dockerfile') { + return !formData.dockerfilePath?.trim(); + } + if (step === 'framework-configuration') { + return !formData.framework || !formData.buildCommand?.trim(); + } + if (step === 'container-image') { + return !formData.containerImageSource?.trim(); + } + return false; } function resetForSourceType(current: AppSourceInfoInputModel, sourceType: SourceType): AppSourceInfoInputModel { - if (sourceType === current.sourceType) { - return current; - } - if (sourceType === 'GIT') { - return { - sourceType, - buildMethod: 'RAILPACK', - gitUrl: '', - gitBranch: '', - gitUsername: '', - gitToken: '', - dockerfilePath: defaultDockerfilePath, - ...emptyFrameworkFields(), - }; - } - if (sourceType === 'GIT_SSH') { - return { - sourceType, - buildMethod: 'RAILPACK', - gitUrl: '', - gitBranch: '', - dockerfilePath: defaultDockerfilePath, - ...emptyFrameworkFields(), - }; - } + if (sourceType === current.sourceType) { + return current; + } + if (sourceType === 'GIT') { return { - sourceType, - buildMethod: 'RAILPACK', - containerImageSource: '', - containerRegistryUsername: '', - containerRegistryPassword: '', - dockerfilePath: defaultDockerfilePath, - ...emptyFrameworkFields(), + sourceType, + buildMethod: 'RAILPACK', + gitUrl: '', + gitBranch: '', + gitUsername: '', + gitToken: '', + dockerfilePath: defaultDockerfilePath, + ...emptyFrameworkFields() }; + } + if (sourceType === 'GIT_SSH') { + return { + sourceType, + buildMethod: 'RAILPACK', + gitUrl: '', + gitBranch: '', + dockerfilePath: defaultDockerfilePath, + ...emptyFrameworkFields() + }; + } + return { + sourceType, + buildMethod: 'RAILPACK', + containerImageSource: '', + containerRegistryUsername: '', + containerRegistryPassword: '', + dockerfilePath: defaultDockerfilePath, + ...emptyFrameworkFields() + }; } function emptyFrameworkFields() { - return { - framework: null, - installCommand: '', - buildCommand: '', - runCommand: '', - rootDirectory: './', - outputDirectory: '', - nodeVersion: '', - }; + return { + framework: null, + installCommand: '', + buildCommand: '', + runCommand: '', + rootDirectory: './', + outputDirectory: '', + nodeVersion: '' + }; } function toSourceInput(app: AppExtendedModel): AppSourceInfoInputModel { - const sourceType = app.appType === 'APP' - ? app.sourceType as SourceType - : 'CONTAINER'; - return { - sourceType, - buildMethod: (app.buildMethod as AppBuildMethod | undefined) ?? 'RAILPACK', - containerImageSource: app.containerImageSource ?? '', - containerRegistryUsername: app.containerRegistryUsername ?? '', - containerRegistryPassword: app.containerRegistryPassword ?? '', - gitUrl: app.gitUrl ?? '', - gitBranch: app.gitBranch ?? '', - gitUsername: app.gitUsername ?? '', - gitToken: app.gitToken ?? '', - dockerfilePath: app.dockerfilePath ?? defaultDockerfilePath, - framework: jsFrameworkZodModel.safeParse(app.framework).data ?? null, - installCommand: app.installCommand ?? '', - buildCommand: app.buildCommand ?? '', - runCommand: app.runCommand ?? '', - rootDirectory: app.rootDirectory ?? './', - outputDirectory: app.outputDirectory ?? '', - nodeVersion: app.nodeVersion ?? '', - }; + const sourceType = app.appType === 'APP' ? (app.sourceType as SourceType) : 'CONTAINER'; + return { + sourceType, + buildMethod: (app.buildMethod as AppBuildMethod | undefined) ?? 'RAILPACK', + containerImageSource: app.containerImageSource ?? '', + containerRegistryUsername: app.containerRegistryUsername ?? '', + containerRegistryPassword: app.containerRegistryPassword ?? '', + gitUrl: app.gitUrl ?? '', + gitBranch: app.gitBranch ?? '', + gitUsername: app.gitUsername ?? '', + gitToken: app.gitToken ?? '', + dockerfilePath: app.dockerfilePath ?? defaultDockerfilePath, + framework: jsFrameworkZodModel.safeParse(app.framework).data ?? null, + installCommand: app.installCommand ?? '', + buildCommand: app.buildCommand ?? '', + runCommand: app.runCommand ?? '', + rootDirectory: app.rootDirectory ?? './', + outputDirectory: app.outputDirectory ?? '', + nodeVersion: app.nodeVersion ?? '' + }; } diff --git a/src/app/project/[projectId]/apps/details/volumes/backups/app-details-backups-tab.tsx b/src/app/project/[projectId]/apps/details/volumes/backups/app-details-backups-tab.tsx index 62672a2b..639afd4a 100644 --- a/src/app/project/[projectId]/apps/details/volumes/backups/app-details-backups-tab.tsx +++ b/src/app/project/[projectId]/apps/details/volumes/backups/app-details-backups-tab.tsx @@ -93,7 +93,9 @@ export function DrawerBackupsTab({ description: `Create a ${scheduleLabels.get(schedule.id)?.toLowerCase()} now?`, okButton: 'Create Backup' }); - if (!confirmed) return; + if (!confirmed) { + return; + } try { setRunningSchedule(schedule.id); await Toast.fromAction(() => runBackupVolumeSchedule(schedule.id), undefined, 'Creating backup...'); @@ -171,7 +173,7 @@ export function DrawerBackupsTab({ - Created + Created Size Backup Location Type @@ -185,7 +187,7 @@ export function DrawerBackupsTab({ const backupId = `${backup.schedule.id}:${backup.key}`; return ( - {formatDateTime(backup.backupDate, true)} + {formatDateTime(backup.backupDate, true)} {backup.sizeBytes ? KubeSizeConverter.convertBytesToReadableSize(backup.sizeBytes) : 'Unknown'}
diff --git a/src/app/project/[projectId]/overview/network-graph/connection-edge.tsx b/src/app/project/[projectId]/overview/network-graph/connection-edge.tsx index 4421f5d9..8ba88a0e 100644 --- a/src/app/project/[projectId]/overview/network-graph/connection-edge.tsx +++ b/src/app/project/[projectId]/overview/network-graph/connection-edge.tsx @@ -4,20 +4,18 @@ import { SmoothStepEdge, type EdgeProps } from '@xyflow/react'; import { ProjectNetworkGraphConnectionContextMenu } from './context-menus/project-network-graph-connection-context-menu'; type ConnectionEdgeData = { - onDelete?: () => void; - internalHostnames: { hostname: string; port: number }[]; + onDelete?: () => void; + internalHostnames: { hostname: string; port: number }[]; }; export function ConnectionEdge(props: EdgeProps) { - const data = props.data as ConnectionEdgeData | undefined; - if (!data) return ; - return ( - - - - ); + const data = props.data as ConnectionEdgeData | undefined; + if (!data) { + return ; + } + return ( + + + + ); } - diff --git a/src/app/project/[projectId]/overview/network-graph/context-menus/project-network-graph-canvas-context-menu.tsx b/src/app/project/[projectId]/overview/network-graph/context-menus/project-network-graph-canvas-context-menu.tsx index 58b0297d..9a4353d1 100644 --- a/src/app/project/[projectId]/overview/network-graph/context-menus/project-network-graph-canvas-context-menu.tsx +++ b/src/app/project/[projectId]/overview/network-graph/context-menus/project-network-graph-canvas-context-menu.tsx @@ -3,13 +3,13 @@ import type { ReactNode } from 'react'; import { Blocks, Bot, Database, File } from 'lucide-react'; import { - ContextMenu, - ContextMenuContent, - ContextMenuItem, - ContextMenuSub, - ContextMenuSubContent, - ContextMenuSubTrigger, - ContextMenuTrigger, + ContextMenu, + ContextMenuContent, + ContextMenuItem, + ContextMenuSub, + ContextMenuSubContent, + ContextMenuSubTrigger, + ContextMenuTrigger } from '@/components/ui/context-menu'; import { useDialog } from '@/frontend/states/zustand.states'; import { EditAppDialog } from '@/app/project/[projectId]/apps/create/edit-app-dialog'; @@ -17,74 +17,73 @@ import { CreateAgentDialog } from '@/app/project/[projectId]/agents/create/creat import ChooseTemplateDialog from '@/app/project/[projectId]/choose-template-dialog'; type ProjectNetworkGraphCanvasContextMenuProps = { - projectId: string; - canCreateApps: boolean; - canCreateAgents: boolean; - children: ReactNode; + projectId: string; + canCreateApps: boolean; + canCreateAgents: boolean; + children: ReactNode; }; -export function ProjectNetworkGraphCanvasContextMenu({ - projectId, - canCreateApps, - canCreateAgents, - children, -}: ProjectNetworkGraphCanvasContextMenuProps) { - const { openDialog } = useDialog(); - const openTemplateDialog = (templateType: 'database' | 'template' | 'agent-template') => { - openDialog(, { maxWidth: '1000px' }); - }; +export function ProjectNetworkGraphCanvasContextMenu({ projectId, canCreateApps, canCreateAgents, children }: ProjectNetworkGraphCanvasContextMenuProps) { + const { openDialog } = useDialog(); + const openTemplateDialog = (templateType: 'database' | 'template' | 'agent-template') => { + openDialog(, { maxWidth: '1000px' }); + }; - if (!canCreateApps && !canCreateAgents) return children; + if (!canCreateApps && !canCreateAgents) { + return children; + } - return ( - - - {children} - - - {canCreateApps && <> - - - - Create App - - - - - - Empty App - - - openTemplateDialog('template')}> - - App from Template - - - - openTemplateDialog('database')}> - - Create Database - - } - {canCreateAgents && - - - Create Agent Sandbox - - - - - - Empty Agent Sandbox - - - openTemplateDialog('agent-template')}> - - Agent Sandbox from Template - - - } - - - ); + return ( + + {children} + + {canCreateApps && ( + <> + + + + Create App + + + + + + Empty App + + + openTemplateDialog('template')}> + + App from Template + + + + openTemplateDialog('database')}> + + Create Database + + + )} + {canCreateAgents && ( + + + + Create Agent Sandbox + + + + + + Empty Agent Sandbox + + + openTemplateDialog('agent-template')}> + + Agent Sandbox from Template + + + + )} + + + ); } diff --git a/src/app/project/[projectId]/overview/network-graph/project-network-graph-drawer-session.ts b/src/app/project/[projectId]/overview/network-graph/project-network-graph-drawer-session.ts index 7649f89a..498c025c 100644 --- a/src/app/project/[projectId]/overview/network-graph/project-network-graph-drawer-session.ts +++ b/src/app/project/[projectId]/overview/network-graph/project-network-graph-drawer-session.ts @@ -2,16 +2,8 @@ import { useCallback, useEffect, useMemo, useState } from 'react'; import { TabNavigationUtils } from '@/frontend/utils/tab-navigation.utils'; -import { - appDrawerTabValues, - AppDrawerNavigationUtils, - defaultAppDrawerTab, - type AppDrawerTab, -} from '@/shared/utils/app-drawer-navigation.utils'; -import { - defaultAgentDrawerTab, - type AgentDrawerTab, -} from '@/shared/utils/agent-drawer-navigation.utils'; +import { appDrawerTabValues, AppDrawerNavigationUtils, defaultAppDrawerTab, type AppDrawerTab } from '@/shared/utils/app-drawer-navigation.utils'; +import { defaultAgentDrawerTab, type AgentDrawerTab } from '@/shared/utils/agent-drawer-navigation.utils'; import type { NetworkGraphNode } from './project-network-graph-projection'; export const drawerTabValues = appDrawerTabValues; @@ -23,114 +15,136 @@ type QueryParams = Pick; type DrawerTarget = { kind: 'APP' | 'AGENT'; id: string }; export function useProjectNetworkGraphDrawerSession({ - searchParams, - appIds, - agentIds, + searchParams, + appIds, + agentIds }: { - searchParams: QueryParams; - appIds: Set; - agentIds: Set; + searchParams: QueryParams; + appIds: Set; + agentIds: Set; }) { - const [selectedNodeId, setSelectedNodeId] = useState(); - const [open, setOpen] = useState(false); - const requestedTab = searchParams.get('drawerTab'); - - const updateQuery = useCallback((target?: DrawerTarget, tab?: AppDrawerTab | AgentDrawerTab) => { - const params = new URLSearchParams(searchParams.toString()); - params.delete('drawerAppId'); - params.delete('drawerAgentId'); - params.delete('drawerTab'); - - if (target) { - params.set(target.kind === 'AGENT' ? 'drawerAgentId' : 'drawerAppId', target.id); - params.set('drawerTab', tab ?? (target.kind === 'AGENT' ? defaultAgentDrawerTab : defaultAppDrawerTab)); - } - - TabNavigationUtils.replaceQuery(params); - }, [searchParams]); - - useEffect(() => { - const requestedAppId = searchParams.get('drawerAppId'); - const requestedAgentId = searchParams.get('drawerAgentId'); - - if (requestedAppId) { - if (!appIds.has(requestedAppId)) { - updateQuery(); - return; - } - setSelectedNodeId(`APP:${requestedAppId}`); - return; - } - - if (requestedAgentId) { - if (!agentIds.has(requestedAgentId)) { - updateQuery(); - return; - } - setSelectedNodeId(`AGENT:${requestedAgentId}`); - } - }, [agentIds, appIds, searchParams, updateQuery]); - - useEffect(() => { - if (selectedNodeId) setOpen(true); - }, [selectedNodeId]); - - const selectNode = useCallback((node: NetworkGraphNode) => { - setSelectedNodeId(node.id); - if (selectedNodeId === node.id) setOpen(true); - if (node.kind === 'APP') { - updateQuery({ kind: 'APP', id: node.id.replace('APP:', '') }); - } else if (node.kind === 'AGENT') { - updateQuery({ kind: 'AGENT', id: node.id.replace('AGENT:', '') }); - } else { - updateQuery(); - } - }, [selectedNodeId, updateQuery]); - - const openAppTab = useCallback((appId: string, tab: DrawerTab) => { - const nodeId = `APP:${appId}`; - setSelectedNodeId(nodeId); - if (selectedNodeId === nodeId) setOpen(true); - updateQuery({ kind: 'APP', id: appId }, tab); - }, [selectedNodeId, updateQuery]); - - const openAgentTab = useCallback((agentId: string, tab: AgentDrawerTab) => { - const nodeId = `AGENT:${agentId}`; - setSelectedNodeId(nodeId); - if (selectedNodeId === nodeId) setOpen(true); - updateQuery({ kind: 'AGENT', id: agentId }, tab); - }, [selectedNodeId, updateQuery]); - - const onOpenChange = useCallback((nextOpen: boolean) => { - setOpen(nextOpen); - if (!nextOpen) { - updateQuery(); - } - }, [updateQuery]); - - const onOpenChangeComplete = useCallback((nextOpen: boolean) => { - // Keep the node mounted until Vaul finishes its exit animation. A click - // during that animation reopens it, so do not clear the new selection. - if (!nextOpen && !open) setSelectedNodeId(undefined); - }, [open]); - - return useMemo(() => ({ - selectedNodeId, - open, - requestedTab, - selectNode, - openAppTab, - openAgentTab, - onOpenChange, - onOpenChangeComplete, - }), [ - onOpenChange, - onOpenChangeComplete, - openAgentTab, - openAppTab, - open, - requestedTab, - selectNode, - selectedNodeId, - ]); + const [selectedNodeId, setSelectedNodeId] = useState(); + const [open, setOpen] = useState(false); + const requestedTab = searchParams.get('drawerTab'); + + const updateQuery = useCallback( + (target?: DrawerTarget, tab?: AppDrawerTab | AgentDrawerTab) => { + const params = new URLSearchParams(searchParams.toString()); + params.delete('drawerAppId'); + params.delete('drawerAgentId'); + params.delete('drawerTab'); + + if (target) { + params.set(target.kind === 'AGENT' ? 'drawerAgentId' : 'drawerAppId', target.id); + params.set('drawerTab', tab ?? (target.kind === 'AGENT' ? defaultAgentDrawerTab : defaultAppDrawerTab)); + } + + TabNavigationUtils.replaceQuery(params); + }, + [searchParams] + ); + + useEffect(() => { + const requestedAppId = searchParams.get('drawerAppId'); + const requestedAgentId = searchParams.get('drawerAgentId'); + + if (requestedAppId) { + if (!appIds.has(requestedAppId)) { + updateQuery(); + return; + } + setSelectedNodeId(`APP:${requestedAppId}`); + return; + } + + if (requestedAgentId) { + if (!agentIds.has(requestedAgentId)) { + updateQuery(); + return; + } + setSelectedNodeId(`AGENT:${requestedAgentId}`); + } + }, [agentIds, appIds, searchParams, updateQuery]); + + useEffect(() => { + if (selectedNodeId) { + setOpen(true); + } + }, [selectedNodeId]); + + const selectNode = useCallback( + (node: NetworkGraphNode) => { + setSelectedNodeId(node.id); + if (selectedNodeId === node.id) { + setOpen(true); + } + if (node.kind === 'APP') { + updateQuery({ kind: 'APP', id: node.id.replace('APP:', '') }); + } else if (node.kind === 'AGENT') { + updateQuery({ kind: 'AGENT', id: node.id.replace('AGENT:', '') }); + } else { + updateQuery(); + } + }, + [selectedNodeId, updateQuery] + ); + + const openAppTab = useCallback( + (appId: string, tab: DrawerTab) => { + const nodeId = `APP:${appId}`; + setSelectedNodeId(nodeId); + if (selectedNodeId === nodeId) { + setOpen(true); + } + updateQuery({ kind: 'APP', id: appId }, tab); + }, + [selectedNodeId, updateQuery] + ); + + const openAgentTab = useCallback( + (agentId: string, tab: AgentDrawerTab) => { + const nodeId = `AGENT:${agentId}`; + setSelectedNodeId(nodeId); + if (selectedNodeId === nodeId) { + setOpen(true); + } + updateQuery({ kind: 'AGENT', id: agentId }, tab); + }, + [selectedNodeId, updateQuery] + ); + + const onOpenChange = useCallback( + (nextOpen: boolean) => { + setOpen(nextOpen); + if (!nextOpen) { + updateQuery(); + } + }, + [updateQuery] + ); + + const onOpenChangeComplete = useCallback( + (nextOpen: boolean) => { + // Keep the node mounted until Vaul finishes its exit animation. A click + // during that animation reopens it, so do not clear the new selection. + if (!nextOpen && !open) { + setSelectedNodeId(undefined); + } + }, + [open] + ); + + return useMemo( + () => ({ + selectedNodeId, + open, + requestedTab, + selectNode, + openAppTab, + openAgentTab, + onOpenChange, + onOpenChangeComplete + }), + [onOpenChange, onOpenChangeComplete, openAgentTab, openAppTab, open, requestedTab, selectNode, selectedNodeId] + ); } diff --git a/src/app/project/[projectId]/overview/network-graph/project-network-graph-projection.ts b/src/app/project/[projectId]/overview/network-graph/project-network-graph-projection.ts index 9b766a66..04241a91 100644 --- a/src/app/project/[projectId]/overview/network-graph/project-network-graph-projection.ts +++ b/src/app/project/[projectId]/overview/network-graph/project-network-graph-projection.ts @@ -7,183 +7,212 @@ export type NetworkGraphNodeKind = WorkloadType | 'INTERNET'; export type NetworkGraphEdgeDirection = 'CONNECTION' | 'INGRESS' | 'EGRESS' | 'INTERNET_CONNECTION' | 'INTERNET_INGRESS' | 'INTERNET_EGRESS'; export type NetworkGraphNode = { - id: string; - kind: NetworkGraphNodeKind; - name: string; - projectId?: string; - external: boolean; - caption?: string; - appType?: string; + id: string; + kind: NetworkGraphNodeKind; + name: string; + projectId?: string; + external: boolean; + caption?: string; + appType?: string; }; export type NetworkGraphEdge = { - id: string; - source: string; - target: string; - direction: NetworkGraphEdgeDirection; - labels: string[]; - external: boolean; - complete?: boolean; - internetIngress?: boolean; - internetEgress?: boolean; - ruleProvenance: AppNetworkPolicyRuleProvenance[]; + id: string; + source: string; + target: string; + direction: NetworkGraphEdgeDirection; + labels: string[]; + external: boolean; + complete?: boolean; + internetIngress?: boolean; + internetEgress?: boolean; + ruleProvenance: AppNetworkPolicyRuleProvenance[]; }; export type ProjectNetworkGraphData = { nodes: NetworkGraphNode[]; edges: NetworkGraphEdge[] }; export function connectionDeletionProvenance( - edge: NetworkGraphEdge | undefined, - writableAppIds: ReadonlySet, + edge: NetworkGraphEdge | undefined, + writableAppIds: ReadonlySet ): AppNetworkPolicyRuleProvenance[] | undefined { - if (!edge || edge.direction.startsWith('INTERNET') || edge.ruleProvenance.length === 0) return undefined; - return edge.ruleProvenance.every(item => writableAppIds.has(item.ownerAppId)) - ? edge.ruleProvenance - : undefined; + if (!edge || edge.direction.startsWith('INTERNET') || edge.ruleProvenance.length === 0) { + return undefined; + } + return edge.ruleProvenance.every((item) => writableAppIds.has(item.ownerAppId)) ? edge.ruleProvenance : undefined; } function workloadNodeId(type: WorkloadType, id: string) { - return `${type}:${id}`; + return `${type}:${id}`; } function formatRuleLabel(port: number, protocol: string) { - return `${port}/${protocol.toUpperCase()}`; + return `${port}/${protocol.toUpperCase()}`; } function aggregateLabels(labels: string[]) { - return Array.from(new Set(labels)).sort((a, b) => { - const portA = parseInt(a, 10); - const portB = parseInt(b, 10); - return !Number.isNaN(portA) && !Number.isNaN(portB) ? portA - portB : a.localeCompare(b); - }); + return Array.from(new Set(labels)).sort((a, b) => { + const portA = parseInt(a, 10); + const portB = parseInt(b, 10); + return !Number.isNaN(portA) && !Number.isNaN(portB) ? portA - portB : a.localeCompare(b); + }); } function consolidateConnections(edges: NetworkGraphEdge[]) { - const internetGroups = new Map(); - for (const edge of edges.filter(edge => edge.direction.startsWith('INTERNET'))) { - const appId = edge.direction === 'INTERNET_INGRESS' ? edge.target : edge.source; - const group = internetGroups.get(appId) ?? { ingress: [], egress: [] }; - if (edge.direction === 'INTERNET_INGRESS') group.ingress.push(edge); - else group.egress.push(edge); - internetGroups.set(appId, group); + const internetGroups = new Map(); + for (const edge of edges.filter((edge) => edge.direction.startsWith('INTERNET'))) { + const appId = edge.direction === 'INTERNET_INGRESS' ? edge.target : edge.source; + const group = internetGroups.get(appId) ?? { ingress: [], egress: [] }; + if (edge.direction === 'INTERNET_INGRESS') { + group.ingress.push(edge); + } else { + group.egress.push(edge); } - const groups = new Map(); - for (const edge of edges.filter(edge => !edge.direction.startsWith('INTERNET'))) { - const key = `${edge.source}:${edge.target}`; - const group = groups.get(key) ?? { ingress: [], egress: [] }; - if (edge.direction === 'INGRESS') group.ingress.push(edge); - else group.egress.push(edge); - groups.set(key, group); + internetGroups.set(appId, group); + } + const groups = new Map(); + for (const edge of edges.filter((edge) => !edge.direction.startsWith('INTERNET'))) { + const key = `${edge.source}:${edge.target}`; + const group = groups.get(key) ?? { ingress: [], egress: [] }; + if (edge.direction === 'INGRESS') { + group.ingress.push(edge); + } else { + group.egress.push(edge); } - const internetConnections = Array.from(internetGroups.entries()).map(([appId, group]) => ({ - id: `INTERNET_CONNECTION:${appId}`, - source: appId, - target: 'INTERNET', - direction: 'INTERNET_CONNECTION' as const, - labels: aggregateLabels([...group.ingress, ...group.egress].flatMap(edge => edge.labels).filter(Boolean)), - external: false, - ruleProvenance: [], - internetIngress: group.ingress.length > 0, - internetEgress: group.egress.length > 0, - })); - return [...internetConnections, ...Array.from(groups.entries()).map(([key, group]) => { - const ingressLabels = aggregateLabels(group.ingress.flatMap(edge => edge.labels)); - const egressLabels = aggregateLabels(group.egress.flatMap(edge => edge.labels)); - const reference = group.egress[0] ?? group.ingress[0]; - return { - id: `CONNECTION:${key}`, - source: reference.source, - target: reference.target, - direction: 'CONNECTION' as const, - labels: aggregateLabels([...ingressLabels, ...egressLabels]), - external: reference.external, - ruleProvenance: [...group.ingress, ...group.egress].flatMap(edge => edge.ruleProvenance), - complete: ingressLabels.length > 0 - && ingressLabels.length === egressLabels.length - && ingressLabels.every((label, index) => label === egressLabels[index]), - }; - })]; + groups.set(key, group); + } + const internetConnections = Array.from(internetGroups.entries()).map(([appId, group]) => ({ + id: `INTERNET_CONNECTION:${appId}`, + source: appId, + target: 'INTERNET', + direction: 'INTERNET_CONNECTION' as const, + labels: aggregateLabels([...group.ingress, ...group.egress].flatMap((edge) => edge.labels).filter(Boolean)), + external: false, + ruleProvenance: [], + internetIngress: group.ingress.length > 0, + internetEgress: group.egress.length > 0 + })); + return [ + ...internetConnections, + ...Array.from(groups.entries()).map(([key, group]) => { + const ingressLabels = aggregateLabels(group.ingress.flatMap((edge) => edge.labels)); + const egressLabels = aggregateLabels(group.egress.flatMap((edge) => edge.labels)); + const reference = group.egress[0] ?? group.ingress[0]; + return { + id: `CONNECTION:${key}`, + source: reference.source, + target: reference.target, + direction: 'CONNECTION' as const, + labels: aggregateLabels([...ingressLabels, ...egressLabels]), + external: reference.external, + ruleProvenance: [...group.ingress, ...group.egress].flatMap((edge) => edge.ruleProvenance), + complete: + ingressLabels.length > 0 && ingressLabels.length === egressLabels.length && ingressLabels.every((label, index) => label === egressLabels[index]) + }; + }) + ]; } /** Projects effective App Network Policy Configuration and App Domain traffic into graph facts. */ export function buildProjectNetworkGraph(apps: AppExtendedModel[], agents: AgentExtendedModel[] = []): ProjectNetworkGraphData { - const projectId = apps[0]?.projectId ?? agents[0]?.projectId; - const internalWorkloadIds = new Set([...apps.map(app => app.id), ...agents.map(agent => agent.id)]); - const nodes = new Map(); - const edges = new Map(); - const addNode = (node: NetworkGraphNode) => { if (!nodes.has(node.id)) nodes.set(node.id, node); }; - const addEdge = ( - source: string, - target: string, - direction: NetworkGraphEdgeDirection, - label: string, - external: boolean, - ruleProvenance: AppNetworkPolicyRuleProvenance[] = [], - ) => { - const key = `${direction}:${source}:${target}`; - const edge = edges.get(key); - if (edge) { - edge.labels.push(label); - edge.ruleProvenance.push(...ruleProvenance); - } else { - edges.set(key, { id: key, source, target, direction, labels: [label], external, ruleProvenance }); + const projectId = apps[0]?.projectId ?? agents[0]?.projectId; + const internalWorkloadIds = new Set([...apps.map((app) => app.id), ...agents.map((agent) => agent.id)]); + const nodes = new Map(); + const edges = new Map(); + const addNode = (node: NetworkGraphNode) => { + if (!nodes.has(node.id)) { + nodes.set(node.id, node); + } + }; + const addEdge = ( + source: string, + target: string, + direction: NetworkGraphEdgeDirection, + label: string, + external: boolean, + ruleProvenance: AppNetworkPolicyRuleProvenance[] = [] + ) => { + const key = `${direction}:${source}:${target}`; + const edge = edges.get(key); + if (edge) { + edge.labels.push(label); + edge.ruleProvenance.push(...ruleProvenance); + } else { + edges.set(key, { id: key, source, target, direction, labels: [label], external, ruleProvenance }); + } + }; + + for (const app of apps) { + const appNodeId = workloadNodeId('APP', app.id); + addNode({ id: appNodeId, kind: 'APP', name: app.name, projectId: app.projectId, external: false, appType: app.appType }); + + if (app.useNetworkPolicy) { + for (const rule of app.appNetworkPolicy?.rules ?? []) { + const target = rule.targetApp ?? rule.targetAgent; + if (!target) { + continue; } - }; - - for (const app of apps) { - const appNodeId = workloadNodeId('APP', app.id); - addNode({ id: appNodeId, kind: 'APP', name: app.name, projectId: app.projectId, external: false, appType: app.appType }); - - if (app.useNetworkPolicy) { - for (const rule of app.appNetworkPolicy?.rules ?? []) { - const target = rule.targetApp ?? rule.targetAgent; - if (!target) continue; - const targetType: WorkloadType = rule.targetApp ? 'APP' : 'AGENT'; - const targetNodeId = workloadNodeId(targetType, target.id); - const external = !internalWorkloadIds.has(target.id); - addNode({ - id: targetNodeId, kind: targetType, name: target.name, projectId: target.projectId, external, - caption: external && target.projectId !== projectId ? 'Other project' : targetType === 'AGENT' ? 'Agent Sandbox' : undefined, - }); - const label = formatRuleLabel(rule.port, rule.protocol); - const ruleProvenance = [{ ownerAppId: app.id, ruleKey: rule.id }]; - if (rule.type === 'INGRESS') addEdge(targetNodeId, appNodeId, 'INGRESS', label, external, ruleProvenance); - else addEdge(appNodeId, targetNodeId, 'EGRESS', label, external, ruleProvenance); - } - if (app.appNetworkPolicy?.allowInternetAccess !== false) { - addNode({ id: 'INTERNET', kind: 'INTERNET', name: 'Internet', external: false }); - addEdge(appNodeId, 'INTERNET', 'INTERNET_EGRESS', '', false); - } + const targetType: WorkloadType = rule.targetApp ? 'APP' : 'AGENT'; + const targetNodeId = workloadNodeId(targetType, target.id); + const external = !internalWorkloadIds.has(target.id); + addNode({ + id: targetNodeId, + kind: targetType, + name: target.name, + projectId: target.projectId, + external, + caption: external && target.projectId !== projectId ? 'Other project' : targetType === 'AGENT' ? 'Agent Sandbox' : undefined + }); + const label = formatRuleLabel(rule.port, rule.protocol); + const ruleProvenance = [{ ownerAppId: app.id, ruleKey: rule.id }]; + if (rule.type === 'INGRESS') { + addEdge(targetNodeId, appNodeId, 'INGRESS', label, external, ruleProvenance); + } else { + addEdge(appNodeId, targetNodeId, 'EGRESS', label, external, ruleProvenance); } + } + if (app.appNetworkPolicy?.allowInternetAccess !== false) { + addNode({ id: 'INTERNET', kind: 'INTERNET', name: 'Internet', external: false }); + addEdge(appNodeId, 'INTERNET', 'INTERNET_EGRESS', '', false); + } + } - if (app.appDomains.length > 0) { - addNode({ id: 'INTERNET', kind: 'INTERNET', name: 'Internet', external: false }); - for (const domain of app.appDomains) addEdge('INTERNET', appNodeId, 'INTERNET_INGRESS', `${domain.hostname}:${domain.port}`, false); - } + if (app.appDomains.length > 0) { + addNode({ id: 'INTERNET', kind: 'INTERNET', name: 'Internet', external: false }); + for (const domain of app.appDomains) { + addEdge('INTERNET', appNodeId, 'INTERNET_INGRESS', `${domain.hostname}:${domain.port}`, false); + } } + } + + for (const agent of agents) { + const agentNodeId = workloadNodeId('AGENT', agent.id); + addNode({ id: agentNodeId, kind: 'AGENT', name: agent.name, projectId: agent.projectId, external: false, caption: 'Agent Sandbox' }); - for (const agent of agents) { - const agentNodeId = workloadNodeId('AGENT', agent.id); - addNode({ id: agentNodeId, kind: 'AGENT', name: agent.name, projectId: agent.projectId, external: false, caption: 'Agent Sandbox' }); - - if (agent.agentNetworkPolicy) { - for (const rule of agent.agentNetworkPolicy.rules) { - const targetApp = rule.targetApp; - if (!targetApp) continue; - const targetNodeId = workloadNodeId('APP', targetApp.id); - const external = !internalWorkloadIds.has(targetApp.id); - addNode({ - id: targetNodeId, kind: 'APP', name: targetApp.name, projectId: targetApp.projectId, external, - caption: external && targetApp.projectId !== projectId ? 'Other project' : undefined, - }); - addEdge(agentNodeId, targetNodeId, 'EGRESS', formatRuleLabel(rule.port, rule.protocol), external); - } - if (agent.agentNetworkPolicy.allowInternetAccess !== false) { - addNode({ id: 'INTERNET', kind: 'INTERNET', name: 'Internet', external: false }); - addEdge(agentNodeId, 'INTERNET', 'INTERNET_EGRESS', '', false); - } + if (agent.agentNetworkPolicy) { + for (const rule of agent.agentNetworkPolicy.rules) { + const targetApp = rule.targetApp; + if (!targetApp) { + continue; } + const targetNodeId = workloadNodeId('APP', targetApp.id); + const external = !internalWorkloadIds.has(targetApp.id); + addNode({ + id: targetNodeId, + kind: 'APP', + name: targetApp.name, + projectId: targetApp.projectId, + external, + caption: external && targetApp.projectId !== projectId ? 'Other project' : undefined + }); + addEdge(agentNodeId, targetNodeId, 'EGRESS', formatRuleLabel(rule.port, rule.protocol), external); + } + if (agent.agentNetworkPolicy.allowInternetAccess !== false) { + addNode({ id: 'INTERNET', kind: 'INTERNET', name: 'Internet', external: false }); + addEdge(agentNodeId, 'INTERNET', 'INTERNET_EGRESS', '', false); + } } + } - const rawEdges = Array.from(edges.values()).map(edge => ({ ...edge, labels: aggregateLabels(edge.labels) })); - return { nodes: Array.from(nodes.values()), edges: consolidateConnections(rawEdges) }; + const rawEdges = Array.from(edges.values()).map((edge) => ({ ...edge, labels: aggregateLabels(edge.labels) })); + return { nodes: Array.from(nodes.values()), edges: consolidateConnections(rawEdges) }; } diff --git a/src/app/project/[projectId]/overview/network-graph/project-network-graph.tsx b/src/app/project/[projectId]/overview/network-graph/project-network-graph.tsx index df4d18bc..7d6be31f 100644 --- a/src/app/project/[projectId]/overview/network-graph/project-network-graph.tsx +++ b/src/app/project/[projectId]/overview/network-graph/project-network-graph.tsx @@ -6,16 +6,16 @@ import { GraphLegend } from './graph-legend'; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; import { useRouter, useSearchParams } from 'next/navigation'; import { - Background, - BackgroundVariant, - Controls, - MarkerType, - ReactFlow, - useNodesState, - type Node, - type NodeTypes, - type Connection, - type ReactFlowInstance, + Background, + BackgroundVariant, + Controls, + MarkerType, + ReactFlow, + useNodesState, + type Node, + type NodeTypes, + type Connection, + type ReactFlowInstance } from '@xyflow/react'; import '@xyflow/react/dist/style.css'; import { Cloud, Info, RotateCcw } from 'lucide-react'; @@ -43,10 +43,7 @@ import { deleteApp } from '@/app/project/[projectId]/actions'; import type { ProjectNetworkGraphPositions } from '@/shared/model/project-network-graph-layout.model'; import type { S3Target } from '@prisma/client'; import type { VolumeBackupExtendedModel } from '@/shared/model/volume-backup-extended.model'; -import { - type DrawerTab, - useProjectNetworkGraphDrawerSession, -} from './project-network-graph-drawer-session'; +import { type DrawerTab, useProjectNetworkGraphDrawerSession } from './project-network-graph-drawer-session'; import { AppDetailsDrawer } from '../../apps/details/app-details-drawer'; import { AgentSandboxDrawer } from '@/app/project/[projectId]/agents/details/agent-drawer'; import { deleteAgent } from '@/app/project/[projectId]/agents/details/agent-actions'; @@ -58,260 +55,293 @@ import { ProjectNetworkGraphAgentWorkloadNode } from './nodes/project-network-gr import { ProjectNetworkGraphInternetNode } from './nodes/project-network-graph-internet-node'; type ProjectNetworkGraphProps = { - apps: AppExtendedModel[]; - agents: AgentExtendedModel[]; - agentsAvailable: boolean; - projectId: string; - session: UserSession; - savedPositions: ProjectNetworkGraphPositions; - s3Targets: S3Target[]; - storageClasses: string[]; - runtimeClasses: string[]; - volumeBackupsByApp: Record; - gitSshPublicKeysByApp: Record; - agentTemplateInfoByAgent: Record; + apps: AppExtendedModel[]; + agents: AgentExtendedModel[]; + agentsAvailable: boolean; + projectId: string; + session: UserSession; + savedPositions: ProjectNetworkGraphPositions; + s3Targets: S3Target[]; + storageClasses: string[]; + runtimeClasses: string[]; + volumeBackupsByApp: Record; + gitSshPublicKeysByApp: Record; + agentTemplateInfoByAgent: Record; }; function stripWorkloadPrefix(nodeId: string | undefined) { - if (!nodeId) return undefined; - const separatorIndex = nodeId.indexOf(':'); - return separatorIndex >= 0 ? nodeId.slice(separatorIndex + 1) : nodeId; + if (!nodeId) { + return undefined; + } + const separatorIndex = nodeId.indexOf(':'); + return separatorIndex >= 0 ? nodeId.slice(separatorIndex + 1) : nodeId; } const nodeTypes = { - 'app-workload': ProjectNetworkGraphAppWorkloadNode, - 'agent-workload': ProjectNetworkGraphAgentWorkloadNode, - internet: ProjectNetworkGraphInternetNode, + 'app-workload': ProjectNetworkGraphAppWorkloadNode, + 'agent-workload': ProjectNetworkGraphAgentWorkloadNode, + internet: ProjectNetworkGraphInternetNode } satisfies NodeTypes; -function getInternalHostnames( - edge: NetworkGraphEdge, - drafts: Record, - apps: AppExtendedModel[], -) { - const hostnames = new Map(); - - for (const provenance of edge.ruleProvenance) { - const rule = drafts[provenance.ownerAppId]?.rules.find(item => item.key === provenance.ruleKey); - if (!rule) continue; +function getInternalHostnames(edge: NetworkGraphEdge, drafts: Record, apps: AppExtendedModel[]) { + const hostnames = new Map(); - const target = rule.type === 'INGRESS' - ? apps.find(app => app.id === provenance.ownerAppId) - : rule.targetType === 'APP' - ? { id: rule.targetId, projectId: rule.targetProjectId } - : undefined; - if (!target?.projectId) continue; + for (const provenance of edge.ruleProvenance) { + const rule = drafts[provenance.ownerAppId]?.rules.find((item) => item.key === provenance.ruleKey); + if (!rule) { + continue; + } - const hostname = InternalHostnameUtils.getInternalBaseUrlForApp(target, rule.port); - hostnames.set(hostname, { hostname, port: rule.port }); + const target = + rule.type === 'INGRESS' + ? apps.find((app) => app.id === provenance.ownerAppId) + : rule.targetType === 'APP' + ? { id: rule.targetId, projectId: rule.targetProjectId } + : undefined; + if (!target?.projectId) { + continue; } - return Array.from(hostnames.values()).sort((left, right) => left.port - right.port); + const hostname = InternalHostnameUtils.getInternalBaseUrlForApp(target, rule.port); + hostnames.set(hostname, { hostname, port: rule.port }); + } + + return Array.from(hostnames.values()).sort((left, right) => left.port - right.port); } const edgeTypes = { connection: ConnectionEdge }; export default function ProjectNetworkGraph(props: ProjectNetworkGraphProps) { - return ; + return ; } function ProjectNetworkGraphEditor({ - apps, - agents, - agentsAvailable, - projectId, - session, - savedPositions, - s3Targets, - storageClasses, - runtimeClasses, - volumeBackupsByApp, - gitSshPublicKeysByApp, - agentTemplateInfoByAgent, + apps, + agents, + agentsAvailable, + projectId, + session, + savedPositions, + s3Targets, + storageClasses, + runtimeClasses, + volumeBackupsByApp, + gitSshPublicKeysByApp, + agentTemplateInfoByAgent }: ProjectNetworkGraphProps) { - const router = useRouter(); - const searchParams = useSearchParams(); - const { openDialog } = useDialog(); - const { openConfirmDialog } = useConfirmDialog(); - const [drafts, setDrafts] = useState>(() => AppNetworkPolicyDraftUtils.collectionFromApps(apps)); - const [baseline, setBaseline] = useState>(() => AppNetworkPolicyDraftUtils.collectionFromApps(apps)); - const [saving, setSaving] = useState(false); - const [connectionSourceNodeId, setConnectionSourceNodeId] = useState(); - const [connectionTargetNodeId, setConnectionTargetNodeId] = useState(); - const [environmentAppId, setEnvironmentAppId] = useState(); - const [graphHeight, setGraphHeight] = useState(); - const graphContainerRef = useRef(null); - const drawerContentRef = useRef(null); - const reactFlowRef = useRef>(null); - const connectionTargetLeaveTimer = useRef | undefined>(undefined); - const graphApps = useMemo(() => apps.map(app => AppNetworkPolicyDraftUtils.applyToApp(app, drafts[app.id])), [apps, drafts]); - const canEditLayout = UserGroupUtils.sessionHasWriteAccessToProject(session, projectId); - const canCreateApps = UserGroupUtils.sessionCanCreateNewAppsForProject(session, projectId); - const canCreateAgents = agentsAvailable && UserGroupUtils.sessionCanCreateProjectWorkloadsForProject(session, projectId); - const { layout, saveNodePosition, resetLayout } = useProjectNetworkGraph(graphApps, agents, projectId, savedPositions); - const dirty = Object.keys(drafts).some(appId => !AppNetworkPolicyDraftUtils.equals(drafts[appId], baseline[appId])); - const localAppIds = useMemo(() => new Set(apps.map(app => app.id)), [apps]); - const localAgentIds = useMemo(() => new Set(agents.map(agent => agent.id)), [agents]); - const localWorkloadIds = useMemo(() => new Set([ - ...apps.map(app => app.id), - ...agents.map(agent => agent.id), - ]), [apps, agents]); - const drawerSession = useProjectNetworkGraphDrawerSession({ - searchParams, - appIds: localAppIds, - agentIds: localAgentIds, - }); - const { selectedNodeId } = drawerSession; - const writable = useCallback( - (appId: string) => UserGroupUtils.sessionHasWriteAccessForApp(session, appId), - [session], - ); - const writableAppIds = useMemo( - () => new Set(apps.filter(app => writable(app.id)).map(app => app.id)), - [apps, writable], - ); + const router = useRouter(); + const searchParams = useSearchParams(); + const { openDialog } = useDialog(); + const { openConfirmDialog } = useConfirmDialog(); + const [drafts, setDrafts] = useState>(() => AppNetworkPolicyDraftUtils.collectionFromApps(apps)); + const [baseline, setBaseline] = useState>(() => AppNetworkPolicyDraftUtils.collectionFromApps(apps)); + const [saving, setSaving] = useState(false); + const [connectionSourceNodeId, setConnectionSourceNodeId] = useState(); + const [connectionTargetNodeId, setConnectionTargetNodeId] = useState(); + const [environmentAppId, setEnvironmentAppId] = useState(); + const [graphHeight, setGraphHeight] = useState(); + const graphContainerRef = useRef(null); + const drawerContentRef = useRef(null); + const reactFlowRef = useRef>(null); + const connectionTargetLeaveTimer = useRef | undefined>(undefined); + const graphApps = useMemo(() => apps.map((app) => AppNetworkPolicyDraftUtils.applyToApp(app, drafts[app.id])), [apps, drafts]); + const canEditLayout = UserGroupUtils.sessionHasWriteAccessToProject(session, projectId); + const canCreateApps = UserGroupUtils.sessionCanCreateNewAppsForProject(session, projectId); + const canCreateAgents = agentsAvailable && UserGroupUtils.sessionCanCreateProjectWorkloadsForProject(session, projectId); + const { layout, saveNodePosition, resetLayout } = useProjectNetworkGraph(graphApps, agents, projectId, savedPositions); + const dirty = Object.keys(drafts).some((appId) => !AppNetworkPolicyDraftUtils.equals(drafts[appId], baseline[appId])); + const localAppIds = useMemo(() => new Set(apps.map((app) => app.id)), [apps]); + const localAgentIds = useMemo(() => new Set(agents.map((agent) => agent.id)), [agents]); + const localWorkloadIds = useMemo(() => new Set([...apps.map((app) => app.id), ...agents.map((agent) => agent.id)]), [apps, agents]); + const drawerSession = useProjectNetworkGraphDrawerSession({ + searchParams, + appIds: localAppIds, + agentIds: localAgentIds + }); + const { selectedNodeId } = drawerSession; + const writable = useCallback((appId: string) => UserGroupUtils.sessionHasWriteAccessForApp(session, appId), [session]); + const writableAppIds = useMemo(() => new Set(apps.filter((app) => writable(app.id)).map((app) => app.id)), [apps, writable]); - useLayoutEffect(() => { - const updateGraphHeight = () => { - const graphContainer = graphContainerRef.current; - if (!graphContainer) return; + useLayoutEffect(() => { + const updateGraphHeight = () => { + const graphContainer = graphContainerRef.current; + if (!graphContainer) { + return; + } - setGraphHeight(Math.max(0, window.innerHeight - graphContainer.getBoundingClientRect().top)); - }; - - updateGraphHeight(); - window.addEventListener('resize', updateGraphHeight); - return () => window.removeEventListener('resize', updateGraphHeight); - }, []); - const cancelConnectionTargetLeave = () => { - if (connectionTargetLeaveTimer.current) clearTimeout(connectionTargetLeaveTimer.current); + setGraphHeight(Math.max(0, window.innerHeight - graphContainer.getBoundingClientRect().top)); }; - const selectableTargets: NetworkPolicySelectableTarget[] = [ - ...apps.map(app => ({ - id: app.id, - name: app.name, - type: 'APP' as const, - appType: app.appType, - project: { id: app.projectId, name: app.project.name }, - })), - ...agents.map(agent => ({ - id: agent.id, - name: agent.name, - type: 'AGENT' as const, - project: { id: agent.projectId, name: agent.project.name }, - })), - ]; - const updateDraft = useCallback((appId: string, update: (draft: AppNetworkPolicyDraft) => AppNetworkPolicyDraft) => { - setDrafts(current => ({ ...current, [appId]: update(current[appId]) })); - }, []); - const openConnectionDialog = (sourceAppId: string, targetAppId: string) => { - const source = apps.find(app => app.id === sourceAppId); - const target = selectableTargets.find(item => item.id === targetAppId); - if (!source || !target || !writable(sourceAppId)) return; - openDialog( item.id !== sourceAppId)} - currentProject={{ id: source.projectId, name: source.project.name }} - initialTarget={target} - isDuplicate={rule => drafts[sourceAppId].rules.some(existing => NetworkPolicyRuleUtils.hasSameContent( - NetworkPolicyRuleUtils.fromEditRule(existing), NetworkPolicyRuleUtils.fromEditRule(rule), - ))} - onAdd={(rule: AppNetworkPolicyRuleEditModel) => updateDraft( - sourceAppId, - draft => AppNetworkPolicyDraftUtils.addRule(draft, rule, target), - )} - />, { maxWidth: 'max-w-md' }); - }; - const deleteConnection = useCallback((edgeId: string) => { - const edge = layout?.edges.find(item => item.id === edgeId); - const provenance = connectionDeletionProvenance(edge, writableAppIds); - if (!provenance) { return; } - setDrafts(current => AppNetworkPolicyDraftUtils.removeProvenance(current, provenance)); - }, [layout?.edges, writableAppIds]); - const deleteLocalApp = useCallback(async (appId: string) => { - if (!await openConfirmDialog({ - title: 'Delete App', - description: 'Are you sure you want to delete this app? All data will be lost and this action cannot be undone.', - })) return; - await Toast.fromAction(() => deleteApp(appId)); - }, [openConfirmDialog]); - const deleteLocalAgent = useCallback(async (agentId: string) => { - if (!await openConfirmDialog({ - title: 'Delete Agent Sandbox', - description: 'Are you sure you want to delete this Agent Sandbox? All data will be lost and this action cannot be undone.', - okButton: 'Delete Agent Sandbox', - })) return; - await Toast.fromAction(() => deleteAgent(agentId), 'Agent Sandbox deleted successfully.'); - }, [openConfirmDialog]); - const toggleInternetAccess = useCallback((appId: string) => { - updateDraft(appId, draft => ({ - ...draft, - allowInternetAccess: !draft.allowInternetAccess, - })); - }, [updateDraft]); - const toggleTraefikAccess = useCallback((appId: string) => { - updateDraft(appId, draft => ({ - ...draft, - allowTraefikAccess: !draft.allowTraefikAccess, - })); - }, [updateDraft]); - const saveChanges = async () => { - const changed = Object.values(drafts).filter(draft => !AppNetworkPolicyDraftUtils.equals(draft, baseline[draft.appId])); - if (!changed.length) { return; } - if (!await openConfirmDialog({ - title: 'Save & apply network policies?', - description: 'The changed network policies take effect immediately and will be deployed.', - okButton: 'Save & Apply', - cancelButton: 'Cancel' - })) { return; } - setSaving(true); - try { - await Toast.fromAction(async () => { - for (const draft of changed) { - const result = await saveAppNetworkPolicyConfiguration(undefined, AppNetworkPolicyDraftUtils.toConfiguration(draft)); - if (result.status !== 'success') return result; - } - return { status: 'success' as const }; - }, 'Network policies saved and applied.', 'Applying network policies...'); - setBaseline(drafts); - router.refresh(); - } finally { - setSaving(false); + updateGraphHeight(); + window.addEventListener('resize', updateGraphHeight); + return () => window.removeEventListener('resize', updateGraphHeight); + }, []); + const cancelConnectionTargetLeave = () => { + if (connectionTargetLeaveTimer.current) { + clearTimeout(connectionTargetLeaveTimer.current); + } + }; + const selectableTargets: NetworkPolicySelectableTarget[] = [ + ...apps.map((app) => ({ + id: app.id, + name: app.name, + type: 'APP' as const, + appType: app.appType, + project: { id: app.projectId, name: app.project.name } + })), + ...agents.map((agent) => ({ + id: agent.id, + name: agent.name, + type: 'AGENT' as const, + project: { id: agent.projectId, name: agent.project.name } + })) + ]; + + const updateDraft = useCallback((appId: string, update: (draft: AppNetworkPolicyDraft) => AppNetworkPolicyDraft) => { + setDrafts((current) => ({ ...current, [appId]: update(current[appId]) })); + }, []); + const openConnectionDialog = (sourceAppId: string, targetAppId: string) => { + const source = apps.find((app) => app.id === sourceAppId); + const target = selectableTargets.find((item) => item.id === targetAppId); + if (!source || !target || !writable(sourceAppId)) { + return; + } + openDialog( + item.id !== sourceAppId)} + currentProject={{ id: source.projectId, name: source.project.name }} + initialTarget={target} + isDuplicate={(rule) => + drafts[sourceAppId].rules.some((existing) => + NetworkPolicyRuleUtils.hasSameContent(NetworkPolicyRuleUtils.fromEditRule(existing), NetworkPolicyRuleUtils.fromEditRule(rule)) + ) } - }; - const discardChanges = () => { - setDrafts(baseline); - setConnectionSourceNodeId(undefined); - setConnectionTargetNodeId(undefined); - }; - const projectedNodes: Node[] = useMemo(() => (layout?.nodes ?? []).map(node => { + onAdd={(rule: AppNetworkPolicyRuleEditModel) => updateDraft(sourceAppId, (draft) => AppNetworkPolicyDraftUtils.addRule(draft, rule, target))} + />, + { maxWidth: 'max-w-md' } + ); + }; + const deleteConnection = useCallback( + (edgeId: string) => { + const edge = layout?.edges.find((item) => item.id === edgeId); + const provenance = connectionDeletionProvenance(edge, writableAppIds); + if (!provenance) { + return; + } + setDrafts((current) => AppNetworkPolicyDraftUtils.removeProvenance(current, provenance)); + }, + [layout?.edges, writableAppIds] + ); + const deleteLocalApp = useCallback( + async (appId: string) => { + if ( + !(await openConfirmDialog({ + title: 'Delete App', + description: 'Are you sure you want to delete this app? All data will be lost and this action cannot be undone.' + })) + ) { + return; + } + await Toast.fromAction(() => deleteApp(appId)); + }, + [openConfirmDialog] + ); + const deleteLocalAgent = useCallback( + async (agentId: string) => { + if ( + !(await openConfirmDialog({ + title: 'Delete Agent Sandbox', + description: 'Are you sure you want to delete this Agent Sandbox? All data will be lost and this action cannot be undone.', + okButton: 'Delete Agent Sandbox' + })) + ) { + return; + } + await Toast.fromAction(() => deleteAgent(agentId), 'Agent Sandbox deleted successfully.'); + }, + [openConfirmDialog] + ); + const toggleInternetAccess = useCallback( + (appId: string) => { + updateDraft(appId, (draft) => ({ + ...draft, + allowInternetAccess: !draft.allowInternetAccess + })); + }, + [updateDraft] + ); + const toggleTraefikAccess = useCallback( + (appId: string) => { + updateDraft(appId, (draft) => ({ + ...draft, + allowTraefikAccess: !draft.allowTraefikAccess + })); + }, + [updateDraft] + ); + const saveChanges = async () => { + const changed = Object.values(drafts).filter((draft) => !AppNetworkPolicyDraftUtils.equals(draft, baseline[draft.appId])); + if (!changed.length) { + return; + } + if ( + !(await openConfirmDialog({ + title: 'Save & apply network policies?', + description: 'The changed network policies take effect immediately and will be deployed.', + okButton: 'Save & Apply', + cancelButton: 'Cancel' + })) + ) { + return; + } + setSaving(true); + try { + await Toast.fromAction( + async () => { + for (const draft of changed) { + const result = await saveAppNetworkPolicyConfiguration(undefined, AppNetworkPolicyDraftUtils.toConfiguration(draft)); + if (result.status !== 'success') { + return result; + } + } + return { status: 'success' as const }; + }, + 'Network policies saved and applied.', + 'Applying network policies...' + ); + setBaseline(drafts); + router.refresh(); + } finally { + setSaving(false); + } + }; + const discardChanges = () => { + setDrafts(baseline); + setConnectionSourceNodeId(undefined); + setConnectionTargetNodeId(undefined); + }; + const projectedNodes: Node[] = useMemo( + () => + (layout?.nodes ?? []).map((node) => { const appId = node.kind === 'APP' ? node.id.replace('APP:', '') : undefined; - const app = appId ? apps.find(item => item.id === appId) : undefined; + const app = appId ? apps.find((item) => item.id === appId) : undefined; const draft = app ? drafts[app.id] : undefined; - const appRole = app - ? UserGroupUtils.getRolePermissionForApp(session, app.id) ?? undefined - : undefined; + const appRole = app ? (UserGroupUtils.getRolePermissionForApp(session, app.id) ?? undefined) : undefined; const agentId = node.kind === 'AGENT' ? node.id.replace('AGENT:', '') : undefined; - const agent = agentId ? agents.find(item => item.id === agentId) : undefined; - const agentRole = agent - ? UserGroupUtils.getRolePermissionForProjectWorkload(session, agent.id) ?? undefined - : undefined; + const agent = agentId ? agents.find((item) => item.id === agentId) : undefined; + const agentRole = agent ? (UserGroupUtils.getRolePermissionForProjectWorkload(session, agent.id) ?? undefined) : undefined; return { - id: node.id, - type: node.kind === 'INTERNET' - ? 'internet' - : node.kind === 'AGENT' - ? 'agent-workload' - : 'app-workload', - position: node.position, - data: { - ...node, - connectionInProgress: !!connectionSourceNodeId, - connectionTarget: node.id === connectionTargetNodeId, - selected: node.id === selectedNodeId, - appContextMenu: app && draft && appRole === RolePermissionEnum.READWRITE ? { + id: node.id, + type: node.kind === 'INTERNET' ? 'internet' : node.kind === 'AGENT' ? 'agent-workload' : 'app-workload', + position: node.position, + data: { + ...node, + connectionInProgress: !!connectionSourceNodeId, + connectionTarget: node.id === connectionTargetNodeId, + selected: node.id === selectedNodeId, + appContextMenu: + app && draft && appRole === RolePermissionEnum.READWRITE + ? { app, role: appRole, allowInternetAccess: draft.allowInternetAccess, @@ -319,275 +349,330 @@ function ProjectNetworkGraphEditor({ allowTraefikAccess: draft.allowTraefikAccess, onToggleTraefikAccess: () => toggleTraefikAccess(app.id), onOpenDrawerTab: (tab: DrawerTab) => { - drawerSession.openAppTab(app.id, tab); + drawerSession.openAppTab(app.id, tab); }, onShowEnvironment: () => { - setEnvironmentAppId(app.id); - drawerSession.openAppTab(app.id, 'settings'); + setEnvironmentAppId(app.id); + drawerSession.openAppTab(app.id, 'settings'); }, - onDelete: () => void deleteLocalApp(app.id), - } : undefined, - agentContextMenu: agent && agentRole === RolePermissionEnum.READWRITE ? { + onDelete: () => void deleteLocalApp(app.id) + } + : undefined, + agentContextMenu: + agent && agentRole === RolePermissionEnum.READWRITE + ? { agent, onOpenDrawerTab: (tab: AgentDrawerTab) => drawerSession.openAgentTab(agent.id, tab), - onDelete: () => void deleteLocalAgent(agent.id), - } : undefined, - connectedToSelection: !selectedNodeId || (layout?.edges ?? []).some(edge => - (edge.source === selectedNodeId && edge.target === node.id) - || (edge.target === selectedNodeId && edge.source === node.id), - ), - }, + onDelete: () => void deleteLocalAgent(agent.id) + } + : undefined, + connectedToSelection: + !selectedNodeId || + (layout?.edges ?? []).some( + (edge) => (edge.source === selectedNodeId && edge.target === node.id) || (edge.target === selectedNodeId && edge.source === node.id) + ) + } }; - }), [agents, apps, connectionSourceNodeId, connectionTargetNodeId, deleteLocalAgent, deleteLocalApp, drafts, drawerSession, layout?.edges, layout?.nodes, selectedNodeId, session, toggleInternetAccess, toggleTraefikAccess]); + }), + [ + agents, + apps, + connectionSourceNodeId, + connectionTargetNodeId, + deleteLocalAgent, + deleteLocalApp, + drafts, + drawerSession, + layout?.edges, + layout?.nodes, + selectedNodeId, + session, + toggleInternetAccess, + toggleTraefikAccess + ] + ); - const [nodes, setNodes, onNodesChange] = useNodesState(projectedNodes); - useEffect(() => setNodes(projectedNodes), [projectedNodes, setNodes]); + const [nodes, setNodes, onNodesChange] = useNodesState(projectedNodes); + useEffect(() => setNodes(projectedNodes), [projectedNodes, setNodes]); - const edges = useMemo(() => (layout?.edges ?? []).map(edge => { + const edges = useMemo( + () => + (layout?.edges ?? []).map((edge) => { const presentation = graphEdgePresentation(edge); const deletionProvenance = connectionDeletionProvenance(edge, writableAppIds); const internalHostnames = getInternalHostnames(edge, drafts, apps); return { - id: edge.id, - source: edge.source, - target: edge.target, - sourceHandle: presentation.sourceHandle, - targetHandle: presentation.targetHandle, - type: edge.direction === 'CONNECTION' && (deletionProvenance || internalHostnames.length > 0) - ? 'connection' - : 'smoothstep', - data: edge.direction === 'CONNECTION' && (deletionProvenance || internalHostnames.length > 0) - ? { - ...(deletionProvenance ? { onDelete: () => deleteConnection(edge.id) } : {}), - internalHostnames, + id: edge.id, + source: edge.source, + target: edge.target, + sourceHandle: presentation.sourceHandle, + targetHandle: presentation.targetHandle, + type: edge.direction === 'CONNECTION' && (deletionProvenance || internalHostnames.length > 0) ? 'connection' : 'smoothstep', + data: + edge.direction === 'CONNECTION' && (deletionProvenance || internalHostnames.length > 0) + ? { + ...(deletionProvenance ? { onDelete: () => deleteConnection(edge.id) } : {}), + internalHostnames } - : undefined, - pathOptions: { offset: 20 }, - markerStart: edge.internetIngress ? { type: MarkerType.ArrowClosed, color: presentation.color, width: 16, height: 16 } : undefined, - markerEnd: edge.direction === 'INTERNET_CONNECTION' - ? edge.internetEgress ? { type: MarkerType.ArrowClosed, color: presentation.color, width: 16, height: 16 } : undefined - : { type: MarkerType.ArrowClosed, color: presentation.color, width: 16, height: 16 }, - style: { - stroke: presentation.color, - strokeWidth: selectedNodeId && (edge.source === selectedNodeId || edge.target === selectedNodeId) ? 2.5 : 1.5, - strokeDasharray: presentation.dashed ? '5 4' : undefined, - opacity: selectedNodeId && edge.source !== selectedNodeId && edge.target !== selectedNodeId ? 0.2 : 1, - }, - label: presentation.label, - labelStyle: { fill: 'var(--muted-foreground)', fontSize: 10, fontWeight: 600 }, - labelBgStyle: { fill: 'var(--card)', fillOpacity: 0.9, stroke: 'var(--border)', strokeWidth: 1 }, - labelBgPadding: [6, 3] as [number, number], - labelBgBorderRadius: 6, + : undefined, + pathOptions: { offset: 20 }, + markerStart: edge.internetIngress ? { type: MarkerType.ArrowClosed, color: presentation.color, width: 16, height: 16 } : undefined, + markerEnd: + edge.direction === 'INTERNET_CONNECTION' + ? edge.internetEgress + ? { type: MarkerType.ArrowClosed, color: presentation.color, width: 16, height: 16 } + : undefined + : { type: MarkerType.ArrowClosed, color: presentation.color, width: 16, height: 16 }, + style: { + stroke: presentation.color, + strokeWidth: selectedNodeId && (edge.source === selectedNodeId || edge.target === selectedNodeId) ? 2.5 : 1.5, + strokeDasharray: presentation.dashed ? '5 4' : undefined, + opacity: selectedNodeId && edge.source !== selectedNodeId && edge.target !== selectedNodeId ? 0.2 : 1 + }, + label: presentation.label, + labelStyle: { fill: 'var(--muted-foreground)', fontSize: 10, fontWeight: 600 }, + labelBgStyle: { fill: 'var(--card)', fillOpacity: 0.9, stroke: 'var(--border)', strokeWidth: 1 }, + labelBgPadding: [6, 3] as [number, number], + labelBgBorderRadius: 6 }; - }), [apps, deleteConnection, drafts, layout?.edges, selectedNodeId, writableAppIds]); + }), + [apps, deleteConnection, drafts, layout?.edges, selectedNodeId, writableAppIds] + ); - const selectedNode = nodes.find(node => node.id === selectedNodeId)?.data as NetworkGraphNode | undefined; - const selectedApp = selectedNode?.kind === 'APP' ? apps.find(app => app.id === selectedNode.id.replace('APP:', '')) : undefined; - const selectedAppRole = selectedApp ? UserGroupUtils.getRolePermissionForApp(session, selectedApp.id) ?? undefined : undefined; - const selectedAgent = selectedNode?.kind === 'AGENT' ? agents.find(agent => agent.id === selectedNode.id.replace('AGENT:', '')) : undefined; - const selectedAgentRole = selectedAgent ? UserGroupUtils.getRolePermissionForProjectWorkload(session, selectedAgent.id) ?? undefined : undefined; + const selectedNode = nodes.find((node) => node.id === selectedNodeId)?.data as NetworkGraphNode | undefined; + const selectedApp = selectedNode?.kind === 'APP' ? apps.find((app) => app.id === selectedNode.id.replace('APP:', '')) : undefined; + const selectedAppRole = selectedApp ? (UserGroupUtils.getRolePermissionForApp(session, selectedApp.id) ?? undefined) : undefined; + const selectedAgent = selectedNode?.kind === 'AGENT' ? agents.find((agent) => agent.id === selectedNode.id.replace('AGENT:', '')) : undefined; + const selectedAgentRole = selectedAgent ? (UserGroupUtils.getRolePermissionForProjectWorkload(session, selectedAgent.id) ?? undefined) : undefined; - useEffect(() => { - if (!selectedNodeId || (selectedNode?.kind !== 'APP' && selectedNode?.kind !== 'AGENT')) return; - if (!window.matchMedia('(min-width: 1024px)').matches) return; + useEffect(() => { + if (!selectedNodeId || (selectedNode?.kind !== 'APP' && selectedNode?.kind !== 'AGENT')) { + return; + } + if (!window.matchMedia('(min-width: 1024px)').matches) { + return; + } - const animationFrame = requestAnimationFrame(() => { - const reactFlow = reactFlowRef.current; - const graphContainer = graphContainerRef.current; - const drawerContent = drawerContentRef.current; - const selectedReactFlowNode = reactFlow?.getNode(selectedNodeId); - if (!reactFlow || !graphContainer || !drawerContent || !selectedReactFlowNode) return; + const animationFrame = requestAnimationFrame(() => { + const reactFlow = reactFlowRef.current; + const graphContainer = graphContainerRef.current; + const drawerContent = drawerContentRef.current; + const selectedReactFlowNode = reactFlow?.getNode(selectedNodeId); + if (!reactFlow || !graphContainer || !drawerContent || !selectedReactFlowNode) { + return; + } - const graphBounds = graphContainer.getBoundingClientRect(); - const drawerWidth = drawerContent.getBoundingClientRect().width; - const nodeWidth = selectedReactFlowNode.measured?.width ?? 240; - const nodeHeight = selectedReactFlowNode.measured?.height ?? 68; - const viewport = getFocusedNodeViewport({ - node: { - x: selectedReactFlowNode.position.x, - y: selectedReactFlowNode.position.y, - width: nodeWidth, - height: nodeHeight, - }, - graphWidth: graphBounds.width, - graphHeight: graphBounds.height, - drawerWidth, - }); + const graphBounds = graphContainer.getBoundingClientRect(); + const drawerWidth = drawerContent.getBoundingClientRect().width; + const nodeWidth = selectedReactFlowNode.measured?.width ?? 240; + const nodeHeight = selectedReactFlowNode.measured?.height ?? 68; + const viewport = getFocusedNodeViewport({ + node: { + x: selectedReactFlowNode.position.x, + y: selectedReactFlowNode.position.y, + width: nodeWidth, + height: nodeHeight + }, + graphWidth: graphBounds.width, + graphHeight: graphBounds.height, + drawerWidth + }); - void reactFlow.setViewport(viewport, { duration: 300 }); - }); + void reactFlow.setViewport(viewport, { duration: 300 }); + }); - return () => cancelAnimationFrame(animationFrame); - }, [selectedNode, selectedNodeId]); + return () => cancelAnimationFrame(animationFrame); + }, [selectedNode, selectedNodeId]); - return ( -
-
+
+
+ + + + Legend + + } + /> + + + + + {canEditLayout && ( + } /> - - - - - {canEditLayout && } -
- - { reactFlowRef.current = instance; }} - nodes={nodes} - edges={edges} - onNodesChange={onNodesChange} - nodeTypes={nodeTypes} - edgeTypes={edgeTypes} - fitView - fitViewOptions={{ padding: 0.2, maxZoom: 1.1 }} - minZoom={0.3} - maxZoom={1.5} - zoomOnScroll - zoomOnPinch={false} - zoomOnDoubleClick={false} - preventScrolling - nodesDraggable={canEditLayout} - nodesConnectable - elementsSelectable={false} - isValidConnection={(connection: Connection) => { - const source = stripWorkloadPrefix(connection.source); - const target = stripWorkloadPrefix(connection.target); - return connection.sourceHandle === 'source-egress' - && connection.targetHandle === 'target-ingress' - && !!source - && !!target - && source !== target - && localAppIds.has(source) - && localWorkloadIds.has(target) - && writable(source); - }} - onConnect={(connection: Connection) => { - const source = stripWorkloadPrefix(connection.source); - const target = stripWorkloadPrefix(connection.target); - if (source && target) openConnectionDialog(source, target); - }} - onConnectStart={(_event, { nodeId, handleId }) => { - if (handleId === 'source-egress') { - cancelConnectionTargetLeave(); - setConnectionSourceNodeId(nodeId ?? undefined); - } - }} - onConnectEnd={() => { - cancelConnectionTargetLeave(); - setConnectionSourceNodeId(undefined); - setConnectionTargetNodeId(undefined); - }} - onPaneClick={() => { - }} - onNodeMouseEnter={(_event, node) => { - cancelConnectionTargetLeave(); - const source = stripWorkloadPrefix(connectionSourceNodeId); - const target = stripWorkloadPrefix(node.id); - if (source && target && source !== target && localAppIds.has(source) && localWorkloadIds.has(target) && writable(source)) { - setConnectionTargetNodeId(node.id); - } - }} - onNodeMouseLeave={(_event, node) => { - cancelConnectionTargetLeave(); - connectionTargetLeaveTimer.current = setTimeout(() => { - setConnectionTargetNodeId(current => current === node.id ? undefined : current); - }, 100); - }} - onNodeDragStop={canEditLayout ? (_event, node) => void saveNodePosition(node.id, node.position) : undefined} - style={{ - '--xy-controls-button-background-color': 'var(--secondary)', - '--xy-controls-button-background-color-hover': 'var(--accent)', - '--xy-controls-button-color': 'var(--secondary-foreground)', - '--xy-controls-button-border-color': 'var(--border)', - '--xy-controls-box-shadow': '0 1px 3px 0 rgb(0 0 0 / 0.1)', - } as CSSProperties} - onNodeClick={(_event, node) => { - const data = node.data as NetworkGraphNode; - if (data.kind === 'INTERNET') return; - drawerSession.selectNode(data); - }} - > - - - - - {dirty && ( - - - - - - - )} - {edges.length === 0 && nodes.length === 0 &&
-

No active network policy connections yet.

-
} - {selectedNode && selectedNode.kind === 'APP' && { - if (selectedApp) drawerSession.openAppTab(selectedApp.id, tab); - }} - openEnvironment={environmentAppId === selectedApp?.id} - onEnvironmentOpened={() => setEnvironmentAppId(undefined)} - />} - {selectedNode && selectedNode.kind === 'AGENT' && { - if (selectedAgent) drawerSession.openAgentTab(selectedAgent.id, tab); - }} - />} -
+ + Reset + + )}
- ); + + { + reactFlowRef.current = instance; + }} + nodes={nodes} + edges={edges} + onNodesChange={onNodesChange} + nodeTypes={nodeTypes} + edgeTypes={edgeTypes} + fitView + fitViewOptions={{ padding: 0.2, maxZoom: 1.1 }} + minZoom={0.3} + maxZoom={1.5} + zoomOnScroll + zoomOnPinch={false} + zoomOnDoubleClick={false} + preventScrolling + nodesDraggable={canEditLayout} + nodesConnectable + elementsSelectable={false} + isValidConnection={(connection: Connection) => { + const source = stripWorkloadPrefix(connection.source); + const target = stripWorkloadPrefix(connection.target); + return ( + connection.sourceHandle === 'source-egress' && + connection.targetHandle === 'target-ingress' && + !!source && + !!target && + source !== target && + localAppIds.has(source) && + localWorkloadIds.has(target) && + writable(source) + ); + }} + onConnect={(connection: Connection) => { + const source = stripWorkloadPrefix(connection.source); + const target = stripWorkloadPrefix(connection.target); + if (source && target) { + openConnectionDialog(source, target); + } + }} + onConnectStart={(_event, { nodeId, handleId }) => { + if (handleId === 'source-egress') { + cancelConnectionTargetLeave(); + setConnectionSourceNodeId(nodeId ?? undefined); + } + }} + onConnectEnd={() => { + cancelConnectionTargetLeave(); + setConnectionSourceNodeId(undefined); + setConnectionTargetNodeId(undefined); + }} + onPaneClick={() => {}} + onNodeMouseEnter={(_event, node) => { + cancelConnectionTargetLeave(); + const source = stripWorkloadPrefix(connectionSourceNodeId); + const target = stripWorkloadPrefix(node.id); + if (source && target && source !== target && localAppIds.has(source) && localWorkloadIds.has(target) && writable(source)) { + setConnectionTargetNodeId(node.id); + } + }} + onNodeMouseLeave={(_event, node) => { + cancelConnectionTargetLeave(); + connectionTargetLeaveTimer.current = setTimeout(() => { + setConnectionTargetNodeId((current) => (current === node.id ? undefined : current)); + }, 100); + }} + onNodeDragStop={canEditLayout ? (_event, node) => void saveNodePosition(node.id, node.position) : undefined} + style={ + { + '--xy-controls-button-background-color': 'var(--secondary)', + '--xy-controls-button-background-color-hover': 'var(--accent)', + '--xy-controls-button-color': 'var(--secondary-foreground)', + '--xy-controls-button-border-color': 'var(--border)', + '--xy-controls-box-shadow': '0 1px 3px 0 rgb(0 0 0 / 0.1)' + } as CSSProperties + } + onNodeClick={(_event, node) => { + const data = node.data as NetworkGraphNode; + if (data.kind === 'INTERNET') { + return; + } + drawerSession.selectNode(data); + }} + > + + + + + {dirty && ( + + + + + + + )} + {edges.length === 0 && nodes.length === 0 && ( +
+ +

No active network policy connections yet.

+
+ )} + {selectedNode && selectedNode.kind === 'APP' && ( + { + if (selectedApp) { + drawerSession.openAppTab(selectedApp.id, tab); + } + }} + openEnvironment={environmentAppId === selectedApp?.id} + onEnvironmentOpened={() => setEnvironmentAppId(undefined)} + /> + )} + {selectedNode && selectedNode.kind === 'AGENT' && ( + { + if (selectedAgent) { + drawerSession.openAgentTab(selectedAgent.id, tab); + } + }} + /> + )} +
+
+ ); } diff --git a/src/app/project/[projectId]/overview/network-graph/use-project-network-graph.ts b/src/app/project/[projectId]/overview/network-graph/use-project-network-graph.ts index 2fd8da0b..9eec7ecb 100644 --- a/src/app/project/[projectId]/overview/network-graph/use-project-network-graph.ts +++ b/src/app/project/[projectId]/overview/network-graph/use-project-network-graph.ts @@ -15,80 +15,92 @@ export type PositionedProjectNetworkGraph = Omit { - const layout = await elk.layout({ - id: 'root', - layoutOptions: { - 'elk.algorithm': 'layered', 'elk.direction': 'RIGHT', - 'elk.layered.nodePlacement.strategy': 'NETWORK_SIMPLEX', - 'elk.layered.crossingMinimization.strategy': 'LAYER_SWEEP', - 'elk.spacing.nodeNode': '70', 'elk.layered.spacing.nodeNodeBetweenLayers': '150', - }, - children: graph.nodes.map(node => ({ id: node.id, width: node.kind === 'INTERNET' ? 96 : 240, height: node.kind === 'INTERNET' ? 96 : 68 })), - edges: graph.edges.map(edge => ({ id: edge.id, sources: [edge.source], targets: [edge.target] })), - }); - const positions = new Map(layout.children?.map(node => [node.id, node]) ?? []); - return { ...graph, nodes: graph.nodes.map(node => ({ ...node, position: { x: positions.get(node.id)?.x ?? 0, y: positions.get(node.id)?.y ?? 0 } })) }; + const layout = await elk.layout({ + id: 'root', + layoutOptions: { + 'elk.algorithm': 'layered', + 'elk.direction': 'RIGHT', + 'elk.layered.nodePlacement.strategy': 'NETWORK_SIMPLEX', + 'elk.layered.crossingMinimization.strategy': 'LAYER_SWEEP', + 'elk.spacing.nodeNode': '70', + 'elk.layered.spacing.nodeNodeBetweenLayers': '150' + }, + children: graph.nodes.map((node) => ({ id: node.id, width: node.kind === 'INTERNET' ? 96 : 240, height: node.kind === 'INTERNET' ? 96 : 68 })), + edges: graph.edges.map((edge) => ({ id: edge.id, sources: [edge.source], targets: [edge.target] })) + }); + const positions = new Map(layout.children?.map((node) => [node.id, node]) ?? []); + return { ...graph, nodes: graph.nodes.map((node) => ({ ...node, position: { x: positions.get(node.id)?.x ?? 0, y: positions.get(node.id)?.y ?? 0 } })) }; } export function applySavedNetworkGraphPositions( - layout: PositionedProjectNetworkGraph, - savedPositions: ProjectNetworkGraphPositions, + layout: PositionedProjectNetworkGraph, + savedPositions: ProjectNetworkGraphPositions ): PositionedProjectNetworkGraph { - return { - ...layout, - nodes: layout.nodes.map(node => ({ - ...node, - position: savedPositions[node.id] ?? node.position, - })), - }; + return { + ...layout, + nodes: layout.nodes.map((node) => ({ + ...node, + position: savedPositions[node.id] ?? node.position + })) + }; } export function useProjectNetworkGraph( - apps: AppExtendedModel[], - agents: AgentExtendedModel[], - projectId: string, - savedPositions: ProjectNetworkGraphPositions, + apps: AppExtendedModel[], + agents: AgentExtendedModel[], + projectId: string, + savedPositions: ProjectNetworkGraphPositions ) { - const graph = useMemo(() => buildProjectNetworkGraph(apps, agents), [apps, agents]); - const [layout, setLayout] = useState(); - const requestId = useRef(0); - const persistedPositions = useRef(savedPositions); - const loadLayout = useCallback(async (useSavedPositions: boolean) => { - const id = ++requestId.current; - const nextLayout = await layoutGraph(graph); - if (id !== requestId.current) return; - const positions = useSavedPositions ? persistedPositions.current : {}; - setLayout(applySavedNetworkGraphPositions(nextLayout, positions)); - }, [graph]); + const graph = useMemo(() => buildProjectNetworkGraph(apps, agents), [apps, agents]); + const [layout, setLayout] = useState(); + const requestId = useRef(0); + const persistedPositions = useRef(savedPositions); + const loadLayout = useCallback( + async (useSavedPositions: boolean) => { + const id = ++requestId.current; + const nextLayout = await layoutGraph(graph); + if (id !== requestId.current) { + return; + } + const positions = useSavedPositions ? persistedPositions.current : {}; + setLayout(applySavedNetworkGraphPositions(nextLayout, positions)); + }, + [graph] + ); - useEffect(() => { - persistedPositions.current = savedPositions; - void loadLayout(true); - }, [loadLayout, savedPositions]); + useEffect(() => { + persistedPositions.current = savedPositions; + void loadLayout(true); + }, [loadLayout, savedPositions]); - const updateNodePosition = useCallback((id: string, position: NetworkGraphPosition) => { - setLayout(current => current && ({ ...current, nodes: current.nodes.map(node => node.id === id ? { ...node, position } : node) })); - }, []); - const saveNodePosition = useCallback(async (id: string, position: NetworkGraphPosition) => { - const previousPosition = layout?.nodes.find(node => node.id === id)?.position; - updateNodePosition(id, position); - const result = await saveProjectNetworkGraphPosition(projectId, { nodeId: id, ...position }); - if (result.status === 'success') { - persistedPositions.current = { ...persistedPositions.current, [id]: position }; - return; - } - if (previousPosition) updateNodePosition(id, previousPosition); - toast.error(result.message ?? 'Could not save the network graph layout.'); - }, [layout?.nodes, projectId, updateNodePosition]); - const resetLayout = useCallback(async () => { - const result = await resetProjectNetworkGraphLayout(projectId); - if (result.status !== 'success') { - toast.error(result.message ?? 'Could not reset the network graph layout.'); - return; - } - persistedPositions.current = {}; - await loadLayout(false); - }, [loadLayout, projectId]); + const updateNodePosition = useCallback((id: string, position: NetworkGraphPosition) => { + setLayout((current) => current && { ...current, nodes: current.nodes.map((node) => (node.id === id ? { ...node, position } : node)) }); + }, []); + const saveNodePosition = useCallback( + async (id: string, position: NetworkGraphPosition) => { + const previousPosition = layout?.nodes.find((node) => node.id === id)?.position; + updateNodePosition(id, position); + const result = await saveProjectNetworkGraphPosition(projectId, { nodeId: id, ...position }); + if (result.status === 'success') { + persistedPositions.current = { ...persistedPositions.current, [id]: position }; + return; + } + if (previousPosition) { + updateNodePosition(id, previousPosition); + } + toast.error(result.message ?? 'Could not save the network graph layout.'); + }, + [layout?.nodes, projectId, updateNodePosition] + ); + const resetLayout = useCallback(async () => { + const result = await resetProjectNetworkGraphLayout(projectId); + if (result.status !== 'success') { + toast.error(result.message ?? 'Could not reset the network graph layout.'); + return; + } + persistedPositions.current = {}; + await loadLayout(false); + }, [loadLayout, projectId]); - return { layout, saveNodePosition, resetLayout }; + return { layout, saveNodePosition, resetLayout }; } diff --git a/src/app/project/[projectId]/overview/project-overview.tsx b/src/app/project/[projectId]/overview/project-overview.tsx index e74ce51d..4d2ec73b 100644 --- a/src/app/project/[projectId]/overview/project-overview.tsx +++ b/src/app/project/[projectId]/overview/project-overview.tsx @@ -1,20 +1,20 @@ 'use client'; -import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; -import ProjectNetworkGraph from "./network-graph/project-network-graph"; -import { UserSession } from "@/shared/model/sim-session.model"; -import { useEffect, useState } from "react"; -import { useSearchParams } from "next/navigation"; -import { Table, Network, Container } from "lucide-react"; -import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty"; -import { UserGroupUtils } from "@/shared/utils/role.utils"; -import CreateProjectActions from "../create-project-actions"; -import PageTitle from "@/components/custom/page-title"; -import { TabNavigationUtils } from "@/frontend/utils/tab-navigation.utils"; -import { AppExtendedModel } from "@/shared/model/app-extended.model"; -import { AgentExtendedModel } from "@/shared/model/agent-extended.model"; +import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; +import ProjectNetworkGraph from './network-graph/project-network-graph'; +import { UserSession } from '@/shared/model/sim-session.model'; +import { useEffect, useState } from 'react'; +import { useSearchParams } from 'next/navigation'; +import { Table, Network, Container } from 'lucide-react'; +import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty'; +import { UserGroupUtils } from '@/shared/utils/role.utils'; +import CreateProjectActions from '../create-project-actions'; +import PageTitle from '@/components/custom/page-title'; +import { TabNavigationUtils } from '@/frontend/utils/tab-navigation.utils'; +import { AppExtendedModel } from '@/shared/model/app-extended.model'; +import { AgentExtendedModel } from '@/shared/model/agent-extended.model'; import type { ProjectNetworkGraphPositions } from '@/shared/model/project-network-graph-layout.model'; -import { useDialog } from "@/frontend/states/zustand.states"; +import { useDialog } from '@/frontend/states/zustand.states'; import NewNetworkPolicyExplanationDialog from '../apps/create/new-network-policy-explanation-dialog'; import type { S3Target } from '@prisma/client'; import type { VolumeBackupExtendedModel } from '@/shared/model/volume-backup-extended.model'; @@ -22,159 +22,157 @@ import type { AgentSandboxTemplateInfo } from '@/shared/model/agent-sandbox-temp import WorkloadsTable from './workloads-table'; interface ProjectOverviewProps { - apps: AppExtendedModel[]; - agents: AgentExtendedModel[]; - agentsAvailable: boolean; - session: UserSession; - projectId: string; - projectName: string; - networkGraphPositions: ProjectNetworkGraphPositions; - showNewNetworkPolicyExplanation: boolean; - s3Targets: S3Target[]; - storageClasses: string[]; - runtimeClasses: string[]; - volumeBackupsByApp: Record; - gitSshPublicKeysByApp: Record; - agentTemplateInfoByAgent: Record; + apps: AppExtendedModel[]; + agents: AgentExtendedModel[]; + agentsAvailable: boolean; + session: UserSession; + projectId: string; + projectName: string; + networkGraphPositions: ProjectNetworkGraphPositions; + showNewNetworkPolicyExplanation: boolean; + s3Targets: S3Target[]; + storageClasses: string[]; + runtimeClasses: string[]; + volumeBackupsByApp: Record; + gitSshPublicKeysByApp: Record; + agentTemplateInfoByAgent: Record; } type ProjectOverviewTab = 'table' | 'graph'; function isProjectOverviewTab(value: string | null): value is ProjectOverviewTab { - return value === 'table' || value === 'graph'; + return value === 'table' || value === 'graph'; } function tabStorageKey() { - return `quickstack:project-overview-tab`; + return `quickstack:project-overview-tab`; } export default function AppProjectOverview({ - apps, - agents, - agentsAvailable, - session, - projectId, - projectName, - networkGraphPositions, - showNewNetworkPolicyExplanation, - s3Targets, - storageClasses, - runtimeClasses, - volumeBackupsByApp, - gitSshPublicKeysByApp, - agentTemplateInfoByAgent, + apps, + agents, + agentsAvailable, + session, + projectId, + projectName, + networkGraphPositions, + showNewNetworkPolicyExplanation, + s3Targets, + storageClasses, + runtimeClasses, + volumeBackupsByApp, + gitSshPublicKeysByApp, + agentTemplateInfoByAgent }: ProjectOverviewProps) { - const searchParams = useSearchParams(); - const { openDialog } = useDialog(); - const requestedTab = searchParams.get('tab'); - const [currentTab, setCurrentTab] = useState('graph'); + const searchParams = useSearchParams(); + const { openDialog } = useDialog(); + const requestedTab = searchParams.get('tab'); + const [currentTab, setCurrentTab] = useState('graph'); - useEffect(() => { - if (!showNewNetworkPolicyExplanation || apps.length === 0) { - return; - } - - void openDialog(, { - width: 'min(720px, calc(100vw - 2rem))', - maxWidth: '720px', - }); - }, [openDialog, showNewNetworkPolicyExplanation, apps.length]); - - useEffect(() => { - if (isProjectOverviewTab(requestedTab)) { - setCurrentTab(requestedTab); - return; - } - const savedTab = window.localStorage.getItem(tabStorageKey()); - setCurrentTab(isProjectOverviewTab(savedTab) ? savedTab : 'graph'); - }, [projectId, requestedTab]); - - const handleTabChange = (value: string) => { - if (!isProjectOverviewTab(value)) return; - setCurrentTab(value); - window.localStorage.setItem(tabStorageKey(), value); - const params = new URLSearchParams(searchParams.toString()); - params.set('tab', value); - TabNavigationUtils.replaceQuery(params); - }; + useEffect(() => { + if (!showNewNetworkPolicyExplanation || apps.length === 0) { + return; + } - const canCreate = UserGroupUtils.sessionCanCreateProjectWorkloadsForProject(session, projectId); - const hasWorkloads = apps.length > 0 || agents.length > 0; + void openDialog(, { + width: 'min(720px, calc(100vw - 2rem))', + maxWidth: '720px' + }); + }, [openDialog, showNewNetworkPolicyExplanation, apps.length]); - if (!hasWorkloads && !canCreate) { - return ( - <> - - - - - - - No Workloads - - No apps or agents available in this project. - - - - - ); + useEffect(() => { + if (isProjectOverviewTab(requestedTab)) { + setCurrentTab(requestedTab); + return; } + const savedTab = window.localStorage.getItem(tabStorageKey()); + setCurrentTab(isProjectOverviewTab(savedTab) ? savedTab : 'graph'); + }, [projectId, requestedTab]); - if (!hasWorkloads) { - return ( - <> - - - - - - - - - No Workloads yet - - Create your first App or Agent to get started. - - - - - ); + const handleTabChange = (value: string) => { + if (!isProjectOverviewTab(value)) { + return; } + setCurrentTab(value); + window.localStorage.setItem(tabStorageKey(), value); + const params = new URLSearchParams(searchParams.toString()); + params.set('tab', value); + TabNavigationUtils.replaceQuery(params); + }; + + const canCreate = UserGroupUtils.sessionCanCreateProjectWorkloadsForProject(session, projectId); + const hasWorkloads = apps.length > 0 || agents.length > 0; + if (!hasWorkloads && !canCreate) { return ( - - -
- - - - - -
- - - {canCreate && } - - -
- -
-
- -
- + <> + + + + + + + No Workloads + No apps or agents available in this project. + + + ); + } + + if (!hasWorkloads) { + return ( + <> + + + + + + + + + No Workloads yet + Create your first App or Agent to get started. + + + + ); + } + + return ( + + +
+ + + + + +
+ + + {canCreate && } + + +
+ +
+
+ +
+ + ); } diff --git a/src/app/project/[projectId]/template-details-panel.tsx b/src/app/project/[projectId]/template-details-panel.tsx index dd41eaf4..20f5340a 100644 --- a/src/app/project/[projectId]/template-details-panel.tsx +++ b/src/app/project/[projectId]/template-details-panel.tsx @@ -5,59 +5,50 @@ import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '@/componen import { Separator } from '@/components/ui/separator'; type TemplateDetails = { - name: string; - iconName?: string | null; - description?: string; - websiteUrl?: string; + name: string; + iconName?: string | null; + description?: string; + websiteUrl?: string; }; function getIconSource(iconName?: string | null): string | undefined { - if (!iconName) return undefined; - return iconName.startsWith('http://') || iconName.startsWith('https://') - ? iconName - : `/template-icons/${iconName}`; + if (!iconName) { + return undefined; + } + return iconName.startsWith('http://') || iconName.startsWith('https://') ? iconName : `/template-icons/${iconName}`; } export function TemplateDetailsPanel({ template }: { template: TemplateDetails }) { - const iconSource = getIconSource(template.iconName); + const iconSource = getIconSource(template.iconName); - return ( - - ); + return ( + + ); } diff --git a/src/app/projects/edit-project-dialog.tsx b/src/app/projects/edit-project-dialog.tsx index 9e8e12f5..5d34f4c7 100644 --- a/src/app/projects/edit-project-dialog.tsx +++ b/src/app/projects/edit-project-dialog.tsx @@ -1,12 +1,7 @@ -'use client' +'use client'; import { Button } from '@/components/ui/button'; -import { - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from '@/components/ui/dialog'; +import { DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Toast } from '@/frontend/utils/toast.utils'; @@ -16,55 +11,48 @@ import { Project } from '@prisma/client'; import { useState } from 'react'; import { createProject } from './actions'; -function EditProjectForm({ existingItem }: { - existingItem?: Project; -}) { - const { closeDialog } = useDialogContext(); - const [name, setName] = useState(existingItem?.name ?? ''); +function EditProjectForm({ existingItem }: { existingItem?: Project }) { + const { closeDialog } = useDialogContext(); + const [name, setName] = useState(existingItem?.name ?? ''); - const submit = async () => { - if (!name.trim()) return; - await Toast.fromAction(() => createProject(name.trim(), existingItem?.id)); - closeDialog(); - }; + const submit = async () => { + if (!name.trim()) { + return; + } + await Toast.fromAction(() => createProject(name.trim(), existingItem?.id)); + closeDialog(); + }; - return <> - - {existingItem ? 'Edit Project' : 'Create Project'} - - {existingItem - ? 'Rename this Project.' - : 'Projects can contain both Apps and Agent Sandboxes.'} - - -
-
- - setName(event.target.value)} - /> -
+ return ( + <> + + {existingItem ? 'Edit Project' : 'Create Project'} + {existingItem ? 'Rename this Project.' : 'Projects can contain both Apps and Agent Sandboxes.'} + +
+
+ + setName(event.target.value)} />
- - - - - ; +
+ + + + + + ); } -export function EditProjectDialog({ children, existingItem }: { - children?: React.ReactNode; - existingItem?: Project; -}) { - const { openDialog } = useDialog(); +export function EditProjectDialog({ children, existingItem }: { children?: React.ReactNode; existingItem?: Project }) { + const { openDialog } = useDialog(); - const handleOpen = () => { - openDialog(, { maxWidth: '425px' }); - }; + const handleOpen = () => { + openDialog(, { maxWidth: '425px' }); + }; - return
{children}
; + return
{children}
; } diff --git a/src/app/settings/access/users/users-table.tsx b/src/app/settings/access/users/users-table.tsx index 7e99e0d3..2c3dbd92 100644 --- a/src/app/settings/access/users/users-table.tsx +++ b/src/app/settings/access/users/users-table.tsx @@ -1,171 +1,214 @@ 'use client'; -import { Button } from "@/components/ui/button"; -import { ChevronDown, EditIcon, KeyRound, Plus, Trash2, TrashIcon, UserPlus } from "lucide-react"; -import { Toast } from "@/frontend/utils/toast.utils"; -import { useConfirmDialog } from "@/frontend/states/zustand.states"; -import React from "react"; -import { SimpleDataTable } from "@/components/custom/simple-data-table"; -import { formatDateTime } from "@/frontend/utils/format.utils"; -import { UserExtended } from "@/shared/model/user-extended.model"; -import { deleteUser } from "./actions"; -import { UserGroupExtended, UserSession } from "@/shared/model/sim-session.model"; -import { SsoProviderUiModel } from "@/shared/model/sso-provider.model"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu"; -import { toast } from "sonner"; -import { Actions } from "@/frontend/utils/nextjs-actions.utils"; -import { useDialog } from "@/frontend/states/zustand.states"; -import { UserApiKeysDialog } from "./user-api-keys-dialog"; -import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; -import { SsoProviderLogo } from "@/components/custom/sso-provider-logo"; -import UserEditOverlay from "./user-edit-overlay"; -import UsersBulkRoleAssignment from "./users-table-bulk-role-assignment"; +import { Button } from '@/components/ui/button'; +import { ChevronDown, EditIcon, KeyRound, Plus, Trash2, TrashIcon, UserPlus } from 'lucide-react'; +import { Toast } from '@/frontend/utils/toast.utils'; +import { useConfirmDialog } from '@/frontend/states/zustand.states'; +import React from 'react'; +import { SimpleDataTable } from '@/components/custom/simple-data-table'; +import { formatDateTime } from '@/frontend/utils/format.utils'; +import { UserExtended } from '@/shared/model/user-extended.model'; +import { deleteUser } from './actions'; +import { UserGroupExtended, UserSession } from '@/shared/model/sim-session.model'; +import { SsoProviderUiModel } from '@/shared/model/sso-provider.model'; +import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; +import { toast } from 'sonner'; +import { Actions } from '@/frontend/utils/nextjs-actions.utils'; +import { useDialog } from '@/frontend/states/zustand.states'; +import { UserApiKeysDialog } from './user-api-keys-dialog'; +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; +import { SsoProviderLogo } from '@/components/custom/sso-provider-logo'; +import UserEditOverlay from './user-edit-overlay'; +import UsersBulkRoleAssignment from './users-table-bulk-role-assignment'; -export default function UsersTable({ users, userGroups, session, ssoProviders }: { - users: UserExtended[]; - userGroups: UserGroupExtended[]; - session: UserSession; - ssoProviders: SsoProviderUiModel[]; +export default function UsersTable({ + users, + userGroups, + session, + ssoProviders +}: { + users: UserExtended[]; + userGroups: UserGroupExtended[]; + session: UserSession; + ssoProviders: SsoProviderUiModel[]; }) { + const { openConfirmDialog: openDialog } = useConfirmDialog(); + const { openDialog: openGenericDialog } = useDialog(); + const [selectedUsers, setSelectedUsers] = React.useState([]); + const [isRoleDialogOpen, setIsRoleDialogOpen] = React.useState(false); - const { openConfirmDialog: openDialog } = useConfirmDialog(); - const { openDialog: openGenericDialog } = useDialog(); - const [selectedUsers, setSelectedUsers] = React.useState([]); - const [isRoleDialogOpen, setIsRoleDialogOpen] = React.useState(false); + const asyncDeleteItem = async (id: string) => { + const confirm = await openDialog({ + title: 'Delete User', + description: 'Do you really want to delete this user?', + okButton: 'Delete' + }); + if (confirm) { + await Toast.fromAction(() => deleteUser(id), 'Deleting User...', 'User deleted successfully'); + } + }; - const asyncDeleteItem = async (id: string) => { - const confirm = await openDialog({ - title: "Delete User", - description: "Do you really want to delete this user?", - okButton: "Delete", - }); - if (confirm) { - await Toast.fromAction(() => deleteUser(id), 'Deleting User...', 'User deleted successfully'); - } - }; - - const handleBulkDelete = async () => { - // Filter out admin users from selected users - const deletableUsers = selectedUsers.filter(user => session.email !== user.email); + const handleBulkDelete = async () => { + // Filter out admin users from selected users + const deletableUsers = selectedUsers.filter((user) => session.email !== user.email); - if (deletableUsers.length === 0) { - toast.error("No deletable users selected (admins cannot be deleted)"); - return; - } + if (deletableUsers.length === 0) { + toast.error('No deletable users selected (admins cannot be deleted)'); + return; + } - const confirm = await openDialog({ - title: "Delete Selected Users", - description: `Do you really want to delete ${deletableUsers.length} user(s)?`, - okButton: "Delete", - }); + const confirm = await openDialog({ + title: 'Delete Selected Users', + description: `Do you really want to delete ${deletableUsers.length} user(s)?`, + okButton: 'Delete' + }); - if (confirm) { - try { - // Delete users one by one - for (const user of deletableUsers) { - await Actions.run(() => deleteUser(user.id)); - } - toast.success(`Successfully deleted ${deletableUsers.length} user(s)`); - } catch (error) { - toast.error("Error deleting users"); - console.error(error); - } + if (confirm) { + try { + // Delete users one by one + for (const user of deletableUsers) { + await Actions.run(() => deleteUser(user.id)); } - }; + toast.success(`Successfully deleted ${deletableUsers.length} user(s)`); + } catch (error) { + toast.error('Error deleting users'); + console.error(error); + } + } + }; - return <> - {item.email}{item.apiOnlyUser && API only}], - ['userGroup.name', 'Group', true], - ['oauthProviderIds', 'OAuth Providers', true, (item) => { - const providers = item.oauthProviderIds - .map((providerId) => ssoProviders.find((provider) => provider.id === providerId)) - .filter((provider): provider is SsoProviderUiModel => !!provider); + return ( + <> + ( + + {item.email} + {item.apiOnlyUser && API only} + + ) + ], + ['userGroup.name', 'Group', true], + [ + 'oauthProviderIds', + 'OAuth Providers', + true, + (item) => { + const providers = item.oauthProviderIds + .map((providerId) => ssoProviders.find((provider) => provider.id === providerId)) + .filter((provider): provider is SsoProviderUiModel => !!provider); - if (providers.length === 0) return "None"; + if (providers.length === 0) { + return 'None'; + } - return ( - -
- {providers.map((provider) => - provider.type !== "OIDC" ? ( - - - - } /> - {provider.name} - - ) : ( - {provider.name} - ), - )} -
-
- ); - }], - ["createdAt", "Created At", true, (item) => formatDateTime(item.createdAt)], - ["updatedAt", "Updated At", false, (item) => formatDateTime(item.updatedAt)], + return ( + +
+ {providers.map((provider) => + provider.type !== 'OIDC' ? ( + + + + + } + /> + {provider.name} + + ) : ( + {provider.name} + ) + )} +
+
+ ); + } + ], + ['createdAt', 'Created At', true, (item) => formatDateTime(item.createdAt)], + ['updatedAt', 'Updated At', false, (item) => formatDateTime(item.updatedAt)] + ]} + data={users} + showSelectCheckbox={true} + onRowSelectionUpdate={setSelectedUsers} + columnFilters={[ + ...userGroups.map((userGroup) => ({ + accessorKey: 'userGroup.name', + filterLabel: userGroup.name, + filterFunction: (item: UserExtended) => item.userGroupId === userGroup.id + })), + { + accessorKey: 'email', + filterLabel: 'API only', + filterFunction: (item: UserExtended) => item.apiOnlyUser + } ]} - data={users} - showSelectCheckbox={true} - onRowSelectionUpdate={setSelectedUsers} - columnFilters={[...userGroups.map((userGroup) => ({ - accessorKey: 'userGroup.name', - filterLabel: userGroup.name, - filterFunction: (item: UserExtended) => item.userGroupId === userGroup.id, - })), { - accessorKey: 'email', - filterLabel: 'API only', - filterFunction: (item: UserExtended) => item.apiOnlyUser, - }]} - actionCol={(item) => + actionCol={(item) => ( + <> +
+
+ + {session.email !== item.email && ( <> -
-
- - {session.email !== item.email && <> - - - - } -
- } - /> -
- - - - {selectedUsers.length > 0 && ( - - Actions } /> - - setIsRoleDialogOpen(true)}> - Assign Group - - - Delete Selected - - - - )} -
+ + + + + + )} +
+ + )} + /> +
+ + + + {selectedUsers.length > 0 && ( + + + {' '} + Actions + + } + /> + + setIsRoleDialogOpen(true)}> + Assign Group + + + Delete Selected + + + + )} +
- - ; + + + ); } diff --git a/src/app/settings/platform/operations/monitoring-history-settings.tsx b/src/app/settings/platform/operations/monitoring-history-settings.tsx index c73b907e..6bf327cd 100644 --- a/src/app/settings/platform/operations/monitoring-history-settings.tsx +++ b/src/app/settings/platform/operations/monitoring-history-settings.tsx @@ -31,8 +31,8 @@ export default function MonitoringHistorySettings() { return ( - App monitoring history - Keep measurements for 1 to 168 hours. Default: 24 hours. + Monitoring history + Keep App and node measurements for 1 to 168 hours. Default: 24 hours.
diff --git a/src/app/settings/platform/storage/qs-system-backup-settings.tsx b/src/app/settings/platform/storage/qs-system-backup-settings.tsx index a99c2122..d15266e5 100644 --- a/src/app/settings/platform/storage/qs-system-backup-settings.tsx +++ b/src/app/settings/platform/storage/qs-system-backup-settings.tsx @@ -1,294 +1,280 @@ 'use client'; -import type { z } from "zod"; -import { SubmitButton } from "@/components/custom/submit-button"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Form } from "@/components/ui/form"; -import { FormUtils } from "@/frontend/utils/form.utilts"; -import { zodResolver } from "@hookform/resolvers/zod"; -import { useForm } from "react-hook-form"; -import { ServerActionResult } from "@/shared/model/server-action-error-return.model"; -import { useActionState, useEffect, useState } from "react"; -import { toast } from "sonner"; -import { listSystemBackups, runSystemBackupNow, setSystemBackupLocation, uploadAndRestoreSystemBackup, downloadSystemBackup } from "../../actions"; -import { S3Target } from "@prisma/client"; -import { SystemBackupLocationSettingsModel, systemBackupLocationSettingsZodModel } from "@/shared/model/system-backup-location-settings.model"; -import SelectFormField from "@/components/custom/select-form-field"; -import Link from "next/link"; -import { Button } from "@/components/ui/button"; -import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"; -import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; -import { FileArchive, Loader2, Play, Download, AlertTriangle } from "lucide-react"; -import { formatBytes, formatDateTime } from "@/frontend/utils/format.utils"; -import { Toast } from "@/frontend/utils/toast.utils"; -import { Constants } from "@/shared/utils/constants"; -import { Input } from "@/components/ui/input"; -import { Alert, AlertDescription } from "@/components/ui/alert"; -import { useConfirmDialog } from "@/frontend/states/zustand.states"; -import { Separator } from "@/components/ui/separator"; +import type { z } from 'zod'; +import { SubmitButton } from '@/components/custom/submit-button'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { Form } from '@/components/ui/form'; +import { FormUtils } from '@/frontend/utils/form.utilts'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { useForm } from 'react-hook-form'; +import { ServerActionResult } from '@/shared/model/server-action-error-return.model'; +import { useActionState, useEffect, useState } from 'react'; +import { toast } from 'sonner'; +import { listSystemBackups, runSystemBackupNow, setSystemBackupLocation, uploadAndRestoreSystemBackup, downloadSystemBackup } from '../../actions'; +import { S3Target } from '@prisma/client'; +import { SystemBackupLocationSettingsModel, systemBackupLocationSettingsZodModel } from '@/shared/model/system-backup-location-settings.model'; +import SelectFormField from '@/components/custom/select-form-field'; +import Link from 'next/link'; +import { Button } from '@/components/ui/button'; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'; +import { FileArchive, Loader2, Play, Download, AlertTriangle } from 'lucide-react'; +import { formatBytes, formatDateTime } from '@/frontend/utils/format.utils'; +import { Toast } from '@/frontend/utils/toast.utils'; +import { Constants } from '@/shared/utils/constants'; +import { Input } from '@/components/ui/input'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { useConfirmDialog } from '@/frontend/states/zustand.states'; +import { Separator } from '@/components/ui/separator'; const DEACTIVATED_VALUE = Constants.QS_SYSTEM_BACKUP_DEACTIVATED; -export default function QuickStackSystemBackupSettings({ - systemBackupLocation, - s3Targets -}: { - systemBackupLocation: string; - s3Targets: S3Target[]; -}) { - const [showBackupsDialog, setShowBackupsDialog] = useState(false); - const [backups, setBackups] = useState([]); - const [loadingBackups, setLoadingBackups] = useState(false); - const [runningBackup, setRunningBackup] = useState(false); - const [uploadingBackup, setUploadingBackup] = useState(false); - const [downloadingBackup, setDownloadingBackup] = useState(null); - const confirmDialog = useConfirmDialog(); +export default function QuickStackSystemBackupSettings({ systemBackupLocation, s3Targets }: { systemBackupLocation: string; s3Targets: S3Target[] }) { + const [showBackupsDialog, setShowBackupsDialog] = useState(false); + const [backups, setBackups] = useState([]); + const [loadingBackups, setLoadingBackups] = useState(false); + const [runningBackup, setRunningBackup] = useState(false); + const [uploadingBackup, setUploadingBackup] = useState(false); + const [downloadingBackup, setDownloadingBackup] = useState(null); + const confirmDialog = useConfirmDialog(); - const form = useForm, unknown, z.output>({ - resolver: zodResolver(systemBackupLocationSettingsZodModel), - defaultValues: { - systemBackupLocation: systemBackupLocation || DEACTIVATED_VALUE, - } - }); + const form = useForm, unknown, z.output>({ + resolver: zodResolver(systemBackupLocationSettingsZodModel), + defaultValues: { + systemBackupLocation: systemBackupLocation || DEACTIVATED_VALUE + } + }); - const [state, formAction] = useActionState((state: ServerActionResult, - payload: SystemBackupLocationSettingsModel) => - setSystemBackupLocation(state, payload), - FormUtils.getInitialFormState()); + const [state, formAction] = useActionState( + (state: ServerActionResult, payload: SystemBackupLocationSettingsModel) => setSystemBackupLocation(state, payload), + FormUtils.getInitialFormState() + ); - useEffect(() => { - if (state.status === 'success') { - toast.success('System backup settings updated successfully.'); - } - FormUtils.mapValidationErrorsToForm(state, form) - }, [form, state]); + useEffect(() => { + if (state.status === 'success') { + toast.success('System backup settings updated successfully.'); + } + FormUtils.mapValidationErrorsToForm(state, form); + }, [form, state]); - const handleViewBackups = async () => { - setShowBackupsDialog(true); - setLoadingBackups(true); - try { - const result = await listSystemBackups(); - if (result.status === 'success') { - setBackups(result.data || []); - } else { - toast.error(result.message || 'Failed to load backups'); - } - } catch { - toast.error('Failed to load backups'); - } finally { - setLoadingBackups(false); - } - }; + const handleViewBackups = async () => { + setShowBackupsDialog(true); + setLoadingBackups(true); + try { + const result = await listSystemBackups(); + if (result.status === 'success') { + setBackups(result.data || []); + } else { + toast.error(result.message || 'Failed to load backups'); + } + } catch { + toast.error('Failed to load backups'); + } finally { + setLoadingBackups(false); + } + }; - const handleRunBackup = async () => { - setRunningBackup(true); - try { - await Toast.fromAction(() => runSystemBackupNow()); - } finally { - setRunningBackup(false); - } - }; + const handleRunBackup = async () => { + setRunningBackup(true); + try { + await Toast.fromAction(() => runSystemBackupNow()); + } finally { + setRunningBackup(false); + } + }; - const handleFileUpload = async (event: React.ChangeEvent) => { - const file = event.target.files?.[0]; - if (!file) return; + const handleFileUpload = async (event: React.ChangeEvent) => { + const file = event.target.files?.[0]; + if (!file) { + return; + } - const confirmed = await confirmDialog.openConfirmDialog({ - title: 'Restore System Backup', - description: 'This will replace your current database with the one from the backup file. This action cannot be undone. Make sure you have a recent backup before proceeding. You will need to restart QuickStack after restoration.', - okButton: 'Restore Backup', - cancelButton: 'Cancel' - }); + const confirmed = await confirmDialog.openConfirmDialog({ + title: 'Restore System Backup', + description: + 'This will replace your current database with the one from the backup file. This action cannot be undone. Make sure you have a recent backup before proceeding. You will need to restart QuickStack after restoration.', + okButton: 'Restore Backup', + cancelButton: 'Cancel' + }); - if (!confirmed) { - event.target.value = ''; // Reset file input - return; - } + if (!confirmed) { + event.target.value = ''; // Reset file input + return; + } - setUploadingBackup(true); - try { - const formData = new FormData(); - formData.append('backupFile', file); + setUploadingBackup(true); + try { + const formData = new FormData(); + formData.append('backupFile', file); - const result = await uploadAndRestoreSystemBackup(formData); + const result = await uploadAndRestoreSystemBackup(formData); - if (result.status === 'success') { - toast.success(result.message || 'Backup restored successfully. Please restart QuickStack.'); - setShowBackupsDialog(false); - } else { - toast.error(result.message || 'Failed to restore backup'); - } - } catch { - toast.error('Failed to restore backup'); - } finally { - setUploadingBackup(false); - event.target.value = ''; // Reset file input - } - }; + if (result.status === 'success') { + toast.success(result.message || 'Backup restored successfully. Please restart QuickStack.'); + setShowBackupsDialog(false); + } else { + toast.error(result.message || 'Failed to restore backup'); + } + } catch { + toast.error('Failed to restore backup'); + } finally { + setUploadingBackup(false); + event.target.value = ''; // Reset file input + } + }; - const handleDownloadBackup = async (backupKey: string) => { - setDownloadingBackup(backupKey); - try { - await Toast.fromAction(() => downloadSystemBackup(backupKey)).then(x => { - if (x.status === 'success' && x.data) { - window.open('/api/volume-data-download?fileName=' + x.data); - } - }); - } finally { - setDownloadingBackup(null); + const handleDownloadBackup = async (backupKey: string) => { + setDownloadingBackup(backupKey); + try { + await Toast.fromAction(() => downloadSystemBackup(backupKey)).then((x) => { + if (x.status === 'success' && x.data) { + window.open('/api/volume-data-download?fileName=' + x.data); } - }; - - return <> - - - System Backup Location - - Configure where QuickStack system files should be backed up (App configurations, QuickStack settings...). - Select an S3 storage target to enable automatic system backups, or deactivate to disable system backups. - - - - - form.handleSubmit((data) => { - return formAction(data); - })()}> -
- - S3 Storage Locations can be configured here. - } - values={[ - [DEACTIVATED_VALUE, Constants.QS_SYSTEM_BACKUP_DEACTIVATED], - ...s3Targets.map((target) => - [target.id, `S3: ${target.name}`]) - ] as [string, string][]} - /> -
- Save Settings - {state?.message &&

{state.message}

} -
-
- - + }); + } finally { + setDownloadingBackup(null); + } + }; - - -
-

Backup Operations

-
- - -
+ return ( + <> + + + System Backup Location + + Configure where QuickStack system files should be backed up (App configurations, QuickStack settings...). Select an S3 storage target to enable + automatic system backups, or deactivate to disable system backups. + + + +
+ + form.handleSubmit((data) => { + return formAction(data); + })() + } + > +
+ + S3 Storage Locations can be configured{' '} + + here + + . + + } + values={ + [[DEACTIVATED_VALUE, Constants.QS_SYSTEM_BACKUP_DEACTIVATED], ...s3Targets.map((target) => [target.id, `S3: ${target.name}`])] as [ + string, + string + ][] + } + /> +
+ Save Settings + {state?.message &&

{state.message}

}
- - +
+ + - - - - System Backups - - All available QuickStack system backups from your configured S3 storage - - + - - - -
-

Upload and Restore Backup

-

- You can upload a system backup file (.tar.gz) to restore your QuickStack instance. - The system will automatically extract and replace the database. You will need to restart QuickStack after restoration. -

-
- - {uploadingBackup && ( -
- - Restoring backup... -
- )} -
-
-
-
+
+

Backup Operations

+
+ + +
+
+
+
- {loadingBackups ? ( -
- -
- ) : backups.length === 0 ? ( -
- No backups found + + + + System Backups + All available QuickStack system backups from your configured S3 storage + + + + + +
+

Upload and Restore Backup

+

+ You can upload a system backup file (.tar.gz) to restore your QuickStack instance. The system will automatically extract and replace the + database. You will need to restart QuickStack after restoration. +

+
+ + {uploadingBackup && ( +
+ + Restoring backup...
- ) : ( -
- - - Backup Date - Size - S3 Key - Actions - - - - {backups.map((backup: any, index: number) => ( - - {formatDateTime(backup.date)} - {formatBytes(backup.sizeBytes)} - {backup.key} - - - - - ))} - -
- )} - - + )} +
+
+ + - ; + {loadingBackups ? ( +
+ +
+ ) : backups.length === 0 ? ( +
No backups found
+ ) : ( + + + + Backup Date + Size + S3 Key + Actions + + + + {backups.map((backup: any, index: number) => ( + + {formatDateTime(backup.date)} + {formatBytes(backup.sizeBytes)} + {backup.key} + + + + + ))} + +
+ )} + + + + ); } diff --git a/src/app/settings/platform/updates/cluster-addon-details-dialog.tsx b/src/app/settings/platform/updates/cluster-addon-details-dialog.tsx index 8701a3db..05ca2bbc 100644 --- a/src/app/settings/platform/updates/cluster-addon-details-dialog.tsx +++ b/src/app/settings/platform/updates/cluster-addon-details-dialog.tsx @@ -2,187 +2,165 @@ import { Alert, AlertDescription } from '@/components/ui/alert'; import { Button } from '@/components/ui/button'; -import { - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from '@/components/ui/dialog'; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from '@/components/ui/dropdown-menu'; +import { DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; import { useDialogContext } from '@/frontend/states/dialog-context'; import { useConfirmDialog } from '@/frontend/states/zustand.states'; import { Toast } from '@/frontend/utils/toast.utils'; -import { - CheckCircle2, - CircleAlert, - Download, - ExternalLink, - LoaderCircle, - MoreHorizontal, - RefreshCw, - Trash2, -} from 'lucide-react'; +import { CheckCircle2, CircleAlert, Download, ExternalLink, LoaderCircle, MoreHorizontal, RefreshCw, Trash2 } from 'lucide-react'; import Link from 'next/link'; import { useRouter } from 'next/navigation'; import { useState } from 'react'; -import { - installClusterAddon, - uninstallClusterAddon, - updateClusterAddon, -} from '../../actions'; +import { installClusterAddon, uninstallClusterAddon, updateClusterAddon } from '../../actions'; import type { ClusterAddonUpdateInfo } from './cluster-addon-update-info'; const statusLabel: Record = { - notInstalled: 'Not installed', - installing: 'Installing', - ready: 'Installed', - updating: 'Updating', - uninstalling: 'Uninstalling', - failed: 'Error', + notInstalled: 'Not installed', + installing: 'Installing', + ready: 'Installed', + updating: 'Updating', + uninstalling: 'Uninstalling', + failed: 'Error' }; export function ClusterAddonDetailsDialog({ addon }: { addon: ClusterAddonUpdateInfo }) { - const { closeDialog } = useDialogContext(); - const { openConfirmDialog } = useConfirmDialog(); - const router = useRouter(); - const [loading, setLoading] = useState(false); + const { closeDialog } = useDialogContext(); + const { openConfirmDialog } = useConfirmDialog(); + const router = useRouter(); + const [loading, setLoading] = useState(false); - const busy = ['installing', 'updating', 'uninstalling'].includes(addon.status); - const canInstall = addon.status === 'notInstalled' - || (addon.status === 'failed' && !addon.installedVersion); - const canUpdate = addon.status === 'ready' && !!addon.availableVersion; - const canRemove = addon.canUninstall - && (addon.status === 'ready' || addon.status === 'failed') - && !!addon.installedVersion; + const busy = ['installing', 'updating', 'uninstalling'].includes(addon.status); + const canInstall = addon.status === 'notInstalled' || (addon.status === 'failed' && !addon.installedVersion); + const canUpdate = addon.status === 'ready' && !!addon.availableVersion; + const canRemove = addon.canUninstall && (addon.status === 'ready' || addon.status === 'failed') && !!addon.installedVersion; - const runOperation = async (operation: 'install' | 'update' | 'remove') => { - const version = operation === 'update' ? ` to ${addon.availableVersion}` : ''; - const actionLabel = operation === 'remove' - ? 'Remove' - : operation === 'install' - ? 'Install' - : 'Update'; + const runOperation = async (operation: 'install' | 'update' | 'remove') => { + const version = operation === 'update' ? ` to ${addon.availableVersion}` : ''; + const actionLabel = operation === 'remove' ? 'Remove' : operation === 'install' ? 'Install' : 'Update'; - const confirmed = await openConfirmDialog({ - title: `${actionLabel} ${addon.displayName}`, - description: operation === 'remove' - ? `Do you want to remove ${addon.displayName}? QuickStack will delete the add-on's Kubernetes resources from this cluster. This cannot be undone.` - : addon.updateWarning - ?
-

{`Do you want to ${operation} ${addon.displayName}${version}? QuickStack will apply the add-on's Kubernetes resources to this cluster.`}

-
-

- {addon.updateWarning.title} -

-
    - {addon.updateWarning.items.map((item) =>
  • {item}
  • )} -
-
-
- : `Do you want to ${operation} ${addon.displayName}${version}? QuickStack will apply the add-on's Kubernetes resources to this cluster.`, - okButton: actionLabel, - }); + const confirmed = await openConfirmDialog({ + title: `${actionLabel} ${addon.displayName}`, + description: + operation === 'remove' ? ( + `Do you want to remove ${addon.displayName}? QuickStack will delete the add-on's Kubernetes resources from this cluster. This cannot be undone.` + ) : addon.updateWarning ? ( +
+

{`Do you want to ${operation} ${addon.displayName}${version}? QuickStack will apply the add-on's Kubernetes resources to this cluster.`}

+
+

{addon.updateWarning.title}

+
    + {addon.updateWarning.items.map((item) => ( +
  • {item}
  • + ))} +
+
+
+ ) : ( + `Do you want to ${operation} ${addon.displayName}${version}? QuickStack will apply the add-on's Kubernetes resources to this cluster.` + ), + okButton: actionLabel + }); - if (!confirmed) return; + if (!confirmed) { + return; + } - try { - setLoading(true); - await Toast.fromAction( - () => operation === 'install' - ? installClusterAddon(addon.id) - : operation === 'update' - ? updateClusterAddon(addon.id) - : uninstallClusterAddon(addon.id), - undefined, - `${operation === 'install' ? 'Installing' : operation === 'update' ? 'Updating' : 'Removing'} ${addon.displayName}...`, - ); - router.refresh(); - closeDialog(); - } finally { - setLoading(false); - } - }; + try { + setLoading(true); + await Toast.fromAction( + () => + operation === 'install' ? installClusterAddon(addon.id) : operation === 'update' ? updateClusterAddon(addon.id) : uninstallClusterAddon(addon.id), + undefined, + `${operation === 'install' ? 'Installing' : operation === 'update' ? 'Updating' : 'Removing'} ${addon.displayName}...` + ); + router.refresh(); + closeDialog(); + } finally { + setLoading(false); + } + }; - return ( - <> - -
-
- {addon.displayName} - {addon.description} -
- - {busy && } - {statusLabel[addon.status]} - -
-
-
-
-

Installed version

-

{addon.installedVersion ?? '—'}

-
- {addon.message && ( - - - {addon.message} - - )} - {canUpdate && ( -
-
-
- -

Next Version Available

-
-

{addon.availableVersion}

- -
-
- )} + return ( + <> + +
+
+ {addon.displayName} + {addon.description} +
+ + {busy && } + {statusLabel[addon.status]} + +
+
+
+
+

Installed version

+

{addon.installedVersion ?? '—'}

+
+ {addon.message && ( + + + {addon.message} + + )} + {canUpdate && ( +
+
+
+ +

Next Version Available

+
+

{addon.availableVersion}

+
- - -
- {canInstall && ( - - )} - {addon.status === 'ready' && !addon.availableVersion && ( - - - Up to date - - )} - {canRemove && ( - - - - Add-on actions - } /> - - runOperation('remove')}> - - Remove - - - - )} -
-
- - ); +
+ )} +
+ + +
+ {canInstall && ( + + )} + {addon.status === 'ready' && !addon.availableVersion && ( + + + Up to date + + )} + {canRemove && ( + + + + Add-on actions + + } + /> + + runOperation('remove')}> + + Remove + + + + )} +
+
+ + ); } diff --git a/src/components/custom/app-monitoring-history.tsx b/src/components/custom/app-monitoring-history.tsx index 0582a718..a25a16e0 100644 --- a/src/components/custom/app-monitoring-history.tsx +++ b/src/components/custom/app-monitoring-history.tsx @@ -13,7 +13,7 @@ import { AppMonitoringHistory } from '@/shared/model/app-monitoring-history.mode import { getAppMonitoringHistory as getOneHistory } from '@/app/project/[projectId]/apps/details/deployments/actions'; import FullLoadingSpinner from '../ui/full-loading-spinnter'; -function HistoryChart({ +export function HistoryChart({ title, data, dataKey, @@ -87,7 +87,9 @@ function HistoryChart({ formatValue(value, true)} /> { - if (!active || !payload?.length) return null; + if (!active || !payload?.length) { + return null; + } const item = payload[0]; return (
@@ -114,6 +116,25 @@ function HistoryChart({ ); } +export function getMonitoringRangeOptions(retentionHours: number) { + const options = [ + { value: '1h', label: 'Last hour', hours: 1 }, + { value: '5h', label: 'Last 5 hours', hours: 5 }, + { value: 'today', label: 'Today', hours: 24 }, + { value: '48h', label: 'Last 48 hours', hours: 48 }, + { value: '7d', label: 'Last 7 days', hours: 168 } + ].filter((option) => option.hours <= retentionHours); + if (![1, 5, 48, 168].includes(retentionHours)) { + options.push({ value: 'all', label: `Last ${retentionHours} hours`, hours: retentionHours }); + } + return options; +} + +export function getMonitoringRangeStart(value: string, hours: number) { + const now = Date.now(); + return value === 'today' ? new Date(new Date(now).setHours(0, 0, 0, 0)).getTime() : now - hours * 60 * 60_000; +} + export default function AppMonitoringHistoryView({ appId, currentUsage }: { appId: string; currentUsage?: PodsResourceInfoModel }) { const [history, setHistory] = useState(); const [error, setError] = useState(false); @@ -132,19 +153,9 @@ export default function AppMonitoringHistoryView({ appId, currentUsage }: { appI }, [appId]); usePolling(refresh, { intervalMs: 60_000, runImmediately: true }); const retentionHours = history?.retentionHours ?? 1; - const options = [ - { value: '1h', label: 'Last hour', hours: 1 }, - { value: '5h', label: 'Last 5 hours', hours: 5 }, - { value: 'today', label: 'Today', hours: 24 }, - { value: '48h', label: 'Last 48 hours', hours: 48 }, - { value: '7d', label: 'Last 7 days', hours: 168 } - ].filter((option) => option.hours <= retentionHours); - if (![1, 5, 48, 168].includes(retentionHours)) { - options.push({ value: 'all', label: `Last ${retentionHours} hours`, hours: retentionHours }); - } + const options = getMonitoringRangeOptions(retentionHours); const selectedRange = options.find((option) => option.value === range) ?? options[0]; - const now = Date.now(); - const start = selectedRange.value === 'today' ? new Date(new Date(now).setHours(0, 0, 0, 0)).getTime() : now - selectedRange.hours * 60 * 60_000; + const start = getMonitoringRangeStart(selectedRange.value, selectedRange.hours); const visiblePoints = history?.points.filter((point) => point.time >= start) ?? []; const collectionStopped = history?.points.at(-1)?.isGap; const sampleCount = visiblePoints.filter((point) => !point.isGap).length; @@ -158,7 +169,9 @@ export default function AppMonitoringHistoryView({ appId, currentUsage }: { appI field.onChange(e.target.value ? `${e.target.value}.${domainSuffix}` : '')} - onBlur={field.onBlur} - name={field.name} - /> + const domainFields = (quickstack = false) => ( +
+ { + if (quickstack) { + const prefixValue = getQuickstackPrefix(field.value || ''); + return ( + + Domain Prefix + +
+ field.onChange(e.target.value ? `${e.target.value}.${domainSuffix}` : '')} + onBlur={field.onBlur} + name={field.name} + /> - - - .{domainSuffix}} /> - -

This ist the quickstack.me
domain for your instance.

-
-
-
-
-
- -
- ); - } - return ( - - Hostname - - - - - - ); - }} - /> - ( - - App Port - - - - - - )} - /> - - {values.useSsl && } -
- ); + + + .{domainSuffix}} /> + +

+ This ist the quickstack.me
+ domain for your instance. +

+
+
+
+
+ + + + ); + } + return ( + + Hostname + + + + + + ); + }} + /> + ( + + App Port + + + + + + )} + /> + + {values.useSsl && } +
+ ); - return ( - <> - - {existingDomain ? 'Edit Domain' : 'Create Domain'} - Configure a custom domain for external access. - -
- form.handleSubmit((data) => formAction(data))()}> - setActiveTab(value as 'custom' | 'quickstack')} className="w-full"> - - Custom Domain - {!!domainSuffix && quickstack.me Domain} - - {domainFields()} - {domainFields(true)} - -
-

{state.message}

- Save -
-
- - - ); + return ( + <> + + {existingDomain ? 'Edit Domain' : 'Create Domain'} + Configure a custom domain for external access. + +
+ form.handleSubmit((data) => formAction(data))()}> + setActiveTab(value as 'custom' | 'quickstack')} className="w-full"> + + Custom Domain + {!!domainSuffix && quickstack.me Domain} + + + {domainFields()} + + + {domainFields(true)} + + +
+

{state.message}

+ Save +
+
+ + + ); } diff --git a/src/components/custom/input-dialog.tsx b/src/components/custom/input-dialog.tsx index f1251864..c30c60cb 100644 --- a/src/components/custom/input-dialog.tsx +++ b/src/components/custom/input-dialog.tsx @@ -1,18 +1,11 @@ -'use client' +'use client'; -import { Button } from "@/components/ui/button" -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from "@/components/ui/dialog" -import React, { useEffect } from "react"; -import { Input } from "../ui/input"; -import { Label } from "../ui/label"; -import { useInputDialog } from "@/frontend/states/zustand.states"; +import { Button } from '@/components/ui/button'; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import React, { useEffect } from 'react'; +import { Input } from '../ui/input'; +import { Label } from '../ui/label'; +import { useInputDialog } from '@/frontend/states/zustand.states'; export function InputDialog() { const { isDialogOpen, data, closeDialog } = useInputDialog(); @@ -31,15 +24,11 @@ export function InputDialog() { {data.title} - {data.description && - {data.description} - } + {data.description && {data.description}}
- {data.fieldName && } + {data.fieldName && } { @@ -53,15 +42,23 @@ export function InputDialog() {
- - + +
- ) + ); } /* @@ -158,4 +155,4 @@ export function InputDialog({ ) } -*/ \ No newline at end of file +*/ diff --git a/src/components/custom/sso-provider-logo.tsx b/src/components/custom/sso-provider-logo.tsx index 5e6d1777..999c37a2 100644 --- a/src/components/custom/sso-provider-logo.tsx +++ b/src/components/custom/sso-provider-logo.tsx @@ -1,30 +1,17 @@ -import Image from "next/image"; -import { SsoProviderType } from "@/shared/model/sso-provider.model"; +import Image from 'next/image'; +import { SsoProviderType } from '@/shared/model/sso-provider.model'; const logoByType: Partial> = { - GOOGLE: "/sso-provider-logos/google.png", - AZURE_AD: "/sso-provider-logos/entra.svg", - GITHUB: "/sso-provider-logos/github.svg", + GOOGLE: '/sso-provider-logos/google.png', + AZURE_AD: '/sso-provider-logos/entra.svg', + GITHUB: '/sso-provider-logos/github.svg' }; -export function SsoProviderLogo({ - type, - className, -}: { - type: SsoProviderType; - className?: string; -}) { +export function SsoProviderLogo({ type, className }: { type: SsoProviderType; className?: string }) { const src = logoByType[type]; - if (!src) return null; + if (!src) { + return null; + } - return ( - - ); + return ; } diff --git a/src/components/ui/calendar.tsx b/src/components/ui/calendar.tsx index 57272617..11ee2516 100644 --- a/src/components/ui/calendar.tsx +++ b/src/components/ui/calendar.tsx @@ -1,37 +1,32 @@ -"use client" +'use client'; -import * as React from "react" -import { cn } from "cn" -import { - DayPicker, - getDefaultClassNames, - type DayButton, - type Locale, -} from "react-day-picker" +import * as React from 'react'; +import { cn } from 'cn'; +import { DayPicker, getDefaultClassNames, type DayButton, type Locale } from 'react-day-picker'; -import { Button, buttonVariants } from "@/components/ui/button" -import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon } from "lucide-react" +import { Button, buttonVariants } from '@/components/ui/button'; +import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon } from 'lucide-react'; function Calendar({ className, classNames, showOutsideDays = true, - captionLayout = "label", - buttonVariant = "ghost", + captionLayout = 'label', + buttonVariant = 'ghost', locale, formatters, components, ...props }: React.ComponentProps & { - buttonVariant?: React.ComponentProps["variant"] + buttonVariant?: React.ComponentProps['variant']; }) { - const defaultClassNames = getDefaultClassNames() + const defaultClassNames = getDefaultClassNames(); return ( svg]:rotate-180`, String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`, className @@ -39,183 +34,118 @@ function Calendar({ captionLayout={captionLayout} locale={locale} formatters={{ - formatMonthDropdown: (date) => - date.toLocaleString(locale?.code, { month: "short" }), - ...formatters, + formatMonthDropdown: (date) => date.toLocaleString(locale?.code, { month: 'short' }), + ...formatters }} classNames={{ - root: cn("w-fit", defaultClassNames.root), - months: cn( - "relative flex flex-col gap-4 md:flex-row", - defaultClassNames.months - ), - month: cn("flex w-full flex-col gap-4", defaultClassNames.month), - nav: cn( - "absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1", - defaultClassNames.nav - ), + root: cn('w-fit', defaultClassNames.root), + months: cn('relative flex flex-col gap-4 md:flex-row', defaultClassNames.months), + month: cn('flex w-full flex-col gap-4', defaultClassNames.month), + nav: cn('absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1', defaultClassNames.nav), button_previous: cn( buttonVariants({ variant: buttonVariant }), - "size-(--cell-size) p-0 select-none aria-disabled:opacity-50", + 'size-(--cell-size) p-0 select-none aria-disabled:opacity-50', defaultClassNames.button_previous ), button_next: cn( buttonVariants({ variant: buttonVariant }), - "size-(--cell-size) p-0 select-none aria-disabled:opacity-50", + 'size-(--cell-size) p-0 select-none aria-disabled:opacity-50', defaultClassNames.button_next ), - month_caption: cn( - "flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)", - defaultClassNames.month_caption - ), - dropdowns: cn( - "flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium", - defaultClassNames.dropdowns - ), - dropdown_root: cn( - "relative rounded-(--cell-radius)", - defaultClassNames.dropdown_root - ), - dropdown: cn( - "absolute inset-0 bg-popover opacity-0", - defaultClassNames.dropdown - ), + month_caption: cn('flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)', defaultClassNames.month_caption), + dropdowns: cn('flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium', defaultClassNames.dropdowns), + dropdown_root: cn('relative rounded-(--cell-radius)', defaultClassNames.dropdown_root), + dropdown: cn('absolute inset-0 bg-popover opacity-0', defaultClassNames.dropdown), caption_label: cn( - "font-medium select-none", - captionLayout === "label" - ? "text-sm" - : "flex items-center gap-1 rounded-(--cell-radius) text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground", + 'font-medium select-none', + captionLayout === 'label' ? 'text-sm' : 'flex items-center gap-1 rounded-(--cell-radius) text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground', defaultClassNames.caption_label ), - month_grid: cn("w-full border-collapse", defaultClassNames.month_grid), - weekdays: cn("flex", defaultClassNames.weekdays), - weekday: cn( - "flex-1 rounded-(--cell-radius) text-[0.8rem] font-normal text-muted-foreground select-none", - defaultClassNames.weekday - ), - week: cn("mt-2 flex w-full", defaultClassNames.week), - week_number_header: cn( - "w-(--cell-size) select-none", - defaultClassNames.week_number_header - ), - week_number: cn( - "text-[0.8rem] text-muted-foreground select-none", - defaultClassNames.week_number - ), + month_grid: cn('w-full border-collapse', defaultClassNames.month_grid), + weekdays: cn('flex', defaultClassNames.weekdays), + weekday: cn('flex-1 rounded-(--cell-radius) text-[0.8rem] font-normal text-muted-foreground select-none', defaultClassNames.weekday), + week: cn('mt-2 flex w-full', defaultClassNames.week), + week_number_header: cn('w-(--cell-size) select-none', defaultClassNames.week_number_header), + week_number: cn('text-[0.8rem] text-muted-foreground select-none', defaultClassNames.week_number), day: cn( - "group/day relative aspect-square h-full w-full rounded-(--cell-radius) p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius)", + 'group/day relative aspect-square h-full w-full rounded-(--cell-radius) p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius)', props.showWeekNumber - ? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)" - : "[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)", + ? '[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)' + : '[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)', defaultClassNames.day ), range_start: cn( - "relative isolate z-0 rounded-l-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:right-0 after:w-4 after:bg-muted", + 'relative isolate z-0 rounded-l-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:right-0 after:w-4 after:bg-muted', defaultClassNames.range_start ), - range_middle: cn("rounded-none", defaultClassNames.range_middle), + range_middle: cn('rounded-none', defaultClassNames.range_middle), range_end: cn( - "relative isolate z-0 rounded-r-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:left-0 after:w-4 after:bg-muted", + 'relative isolate z-0 rounded-r-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:left-0 after:w-4 after:bg-muted', defaultClassNames.range_end ), - today: cn( - "rounded-(--cell-radius) bg-muted text-foreground data-[selected=true]:rounded-none", - defaultClassNames.today - ), - outside: cn( - "text-muted-foreground aria-selected:text-muted-foreground", - defaultClassNames.outside - ), - disabled: cn( - "text-muted-foreground opacity-50", - defaultClassNames.disabled - ), - hidden: cn("invisible", defaultClassNames.hidden), - ...classNames, + today: cn('rounded-(--cell-radius) bg-muted text-foreground data-[selected=true]:rounded-none', defaultClassNames.today), + outside: cn('text-muted-foreground aria-selected:text-muted-foreground', defaultClassNames.outside), + disabled: cn('text-muted-foreground opacity-50', defaultClassNames.disabled), + hidden: cn('invisible', defaultClassNames.hidden), + ...classNames }} components={{ Root: ({ className, rootRef, ...props }) => { - return ( -
- ) + return
; }, Chevron: ({ className, orientation, ...props }) => { - if (orientation === "left") { - return ( - - ) + if (orientation === 'left') { + return ; } - if (orientation === "right") { - return ( - - ) + if (orientation === 'right') { + return ; } - return ( - - ) + return ; }, - DayButton: ({ ...props }) => ( - - ), + DayButton: ({ ...props }) => , WeekNumber: ({ children, ...props }) => { return ( -
- {children} -
+
{children}
- ) + ); }, - ...components, + ...components }} {...props} /> - ) + ); } -function CalendarDayButton({ - className, - day, - modifiers, - locale, - ...props -}: React.ComponentProps & { locale?: Partial }) { - const defaultClassNames = getDefaultClassNames() +function CalendarDayButton({ className, day, modifiers, locale, ...props }: React.ComponentProps & { locale?: Partial }) { + const defaultClassNames = getDefaultClassNames(); - const ref = React.useRef(null) + const ref = React.useRef(null); React.useEffect(() => { - if (modifiers.focused) ref.current?.focus() - }, [modifiers.focused]) + if (modifiers.focused) { + ref.current?.focus(); + } + }, [modifiers.focused]); return (