This commit is contained in:
jarek committed 2026-01-02 12:24:43 +01:00
1 parent 659d074d00
commit 607d340b71
15 files changed
+619 -375

No files matched your search

+28 -7
View File
@@ -1,5 +1,5 @@
import { json } from '@sveltejs/kit';
import { listComposeStacks, deployStack, saveStackComposeFile, saveStackEnvVars } from '$lib/server/stacks';
import { listComposeStacks, deployStack, saveStackComposeFile, saveStackEnvVars, writeRawStackEnvFile, saveStackEnvVarsToDb } from '$lib/server/stacks';
import { EnvironmentNotFoundError } from '$lib/server/docker';
import { upsertStackSource, getStackSources } from '$lib/server/db';
import { authorize } from '$lib/server/authorize';
@@ -78,7 +78,7 @@ export const POST: RequestHandler = async ({ request, url, cookies }) => {
try {
const body = await request.json();
const { name, compose, start, envVars } = body;
const { name, compose, start, envVars, rawEnvContent } = body;
if (!name || typeof name !== 'string') {
return json({ error: 'Stack name is required' }, { status: 400 });
@@ -95,8 +95,18 @@ export const POST: RequestHandler = async ({ request, url, cookies }) => {
return json({ error: result.error }, { status: 400 });
}
// Save environment variables if provided (to both DB and .env file)
if (envVars && Array.isArray(envVars) && envVars.length > 0) {
// Save environment variables
// NEW SIMPLIFIED: rawEnvContent contains ALL vars including secrets (with real values)
// Secrets are visually masked in the UI but stored with real values in .env file
if (rawEnvContent) {
// Write raw content directly to .env file (includes secrets with real values)
await writeRawStackEnvFile(name, rawEnvContent);
// Save secret metadata to DB (for UI masking purposes)
if (envVars && Array.isArray(envVars) && envVars.length > 0) {
await saveStackEnvVarsToDb(name, envVars, envIdNum);
}
} else if (envVars && Array.isArray(envVars) && envVars.length > 0) {
// Fallback: generate from vars (no raw content provided)
await saveStackEnvVars(name, envVars, envIdNum);
}
@@ -111,11 +121,22 @@ export const POST: RequestHandler = async ({ request, url, cookies }) => {
}
// Save environment variables BEFORE deploying so they're available during start
if (envVars && Array.isArray(envVars) && envVars.length > 0) {
if (rawEnvContent || (envVars && Array.isArray(envVars) && envVars.length > 0)) {
// First ensure the stack directory exists by saving compose file
await saveStackComposeFile(name, compose, true);
// Save to both DB and .env file
await saveStackEnvVars(name, envVars, envIdNum);
// NEW SIMPLIFIED: rawEnvContent contains ALL vars including secrets (with real values)
if (rawEnvContent) {
// Write raw content directly to .env file (includes secrets with real values)
await writeRawStackEnvFile(name, rawEnvContent);
// Save secret metadata to DB (for UI masking purposes)
if (envVars && Array.isArray(envVars) && envVars.length > 0) {
await saveStackEnvVarsToDb(name, envVars, envIdNum);
}
} else {
// Fallback: generate from vars (no raw content provided)
await saveStackEnvVars(name, envVars, envIdNum);
}
}
// Deploy and start the stack
@@ -19,7 +19,7 @@ export const GET: RequestHandler = async ({ params, cookies }) => {
return json({ error: result.error }, { status: 404 });
}
return json({ content: result.content });
return json({ content: result.content, stackDir: result.stackDir });
} catch (error: any) {
console.error(`Error getting compose file for stack ${name}:`, error);
return json({ error: error.message || 'Failed to get compose file' }, { status: 500 });
+21 -94
View File
@@ -30,68 +30,14 @@ function parseEnvFile(content: string): Record<string, string> {
return result;
}
/**
* Merge new variables into existing .env file content.
* - Keeps comments and formatting
* - Updates values for existing keys
* - REMOVES keys that are not in newVars (user deleted them)
* - Appends new keys at the end
*/
function mergeEnvFileContent(
existingContent: string,
newVars: { key: string; value: string }[]
): string {
const newVarsMap = new Map(newVars.map(v => [v.key, v.value]));
const handledKeys = new Set<string>();
const lines = existingContent.split('\n');
const resultLines: string[] = [];
for (const line of lines) {
const trimmed = line.trim();
// Keep comments and blank lines as-is
if (!trimmed || trimmed.startsWith('#')) {
resultLines.push(line);
continue;
}
// Check if this is a variable line
const eqIndex = trimmed.indexOf('=');
if (eqIndex > 0) {
const key = trimmed.substring(0, eqIndex).trim();
if (newVarsMap.has(key)) {
// Update existing variable with new value from UI
resultLines.push(`${key}=${newVarsMap.get(key)}`);
handledKeys.add(key);
}
// If key not in newVarsMap, it was deleted - skip it (don't add to resultLines)
} else {
// Not a valid variable line, keep as-is
resultLines.push(line);
}
}
// Append any new variables that weren't in the original file
for (const v of newVars) {
if (!handledKeys.has(v.key)) {
resultLines.push(`${v.key}=${v.value}`);
}
}
// Ensure file ends with newline
let result = resultLines.join('\n');
if (!result.endsWith('\n')) {
result += '\n';
}
return result;
}
/**
* GET /api/stacks/[name]/env?env=X
* Get all environment variables for a stack.
* Merges variables from database with .env file (file values shown if different).
* Secrets are masked with '***' in the response.
* Merges variables from database with .env file (file values override for non-secrets).
*
* SECURITY: Secrets are returned as '***' (masked) - they are NEVER sent in plain text.
* Secrets are stored only in the database and injected via shell environment at runtime.
* The .env file only contains non-secret variables.
*/
export const GET: RequestHandler = async ({ params, url, cookies }) => {
const auth = await authorize(cookies);
@@ -111,11 +57,11 @@ export const GET: RequestHandler = async ({ params, url, cookies }) => {
try {
const stackName = decodeURIComponent(params.name);
// Get variables from database
// Get variables from database (masked - secrets show as '***')
const dbVariables = await getStackEnvVars(stackName, envIdNum, true);
const dbByKey = new Map(dbVariables.map(v => [v.key, v]));
// Try to read .env file from stack directory
// Try to read .env file from stack directory (only contains non-secrets)
const stacksDir = getStacksDir();
const envFilePath = join(stacksDir, stackName, '.env');
let fileVars: Record<string, string> = {};
@@ -129,7 +75,9 @@ export const GET: RequestHandler = async ({ params, url, cookies }) => {
}
}
// Merge: start with DB variables, add any new keys from file
// Merge: DB variables (with secrets masked) + file variables (non-secrets only)
// For non-secrets: file value overrides DB value (user may have edited file)
// For secrets: only DB value exists (masked as '***')
const mergedKeys = new Set([...dbByKey.keys(), ...Object.keys(fileVars)]);
const variables: { key: string; value: string; isSecret: boolean }[] = [];
@@ -138,15 +86,14 @@ export const GET: RequestHandler = async ({ params, url, cookies }) => {
const fileValue = fileVars[key];
if (dbVar) {
// Variable exists in DB
if (dbVar.isSecret) {
// Keep secret masked
// Secret: use masked value from DB, ignore any file value
variables.push({ key, value: dbVar.value, isSecret: true });
} else if (fileValue !== undefined && fileValue !== dbVar.value) {
// File has different value - use file value (user may have edited it)
} else if (fileValue !== undefined) {
// Non-secret with file value: file overrides (user may have edited)
variables.push({ key, value: fileValue, isSecret: false });
} else {
// Use DB value
// Non-secret only in DB: use DB value
variables.push({ key, value: dbVar.value, isSecret: false });
}
} else if (fileValue !== undefined) {
@@ -167,8 +114,12 @@ export const GET: RequestHandler = async ({ params, url, cookies }) => {
* Set/replace all environment variables for a stack.
* Body: { variables: [{ key, value, isSecret? }] }
*
* Note: For secrets, if the value is '***' (the masked placeholder), the original
* SECURITY: Secrets are stored ONLY in the database, NEVER written to .env file.
* For secrets, if the value is '***' (the masked placeholder), the original
* secret value from the database is preserved instead of overwriting with '***'.
*
* The .env file only contains non-secret variables (can be edited manually).
* Secrets are injected via shell environment variables at runtime.
*/
export const PUT: RequestHandler = async ({ params, url, cookies, request }) => {
const auth = await authorize(cookies);
@@ -234,34 +185,10 @@ export const PUT: RequestHandler = async ({ params, url, cookies, request }) =>
});
}
// Save ALL variables (including secrets) to database
// Note: The .env file is written by PUT /env/raw endpoint, which preserves comments
await setStackEnvVars(stackName, envIdNum, variablesToSave);
// Also write the .env file to the stack directory
// This allows users to see/edit variables outside of Dockhand
const stacksDir = getStacksDir();
const stackDir = join(stacksDir, stackName);
const envFilePath = join(stackDir, '.env');
// Only write if stack directory exists
if (existsSync(stackDir)) {
// Read existing file to preserve comments and formatting
let existingContent = '';
if (existsSync(envFilePath)) {
try {
existingContent = await Bun.file(envFilePath).text();
} catch {
// File read failed, start fresh
}
}
// Merge UI vars with existing file (preserves comments, keeps file vars)
const envContent = mergeEnvFileContent(
existingContent,
variablesToSave.map((v: { key: string; value: string }) => ({ key: v.key, value: v.value }))
);
await Bun.write(envFilePath, envContent);
}
return json({ success: true, count: variablesToSave.length });
} catch (error) {
console.error('Error setting stack env vars:', error);
+20 -3
View File
@@ -1,7 +1,7 @@
import { json } from '@sveltejs/kit';
import { getStacksDir } from '$lib/server/stacks';
import { authorize } from '$lib/server/authorize';
import { existsSync } from 'node:fs';
import { existsSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import type { RequestHandler } from './$types';
@@ -82,9 +82,26 @@ export const PUT: RequestHandler = async ({ params, url, cookies, request }) =>
return json({ error: 'Stack directory not found' }, { status: 404 });
}
// Ensure content ends with newline
let content = body.content;
if (content && !content.endsWith('\n')) {
// If content is empty, delete the .env file instead of writing empty file
if (!content || !content.trim()) {
if (existsSync(envFilePath)) {
rmSync(envFilePath);
return json({ success: true, deleted: true });
}
return json({ success: true });
}
// Guard against writing masked secret placeholders (would corrupt the file)
if (content.match(/^[A-Za-z_][A-Za-z0-9_]*=\*\*\*$/m)) {
return json({
error: 'Cannot write masked placeholder "***" to .env file - this would corrupt secret values'
}, { status: 400 });
}
// Ensure content ends with newline
if (!content.endsWith('\n')) {
content += '\n';
}
@@ -7,7 +7,8 @@
import { Badge } from '$lib/components/ui/badge';
import { TogglePill } from '$lib/components/ui/toggle-pill';
import { Checkbox } from '$lib/components/ui/checkbox';
import { Plus, Check, RefreshCw, Mail, Zap, Info, Send, CheckCircle2, XCircle, Key, ChevronDown } from 'lucide-svelte';
import { Plus, Check, RefreshCw, Mail, Zap, Info, Send, CheckCircle2, XCircle, Key, ChevronDown, HelpCircle } from 'lucide-svelte';
import * as Tooltip from '$lib/components/ui/tooltip';
import { toast } from 'svelte-sonner';
import { focusFirstInput } from '$lib/utils';
@@ -343,7 +344,20 @@
{#if formType === 'smtp'}
<div class="space-y-4 border-t pt-4 min-h-[380px]">
<p class="text-xs font-semibold uppercase tracking-wider text-muted-foreground">SMTP configuration</p>
<div class="flex items-center gap-2">
<p class="text-xs font-semibold uppercase tracking-wider text-muted-foreground">SMTP configuration</p>
<Tooltip.Root>
<Tooltip.Trigger>
<HelpCircle class="w-3.5 h-3.5 text-muted-foreground hover:text-foreground cursor-help" />
</Tooltip.Trigger>
<Tooltip.Portal>
<Tooltip.Content side="right" class="w-80">
<p class="text-xs"><span class="font-semibold">Gmail:</span> smtp.gmail.com, port 587, TLS/SSL off. Use an App Password.</p>
<p class="text-xs mt-1"><span class="font-semibold">Outlook:</span> smtp.office365.com, port 587, TLS/SSL off.</p>
</Tooltip.Content>
</Tooltip.Portal>
</Tooltip.Root>
</div>
<div class="grid grid-cols-3 gap-4">
<div class="space-y-2 col-span-2">
<Label for="notif-smtp-host">SMTP host *</Label>
+26 -37
View File
@@ -24,6 +24,7 @@
import PageHeader from '$lib/components/PageHeader.svelte';
import { DataGrid } from '$lib/components/data-grid';
import type { DataGridSortState } from '$lib/components/data-grid/types';
import { ErrorDialog } from '$lib/components/ui/error-dialog';
type SortField = 'name' | 'containers' | 'status' | 'cpu' | 'memory';
type SortDirection = 'asc' | 'desc';
@@ -281,14 +282,13 @@
let confirmPauseContainerId = $state<string | null>(null);
// Operation error state (for stack and container operations)
let operationError = $state<{ id: string; message: string } | null>(null);
let errorTimeouts: ReturnType<typeof setTimeout>[] = [];
let operationError = $state<{ id: string; title: string; message: string } | null>(null);
function clearErrorAfterDelay(id: string) {
const timeoutId = setTimeout(() => {
if (operationError?.id === id) operationError = null;
}, 5000);
errorTimeouts.push(timeoutId);
// Error dialog state (for showing detailed errors)
let errorDialogData = $state<{ title: string; message: string } | null>(null);
function showErrorDialog(title: string, message: string) {
errorDialogData = { title, message };
}
// Container inspect modal state
@@ -673,9 +673,7 @@
if (!response.ok) {
const data = await response.json();
const errorMsg = data.error || 'Failed to start stack';
operationError = { id: name, message: errorMsg };
toast.error(errorMsg);
clearErrorAfterDelay(name);
showErrorDialog(`Failed to start ${name}`, errorMsg);
return;
}
toast.success(`Started ${name}`);
@@ -683,9 +681,7 @@
} catch (error) {
console.error('Failed to start stack:', error);
const errorMsg = error instanceof Error ? error.message : 'Failed to start stack';
operationError = { id: name, message: errorMsg };
toast.error(errorMsg);
clearErrorAfterDelay(name);
showErrorDialog(`Failed to start ${name}`, errorMsg);
} finally {
stackActionLoading = null;
}
@@ -699,9 +695,7 @@
if (!response.ok) {
const data = await response.json();
const errorMsg = data.error || 'Failed to stop stack';
operationError = { id: name, message: errorMsg };
toast.error(errorMsg);
clearErrorAfterDelay(name);
showErrorDialog(`Failed to stop ${name}`, errorMsg);
return;
}
toast.success(`Stopped ${name}`);
@@ -709,9 +703,7 @@
} catch (error) {
console.error('Failed to stop stack:', error);
const errorMsg = error instanceof Error ? error.message : 'Failed to stop stack';
operationError = { id: name, message: errorMsg };
toast.error(errorMsg);
clearErrorAfterDelay(name);
showErrorDialog(`Failed to stop ${name}`, errorMsg);
} finally {
stackActionLoading = null;
}
@@ -725,9 +717,7 @@
if (!response.ok) {
const data = await response.json();
const errorMsg = data.error || 'Failed to restart stack';
operationError = { id: name, message: errorMsg };
toast.error(errorMsg);
clearErrorAfterDelay(name);
showErrorDialog(`Failed to restart ${name}`, errorMsg);
return;
}
toast.success(`Restarted ${name}`);
@@ -735,9 +725,7 @@
} catch (error) {
console.error('Failed to restart stack:', error);
const errorMsg = error instanceof Error ? error.message : 'Failed to restart stack';
operationError = { id: name, message: errorMsg };
toast.error(errorMsg);
clearErrorAfterDelay(name);
showErrorDialog(`Failed to restart ${name}`, errorMsg);
} finally {
stackActionLoading = null;
}
@@ -751,9 +739,7 @@
if (!response.ok) {
const data = await response.json();
const errorMsg = data.error || 'Failed to bring down stack';
operationError = { id: name, message: errorMsg };
toast.error(errorMsg);
clearErrorAfterDelay(name);
showErrorDialog(`Failed to bring down ${name}`, errorMsg);
return;
}
toast.success(`Brought down ${name}`);
@@ -761,9 +747,7 @@
} catch (error) {
console.error('Failed to bring down stack:', error);
const errorMsg = error instanceof Error ? error.message : 'Failed to bring down stack';
operationError = { id: name, message: errorMsg };
toast.error(errorMsg);
clearErrorAfterDelay(name);
showErrorDialog(`Failed to bring down ${name}`, errorMsg);
} finally {
stackActionLoading = null;
}
@@ -789,9 +773,7 @@
if (!response.ok) {
const data = await response.json();
const errorMsg = data.error || 'Failed to remove stack';
operationError = { id: name, message: errorMsg };
toast.error(errorMsg);
clearErrorAfterDelay(name);
showErrorDialog(`Failed to remove ${name}`, errorMsg);
return;
}
toast.success(`Removed ${name}`);
@@ -799,9 +781,7 @@
} catch (error) {
console.error('Failed to remove stack:', error);
const errorMsg = error instanceof Error ? error.message : 'Failed to remove stack';
operationError = { id: name, message: errorMsg };
toast.error(errorMsg);
clearErrorAfterDelay(name);
showErrorDialog(`Failed to remove ${name}`, errorMsg);
}
}
@@ -1970,3 +1950,12 @@
onClose={() => showBatchOpModal = false}
onComplete={handleBatchComplete}
/>
{#if errorDialogData}
<ErrorDialog
open={true}
title={errorDialogData.title}
message={errorDialogData.message}
onClose={() => errorDialogData = null}
/>
{/if}
+97 -60
View File
@@ -7,11 +7,12 @@
import CodeEditor, { type VariableMarker } from '$lib/components/CodeEditor.svelte';
import StackEnvVarsPanel from '$lib/components/StackEnvVarsPanel.svelte';
import { type EnvVar, type ValidationResult } from '$lib/components/StackEnvVarsEditor.svelte';
import { Layers, Save, Play, Code, GitGraph, Loader2, AlertCircle, X, Sun, Moon, TriangleAlert, ChevronsLeft, ChevronsRight, Variable, HelpCircle, GripVertical } from 'lucide-svelte';
import { Layers, Save, Play, Code, GitGraph, Loader2, AlertCircle, X, Sun, Moon, TriangleAlert, ChevronsLeft, ChevronsRight, Variable, HelpCircle, GripVertical, FolderOpen } from 'lucide-svelte';
import * as Tooltip from '$lib/components/ui/tooltip';
import { currentEnvironment, appendEnvParam } from '$lib/stores/environment';
import { focusFirstInput } from '$lib/utils';
import * as Alert from '$lib/components/ui/alert';
import { ErrorDialog } from '$lib/components/ui/error-dialog';
import ComposeGraphViewer from './ComposeGraphViewer.svelte';
// localStorage key for persisted split ratio
@@ -41,20 +42,30 @@
// Environment variables state
let envVars = $state<EnvVar[]>([]);
let rawEnvContent = $state('');
let rawEnvContent = $state(''); // Raw .env file content (comments preserved)
let envValidation = $state<ValidationResult | null>(null);
let validating = $state(false);
let existingSecretKeys = $state<Set<string>>(new Set());
let hadExistingDbVars = $state(false); // Track if DB had any vars on load (for proper cleanup)
// Simple dirty flag - only set when user touches something
let isDirty = $state(false);
// Error dialog state
let operationError = $state<{ title: string; message: string; details?: string } | null>(null);
// Stack location (for edit mode)
let stackLocation = $state<string | null>(null);
// CodeEditor reference for explicit marker updates
let codeEditorRef: CodeEditor | null = $state(null);
// ComposeGraphViewer reference for resize on panel toggle
let graphViewerRef: ComposeGraphViewer | null = $state(null);
// EnvVarsPanel reference for sync before save
let envVarsPanelRef: StackEnvVarsPanel | null = $state(null);
// Resizable split panel state
let splitRatio = $state(60); // percentage for compose panel
let isDraggingSplit = $state(false);
@@ -239,33 +250,37 @@ services:
}
composeContent = data.content;
stackLocation = data.stackDir || null;
// Load environment variables (parsed)
const envResponse = await fetch(appendEnvParam(`/api/stacks/${encodeURIComponent(stackName)}/env`, envId));
if (envResponse.ok) {
const envData = await envResponse.json();
envVars = envData.variables || [];
// Track if DB had any vars (for proper cleanup on clear-all)
hadExistingDbVars = envVars.length > 0;
// Track existing secret keys (secrets loaded from DB cannot have visibility toggled)
existingSecretKeys = new Set(
envVars.filter(v => v.isSecret && v.key.trim()).map(v => v.key.trim())
);
}
// Load raw .env file content
// Load raw .env file content (for preserving comments)
const rawEnvResponse = await fetch(appendEnvParam(`/api/stacks/${encodeURIComponent(stackName)}/env/raw`, envId));
if (rawEnvResponse.ok) {
const rawEnvData = await rawEnvResponse.json();
rawEnvContent = rawEnvData.content || '';
console.log('[loadComposeFile] rawEnvContent loaded:', rawEnvContent);
}
// Wait for $effects in StackEnvVarsPanel to settle (parses raw content, syncs variables)
await tick();
// Reset dirty flag after loading completes
isDirty = false;
} catch (e: any) {
loadError = e.message;
} finally {
loading = false;
// Merge variables and rawContent after both are loaded
await tick();
envVarsPanelRef?.mergeOnLoad();
// Reset dirty flag after loading completes
isDirty = false;
}
}
@@ -328,13 +343,13 @@ services:
saving = true;
error = null;
// Prepare env vars for creating - syncs variables and rawContent
const prepared = envVarsPanelRef?.prepareForSave() || { rawContent: '', variables: [] };
try {
const envId = $currentEnvironment?.id ?? null;
// Collect environment variables
const definedVars = envVars.filter(v => v.key.trim());
// Create the stack (include env vars so they're available before start)
// Create the stack (include env vars and raw content for .env file)
const response = await fetch(appendEnvParam('/api/stacks', envId), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -342,7 +357,10 @@ services:
name: newStackName.trim(),
compose: content,
start,
envVars: definedVars.length > 0 ? definedVars.map(v => ({
// Send raw env content (non-secrets only, preserves comments/formatting)
rawEnvContent: prepared.rawContent.trim() ? prepared.rawContent : undefined,
// Also send parsed vars for DB secret tracking (includes secrets)
envVars: prepared.variables.length > 0 ? prepared.variables.map(v => ({
key: v.key.trim(),
value: v.value,
isSecret: v.isSecret
@@ -358,7 +376,11 @@ services:
onSuccess();
handleClose();
} catch (e: any) {
error = e.message;
operationError = {
title: 'Failed to create stack',
message: e.message || 'An error occurred while creating the stack',
details: e.details
};
} finally {
saving = false;
}
@@ -375,6 +397,9 @@ services:
saving = true;
error = null;
// Prepare env vars for saving - syncs variables and rawContent
const prepared = envVarsPanelRef?.prepareForSave() || { rawContent: '', variables: [] };
try {
const envId = $currentEnvironment?.id ?? null;
@@ -397,56 +422,50 @@ services:
throw new Error(data.error || 'Failed to save compose file');
}
// Save environment variables
// Always save to raw endpoint for consistency
// If no raw content but has env vars, generate raw content from vars (backward compat)
const definedVars = envVars.filter(v => v.key.trim());
let contentToSave = rawEnvContent;
// Save raw content to .env file (non-secrets only, comments preserved)
const rawEnvResponse = await fetch(
appendEnvParam(`/api/stacks/${encodeURIComponent(stackName)}/env/raw`, envId),
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content: prepared.rawContent })
}
);
// Backward compatibility: if no raw file but has DB envs, generate raw content
if (!contentToSave.trim() && definedVars.length > 0) {
contentToSave = definedVars.map(v => `${v.key.trim()}=${v.value}`).join('\n') + '\n';
if (!rawEnvResponse.ok) {
const rawEnvError = await rawEnvResponse.json().catch(() => ({ error: 'Failed to save environment file' }));
throw new Error(rawEnvError.error || 'Failed to save environment file');
}
// Save if there's any content
if (contentToSave.trim() || definedVars.length > 0) {
const rawEnvResponse = await fetch(
appendEnvParam(`/api/stacks/${encodeURIComponent(stackName)}/env/raw`, envId),
// Save ALL vars to DB (includes secrets with real values)
const definedVars = prepared.variables;
if (definedVars.length > 0 || hadExistingDbVars) {
const envResponse = await fetch(
appendEnvParam(`/api/stacks/${encodeURIComponent(stackName)}/env`, envId),
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content: contentToSave })
body: JSON.stringify({
variables: definedVars.map(v => ({
key: v.key.trim(),
value: v.value,
isSecret: v.isSecret
}))
})
}
);
if (!rawEnvResponse.ok) {
console.error('Failed to save environment file');
if (!envResponse.ok) {
// Log but don't fail - DB stores secret metadata
console.warn('Failed to save environment variable metadata to database');
}
// Also save to DB for secret tracking
if (definedVars.some(v => v.isSecret)) {
const envResponse = await fetch(
appendEnvParam(`/api/stacks/${encodeURIComponent(stackName)}/env`, envId),
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
variables: definedVars.map(v => ({
key: v.key.trim(),
value: v.value,
isSecret: v.isSecret
}))
})
}
);
if (!envResponse.ok) {
console.error('Failed to save secret markers to database');
}
}
hadExistingDbVars = definedVars.length > 0;
existingSecretKeys = new Set(
definedVars.filter(v => v.isSecret && v.key.trim()).map(v => v.key.trim())
);
}
rawEnvContent = contentToSave; // Sync raw content if it was generated
isDirty = false; // Reset dirty flag after successful save
onSuccess();
@@ -457,7 +476,11 @@ services:
handleClose();
}
} catch (e: any) {
error = e.message;
operationError = {
title: restart ? 'Failed to apply stack' : 'Failed to save stack',
message: e.message || (restart ? 'An error occurred while applying the stack' : 'An error occurred while saving the stack'),
details: e.details
};
} finally {
saving = false;
}
@@ -481,16 +504,19 @@ services:
newStackName = '';
error = null;
loadError = null;
rawEnvContent = '';
errors = {};
composeContent = '';
envVars = [];
rawEnvContent = '';
envValidation = null;
isDirty = false;
existingSecretKeys = new Set();
hadExistingDbVars = false;
activeTab = 'editor';
showConfirmClose = false;
codeEditorRef = null;
operationError = null;
stackLocation = null;
onClose();
}
@@ -575,6 +601,11 @@ services:
<Dialog.Description class="text-xs text-zinc-500 dark:text-zinc-400">
{#if mode === 'create'}
Create a new Docker Compose stack
{:else if stackLocation}
<span class="flex items-center gap-1">
<FolderOpen class="w-3 h-3" />
<code class="bg-zinc-200 dark:bg-zinc-700 px-1 rounded text-2xs">{stackLocation}</code>
</span>
{:else}
Edit compose file and view stack structure
{/if}
@@ -629,13 +660,6 @@ services:
</Dialog.Header>
<div class="flex-1 overflow-hidden flex flex-col min-h-0">
{#if error}
<Alert.Root variant="destructive" class="mx-6 mt-4">
<TriangleAlert class="h-4 w-4" />
<Alert.Description>{error}</Alert.Description>
</Alert.Root>
{/if}
{#if errors.compose}
<Alert.Root variant="destructive" class="mx-6 mt-4">
<TriangleAlert class="h-4 w-4" />
@@ -757,6 +781,7 @@ services:
</div>
<div class="flex-1 min-h-0 overflow-hidden">
<StackEnvVarsPanel
bind:this={envVarsPanelRef}
bind:variables={envVars}
bind:rawContent={rawEnvContent}
validation={envValidation}
@@ -858,3 +883,15 @@ services:
</div>
</Dialog.Content>
</Dialog.Root>
<!-- Error dialog for failed operations -->
{#if operationError}
{@const errorDialogOpen = true}
<ErrorDialog
open={errorDialogOpen}
title={operationError.title}
message={operationError.message}
details={operationError.details}
onClose={() => operationError = null}
/>
{/if}