diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ee57a2e..3ffe49da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,10 +8,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +* **auto-update:** Auto-Update Policies — schedule automatic image checks and container updates per stack (Skipper & Admiral) +* **auto-update:** Dedicated Auto-Update Policies view with create/edit dialog, cron presets, run history, and manual trigger +* **auto-update:** Extends the existing SchedulerService with a new `update` action type, reusing cron scheduling and run history infrastructure +* **docs:** Auto-Update Policies feature documentation page * **docs:** OpenAPI 3.1 spec covering ~55 public API endpoints across 8 categories (Stacks, Containers, API Tokens, Webhooks, Nodes, Fleet, Scheduled Tasks, Health) * **docs:** Interactive API Reference tab in Mintlify documentation powered by native OpenAPI rendering * **docs:** API overview page with authentication guide, token scopes, node routing, error format, and WebSocket examples +### Fixed + +* **image-updates:** Fix stack name key mismatch — use `com.docker.compose.project.working_dir` label instead of `com.docker.compose.project` so update indicators work when compose files set `name:` +* **image-updates:** Add 5-minute periodic polling so background check results are picked up without manual refresh +* **image-updates:** Replace fixed 3-second timeout with polling-based refresh that waits for the check to complete (up to 60s) +* **image-updates:** Clear update status (blue dot) after a stack is updated via the UI + ## [0.23.0](https://github.com/AnsoCode/Sencho/compare/v0.22.1...v0.23.0) (2026-03-31) diff --git a/backend/src/index.ts b/backend/src/index.ts index e3133144..1878502a 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -807,6 +807,12 @@ const requireAdmin = (req: Request, res: Response): boolean => { return true; }; +// Tier gate for scheduled tasks: 'update' action requires Pro, everything else requires Admiral. +const requireScheduledTaskTier = (action: string, _req: Request, res: Response): boolean => { + if (action === 'update') return requirePro(_req, res); + return requireAdmiral(_req, res); +}; + // --- Scoped RBAC Permission Engine (Admiral) --- type PermissionAction = @@ -2835,6 +2841,7 @@ app.post('/api/stacks/:stackName/update', async (req: Request, res: Response) => try { const atomic = LicenseService.getInstance().getTier() === 'pro'; await ComposeService.getInstance(req.nodeId).updateStack(stackName, terminalWs || undefined, atomic); + DatabaseService.getInstance().clearStackUpdateStatus(stackName); res.json({ status: 'Update completed' }); } catch (error) { const rolledBack = LicenseService.getInstance().getTier() === 'pro'; @@ -3693,9 +3700,14 @@ app.delete('/api/api-tokens/:id', authMiddleware, async (req: Request, res: Resp app.get('/api/scheduled-tasks', (req: Request, res: Response): void => { if (!requireAdmin(req, res)) return; - if (!requireAdmiral(req, res)) return; + if (!requirePro(req, res)) return; try { - const tasks = DatabaseService.getInstance().getScheduledTasks(); + let tasks = DatabaseService.getInstance().getScheduledTasks(); + // Skipper users only see 'update' tasks; Admiral sees all + const ls = LicenseService.getInstance(); + if (ls.getVariant() !== 'team') { + tasks = tasks.filter(t => t.action === 'update'); + } res.json(tasks); } catch (error) { console.error('[ScheduledTasks] List error:', error); @@ -3705,7 +3717,6 @@ app.get('/api/scheduled-tasks', (req: Request, res: Response): void => { app.post('/api/scheduled-tasks', (req: Request, res: Response): void => { if (!requireAdmin(req, res)) return; - if (!requireAdmiral(req, res)) return; try { const { name, target_type, target_id, node_id, action, cron_expression, enabled, prune_targets, target_services, prune_label_filter } = req.body; @@ -3715,13 +3726,18 @@ app.post('/api/scheduled-tasks', (req: Request, res: Response): void => { if (!['stack', 'fleet', 'system'].includes(target_type)) { res.status(400).json({ error: 'Invalid target_type. Must be stack, fleet, or system.' }); return; } - if (!['restart', 'snapshot', 'prune'].includes(action)) { - res.status(400).json({ error: 'Invalid action. Must be restart, snapshot, or prune.' }); return; + if (!['restart', 'snapshot', 'prune', 'update'].includes(action)) { + res.status(400).json({ error: 'Invalid action. Must be restart, snapshot, prune, or update.' }); return; } + // Tier gate based on action type + if (!requireScheduledTaskTier(action, req, res)) return; // Validate action-target combos if (action === 'restart' && target_type !== 'stack') { res.status(400).json({ error: 'Restart action requires target_type "stack".' }); return; } + if (action === 'update' && target_type !== 'stack') { + res.status(400).json({ error: 'Update action requires target_type "stack".' }); return; + } if (action === 'snapshot' && target_type !== 'fleet') { res.status(400).json({ error: 'Snapshot action requires target_type "fleet".' }); return; } @@ -3795,12 +3811,13 @@ app.post('/api/scheduled-tasks', (req: Request, res: Response): void => { app.get('/api/scheduled-tasks/:id', (req: Request, res: Response): void => { if (!requireAdmin(req, res)) return; - if (!requireAdmiral(req, res)) return; + if (!requirePro(req, res)) return; try { const id = parseInt(req.params.id as string, 10); if (isNaN(id)) { res.status(400).json({ error: 'Invalid task ID' }); return; } const task = DatabaseService.getInstance().getScheduledTask(id); if (!task) { res.status(404).json({ error: 'Scheduled task not found' }); return; } + if (!requireScheduledTaskTier(task.action, req, res)) return; res.json(task); } catch (error) { console.error('[ScheduledTasks] Get error:', error); @@ -3810,7 +3827,7 @@ app.get('/api/scheduled-tasks/:id', (req: Request, res: Response): void => { app.put('/api/scheduled-tasks/:id', (req: Request, res: Response): void => { if (!requireAdmin(req, res)) return; - if (!requireAdmiral(req, res)) return; + if (!requirePro(req, res)) return; try { const id = parseInt(req.params.id as string, 10); if (isNaN(id)) { res.status(400).json({ error: 'Invalid task ID' }); return; } @@ -3818,13 +3835,14 @@ app.put('/api/scheduled-tasks/:id', (req: Request, res: Response): void => { const db = DatabaseService.getInstance(); const existing = db.getScheduledTask(id); if (!existing) { res.status(404).json({ error: 'Scheduled task not found' }); return; } + if (!requireScheduledTaskTier(existing.action, req, res)) return; const { name, target_type, target_id, node_id, action, cron_expression, enabled, prune_targets, target_services, prune_label_filter } = req.body; if (target_type && !['stack', 'fleet', 'system'].includes(target_type)) { res.status(400).json({ error: 'Invalid target_type' }); return; } - if (action && !['restart', 'snapshot', 'prune'].includes(action)) { + if (action && !['restart', 'snapshot', 'prune', 'update'].includes(action)) { res.status(400).json({ error: 'Invalid action' }); return; } @@ -3833,6 +3851,9 @@ app.put('/api/scheduled-tasks/:id', (req: Request, res: Response): void => { if (finalAction === 'restart' && finalTargetType !== 'stack') { res.status(400).json({ error: 'Restart action requires target_type "stack".' }); return; } + if (finalAction === 'update' && finalTargetType !== 'stack') { + res.status(400).json({ error: 'Update action requires target_type "stack".' }); return; + } if (finalAction === 'snapshot' && finalTargetType !== 'fleet') { res.status(400).json({ error: 'Snapshot action requires target_type "fleet".' }); return; } @@ -3904,7 +3925,7 @@ app.put('/api/scheduled-tasks/:id', (req: Request, res: Response): void => { app.delete('/api/scheduled-tasks/:id', (req: Request, res: Response): void => { if (!requireAdmin(req, res)) return; - if (!requireAdmiral(req, res)) return; + if (!requirePro(req, res)) return; try { const id = parseInt(req.params.id as string, 10); if (isNaN(id)) { res.status(400).json({ error: 'Invalid task ID' }); return; } @@ -3912,6 +3933,7 @@ app.delete('/api/scheduled-tasks/:id', (req: Request, res: Response): void => { const db = DatabaseService.getInstance(); const existing = db.getScheduledTask(id); if (!existing) { res.status(404).json({ error: 'Scheduled task not found' }); return; } + if (!requireScheduledTaskTier(existing.action, req, res)) return; db.deleteScheduledTask(id); res.json({ success: true }); @@ -3923,7 +3945,7 @@ app.delete('/api/scheduled-tasks/:id', (req: Request, res: Response): void => { app.patch('/api/scheduled-tasks/:id/toggle', (req: Request, res: Response): void => { if (!requireAdmin(req, res)) return; - if (!requireAdmiral(req, res)) return; + if (!requirePro(req, res)) return; try { const id = parseInt(req.params.id as string, 10); if (isNaN(id)) { res.status(400).json({ error: 'Invalid task ID' }); return; } @@ -3931,6 +3953,7 @@ app.patch('/api/scheduled-tasks/:id/toggle', (req: Request, res: Response): void const db = DatabaseService.getInstance(); const existing = db.getScheduledTask(id); if (!existing) { res.status(404).json({ error: 'Scheduled task not found' }); return; } + if (!requireScheduledTaskTier(existing.action, req, res)) return; const newEnabled = existing.enabled ? 0 : 1; const nextRun = newEnabled ? SchedulerService.getInstance().calculateNextRun(existing.cron_expression) : null; @@ -3951,7 +3974,7 @@ app.patch('/api/scheduled-tasks/:id/toggle', (req: Request, res: Response): void app.post('/api/scheduled-tasks/:id/run', async (req: Request, res: Response): Promise => { if (!requireAdmin(req, res)) return; - if (!requireAdmiral(req, res)) return; + if (!requirePro(req, res)) return; try { const id = parseInt(req.params.id as string, 10); if (isNaN(id)) { res.status(400).json({ error: 'Invalid task ID' }); return; } @@ -3959,6 +3982,7 @@ app.post('/api/scheduled-tasks/:id/run', async (req: Request, res: Response): Pr const db = DatabaseService.getInstance(); const existing = db.getScheduledTask(id); if (!existing) { res.status(404).json({ error: 'Scheduled task not found' }); return; } + if (!requireScheduledTaskTier(existing.action, req, res)) return; await SchedulerService.getInstance().triggerTask(id); @@ -3973,7 +3997,7 @@ app.post('/api/scheduled-tasks/:id/run', async (req: Request, res: Response): Pr app.get('/api/scheduled-tasks/:id/runs/export', (req: Request, res: Response): void => { if (!requireAdmin(req, res)) return; - if (!requireAdmiral(req, res)) return; + if (!requirePro(req, res)) return; try { const id = parseInt(req.params.id as string, 10); if (isNaN(id)) { res.status(400).json({ error: 'Invalid task ID' }); return; } @@ -3981,6 +4005,7 @@ app.get('/api/scheduled-tasks/:id/runs/export', (req: Request, res: Response): v const db = DatabaseService.getInstance(); const task = db.getScheduledTask(id); if (!task) { res.status(404).json({ error: 'Scheduled task not found' }); return; } + if (!requireScheduledTaskTier(task.action, req, res)) return; const runs = db.getAllScheduledTaskRuns(id); @@ -4015,7 +4040,7 @@ app.get('/api/scheduled-tasks/:id/runs/export', (req: Request, res: Response): v app.get('/api/scheduled-tasks/:id/runs', (req: Request, res: Response): void => { if (!requireAdmin(req, res)) return; - if (!requireAdmiral(req, res)) return; + if (!requirePro(req, res)) return; try { const id = parseInt(req.params.id as string, 10); if (isNaN(id)) { res.status(400).json({ error: 'Invalid task ID' }); return; } @@ -4023,6 +4048,7 @@ app.get('/api/scheduled-tasks/:id/runs', (req: Request, res: Response): void => const db = DatabaseService.getInstance(); const existing = db.getScheduledTask(id); if (!existing) { res.status(404).json({ error: 'Scheduled task not found' }); return; } + if (!requireScheduledTaskTier(existing.action, req, res)) return; const limit = Math.min(parseInt(req.query.limit as string, 10) || 20, 100); const offset = Math.max(parseInt(req.query.offset as string, 10) || 0, 0); @@ -4429,6 +4455,10 @@ app.post('/api/image-updates/refresh', authMiddleware, (_req: Request, res: Resp } }); +app.get('/api/image-updates/status', authMiddleware, (_req: Request, res: Response) => { + res.json({ checking: ImageUpdateService.getInstance().isChecking() }); +}); + // ========================= // Node Management API // ========================= diff --git a/backend/src/services/DatabaseService.ts b/backend/src/services/DatabaseService.ts index b7116827..ccbd3c6b 100644 --- a/backend/src/services/DatabaseService.ts +++ b/backend/src/services/DatabaseService.ts @@ -155,7 +155,7 @@ export interface ScheduledTask { target_type: 'stack' | 'fleet' | 'system'; target_id: string | null; node_id: number | null; - action: 'restart' | 'snapshot' | 'prune'; + action: 'restart' | 'snapshot' | 'prune' | 'update'; cron_expression: string; enabled: number; created_by: string; @@ -851,6 +851,10 @@ export class DatabaseService { return result; } + public clearStackUpdateStatus(stackName: string): void { + this.db.prepare('DELETE FROM stack_update_status WHERE stack_name = ?').run(stackName); + } + // --- Webhooks --- public getWebhooks(): Webhook[] { diff --git a/backend/src/services/ImageUpdateService.ts b/backend/src/services/ImageUpdateService.ts index da93b7b1..e367c2c5 100644 --- a/backend/src/services/ImageUpdateService.ts +++ b/backend/src/services/ImageUpdateService.ts @@ -1,8 +1,10 @@ import https from 'https'; import http from 'http'; +import path from 'path'; import DockerController from './DockerController'; import { DatabaseService } from './DatabaseService'; import { RegistryService } from './RegistryService'; +import { NodeRegistry } from './NodeRegistry'; // ─── Image ref parsing ──────────────────────────────────────────────────────── @@ -230,14 +232,22 @@ export class ImageUpdateService { private async checkNode(nodeId: number, db: DatabaseService) { const docker = DockerController.getInstance(nodeId); const containers = await docker.getAllContainers(); + const composeDir = path.resolve(NodeRegistry.getInstance().getComposeDir(nodeId)); // stackName → set of image refs used by that stack + // Key by directory name (matching FileSystemService.getStacks()) rather than + // com.docker.compose.project label, which diverges when compose files set `name:`. const stackImages = new Map>(); for (const c of containers) { - const stackName: string | undefined = c.Labels?.['com.docker.compose.project']; - if (!stackName) continue; + const workingDir: string | undefined = c.Labels?.['com.docker.compose.project.working_dir']; + if (!workingDir) continue; + // Only consider containers managed under COMPOSE_DIR + const resolved = path.resolve(workingDir); + if (resolved !== composeDir && !resolved.startsWith(composeDir + path.sep)) continue; + + const stackName = path.basename(resolved); const imageRef: string = c.Image ?? ''; if (!imageRef || imageRef.startsWith('sha256:')) continue; @@ -270,7 +280,7 @@ export class ImageUpdateService { } } - private async checkImage(docker: DockerController, imageRef: string): Promise { + public async checkImage(docker: DockerController, imageRef: string): Promise { const parsed = parseImageRef(imageRef); if (!parsed) return false; diff --git a/backend/src/services/SchedulerService.ts b/backend/src/services/SchedulerService.ts index 52383ffe..25149265 100644 --- a/backend/src/services/SchedulerService.ts +++ b/backend/src/services/SchedulerService.ts @@ -3,7 +3,9 @@ import { DatabaseService } from './DatabaseService'; import type { ScheduledTask } from './DatabaseService'; import { LicenseService } from './LicenseService'; import DockerController from './DockerController'; +import { ComposeService } from './ComposeService'; import { FileSystemService } from './FileSystemService'; +import { ImageUpdateService } from './ImageUpdateService'; import { NodeRegistry } from './NodeRegistry'; import { NotificationService } from './NotificationService'; @@ -47,7 +49,9 @@ export class SchedulerService { this.isProcessing = true; try { const ls = LicenseService.getInstance(); - if (ls.getTier() !== 'pro' || ls.getVariant() !== 'team') return; + const isPro = ls.getTier() === 'pro'; + const isAdmiral = isPro && ls.getVariant() === 'team'; + if (!isPro) return; // No scheduled tasks for non-Pro tiers const db = DatabaseService.getInstance(); const now = Date.now(); @@ -57,6 +61,8 @@ export class SchedulerService { db.cleanupOldTaskRuns(30); for (const task of dueTasks) { + // Skipper users can only run 'update' tasks; other actions require Admiral + if (!isAdmiral && task.action !== 'update') continue; if (this.runningTasks.has(task.id)) continue; this.runningTasks.add(task.id); this.executeTask(task).finally(() => this.runningTasks.delete(task.id)); @@ -107,6 +113,9 @@ export class SchedulerService { case 'prune': output = await this.executePrune(task); break; + case 'update': + output = await this.executeUpdate(task); + break; } const nextRun = this.calculateNextRun(task.cron_expression); @@ -345,4 +354,91 @@ export class SchedulerService { const filterSuffix = labelFilter ? ` (label: ${labelFilter})` : ''; return `System prune completed${filterSuffix}: ${results.join('; ')}`; } + + private async executeUpdate(task: ScheduledTask): Promise { + if (!task.target_id || task.node_id == null) { + throw new Error('Auto-update requires target_id (stack name or "*") and node_id'); + } + + // Resolve target stacks: "*" means all stacks on the node + let stackNames: string[]; + if (task.target_id === '*') { + stackNames = await FileSystemService.getInstance(task.node_id).getStacks(); + if (stackNames.length === 0) { + return 'No stacks found on node — skipped.'; + } + } else { + stackNames = [task.target_id]; + } + + const docker = DockerController.getInstance(task.node_id); + const imageUpdateService = ImageUpdateService.getInstance(); + const compose = ComposeService.getInstance(task.node_id); + const db = DatabaseService.getInstance(); + const results: string[] = []; + + for (const stackName of stackNames) { + try { + const output = await this.executeUpdateForStack(stackName, docker, imageUpdateService, compose, db); + results.push(output); + } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + results.push(`Stack "${stackName}" failed: ${msg}`); + console.error(`[SchedulerService] Auto-update failed for stack "${stackName}":`, e); + } + } + + return results.join('\n'); + } + + private async executeUpdateForStack( + stackName: string, + docker: DockerController, + imageUpdateService: ImageUpdateService, + compose: ComposeService, + db: DatabaseService + ): Promise { + const containers = await docker.getContainersByStack(stackName); + if (!containers || containers.length === 0) { + return `Stack "${stackName}": no containers found — skipped.`; + } + + const imageRefs = [...new Set( + containers + .map((c: { Image?: string }) => c.Image) + .filter((img): img is string => !!img && !img.startsWith('sha256:')) + )]; + + if (imageRefs.length === 0) { + return `Stack "${stackName}": no pullable images — skipped.`; + } + + let hasUpdate = false; + const updatedImages: string[] = []; + + for (const imageRef of imageRefs) { + try { + if (await imageUpdateService.checkImage(docker, imageRef)) { + hasUpdate = true; + updatedImages.push(imageRef); + } + } catch (e) { + console.warn(`[SchedulerService] Failed to check image ${imageRef}:`, e); + } + } + + if (!hasUpdate) { + return `Stack "${stackName}": all images up to date.`; + } + + await compose.updateStack(stackName, undefined, true); + db.clearStackUpdateStatus(stackName); + + NotificationService.getInstance().dispatchAlert( + 'info', + `Auto-update: stack "${stackName}" updated with new images` + ); + + return `Stack "${stackName}": updated (${updatedImages.join(', ')}).`; + } } diff --git a/docs/docs.json b/docs/docs.json index 0f402768..c9b6282e 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -111,6 +111,7 @@ "features/audit-log", "features/api-tokens", "features/private-registries", + "features/auto-update-policies", "features/scheduled-operations", "features/sso", "features/licensing" diff --git a/docs/features/auto-update-policies.mdx b/docs/features/auto-update-policies.mdx new file mode 100644 index 00000000..d2c457c6 --- /dev/null +++ b/docs/features/auto-update-policies.mdx @@ -0,0 +1,115 @@ +--- +title: "Auto-Update Policies" +description: "Automatically check for and apply container image updates on a schedule." +--- + + + Auto-Update Policies require a **Skipper** or **Admiral** license. + + +## Overview + +Auto-Update Policies let you define schedules for Sencho to automatically check your container images for updates and apply them when new versions are available. Think of it as a built-in Watchtower — but integrated directly into your Sencho dashboard with full visibility into what was updated and when. + +Each policy targets a specific stack and runs on a cron schedule. When triggered, Sencho: + +1. Inspects every container in the target stack +2. Compares local image digests against the remote registry +3. If any image has a newer version, pulls the update and recreates the stack with `docker compose up -d` +4. Records the result in run history for auditability + + + Auto-Update Policies view showing the policies list + + +## Creating a Policy + +Navigate to **Auto-Update** in the sidebar and click **New Policy**. + + + Create auto-update policy dialog + + +Fill in the following fields: + +| Field | Description | +|-------|-------------| +| **Name** | A descriptive name for the policy (e.g., "Nightly media stack update") | +| **Node** | The node where the target stack runs | +| **Stack** | The stack to monitor and update | +| **Schedule** | A cron expression or preset defining how often to check | + +### Schedule Presets + +For convenience, Sencho offers common schedule presets: + +| Preset | Cron Expression | Description | +|--------|----------------|-------------| +| Every 6 hours | `0 */6 * * *` | Check four times per day | +| Every 12 hours | `0 */12 * * *` | Check twice per day | +| Daily at 3 AM | `0 3 * * *` | Low-traffic window for most users | +| Daily at midnight | `0 0 * * *` | Start of each day | +| Weekly (Sunday 3 AM) | `0 3 * * 0` | Minimal disruption for stable stacks | +| Custom | User-defined | Any valid cron expression | + +## Managing Policies + +Each policy in the list shows: + +- **Name** and target stack +- **Schedule** in human-readable form (e.g., "Every 6 hours") +- **Status** — enabled or disabled +- **Last run** — when it last executed and whether it succeeded +- **Next run** — when it will execute next + +### Available Actions + +- **Toggle** — Enable or disable a policy without deleting it +- **Run Now** — Trigger an immediate check-and-update cycle +- **Edit** — Modify the policy name, target, or schedule +- **Delete** — Permanently remove the policy + +## Run History + +Click the clock icon on any policy to view its run history. Each entry shows: + +- **Timestamp** — When the run started +- **Status** — Success or failure +- **Output** — Detailed log of what was checked and whether updates were applied + +This gives you full auditability over what changed and when. + +## How It Works + +Under the hood, Auto-Update Policies are built on the same scheduling engine as [Scheduled Operations](/features/scheduled-operations). The key difference is that auto-update policies: + +- Are available to **Skipper** tier (Scheduled Operations requires Admiral) +- Always target a **stack** (not individual containers) +- Perform a **check-then-update** flow rather than a blind restart + +### The Check-Then-Update Flow + +1. **Enumerate images** — Sencho lists all unique images used by containers in the target stack +2. **Check digests** — For each image, Sencho compares the local `RepoDigests` against the remote registry manifest digest +3. **Conditional update** — Only if at least one image has a newer version does Sencho run `docker compose up -d` to pull and recreate +4. **Clear indicators** — After a successful update, the blue update indicator dot is automatically cleared + +If no updates are found, the run completes with a "No updates available" message and no containers are restarted. + +## Relationship to Image Update Detection + +Sencho has two complementary features for keeping your images current: + +| Feature | Purpose | Tier | +|---------|---------|------| +| **Image Update Detection** | Passive — shows a blue dot on stacks with available updates | All tiers | +| **Auto-Update Policies** | Active — automatically applies updates on a schedule | Skipper+ | + +Image Update Detection runs in the background every 6 hours and highlights stacks that have newer images available. Auto-Update Policies take this a step further by automatically applying those updates based on your defined schedule. + +## Best Practices + +- **Start with longer intervals** — Use "Daily at 3 AM" or "Weekly" for production stacks. Reserve shorter intervals for dev/staging environments. +- **Pin critical images** — If a stack uses `image: postgres:16.2` (pinned tag), auto-update will only detect updates to that exact tag. Use floating tags like `postgres:16` if you want minor version updates. +- **Monitor run history** — Check run history periodically to ensure updates are applying cleanly. Failed runs may indicate registry authentication issues or compose file problems. +- **Combine with notifications** — Sencho sends alert notifications when auto-updates are applied, so you stay informed even when updates happen automatically. diff --git a/docs/images/auto-update-policies/create-dialog.png b/docs/images/auto-update-policies/create-dialog.png new file mode 100644 index 00000000..d865f8b7 Binary files /dev/null and b/docs/images/auto-update-policies/create-dialog.png differ diff --git a/docs/images/auto-update-policies/overview.png b/docs/images/auto-update-policies/overview.png new file mode 100644 index 00000000..0f371815 Binary files /dev/null and b/docs/images/auto-update-policies/overview.png differ diff --git a/frontend/src/components/AutoUpdatePoliciesView.tsx b/frontend/src/components/AutoUpdatePoliciesView.tsx new file mode 100644 index 00000000..24693ddb --- /dev/null +++ b/frontend/src/components/AutoUpdatePoliciesView.tsx @@ -0,0 +1,570 @@ +import { useState, useEffect, useCallback } from 'react'; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; +import { Combobox } from '@/components/ui/combobox'; +import { Badge } from '@/components/ui/badge'; +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'; +import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'; +import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet'; +import { Switch } from '@/components/ui/switch'; +import { Label } from '@/components/ui/label'; +import { RefreshCw, Plus, Pencil, Trash2, History, Play, ChevronLeft, ChevronRight, Download } from 'lucide-react'; +import { toast } from '@/components/ui/toast-store'; +import { apiFetch, fetchForNode } from '@/lib/api'; +import { ProGate } from '@/components/ProGate'; +import cronstrue from 'cronstrue'; + +interface ScheduledTask { + id: number; + name: string; + target_type: 'stack' | 'fleet' | 'system'; + target_id: string | null; + node_id: number | null; + action: 'restart' | 'snapshot' | 'prune' | 'update'; + cron_expression: string; + enabled: number; + created_by: string; + created_at: number; + updated_at: number; + last_run_at: number | null; + next_run_at: number | null; + last_status: string | null; + last_error: string | null; +} + +interface TaskRun { + id: number; + task_id: number; + started_at: number; + completed_at: number | null; + status: 'running' | 'success' | 'failure'; + output: string | null; + error: string | null; + triggered_by: 'scheduler' | 'manual'; +} + +interface NodeOption { + id: number; + name: string; +} + +const CRON_PRESETS = [ + { label: 'Every 6 hours', value: '0 */6 * * *' }, + { label: 'Every 12 hours', value: '0 */12 * * *' }, + { label: 'Daily at 3 AM', value: '0 3 * * *' }, + { label: 'Daily at midnight', value: '0 0 * * *' }, + { label: 'Weekly (Sunday 3 AM)', value: '0 3 * * 0' }, + { label: 'Custom', value: 'custom' }, +]; + +function getCronDescription(expression: string): string { + try { + return cronstrue.toString(expression); + } catch { + return 'Invalid expression'; + } +} + +function formatTimestamp(ts: number | null): string { + if (!ts) return '-'; + return new Date(ts).toLocaleString(); +} + +function AutoUpdatePoliciesContent() { + const [policies, setPolicies] = useState([]); + const [loading, setLoading] = useState(true); + const [dialogOpen, setDialogOpen] = useState(false); + const [editingPolicy, setEditingPolicy] = useState(null); + const [deleteTarget, setDeleteTarget] = useState(null); + const [runsTask, setRunsTask] = useState(null); + const [runs, setRuns] = useState([]); + const [runsLoading, setRunsLoading] = useState(false); + + // Form state + const [formName, setFormName] = useState(''); + const [formTargetId, setFormTargetId] = useState(''); + const [formNodeId, setFormNodeId] = useState(''); + const [formCron, setFormCron] = useState('0 3 * * *'); + const [formCronPreset, setFormCronPreset] = useState('0 3 * * *'); + const [formEnabled, setFormEnabled] = useState(true); + const [saving, setSaving] = useState(false); + const [runningPolicyId, setRunningPolicyId] = useState(null); + const [runsPage, setRunsPage] = useState(1); + const [runsTotal, setRunsTotal] = useState(0); + const runsLimit = 20; + + // Available stacks and nodes + const [stacks, setStacks] = useState([]); + const [nodes, setNodes] = useState([]); + + const fetchPolicies = useCallback(async () => { + setLoading(true); + try { + const res = await apiFetch('/scheduled-tasks', { localOnly: true }); + if (res.ok) { + const all: ScheduledTask[] = await res.json(); + setPolicies(all.filter(t => t.action === 'update')); + } + } catch { + // Non-critical + } finally { + setLoading(false); + } + }, []); + + const fetchStacks = useCallback(async (nodeId?: string) => { + try { + const res = nodeId + ? await fetchForNode('/stacks', parseInt(nodeId, 10)) + : await apiFetch('/stacks'); + if (res.ok) setStacks(await res.json()); + else setStacks([]); + } catch { setStacks([]); } + }, []); + + const fetchNodes = useCallback(async () => { + try { + const res = await apiFetch('/nodes', { localOnly: true }); + if (res.ok) { + const data = await res.json(); + setNodes(data.map((n: { id: number; name: string }) => ({ id: n.id, name: n.name }))); + } + } catch { /* Non-critical */ } + }, []); + + useEffect(() => { + fetchPolicies(); + fetchStacks(); + fetchNodes(); + }, [fetchPolicies, fetchStacks, fetchNodes]); + + // Re-fetch stacks when selected node changes in the dialog + useEffect(() => { + if (dialogOpen && formNodeId) { + fetchStacks(formNodeId); + setFormTargetId(''); + } + }, [formNodeId, dialogOpen, fetchStacks]); + + const openCreate = () => { + setEditingPolicy(null); + setFormName(''); + setFormTargetId(''); + setFormNodeId(''); + setFormCron('0 3 * * *'); + setFormCronPreset('0 3 * * *'); + setFormEnabled(true); + setDialogOpen(true); + }; + + const openEdit = (policy: ScheduledTask) => { + setEditingPolicy(policy); + setFormName(policy.name); + setFormTargetId(policy.target_id || ''); + setFormNodeId(policy.node_id != null ? String(policy.node_id) : ''); + setFormCron(policy.cron_expression); + const matchingPreset = CRON_PRESETS.find(p => p.value === policy.cron_expression); + setFormCronPreset(matchingPreset ? matchingPreset.value : 'custom'); + setFormEnabled(policy.enabled === 1); + setDialogOpen(true); + }; + + const handleSave = async () => { + const body: Record = { + name: formName, + target_type: 'stack', + action: 'update', + target_id: formTargetId, + node_id: formNodeId ? parseInt(formNodeId, 10) : null, + cron_expression: formCron, + enabled: formEnabled, + }; + + setSaving(true); + try { + const res = editingPolicy + ? await apiFetch(`/scheduled-tasks/${editingPolicy.id}`, { method: 'PUT', body: JSON.stringify(body), localOnly: true }) + : await apiFetch('/scheduled-tasks', { method: 'POST', body: JSON.stringify(body), localOnly: true }); + + if (res.ok) { + toast.success(editingPolicy ? 'Policy updated' : 'Policy created'); + setDialogOpen(false); + fetchPolicies(); + } else { + const data = await res.json().catch(() => ({})); + toast.error(data?.error || 'Failed to save policy'); + } + } catch (error: unknown) { + const msg = error instanceof Error ? error.message : 'Something went wrong.'; + toast.error(msg); + } finally { + setSaving(false); + } + }; + + const handleToggle = async (policy: ScheduledTask) => { + try { + const res = await apiFetch(`/scheduled-tasks/${policy.id}/toggle`, { method: 'PATCH', localOnly: true }); + if (res.ok) { + fetchPolicies(); + } else { + const data = await res.json().catch(() => ({})); + toast.error(data?.error || 'Failed to toggle policy'); + } + } catch { + toast.error('Something went wrong.'); + } + }; + + const handleDelete = async () => { + if (!deleteTarget) return; + try { + const res = await apiFetch(`/scheduled-tasks/${deleteTarget.id}`, { method: 'DELETE', localOnly: true }); + if (res.ok) { + toast.success('Policy deleted'); + setDeleteTarget(null); + fetchPolicies(); + } else { + const data = await res.json().catch(() => ({})); + toast.error(data?.error || 'Failed to delete policy'); + } + } catch { + toast.error('Something went wrong.'); + } + }; + + const openRuns = async (task: ScheduledTask, page = 1) => { + setRunsTask(task); + setRunsPage(page); + setRunsLoading(true); + const offset = (page - 1) * runsLimit; + try { + const res = await apiFetch(`/scheduled-tasks/${task.id}/runs?limit=${runsLimit}&offset=${offset}`, { localOnly: true }); + if (res.ok) { + const data = await res.json(); + setRuns(data.runs); + setRunsTotal(data.total); + } + } catch { /* Non-critical */ } + finally { setRunsLoading(false); } + }; + + const handleRunNow = async (policy: ScheduledTask) => { + setRunningPolicyId(policy.id); + try { + const res = await apiFetch(`/scheduled-tasks/${policy.id}/run`, { method: 'POST', localOnly: true }); + if (res.ok) { + toast.success(`Checking for updates on "${policy.target_id}"...`); + fetchPolicies(); + } else { + const data = await res.json().catch(() => ({})); + toast.error(data?.error || 'Failed to run policy'); + } + } catch { + toast.error('Something went wrong.'); + } finally { + setRunningPolicyId(null); + } + }; + + const cronDescription = getCronDescription(formCron); + + return ( +
+ + +
+
+ + Auto-Update Policies +
+
+ + +
+
+

+ Automatically check for new images and update your stacks on a schedule. +

+
+ + {loading && policies.length === 0 ? ( +
Loading...
+ ) : policies.length === 0 ? ( +
+ No auto-update policies yet. Create one to keep your stacks up to date automatically. +
+ ) : ( + + + + Name + Stack + Schedule + Status + Last Run + Next Run + Enabled + Actions + + + + {policies.map((policy) => ( + + {policy.name} + {policy.target_id === '*' ? 'All Stacks' : policy.target_id} + +
{getCronDescription(policy.cron_expression)}
+
{policy.cron_expression}
+
+ + {policy.last_status === 'success' ? ( + Success + ) : policy.last_status === 'failure' ? ( + Failed + ) : ( + Never run + )} + + + {formatTimestamp(policy.last_run_at)} + + + {formatTimestamp(policy.next_run_at)} + + + handleToggle(policy)} + /> + + +
+ + + + +
+
+
+ ))} +
+
+ )} +
+
+ + {/* Create/Edit Dialog */} + + + + {editingPolicy ? 'Edit Auto-Update Policy' : 'New Auto-Update Policy'} + +
+
+ + setFormName(e.target.value)} /> +
+ +
+ + ({ value: String(n.id), label: n.name }))} + value={formNodeId} + onValueChange={setFormNodeId} + placeholder="Select node..." + searchPlaceholder="Search nodes..." + emptyText="No nodes found." + /> +
+ +
+ + ({ value: s, label: s })), + ]} + value={formTargetId} + onValueChange={setFormTargetId} + placeholder={formNodeId ? "Select stack..." : "Select a node first"} + searchPlaceholder="Search stacks..." + emptyText="No stacks found." + disabled={!formNodeId} + /> +
+ +
+ + + {formCronPreset === 'custom' && ( + setFormCron(e.target.value)} + className="font-mono" + /> + )} +

{cronDescription}

+
+ +
+ + +
+
+ + + + +
+
+ + {/* Delete Confirmation */} + { if (!open) setDeleteTarget(null); }}> + + + Delete Auto-Update Policy + + Are you sure you want to delete “{deleteTarget?.name}”? This will also remove all execution history. This action cannot be undone. + + + + Cancel + + Delete + + + + + + {/* Run History Sheet */} + { if (!open) setRunsTask(null); }}> + + +
+ Update History - {runsTask?.name} + {runsTask && runs.length > 0 && ( + + )} +
+
+
+ {runsLoading ? ( +
Loading...
+ ) : runs.length === 0 ? ( +
No executions yet.
+ ) : ( + <> + + + + Time + Source + Status + Duration + Details + + + + {runs.map((run) => { + const duration = run.completed_at && run.started_at + ? `${((run.completed_at - run.started_at) / 1000).toFixed(1)}s` + : '-'; + return ( + + + {new Date(run.started_at).toLocaleString()} + + + + {run.triggered_by === 'manual' ? 'Manual' : 'Scheduled'} + + + + {run.status === 'success' ? ( + Success + ) : run.status === 'failure' ? ( + Failed + ) : ( + Running + )} + + {duration} + + {run.error || run.output || '-'} + + + ); + })} + +
+ {Math.ceil(runsTotal / runsLimit) > 1 && runsTask && ( +
+

+ Page {runsPage} of {Math.ceil(runsTotal / runsLimit)} +

+
+ + +
+
+ )} + + )} +
+
+
+
+ ); +} + +export default function AutoUpdatePoliciesView() { + return ( + + + + ); +} diff --git a/frontend/src/components/EditorLayout.tsx b/frontend/src/components/EditorLayout.tsx index 7cd7d9f9..860141ea 100644 --- a/frontend/src/components/EditorLayout.tsx +++ b/frontend/src/components/EditorLayout.tsx @@ -43,6 +43,7 @@ import { GlobalObservabilityView } from './GlobalObservabilityView'; import { FleetView } from './FleetView'; import { AuditLogView } from './AuditLogView'; import ScheduledOperationsView from './ScheduledOperationsView'; +import AutoUpdatePoliciesView from './AutoUpdatePoliciesView'; import { useNodes } from '@/context/NodeContext'; import type { Node } from '@/context/NodeContext'; import { useAuth } from '@/context/AuthContext'; @@ -126,7 +127,7 @@ export default function EditorLayout() { window.matchMedia('(prefers-color-scheme: dark)').matches ); const isDarkMode = theme === 'dark' || (theme === 'auto' && systemDark); - const [activeView, setActiveView] = useState<'dashboard' | 'editor' | 'host-console' | 'resources' | 'templates' | 'global-observability' | 'fleet' | 'audit-log' | 'scheduled-ops'>('dashboard'); + const [activeView, setActiveView] = useState<'dashboard' | 'editor' | 'host-console' | 'resources' | 'templates' | 'global-observability' | 'fleet' | 'audit-log' | 'scheduled-ops' | 'auto-updates'>('dashboard'); const [isEditing, setIsEditing] = useState(false); const [searchQuery, setSearchQuery] = useState(''); const [stackStatuses, setStackStatuses] = useState({}); @@ -168,6 +169,9 @@ export default function EditorLayout() { { value: 'templates', label: 'App Store', icon: CloudDownload }, { value: 'global-observability', label: 'Logs', icon: Activity }, ); + if (isPro && isAdmin) { + items.push({ value: 'auto-updates', label: 'Auto-Update', icon: RefreshCw }); + } if (isPro && license?.variant === 'team') { if (isAdmin) items.push({ value: 'host-console', label: 'Console', icon: Terminal }); if (can('system:audit')) items.push({ value: 'audit-log', label: 'Audit', icon: ScrollText }); @@ -445,6 +449,10 @@ export default function EditorLayout() { refreshStacks(); fetchImageUpdates(); + + // Poll for image update results every 5 minutes so background checks are picked up + const imageUpdateInterval = setInterval(fetchImageUpdates, 5 * 60 * 1000); + return () => clearInterval(imageUpdateInterval); }, [activeNode?.id]); // eslint-disable-line react-hooks/exhaustive-deps const fetchNotifications = async () => { @@ -979,6 +987,7 @@ export default function EditorLayout() { setContainers(Array.isArray(conts) ? conts : []); } await refreshStacks(true); + if (action === 'update') fetchImageUpdates(); if (action === 'deploy' && isPro) { try { const backupRes = await apiFetch(`/stacks/${stackName}/backup`); @@ -999,7 +1008,25 @@ export default function EditorLayout() { const res = await apiFetch('/image-updates/refresh', { method: 'POST' }); if (res.ok) { toast.success('Checking for image updates...'); - setTimeout(() => fetchImageUpdates(), 3000); + // Poll until the background check completes instead of using a fixed timeout + let elapsed = 0; + const poll = setInterval(async () => { + elapsed += 2000; + try { + const statusRes = await apiFetch('/image-updates/status'); + if (statusRes.ok) { + const { checking } = await statusRes.json(); + if (!checking || elapsed >= 60000) { + clearInterval(poll); + await fetchImageUpdates(); + if (!checking) toast.success('Image update check complete.'); + } + } + } catch { + clearInterval(poll); + await fetchImageUpdates(); + } + }, 2000); } else { const data = await res.json().catch(() => ({})); toast.error(data.error || 'Failed to check for updates'); @@ -1809,6 +1836,8 @@ export default function EditorLayout() { }} /> ) : activeView === 'audit-log' ? ( + ) : activeView === 'auto-updates' ? ( + ) : activeView === 'scheduled-ops' ? ( ) : ( diff --git a/frontend/src/components/ScheduledOperationsView.tsx b/frontend/src/components/ScheduledOperationsView.tsx index 5130564e..881162a7 100644 --- a/frontend/src/components/ScheduledOperationsView.tsx +++ b/frontend/src/components/ScheduledOperationsView.tsx @@ -2,7 +2,6 @@ import { useState, useEffect, useCallback } from 'react'; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; -import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { Badge } from '@/components/ui/badge'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'; @@ -13,7 +12,8 @@ import { Label } from '@/components/ui/label'; import { Checkbox } from '@/components/ui/checkbox'; import { Clock, Plus, Pencil, Trash2, History, RefreshCw, Play, ChevronLeft, ChevronRight, Download } from 'lucide-react'; import { toast } from '@/components/ui/toast-store'; -import { apiFetch } from '@/lib/api'; +import { apiFetch, fetchForNode } from '@/lib/api'; +import { Combobox } from '@/components/ui/combobox'; import cronstrue from 'cronstrue'; interface ScheduledTask { @@ -117,9 +117,11 @@ export default function ScheduledOperationsView() { } }, []); - const fetchStacks = useCallback(async () => { + const fetchStacks = useCallback(async (nodeId?: string) => { try { - const res = await apiFetch('/stacks'); + const res = nodeId + ? await fetchForNode('/stacks', parseInt(nodeId, 10)) + : await apiFetch('/stacks'); if (res.ok) { setStacks(await res.json()); } @@ -166,6 +168,17 @@ export default function ScheduledOperationsView() { return () => { cancelled = true; }; }, [formAction, formTargetId]); + // Re-fetch stacks when node changes + useEffect(() => { + if (!dialogOpen) return; + if (formNodeId) { + fetchStacks(formNodeId); + setFormTargetId(''); + } else { + setStacks([]); + } + }, [formNodeId, dialogOpen, fetchStacks]); + const openCreate = () => { setEditingTask(null); setFormName(''); @@ -435,45 +448,34 @@ export default function ScheduledOperationsView() {
- + ({ value: o.value, label: o.label }))} + value={formAction} + onValueChange={(val) => { setFormAction(val); setFormTargetId(''); setFormNodeId(''); setFormTargetServices([]); setFormPruneLabelFilter(''); }} + placeholder="Select action..." + />
{targetType === 'stack' && ( <>
- - + + ({ value: String(n.id), label: n.name }))} + value={formNodeId} + onValueChange={setFormNodeId} + placeholder="Select node..." + />
- - + + ({ value: s, label: s }))} + value={formTargetId} + onValueChange={setFormTargetId} + placeholder={formNodeId ? "Select stack..." : "Select a node first"} + disabled={!formNodeId} + />
{formAction === 'restart' && formTargetId && availableServices.length > 0 && (
diff --git a/frontend/src/components/ui/combobox.tsx b/frontend/src/components/ui/combobox.tsx new file mode 100644 index 00000000..260acf11 --- /dev/null +++ b/frontend/src/components/ui/combobox.tsx @@ -0,0 +1,148 @@ +import * as React from "react" +import { Check, ChevronsUpDown } from "lucide-react" + +import { cn } from "@/lib/utils" + +export interface ComboboxOption { + value: string + label: string +} + +interface ComboboxProps { + options: ComboboxOption[] + value: string + onValueChange: (value: string) => void + placeholder?: string + searchPlaceholder?: string + emptyText?: string + disabled?: boolean + className?: string +} + +export function Combobox({ + options, + value, + onValueChange, + placeholder = "Select...", + searchPlaceholder, + emptyText = "No results found.", + disabled = false, + className, +}: ComboboxProps) { + const [open, setOpen] = React.useState(false) + const [search, setSearch] = React.useState("") + const wrapperRef = React.useRef(null) + const inputRef = React.useRef(null) + + const selectedLabel = options.find((o) => o.value === value)?.label + + const filtered = search + ? options.filter((o) => + o.label.toLowerCase().includes(search.toLowerCase()) + ) + : options + + React.useEffect(() => { + if (!open) return + const handler = (e: MouseEvent) => { + if (wrapperRef.current && !wrapperRef.current.contains(e.target as Node)) { + setOpen(false) + setSearch("") + } + } + document.addEventListener("mousedown", handler) + return () => document.removeEventListener("mousedown", handler) + }, [open]) + + React.useEffect(() => { + if (!open) return + const handler = (e: KeyboardEvent) => { + if (e.key === "Escape") { + e.stopPropagation() + setOpen(false) + setSearch("") + } + } + document.addEventListener("keydown", handler, true) + return () => document.removeEventListener("keydown", handler, true) + }, [open]) + + const handleSelect = (option: ComboboxOption) => { + onValueChange(option.value === value ? "" : option.value) + setOpen(false) + setSearch("") + } + + return ( +
+ {/* Trigger: static button when closed, inline search input when open */} + {open ? ( +
+ setSearch(e.target.value)} + placeholder={searchPlaceholder ?? selectedLabel ?? placeholder} + className="h-full w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground" + autoFocus + /> + +
+ ) : ( + + )} + + {/* Options list — absolutely positioned overlay */} + {open && ( +
+
+ {filtered.length === 0 ? ( +
+ {emptyText} +
+ ) : ( + filtered.map((option) => ( + + )) + )} +
+
+ )} +
+ ) +} diff --git a/frontend/src/components/ui/toast.tsx b/frontend/src/components/ui/toast.tsx index c83470b8..c9223d45 100644 --- a/frontend/src/components/ui/toast.tsx +++ b/frontend/src/components/ui/toast.tsx @@ -113,7 +113,7 @@ function ToastItem({ id, type, message }: { id: string; type: ToastType; message animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: 100 }} transition={{ duration: 0.3 }} - className="relative w-full max-w-sm rounded-xl p-4 backdrop-blur-xl bg-white/15 dark:bg-black/15 border border-gray-300/60 dark:border-gray-700/60 overflow-hidden ring-1 ring-gray-200/40 dark:ring-gray-700/40 drop-shadow-xl transition-all duration-300 ease-in-out transform hover:scale-105" + className="relative w-full max-w-sm rounded-xl p-4 backdrop-blur-xl bg-white/15 dark:bg-black/15 border border-gray-300/60 dark:border-gray-700/60 overflow-hidden ring-1 ring-gray-200/40 dark:ring-gray-700/40 drop-shadow-xl transition-all duration-300 ease-in-out transform hover:scale-105 font-[family-name:var(--font-sans)]" onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)} >