This commit is contained in:
jarek committed 2026-06-15 14:56:51 +02:00
1 parent d465ecfe96
commit 83c3a5ea09
85 files changed
+10118 -1046

No files matched your search

@@ -0,0 +1,80 @@
/**
* POST /api/containers/[id]/update-runtime
*
* In-place update of a running container's restart policy, CPU/memory limits,
* blkio weights, and pids limit — the only properties Docker can change
* without recreating the container. The body must contain ONLY fields from
* IN_PLACE_UPDATE_FIELDS (see docker.ts); any unknown fields are silently
* dropped so a confused or malicious caller can't sneak a recreate-only
* field (image, env, ports, etc.) through this path.
*
* Returns Docker's response — typically `{ Warnings: string[] | null }`.
*/
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { authorize } from '$lib/server/authorize';
import { auditContainer } from '$lib/server/audit';
import { validateDockerIdParam } from '$lib/server/docker-validation';
import { inspectContainer, updateContainerRuntime, IN_PLACE_UPDATE_FIELDS, type InPlaceUpdateField } from '$lib/server/docker';
export const POST: RequestHandler = async (event) => {
const { params, request, url, cookies } = event;
const invalid = validateDockerIdParam(params.id, 'container');
if (invalid) return invalid;
const auth = await authorize(cookies);
const envId = url.searchParams.get('env');
const envIdNum = envId ? parseInt(envId) : undefined;
// Same permission as the recreate-style update — anyone who could edit
// the container the slow way should be able to edit it the fast way.
if (auth.authEnabled && !await auth.can('containers', 'create', envIdNum)) {
return json({ error: 'Permission denied' }, { status: 403 });
}
let body: Record<string, unknown>;
try {
body = await request.json();
} catch {
return json({ error: 'Invalid JSON body' }, { status: 400 });
}
// Sanity-check: at least one allowed field must be present. Empty/all-unknown
// payloads get a clear error rather than silently calling Docker with {}.
const allowed = new Set<string>(IN_PLACE_UPDATE_FIELDS);
const filtered: Partial<Record<InPlaceUpdateField, unknown>> = {};
for (const [k, v] of Object.entries(body)) {
if (allowed.has(k) && v !== undefined) filtered[k as InPlaceUpdateField] = v;
}
if (Object.keys(filtered).length === 0) {
return json({
error: 'No supported fields provided',
supportedFields: Array.from(allowed)
}, { status: 400 });
}
try {
const result = await updateContainerRuntime(params.id, filtered, envIdNum);
// Audit log — include which fields were touched, not their values
// (CPU/memory numbers are non-sensitive, but the audit row stays
// cleaner if we just record the keys).
let containerName = params.id;
try {
const inspect = await inspectContainer(params.id, envIdNum);
containerName = inspect.Name?.replace(/^\//, '') || params.id;
} catch { /* fallback to id */ }
await auditContainer(event, 'update', params.id, containerName, envIdNum, {
inPlace: true,
fields: Object.keys(filtered),
warnings: result.Warnings ?? []
});
return json({ success: true, warnings: result.Warnings ?? [] });
} catch (error: any) {
if (error?.statusCode === 404) {
return json({ error: 'Container not found' }, { status: 404 });
}
return json({ error: error?.message || 'Update failed' }, { status: 500 });
}
};
@@ -4,7 +4,7 @@ import { authorize } from '$lib/server/authorize';
import { listContainers, inspectContainer, checkImageUpdateAvailable } from '$lib/server/docker';
import { clearPendingContainerUpdates, addPendingContainerUpdate } from '$lib/server/db';
import { isSystemContainer } from '$lib/server/scheduler/tasks/update-utils';
import { isUpdateDisabledByLabel } from '$lib/server/container-labels';
import { isUpdateDisabledByLabel, isHiddenByLabel } from '$lib/server/container-labels';
import { createJobResponse } from '$lib/server/sse';
export interface UpdateCheckResult {
@@ -42,7 +42,9 @@ export const POST: RequestHandler = async ({ url, cookies, request }) => {
}
const allContainers = await listContainers(true, envIdNum);
const containers = allContainers;
// Containers labeled dockhand.hidden=true are excluded from update checks —
// they're invisible to the user, so we won't alert on updates for them either (#1083).
const containers = allContainers.filter(c => !isHiddenByLabel(c.labels));
send('progress', { checked: 0, total: containers.length });
@@ -65,8 +67,19 @@ export const POST: RequestHandler = async ({ url, cookies, request }) => {
};
}
const result = await checkImageUpdateAvailable(imageName, currentImageId, envIdNum);
const updateDisabled = isUpdateDisabledByLabel(inspectData.Config?.Labels);
if (updateDisabled) {
return {
containerId: container.id,
containerName: container.name,
imageName,
hasUpdate: false,
systemContainer: isSystemContainer(imageName) || null,
updateDisabled: true
};
}
const result = await checkImageUpdateAvailable(imageName, currentImageId, envIdNum);
return {
containerId: container.id,
+4 -2
View File
@@ -7,6 +7,7 @@ import { invalidateTokenCacheForUser } from '$lib/server/api-tokens';
import { refreshSubprocessEnvironments } from '$lib/server/subprocess-manager';
import { serializeLabels, parseLabels, MAX_LABELS } from '$lib/utils/label-colors';
import { cleanPem } from '$lib/utils/pem';
import { validateEnvName } from '$lib/utils/env-name';
export const GET: RequestHandler = async ({ cookies }) => {
const auth = await authorize(cookies);
@@ -71,8 +72,9 @@ export const POST: RequestHandler = async (event) => {
try {
const data = await request.json();
if (!data.name) {
return json({ error: 'Name is required' }, { status: 400 });
const nameCheck = validateEnvName(data.name);
if (!nameCheck.ok) {
return json({ error: nameCheck.reason }, { status: 400 });
}
// Check if environment with this name already exists
+61 -1
View File
@@ -1,6 +1,6 @@
import { json } from '@sveltejs/kit';
import { join } from 'path';
import { existsSync, rmSync } from 'fs';
import { existsSync, rmSync, renameSync } from 'fs';
import type { RequestHandler } from './$types';
import { getEnvironment, updateEnvironment, deleteEnvironment, getEnvironmentPublicIps, setEnvironmentPublicIp, deleteEnvironmentPublicIp, deleteEnvUpdateCheckSettings, deleteImagePruneSettings, getGitStacksForEnvironmentOnly, deleteGitStack } from '$lib/server/db';
import { clearDockerClientCache } from '$lib/server/docker';
@@ -11,6 +11,7 @@ import { auditEnvironment } from '$lib/server/audit';
import { refreshSubprocessEnvironments } from '$lib/server/subprocess-manager';
import { serializeLabels, parseLabels, MAX_LABELS } from '$lib/utils/label-colors';
import { cleanPem } from '$lib/utils/pem';
import { validateEnvName } from '$lib/utils/env-name';
import { unregisterSchedule } from '$lib/server/scheduler';
import { closeEdgeConnection } from '$lib/server/hawser';
import { computeAuditDiff } from '$lib/utils/diff';
@@ -64,6 +65,65 @@ export const PUT: RequestHandler = async (event) => {
const data = await request.json();
// #1179: validate name if it's being changed. Existing invalid names are
// not auto-corrected — only writes go through this check.
const isRename = data.name !== undefined && data.name !== oldEnv.name;
if (isRename) {
const nameCheck = validateEnvName(data.name);
if (!nameCheck.ok) {
return json({ error: nameCheck.reason }, { status: 400 });
}
}
// Rename on-disk directories BEFORE the DB write. If the fs rename
// fails (cross-mount EXDEV, perm error, target exists), we surface a
// 409 and leave the DB untouched — better than the previous behavior
// of silently orphaning stacks under the old name.
//
// Applies to ALL connection types. For socket/direct envs the staging
// dir IS the deployed dir, so containers need a redeploy after rename
// (see client warning). For Hawser envs the agent owns the deployed
// dir on the remote host and isn't affected, but Dockhand still keeps
// a local staging copy under stacks/<envName>/<stackName>/ (for the
// in-app editor) and ALL git stacks clone to git-repos/<envName>/
// regardless of where they ultimately deploy — so the rename matters
// locally for every env type.
if (isRename) {
const stacksDir = getStacksDir();
const gitReposDir = getGitReposDir();
const oldStacks = join(stacksDir, oldEnv.name);
const newStacks = join(stacksDir, data.name);
const oldRepos = join(gitReposDir, oldEnv.name);
const newRepos = join(gitReposDir, data.name);
// Refuse to overwrite a target dir that already holds someone
// else's data.
if (existsSync(oldStacks) && existsSync(newStacks)) {
return json({
error: `Cannot rename: ${newStacks} already exists. Pick a different name or move that directory out of the way.`
}, { status: 409 });
}
if (existsSync(oldRepos) && existsSync(newRepos)) {
return json({
error: `Cannot rename: ${newRepos} already exists. Pick a different name or move that directory out of the way.`
}, { status: 409 });
}
try {
if (existsSync(oldStacks)) renameSync(oldStacks, newStacks);
if (existsSync(oldRepos)) renameSync(oldRepos, newRepos);
} catch (err: any) {
// Best-effort rollback if the second rename failed after the first
// succeeded. Avoids leaving the filesystem in a split state.
try { if (existsSync(newStacks) && !existsSync(oldStacks)) renameSync(newStacks, oldStacks); } catch {}
try { if (existsSync(newRepos) && !existsSync(oldRepos)) renameSync(newRepos, oldRepos); } catch {}
const code = err?.code === 'EXDEV'
? 'EXDEV: stacks dir is on a different filesystem from the rename target. Move it back to the same filesystem to rename this environment.'
: (err?.message || 'Rename failed');
return json({ error: code }, { status: 409 });
}
}
// Clear cached Docker client before updating
clearDockerClientCache(id);
+16 -3
View File
@@ -1,6 +1,7 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { inspectImage, tagImage, pushImage, parseRegistryUrl } from '$lib/server/docker';
import { encodeRegistryAuth } from '$lib/server/registry-auth';
import { getRegistry, getEnvironment } from '$lib/server/db';
import { authorize } from '$lib/server/authorize';
import { auditImage } from '$lib/server/audit';
@@ -110,8 +111,9 @@ export const POST: RequestHandler = async (event) => {
const authServerAddress = isDockerHub ? 'https://index.docker.io/v1/' : registryHost;
const authConfig = registry.username && registry.password
? {
username: registry.username,
password: registry.password,
// Trim to neutralize stray whitespace in legacy stored credentials (#1105)
username: registry.username.trim(),
password: registry.password.trim(),
serveraddress: authServerAddress
}
: {
@@ -148,7 +150,18 @@ export const POST: RequestHandler = async (event) => {
return;
}
const authHeader = Buffer.from(JSON.stringify(authConfig)).toString('base64');
const authHeader = encodeRegistryAuth(authConfig);
{
const u = (authConfig as { username?: string }).username ?? '';
const p = (authConfig as { password?: string }).password ?? '';
const userLast = u.length ? u.charCodeAt(u.length - 1).toString(16) : 'na';
const pwLast = p.length ? p.charCodeAt(p.length - 1).toString(16) : 'na';
console.log(
`[Push/Edge] auth: registry=${registryHost} user(len=${u.length},last=0x${userLast}) ` +
`pw(len=${p.length},last=0x${pwLast}) serveraddress=${authConfig.serveraddress} ` +
`authHeader(len=${authHeader.length},prefix=${authHeader.slice(0, 16)})`
);
}
await new Promise<void>((resolve, reject) => {
sendEdgeStreamRequest(
+1 -1
View File
@@ -63,7 +63,7 @@ export const POST: RequestHandler = async (event) => {
} else if (type === 'apprise') {
const appriseConfig = config as AppriseConfig;
if (!appriseConfig.urls?.length) {
return json({ error: 'Apprise config requires at least one URL' }, { status: 400 });
return json({ error: 'Webhook config requires at least one URL' }, { status: 400 });
}
}
+1 -1
View File
@@ -82,7 +82,7 @@ export const PUT: RequestHandler = async (event) => {
} else if (existing.type === 'apprise') {
const appriseConfig = config as AppriseConfig;
if (!appriseConfig.urls?.length) {
return json({ error: 'Apprise config requires at least one URL' }, { status: 400 });
return json({ error: 'Webhook config requires at least one URL' }, { status: 400 });
}
}
}
+1 -1
View File
@@ -29,7 +29,7 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
if (data.type === 'apprise') {
const config = data.config;
if (!config.urls?.length) {
return json({ error: 'At least one Apprise URL is required' }, { status: 400 });
return json({ error: 'At least one webhook URL is required' }, { status: 400 });
}
}
@@ -45,7 +45,7 @@ export const PUT: RequestHandler = async ({ request, cookies }) => {
const validTerminalFontIds = monospaceFonts.map(f => f.id);
const validFontSizes = ['xsmall', 'small', 'normal', 'medium', 'large', 'xlarge'];
const updates: { lightTheme?: string; darkTheme?: string; font?: string; fontSize?: string; gridFontSize?: string; terminalFont?: string; editorFont?: string } = {};
const updates: { lightTheme?: string; darkTheme?: string; font?: string; fontSize?: string; gridFontSize?: string; terminalFont?: string; editorFont?: string; animateIcons?: boolean } = {};
if (data.lightTheme !== undefined) {
if (!validLightThemeIds.includes(data.lightTheme)) {
@@ -96,6 +96,13 @@ export const PUT: RequestHandler = async ({ request, cookies }) => {
updates.editorFont = data.editorFont;
}
if (data.animateIcons !== undefined) {
if (typeof data.animateIcons !== 'boolean') {
return json({ error: 'Invalid animateIcons' }, { status: 400 });
}
updates.animateIcons = data.animateIcons;
}
await setUserThemePreferences(currentUser.id, updates);
// Return updated preferences
+13 -2
View File
@@ -3,6 +3,7 @@ import type { RequestHandler } from './$types';
import { getRegistries, createRegistry, setDefaultRegistry } from '$lib/server/db';
import { authorize } from '$lib/server/authorize';
import { auditRegistry } from '$lib/server/audit';
import { parseRegistryUrl, DOCKER_HUB_HOSTS } from '$lib/server/docker';
export const GET: RequestHandler = async ({ cookies }) => {
const auth = await authorize(cookies);
@@ -38,11 +39,21 @@ export const POST: RequestHandler = async (event) => {
return json({ error: 'Name and URL are required' }, { status: 400 });
}
// Trim username/password to prevent stray whitespace from copy-paste corrupting
// the X-Registry-Auth / Authorization headers (#1105).
const trimmedUsername = typeof data.username === 'string' ? data.username.trim() : undefined;
const trimmedPassword = typeof data.password === 'string' ? data.password.trim() : undefined;
// Diagnostic logging (#1105) — never logs the plaintext credential
const { host: normalizedHost } = parseRegistryUrl(data.url);
const hubTag = DOCKER_HUB_HOSTS.has(normalizedHost) ? ' (docker-hub)' : '';
console.log(`[Registry] create: url=${data.url} normalized=${normalizedHost}${hubTag} user(len=${trimmedUsername?.length ?? 0}) pw(len=${trimmedPassword?.length ?? 0})`);
const registry = await createRegistry({
name: data.name,
url: data.url,
username: data.username || undefined,
password: data.password || undefined,
username: trimmedUsername || undefined,
password: trimmedPassword || undefined,
isDefault: data.isDefault || false
});
+14 -2
View File
@@ -4,6 +4,7 @@ import { getRegistry, updateRegistry, deleteRegistry, setDefaultRegistry } from
import { authorize } from '$lib/server/authorize';
import { auditRegistry } from '$lib/server/audit';
import { computeAuditDiff } from '$lib/utils/diff';
import { parseRegistryUrl, DOCKER_HUB_HOSTS } from '$lib/server/docker';
export const GET: RequestHandler = async ({ params, cookies }) => {
const auth = await authorize(cookies);
@@ -51,11 +52,22 @@ export const PUT: RequestHandler = async (event) => {
}
const data = await request.json();
// Trim username/password to prevent stray whitespace from copy-paste corrupting
// the X-Registry-Auth / Authorization headers (#1105).
const trimmedUsername = typeof data.username === 'string' ? data.username.trim() : data.username;
const trimmedPassword = typeof data.password === 'string' ? data.password.trim() : data.password;
// Diagnostic logging (#1105) — never logs the plaintext credential
const userLen = typeof trimmedUsername === 'string' ? trimmedUsername.length : 0;
const pwLen = typeof trimmedPassword === 'string' ? trimmedPassword.length : 0;
const { host: normalizedHost } = parseRegistryUrl(data.url);
const hubTag = DOCKER_HUB_HOSTS.has(normalizedHost) ? ' (docker-hub)' : '';
console.log(`[Registry] update id=${id}: url=${data.url} normalized=${normalizedHost}${hubTag} user(len=${userLen}) pw(len=${pwLen})`);
const registry = await updateRegistry(id, {
name: data.name,
url: data.url,
username: data.username,
password: data.password,
username: trimmedUsername,
password: trimmedPassword,
isDefault: data.isDefault
});
+130
View File
@@ -0,0 +1,130 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { authorize } from '$lib/server/authorize';
import { parseRegistryUrl, getRegistryAuthHeader, DOCKER_HUB_HOSTS } from '$lib/server/docker';
import { getRegistry } from '$lib/server/db';
/**
* Test registry connectivity and credentials.
*
* Accepts either inline credentials (from the modal form) or a registry ID
* (to test an already-saved registry using stored credentials).
*/
export const POST: RequestHandler = async ({ request, cookies }) => {
const auth = await authorize(cookies);
if (auth.authEnabled && !await auth.can('registries', 'view')) {
return json({ error: 'Permission denied' }, { status: 403 });
}
const data = await request.json();
let url: string;
let username: string | undefined;
let password: string | undefined;
if (data.registryId) {
// Test a saved registry — fetch credentials from DB
const reg = await getRegistry(data.registryId);
if (!reg) return json({ error: 'Registry not found' }, { status: 404 });
url = reg.url;
username = reg.username || undefined;
password = reg.password || undefined;
} else {
url = data.url;
username = data.username?.trim() || undefined;
password = data.password?.trim() || undefined;
}
if (!url) {
return json({ error: 'URL is required' }, { status: 400 });
}
const parsed = parseRegistryUrl(url);
const apiBase = `${parsed.protocol}://${parsed.host}`;
try {
// Step 1: connectivity — can we reach /v2/ at all?
const pingResp = await fetch(`${apiBase}/v2/`, {
method: 'GET',
headers: { 'User-Agent': 'Dockhand/1.0' },
signal: AbortSignal.timeout(10_000)
});
const hasAuth = pingResp.status === 401;
const isOpen = pingResp.ok;
if (!isOpen && !hasAuth) {
return json({
success: false,
connectivity: false,
message: `Registry returned HTTP ${pingResp.status}`
});
}
// Step 2: if credentials provided, test authentication.
// Empty scope — we only care whether the registry accepts the login.
// Asking for a privileged scope like registry:catalog:* causes Docker
// Hub to reject the request with HTTP 400 for non-admin users even
// when their credentials are valid.
if (username && password) {
const authHeader = await getRegistryAuthHeader(url, '', { username, password });
if (!authHeader) {
return json({
success: false,
connectivity: true,
authenticated: false,
message: 'Authentication failed — check username and password'
});
}
// Verify the token works
const authResp = await fetch(`${apiBase}/v2/`, {
method: 'GET',
headers: {
'User-Agent': 'Dockhand/1.0',
'Authorization': authHeader
},
signal: AbortSignal.timeout(10_000)
});
if (!authResp.ok) {
return json({
success: false,
connectivity: true,
authenticated: false,
message: `Authentication token rejected (HTTP ${authResp.status})`
});
}
const isHub = DOCKER_HUB_HOSTS.has(parsed.host);
return json({
success: true,
connectivity: true,
authenticated: true,
message: isHub
? `Connected to Docker Hub as ${username}`
: `Connected and authenticated as ${username}`
});
}
// No credentials — just report connectivity
const isHub = DOCKER_HUB_HOSTS.has(parsed.host);
return json({
success: true,
connectivity: true,
authenticated: null,
message: isHub
? 'Docker Hub is reachable (no credentials to test)'
: isOpen
? 'Registry is reachable (no auth required)'
: 'Registry is reachable (requires authentication)'
});
} catch (e: any) {
const msg = e?.cause?.code || e?.message || String(e);
return json({
success: false,
connectivity: false,
message: `Connection failed: ${msg}`
});
}
};
+19 -7
View File
@@ -90,6 +90,8 @@ export interface GeneralSettings {
defaultComposeTemplate: string;
// Label filter mode
labelFilterMode: 'any' | 'all';
// Whether spinning icons (animate-spin etc.) are animated (#1169)
animateIcons: boolean;
}
const DEFAULT_SETTINGS: Omit<GeneralSettings, 'scheduleRetentionDays' | 'eventRetentionDays' | 'scheduleCleanupCron' | 'eventCleanupCron' | 'scheduleCleanupEnabled' | 'eventCleanupEnabled' | 'scannerCleanupCron' | 'scannerCleanupEnabled'> = {
@@ -122,6 +124,7 @@ const DEFAULT_SETTINGS: Omit<GeneralSettings, 'scheduleRetentionDays' | 'eventRe
defaultGrypeImage: DEFAULT_GRYPE_IMAGE,
defaultTrivyImage: DEFAULT_TRIVY_IMAGE,
labelFilterMode: 'any' as const,
animateIcons: true,
defaultComposeTemplate: `version: "3.8"
services:
@@ -199,7 +202,8 @@ export const GET: RequestHandler = async ({ cookies }) => {
defaultGrypeImage,
defaultTrivyImage,
defaultComposeTemplate,
labelFilterMode
labelFilterMode,
animateIcons
] = await Promise.all([
getSetting('confirm_destructive'),
getSetting('show_stopped_containers'),
@@ -238,7 +242,8 @@ export const GET: RequestHandler = async ({ cookies }) => {
getSetting('default_grype_image'),
getSetting('default_trivy_image'),
getSetting('default_compose_template'),
getSetting('label_filter_mode')
getSetting('label_filter_mode'),
getSetting('animate_icons')
]);
const settings: GeneralSettings = {
@@ -281,7 +286,8 @@ export const GET: RequestHandler = async ({ cookies }) => {
defaultGrypeImage: defaultGrypeImage ?? DEFAULT_GRYPE_IMAGE,
defaultTrivyImage: defaultTrivyImage ?? DEFAULT_TRIVY_IMAGE,
defaultComposeTemplate: defaultComposeTemplate ?? DEFAULT_SETTINGS.defaultComposeTemplate,
labelFilterMode: labelFilterMode ?? DEFAULT_SETTINGS.labelFilterMode
labelFilterMode: labelFilterMode ?? DEFAULT_SETTINGS.labelFilterMode,
animateIcons: animateIcons ?? DEFAULT_SETTINGS.animateIcons
};
return json(settings);
@@ -299,7 +305,7 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
try {
const body = await request.json();
const { confirmDestructive, showStoppedContainers, highlightUpdates, timeFormat, dateFormat, downloadFormat, defaultGrypeArgs, defaultTrivyArgs, scheduleRetentionDays, eventRetentionDays, scheduleCleanupCron, eventCleanupCron, scheduleCleanupEnabled, eventCleanupEnabled, scannerCleanupCron, scannerCleanupEnabled, logBufferSizeKb, logMaxLines, defaultTimezone, eventCollectionMode, eventPollInterval, metricsCollectionInterval, lightTheme, darkTheme, font, fontSize, gridFontSize, terminalFont, editorFont, compactPorts, showExposedPorts, formatLogTimestamps, externalStackPaths, primaryStackLocation, defaultGrypeImage, defaultTrivyImage, defaultComposeTemplate, labelFilterMode } = body;
const { confirmDestructive, showStoppedContainers, highlightUpdates, timeFormat, dateFormat, downloadFormat, defaultGrypeArgs, defaultTrivyArgs, scheduleRetentionDays, eventRetentionDays, scheduleCleanupCron, eventCleanupCron, scheduleCleanupEnabled, eventCleanupEnabled, scannerCleanupCron, scannerCleanupEnabled, logBufferSizeKb, logMaxLines, defaultTimezone, eventCollectionMode, eventPollInterval, metricsCollectionInterval, lightTheme, darkTheme, font, fontSize, gridFontSize, terminalFont, editorFont, compactPorts, showExposedPorts, formatLogTimestamps, externalStackPaths, primaryStackLocation, defaultGrypeImage, defaultTrivyImage, defaultComposeTemplate, labelFilterMode, animateIcons } = body;
if (confirmDestructive !== undefined) {
await setSetting('confirm_destructive', confirmDestructive);
@@ -439,6 +445,9 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
if (labelFilterMode !== undefined && (labelFilterMode === 'any' || labelFilterMode === 'all')) {
await setSetting('label_filter_mode', labelFilterMode);
}
if (animateIcons !== undefined && typeof animateIcons === 'boolean') {
await setSetting('animate_icons', animateIcons);
}
// Fetch all settings in parallel for the response
const [
@@ -479,7 +488,8 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
defaultGrypeImageVal,
defaultTrivyImageVal,
defaultComposeTemplateVal,
labelFilterModeVal
labelFilterModeVal,
animateIconsVal
] = await Promise.all([
getSetting('confirm_destructive'),
getSetting('show_stopped_containers'),
@@ -518,7 +528,8 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
getSetting('default_grype_image'),
getSetting('default_trivy_image'),
getSetting('default_compose_template'),
getSetting('label_filter_mode')
getSetting('label_filter_mode'),
getSetting('animate_icons')
]);
const settings: GeneralSettings = {
@@ -561,7 +572,8 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
defaultGrypeImage: defaultGrypeImageVal ?? DEFAULT_GRYPE_IMAGE,
defaultTrivyImage: defaultTrivyImageVal ?? DEFAULT_TRIVY_IMAGE,
defaultComposeTemplate: defaultComposeTemplateVal ?? DEFAULT_SETTINGS.defaultComposeTemplate,
labelFilterMode: labelFilterModeVal ?? DEFAULT_SETTINGS.labelFilterMode
labelFilterMode: labelFilterModeVal ?? DEFAULT_SETTINGS.labelFilterMode,
animateIcons: animateIconsVal ?? DEFAULT_SETTINGS.animateIcons
};
return json(settings);
+8 -4
View File
@@ -13,7 +13,8 @@ const DEFAULT_THEME_SETTINGS = {
fontSize: 'normal',
gridFontSize: 'normal',
terminalFont: 'system-mono',
editorFont: 'system-mono'
editorFont: 'system-mono',
animateIcons: true
};
export const GET: RequestHandler = async () => {
@@ -25,7 +26,8 @@ export const GET: RequestHandler = async () => {
fontSize,
gridFontSize,
terminalFont,
editorFont
editorFont,
animateIcons
] = await Promise.all([
getSetting('theme_light'),
getSetting('theme_dark'),
@@ -33,7 +35,8 @@ export const GET: RequestHandler = async () => {
getSetting('theme_font_size'),
getSetting('theme_grid_font_size'),
getSetting('theme_terminal_font'),
getSetting('theme_editor_font')
getSetting('theme_editor_font'),
getSetting('animate_icons')
]);
return json({
@@ -43,7 +46,8 @@ export const GET: RequestHandler = async () => {
fontSize: fontSize ?? DEFAULT_THEME_SETTINGS.fontSize,
gridFontSize: gridFontSize ?? DEFAULT_THEME_SETTINGS.gridFontSize,
terminalFont: terminalFont ?? DEFAULT_THEME_SETTINGS.terminalFont,
editorFont: editorFont ?? DEFAULT_THEME_SETTINGS.editorFont
editorFont: editorFont ?? DEFAULT_THEME_SETTINGS.editorFont,
animateIcons: animateIcons ?? DEFAULT_THEME_SETTINGS.animateIcons
});
} catch (error) {
console.error('Failed to get theme settings:', error);
+3 -2
View File
@@ -158,8 +158,9 @@ export const POST: RequestHandler = async ({ params, url, cookies, request }) =>
defined = envVars.map(v => v.key).sort();
}
// Calculate missing and unused
const missing = required.filter(v => !defined.includes(v));
// Calculate missing and unused. Built-in Docker/Compose vars are provided implicitly
// by the runtime, so they're never "missing" even if not in the user's env panel.
const missing = required.filter(v => !defined.includes(v) && !DOCKER_COMPOSE_BUILTIN_VARS.has(v));
const unused = defined.filter(v => !required.includes(v) && !optional.includes(v) && !DOCKER_COMPOSE_BUILTIN_VARS.has(v));
const result: ValidationResult = {
+1 -1
View File
@@ -1929,7 +1929,7 @@
class="inline-flex items-center gap-0.5 text-xs {portUrl ? 'bg-primary/10 hover:bg-primary/20 text-primary' : 'bg-muted hover:bg-blue-500/20 hover:text-blue-500'} px-1 py-0.5 rounded transition-colors shrink-0"
title="Open {url} in new tab"
>
<code>{port.display}</code>
<code>{portParsed?.name ?? port.display}</code>
<ExternalLink class="w-2.5 h-2.5 {portUrl ? 'opacity-60' : 'text-muted-foreground'}" />
</a>
{:else}
@@ -1,5 +1,6 @@
<script lang="ts">
import { onDestroy } from 'svelte';
import { goto } from '$app/navigation';
import * as Dialog from '$lib/components/ui/dialog';
import * as Tabs from '$lib/components/ui/tabs';
import { Button } from '$lib/components/ui/button';
@@ -621,6 +622,29 @@
<Pencil class="w-3 h-3 text-muted-foreground hover:text-foreground" />
</button>
{/if}
{@const composeStack = containerData?.Config?.Labels?.['com.docker.compose.project']}
{#if composeStack && !loading}
<Tooltip.Root>
<Tooltip.Trigger>
<button
type="button"
onclick={() => {
open = false;
goto(appendEnvParam(`/stacks?search=${encodeURIComponent(composeStack)}`, $currentEnvironment?.id ?? null));
}}
class="cursor-pointer inline-flex items-center"
>
<Badge variant="outline" class="text-xs py-0 px-1.5 hover:bg-primary/10 hover:border-primary/50 transition-colors gap-1">
<Layers class="w-3 h-3" />
{composeStack}
</Badge>
</button>
</Tooltip.Trigger>
<Tooltip.Content>
<p class="text-xs whitespace-nowrap">Open stack "{composeStack}"</p>
</Tooltip.Content>
</Tooltip.Root>
{/if}
{#if containerData?.State?.Running && !loading}
<span class="inline-flex items-center gap-1.5 ml-2 text-xs {isLiveConnected ? 'text-emerald-500' : 'text-muted-foreground'}" title={isLiveConnected ? 'Receiving live updates' : 'Connection lost'}>
<Wifi class="w-3.5 h-3.5 {isLiveConnected ? 'animate-pulse' : ''}" />
@@ -1143,7 +1167,7 @@
class="inline-flex items-center gap-1 text-primary hover:underline"
title="Open {url}"
>
<code>{binding.HostIp || '0.0.0.0'}:{binding.HostPort}</code>
<code>{portParsedOverride?.name ?? `${binding.HostIp || '0.0.0.0'}:${binding.HostPort}`}</code>
<ExternalLink class="w-3 h-3" />
</a>
{:else}
+218 -49
View File
@@ -8,7 +8,9 @@
import { Button } from '$lib/components/ui/button';
import { Checkbox } from '$lib/components/ui/checkbox';
import { TogglePill, ToggleGroup } from '$lib/components/ui/toggle-pill';
import { Plus, Trash2, Settings2, RefreshCw, Network, X, Ban, RotateCw, AlertTriangle, PauseCircle, Share2, Server, CircleOff, Box, ChevronDown, ChevronsUpDown, Check, ChevronRight, Cpu, Shield, HeartPulse, Wifi, HardDrive, Lock, Loader2, CheckCircle2, Package, Gpu, Search, CircleHelp } from 'lucide-svelte';
import { Plus, Trash2, Settings2, RefreshCw, Network, X, Ban, RotateCw, AlertTriangle, PauseCircle, Share2, Server, CircleOff, Box, ChevronDown, ChevronsUpDown, Check, ChevronRight, Cpu, Shield, HeartPulse, Wifi, HardDrive, Lock, Loader2, CheckCircle2, Package, Gpu, Search, CircleHelp, CornerDownLeft } from 'lucide-svelte';
import { toast } from 'svelte-sonner';
import { parseMemory, parseNanoCpus, parsePositiveInt } from '$lib/utils/container-resources';
import { parseHostPort, validatePort, validateIp, formatHostPort, expandPortBindings } from '$lib/utils/port-parse';
import * as Tooltip from '$lib/components/ui/tooltip';
import { currentEnvironment } from '$lib/stores/environment';
@@ -159,6 +161,11 @@
totalVulnerabilities?: number;
hasCriticalOrHigh?: boolean;
};
// Edit mode specific — needed for inline "Apply" in-place updates
// (restart policy, CPU/memory limits) without recreating the container.
// Omitted in create mode; the per-field Apply buttons are hidden then.
containerId?: string;
envId?: number;
}
let {
@@ -213,7 +220,9 @@
configSets,
selectedConfigSetId = $bindable(),
errors = $bindable(),
imageSummary
imageSummary,
containerId,
envId
}: Props = $props();
// Fetch networks and containers from current environment
@@ -649,6 +658,111 @@
}
}
// ---------------------------------------------------------------------
// In-place ("live") property updates — restart policy + resource limits.
// Calls POST /api/containers/[id]/update-runtime which wraps Docker's
// /containers/{id}/update endpoint. ONLY the property fields documented
// in IN_PLACE_UPDATE_FIELDS (see docker.ts) are eligible — anything else
// would silently fail or, worse, look like it worked. Apply buttons next
// to those fields call this helper; the rest of the form still requires
// the bottom Save button which recreates the container.
// ---------------------------------------------------------------------
type InPlaceFieldKey = 'restart' | 'memory' | 'memoryReservation' | 'nanoCpus' | 'cpuShares' | 'cpuQuota' | 'cpuPeriod' | 'pidsLimit';
let applyingField = $state<InPlaceFieldKey | null>(null);
/** True when this tab is wired for in-place updates (edit mode + we have an id). */
const canApplyInPlace = $derived(mode === 'edit' && !!containerId);
async function applyInPlace(field: InPlaceFieldKey, body: Record<string, unknown>) {
if (!canApplyInPlace || !containerId) return;
applyingField = field;
try {
const url = `/api/containers/${containerId}/update-runtime${envId ? `?env=${envId}` : ''}`;
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(data.error || 'Update failed');
return;
}
toast.success('Applied — no restart needed');
// Surface Docker warnings (e.g. "Memory swap will fall back to ...") inline.
if (Array.isArray(data.warnings) && data.warnings.length > 0) {
for (const w of data.warnings) toast.warning(w);
}
} catch (err: any) {
toast.error(err?.message || 'Update failed');
} finally {
applyingField = null;
}
}
function applyRestartPolicy() {
const payload: Record<string, unknown> = { Name: restartPolicy };
if (restartPolicy === 'on-failure' && restartMaxRetries !== '' && restartMaxRetries !== null) {
payload.MaximumRetryCount = Number(restartMaxRetries);
}
return applyInPlace('restart', { RestartPolicy: payload });
}
function applyMemoryLimit() {
const bytes = parseMemory(memoryLimit);
if (memoryLimit && bytes === undefined) {
toast.error('Invalid memory value (e.g. 512m, 1g)');
return;
}
// Docker uses 0 to clear an existing limit.
return applyInPlace('memory', { Memory: bytes ?? 0 });
}
function applyMemoryReservation() {
const bytes = parseMemory(memoryReservation);
if (memoryReservation && bytes === undefined) {
toast.error('Invalid memory value');
return;
}
return applyInPlace('memoryReservation', { MemoryReservation: bytes ?? 0 });
}
function applyNanoCpus() {
const n = parseNanoCpus(nanoCpus);
if (nanoCpus && n === undefined) {
toast.error('Invalid CPU limit (e.g. 0.5, 1.5, 2)');
return;
}
return applyInPlace('nanoCpus', { NanoCpus: n ?? 0 });
}
function applyCpuShares() {
const n = parsePositiveInt(cpuShares);
if (cpuShares && n === undefined) {
toast.error('Invalid CPU shares');
return;
}
return applyInPlace('cpuShares', { CpuShares: n ?? 0 });
}
function applyCpuQuota() {
const n = parsePositiveInt(cpuQuota);
if (cpuQuota && n === undefined) {
toast.error('Invalid CPU quota');
return;
}
return applyInPlace('cpuQuota', { CpuQuota: n ?? 0 });
}
function applyCpuPeriod() {
const n = parsePositiveInt(cpuPeriod);
if (cpuPeriod && n === undefined) {
toast.error('Invalid CPU period');
return;
}
return applyInPlace('cpuPeriod', { CpuPeriod: n ?? 0 });
}
function getDriverBadgeClasses(driver: string): string {
const base = 'text-2xs px-1.5 py-0.5 rounded font-medium';
switch (driver.toLowerCase()) {
@@ -775,48 +889,67 @@
<div class="grid grid-cols-2 gap-3">
<div class="space-y-1.5">
<Label class="text-xs font-medium">Restart policy</Label>
<Select.Root type="single" bind:value={restartPolicy}>
<Select.Trigger id="restartPolicy" tabindex={0} class="w-full h-9">
<span class="flex items-center">
{#if restartPolicy === 'no'}
<Ban class="w-3.5 h-3.5 mr-2 text-muted-foreground" />
{:else if restartPolicy === 'always'}
<RotateCw class="w-3.5 h-3.5 mr-2 text-green-500" />
{:else if restartPolicy === 'on-failure'}
<AlertTriangle class="w-3.5 h-3.5 mr-2 text-amber-500" />
<div class="flex items-center gap-1.5">
<Select.Root type="single" bind:value={restartPolicy}>
<Select.Trigger id="restartPolicy" tabindex={0} class="w-full h-9">
<span class="flex items-center">
{#if restartPolicy === 'no'}
<Ban class="w-3.5 h-3.5 mr-2 text-muted-foreground" />
{:else if restartPolicy === 'always'}
<RotateCw class="w-3.5 h-3.5 mr-2 text-green-500" />
{:else if restartPolicy === 'on-failure'}
<AlertTriangle class="w-3.5 h-3.5 mr-2 text-amber-500" />
{:else}
<PauseCircle class="w-3.5 h-3.5 mr-2 text-blue-500" />
{/if}
{restartPolicy === 'no' ? 'No' : restartPolicy === 'always' ? 'Always' : restartPolicy === 'on-failure' ? 'On failure' : 'Unless stopped'}
</span>
</Select.Trigger>
<Select.Content>
<Select.Item value="no">
{#snippet children()}
<Ban class="w-3.5 h-3.5 mr-2 text-muted-foreground" />
No
{/snippet}
</Select.Item>
<Select.Item value="always">
{#snippet children()}
<RotateCw class="w-3.5 h-3.5 mr-2 text-green-500" />
Always
{/snippet}
</Select.Item>
<Select.Item value="on-failure">
{#snippet children()}
<AlertTriangle class="w-3.5 h-3.5 mr-2 text-amber-500" />
On failure
{/snippet}
</Select.Item>
<Select.Item value="unless-stopped">
{#snippet children()}
<PauseCircle class="w-3.5 h-3.5 mr-2 text-blue-500" />
Unless stopped
{/snippet}
</Select.Item>
</Select.Content>
</Select.Root>
{#if canApplyInPlace}
<Button
type="button"
variant="outline"
size="sm"
class="h-9 shrink-0 px-2"
disabled={applyingField !== null}
onclick={applyRestartPolicy}
title="Apply"
>
{#if applyingField === 'restart'}
<Loader2 class="w-3.5 h-3.5 animate-spin" />
{:else}
<PauseCircle class="w-3.5 h-3.5 mr-2 text-blue-500" />
<CornerDownLeft class="w-3.5 h-3.5" />
{/if}
{restartPolicy === 'no' ? 'No' : restartPolicy === 'always' ? 'Always' : restartPolicy === 'on-failure' ? 'On failure' : 'Unless stopped'}
</span>
</Select.Trigger>
<Select.Content>
<Select.Item value="no">
{#snippet children()}
<Ban class="w-3.5 h-3.5 mr-2 text-muted-foreground" />
No
{/snippet}
</Select.Item>
<Select.Item value="always">
{#snippet children()}
<RotateCw class="w-3.5 h-3.5 mr-2 text-green-500" />
Always
{/snippet}
</Select.Item>
<Select.Item value="on-failure">
{#snippet children()}
<AlertTriangle class="w-3.5 h-3.5 mr-2 text-amber-500" />
On failure
{/snippet}
</Select.Item>
<Select.Item value="unless-stopped">
{#snippet children()}
<PauseCircle class="w-3.5 h-3.5 mr-2 text-blue-500" />
Unless stopped
{/snippet}
</Select.Item>
</Select.Content>
</Select.Root>
</Button>
{/if}
</div>
{#if restartPolicy === 'on-failure'}
<div class="space-y-1.5 mt-2">
<Label class="text-xs font-medium">Max retry count</Label>
@@ -1334,36 +1467,72 @@
</button>
{#if showResources}
<div class="px-3 pb-3 space-y-3 border-t">
<p class="text-xs text-muted-foreground pt-2">Configure memory and CPU limits for this container</p>
<p class="text-xs text-muted-foreground pt-2">
Configure memory and CPU limits for this container.
{#if canApplyInPlace}
The <CornerDownLeft class="w-3 h-3 inline-block -mt-0.5" /> button next to each field applies the change without restarting.
{/if}
</p>
{#snippet inlineApplyBtn(field: InPlaceFieldKey, onclick: () => void)}
{#if canApplyInPlace}
<Button type="button" variant="outline" size="sm" class="h-9 shrink-0 px-2" disabled={applyingField !== null} {onclick} title="Apply">
{#if applyingField === field}
<Loader2 class="w-3.5 h-3.5 animate-spin" />
{:else}
<CornerDownLeft class="w-3.5 h-3.5" />
{/if}
</Button>
{/if}
{/snippet}
<div class="grid grid-cols-2 gap-3">
<div class="space-y-1.5">
<Label for="memoryLimit" class="text-xs font-medium">Memory limit</Label>
<Input id="memoryLimit" bind:value={memoryLimit} placeholder="e.g., 512m, 1g" class="h-9" />
<div class="flex items-center gap-1.5">
<Input id="memoryLimit" bind:value={memoryLimit} placeholder="e.g., 512m, 1g" class="h-9" />
{@render inlineApplyBtn('memory', applyMemoryLimit)}
</div>
</div>
<div class="space-y-1.5">
<Label for="memoryReservation" class="text-xs font-medium">Memory reservation</Label>
<Input id="memoryReservation" bind:value={memoryReservation} placeholder="e.g., 256m" class="h-9" />
<div class="flex items-center gap-1.5">
<Input id="memoryReservation" bind:value={memoryReservation} placeholder="e.g., 256m" class="h-9" />
{@render inlineApplyBtn('memoryReservation', applyMemoryReservation)}
</div>
</div>
</div>
<div class="grid grid-cols-2 gap-3">
<div class="space-y-1.5">
<Label for="nanoCpus" class="text-xs font-medium">CPU limit</Label>
<Input id="nanoCpus" bind:value={nanoCpus} placeholder="e.g., 0.5, 1.5, 2" class="h-9" />
<div class="flex items-center gap-1.5">
<Input id="nanoCpus" bind:value={nanoCpus} placeholder="e.g., 0.5, 1.5, 2" class="h-9" />
{@render inlineApplyBtn('nanoCpus', applyNanoCpus)}
</div>
</div>
<div class="space-y-1.5">
<Label for="cpuShares" class="text-xs font-medium">CPU shares</Label>
<Input id="cpuShares" bind:value={cpuShares} type="number" placeholder="1024" class="h-9" />
<div class="flex items-center gap-1.5">
<Input id="cpuShares" bind:value={cpuShares} type="number" placeholder="1024" class="h-9" />
{@render inlineApplyBtn('cpuShares', applyCpuShares)}
</div>
</div>
</div>
<div class="grid grid-cols-2 gap-3">
<div class="space-y-1.5">
<Label for="cpuQuota" class="text-xs font-medium">CPU quota</Label>
<Input id="cpuQuota" bind:value={cpuQuota} type="number" placeholder="e.g., 50000" class="h-9" />
<div class="flex items-center gap-1.5">
<Input id="cpuQuota" bind:value={cpuQuota} type="number" placeholder="e.g., 50000" class="h-9" />
{@render inlineApplyBtn('cpuQuota', applyCpuQuota)}
</div>
<p class="text-xs text-muted-foreground">Microseconds per period</p>
</div>
<div class="space-y-1.5">
<Label for="cpuPeriod" class="text-xs font-medium">CPU period</Label>
<Input id="cpuPeriod" bind:value={cpuPeriod} type="number" placeholder="Default: 100000" class="h-9" />
<div class="flex items-center gap-1.5">
<Input id="cpuPeriod" bind:value={cpuPeriod} type="number" placeholder="Default: 100000" class="h-9" />
{@render inlineApplyBtn('cpuPeriod', applyCpuPeriod)}
</div>
<p class="text-xs text-muted-foreground">Period in microseconds</p>
</div>
</div>
@@ -1110,6 +1110,8 @@
<ContainerSettingsTab
mode="edit"
{containerId}
envId={$currentEnvironment?.id ?? undefined}
bind:name
bind:image
bind:command
+29 -3
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { onMount } from 'svelte';
import { onMount, onDestroy } from 'svelte';
import { Button } from '$lib/components/ui/button';
import * as Table from '$lib/components/ui/table';
import * as Dialog from '$lib/components/ui/dialog';
@@ -229,6 +229,29 @@
}
});
// ESC inside the file viewer/editor closes JUST the file, not the whole
// dialog. Captured at window level so the Dialog.Root wrapper never sees
// the key. When no file is open, ESC bubbles normally and closes the dialog.
function handleEscape(e: KeyboardEvent) {
if (e.key !== 'Escape') return;
if (editingFile) {
e.stopPropagation();
e.preventDefault();
closeEditor();
} else if (viewingFile) {
e.stopPropagation();
e.preventDefault();
closeViewer();
}
}
onMount(() => {
window.addEventListener('keydown', handleEscape, true);
});
onDestroy(() => {
window.removeEventListener('keydown', handleEscape, true);
});
function toggleEditorTheme() {
editorTheme = editorTheme === 'light' ? 'dark' : 'light';
localStorage.setItem('dockhand-editor-theme', editorTheme);
@@ -245,7 +268,7 @@
// Get language from filename for CodeMirror
function getLanguageFromFilename(filename: string): string {
const name = filename.toLowerCase();
if (name === 'dockerfile') return 'shell';
if (name === 'dockerfile' || name.endsWith('.dockerfile')) return 'dockerfile';
if (name === 'makefile' || name === 'rakefile') return 'shell';
if (name.endsWith('.yml') || name.endsWith('.yaml')) return 'yaml';
if (name.endsWith('.json')) return 'json';
@@ -260,7 +283,10 @@
if (name.endsWith('.css') || name.endsWith('.scss') || name.endsWith('.sass') || name.endsWith('.less')) return 'css';
if (name.endsWith('.xml')) return 'xml';
if (name.endsWith('.sql')) return 'sql';
return 'shell';
if (name.endsWith('.toml')) return 'toml';
if (name === '.env' || name.startsWith('.env.') || name.endsWith('.env')) return 'dotenv';
if (name.endsWith('.ini') || name.endsWith('.conf') || name.endsWith('.cfg') || name.endsWith('.properties')) return 'ini';
return '';
}
// Check if file is editable
+3 -1
View File
@@ -38,6 +38,7 @@
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
import * as Table from '$lib/components/ui/table';
import ThemeSelector from '$lib/components/ThemeSelector.svelte';
import AnimateIconsToggle from '$lib/components/AnimateIconsToggle.svelte';
import { themeStore } from '$lib/stores/theme';
import PageHeader from '$lib/components/PageHeader.svelte';
@@ -723,8 +724,9 @@
</Card.Title>
<Card.Description>Customize the look of the application</Card.Description>
</Card.Header>
<Card.Content>
<Card.Content class="space-y-4">
<ThemeSelector userId={profile.id} />
<AnimateIconsToggle userId={profile.id} />
</Card.Content>
</Card.Root>
+2 -1
View File
@@ -13,6 +13,7 @@
import LicenseModal from './LicenseModal.svelte';
import PrivacyModal from './PrivacyModal.svelte';
import SelfUpdateDialog from './SelfUpdateDialog.svelte';
import ChangelogText from '$lib/components/ChangelogText.svelte';
interface Dependency {
name: string;
@@ -885,7 +886,7 @@
Fix
</span>
{/if}
<span>{change.text}</span>
<ChangelogText text={change.text} />
</li>
{/each}
</ul>
@@ -1,6 +1,7 @@
<script lang="ts">
import { toast } from 'svelte-sonner';
import { readJobResponse } from '$lib/utils/sse-fetch';
import { validateEnvName } from '$lib/utils/env-name';
import { Button } from '$lib/components/ui/button';
import { Badge } from '$lib/components/ui/badge';
import * as Dialog from '$lib/components/ui/dialog';
@@ -60,7 +61,9 @@
ChevronDown,
ChevronRight,
XCircle,
ImageUp
ImageUp,
Upload,
ArrowRight
} from 'lucide-svelte';
import * as Tooltip from '$lib/components/ui/tooltip';
import * as Alert from '$lib/components/ui/alert';
@@ -285,6 +288,20 @@
let formPublicIp = $state('');
let formTimezone = $state('UTC');
let formError = $state('');
// Env-rename confirmation dialog state.
let showRenameConfirm = $state(false);
let renameConfirmFrom = $state('');
let renameConfirmTo = $state('');
let renameStackCount = $state(0);
let renameGitStackCount = $state(0);
// Set when we couldn't reliably enumerate stacks (network/permission
// failure). The dialog falls back to generic text instead of a count, so
// we never silent-rename on a transient error.
let renameCountsUnknown = $state(false);
// Whether running containers will be affected by the rename. True for
// socket/direct (they deploy from the staging dir). False for Hawser
// (the agent's deployed dir doesn't include env name).
let renameAffectsContainers = $state(false);
let formErrors = $state<{ name?: string; host?: string }>({});
let formSaving = $state(false);
@@ -362,6 +379,33 @@
return cleaned || undefined;
}
/**
* Read a PEM file picked via <input type="file"> into the bound textarea state.
* Pasting still works; this is purely additive (#125).
*/
async function loadPemFromFile(
event: Event,
assign: (text: string) => void,
label: string
) {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
try {
const text = await file.text();
if (!text.includes('-----BEGIN')) {
toast.error(`${file.name} does not look like a PEM file (no BEGIN block)`);
return;
}
assign(text);
toast.success(`Loaded ${label} from ${file.name}`);
} catch (err: any) {
toast.error(`Failed to read ${file.name}: ${err?.message ?? err}`);
} finally {
input.value = ''; // allow re-uploading the same file
}
}
/**
* Extract hostname/IP from a URL string
* Handles tcp://, http://, https:// protocols and plain hostnames
@@ -725,6 +769,12 @@
if (!formName.trim()) {
formErrors.name = 'Name is required';
hasErrors = true;
} else {
const nameCheck = validateEnvName(formName.trim());
if (!nameCheck.ok) {
formErrors.name = nameCheck.reason!;
hasErrors = true;
}
}
// Host is only required for direct and hawser-standard connection types
if (formConnectionType === 'direct' || formConnectionType === 'hawser-standard') {
@@ -843,6 +893,12 @@
if (!formName.trim()) {
formErrors.name = 'Name is required';
hasErrors = true;
} else {
const nameCheck = validateEnvName(formName.trim());
if (!nameCheck.ok) {
formErrors.name = nameCheck.reason!;
hasErrors = true;
}
}
// Host is only required for direct and hawser-standard connection types
if (formConnectionType === 'direct' || formConnectionType === 'hawser-standard') {
@@ -860,6 +916,61 @@
if (hasErrors) return;
// Every env type stores something locally under the env name:
// - socket/direct: the deploy staging dir AND the in-app editor source
// (containers' compose project labels point here, so redeploy is
// required after rename or next restart fails)
// - hawser-standard/edge: the in-app editor source for ALL stacks
// PLUS the git-repos clones for git stacks (the agent's deployed
// dir lives on the remote host and is not affected)
// → fire the warning whenever the name changes.
const newName = formName.trim();
const willRenameOnDisk = newName !== environment.name;
// "Affects containers" = redeploy required. Only true for envs where
// Dockhand deploys directly (socket/direct), not Hawser.
renameAffectsContainers =
environment.connectionType === 'socket' || environment.connectionType === 'direct';
if (willRenameOnDisk) {
// Count actual stacks on this env. Fail closed: if either request
// fails (network, 403, parse error) we treat the counts as
// unknown and still show the warning — better to spook the user
// than silent-rename when stacks might exist.
const [stacksRes, gitRes] = await Promise.all([
fetch(`/api/stacks?env=${environment.id}`).catch(() => null),
fetch(`/api/git/stacks?env=${environment.id}`).catch(() => null)
]);
let unknown = false;
let stacks: unknown[] = [];
let gitStacks: unknown[] = [];
if (stacksRes?.ok) {
try { stacks = await stacksRes.json(); } catch { unknown = true; }
} else {
unknown = true;
}
if (gitRes?.ok) {
try { gitStacks = await gitRes.json(); } catch { unknown = true; }
} else {
unknown = true;
}
renameStackCount = Array.isArray(stacks) ? stacks.length : 0;
renameGitStackCount = Array.isArray(gitStacks) ? gitStacks.length : 0;
renameCountsUnknown = unknown;
renameConfirmFrom = environment.name;
renameConfirmTo = newName;
showRenameConfirm = true;
return;
}
await commitEnvironmentUpdate();
}
// Extracted from updateEnvironment() so the rename-confirm dialog can call
// it after the user clicks "Rename and continue".
async function commitEnvironmentUpdate() {
if (!environment) return;
formSaving = true;
formError = '';
@@ -1475,7 +1586,7 @@
</Tabs.Trigger>
</Tabs.List>
<div class="overflow-y-auto py-4 h-[520px]">
<div class="overflow-y-auto py-4 h-[520px] [scrollbar-gutter:stable] pr-1">
<!-- General Tab (Connection Settings) -->
<Tabs.Content value="general" class="space-y-4 mt-0 h-full">
<!-- Name field -->
@@ -1833,9 +1944,22 @@
</div>
{#if formProtocol === 'https'}
<div class="space-y-4 pt-2 border-t">
<p class="text-xs text-muted-foreground">TLS certificates for mTLS authentication (RSA or ECDSA)</p>
<p class="text-xs text-muted-foreground">TLS certificates for mTLS authentication (RSA or ECDSA). Paste the PEM content or upload a file.</p>
<div class="space-y-2">
<Label for="edit-env-tls_ca">CA certificate</Label>
<div class="flex items-center justify-between gap-2">
<Label for="edit-env-tls_ca">CA certificate</Label>
<Button variant="ghost" size="sm" type="button" class="h-7 px-2 text-xs" onclick={() => document.getElementById('edit-env-tls_ca-file')?.click()}>
<Upload class="w-3 h-3 mr-1" />
Upload file
</Button>
<input
id="edit-env-tls_ca-file"
type="file"
accept=".pem,.crt,.cer,.ca,.cert,application/x-pem-file,application/x-x509-ca-cert"
class="hidden"
onchange={(e) => loadPemFromFile(e, (t) => (formTlsCa = t), 'CA certificate')}
/>
</div>
<textarea
id="edit-env-tls_ca"
bind:value={formTlsCa}
@@ -1844,7 +1968,20 @@
></textarea>
</div>
<div class="space-y-2">
<Label for="edit-env-tls_cert">Client certificate</Label>
<div class="flex items-center justify-between gap-2">
<Label for="edit-env-tls_cert">Client certificate</Label>
<Button variant="ghost" size="sm" type="button" class="h-7 px-2 text-xs" onclick={() => document.getElementById('edit-env-tls_cert-file')?.click()}>
<Upload class="w-3 h-3 mr-1" />
Upload file
</Button>
<input
id="edit-env-tls_cert-file"
type="file"
accept=".pem,.crt,.cer,.cert,application/x-pem-file"
class="hidden"
onchange={(e) => loadPemFromFile(e, (t) => (formTlsCert = t), 'client certificate')}
/>
</div>
<textarea
id="edit-env-tls_cert"
bind:value={formTlsCert}
@@ -1853,7 +1990,20 @@
></textarea>
</div>
<div class="space-y-2">
<Label for="edit-env-tls_key">Client key</Label>
<div class="flex items-center justify-between gap-2">
<Label for="edit-env-tls_key">Client key</Label>
<Button variant="ghost" size="sm" type="button" class="h-7 px-2 text-xs" onclick={() => document.getElementById('edit-env-tls_key-file')?.click()}>
<Upload class="w-3 h-3 mr-1" />
Upload file
</Button>
<input
id="edit-env-tls_key-file"
type="file"
accept=".pem,.key,application/x-pem-file"
class="hidden"
onchange={(e) => loadPemFromFile(e, (t) => (formTlsKey = t), 'client key')}
/>
</div>
<textarea
id="edit-env-tls_key"
bind:value={formTlsKey}
@@ -1919,7 +2069,20 @@
</div>
{#if formProtocol === 'https'}
<div class="space-y-2">
<Label for="edit-env-hawser-tls-ca">CA certificate (for self-signed)</Label>
<div class="flex items-center justify-between gap-2">
<Label for="edit-env-hawser-tls-ca">CA certificate (for self-signed)</Label>
<Button variant="ghost" size="sm" type="button" class="h-7 px-2 text-xs" disabled={formTlsSkipVerify} onclick={() => document.getElementById('edit-env-hawser-tls-ca-file')?.click()}>
<Upload class="w-3 h-3 mr-1" />
Upload file
</Button>
<input
id="edit-env-hawser-tls-ca-file"
type="file"
accept=".pem,.crt,.cer,.ca,.cert,application/x-pem-file,application/x-x509-ca-cert"
class="hidden"
onchange={(e) => loadPemFromFile(e, (t) => (formTlsCa = t), 'CA certificate')}
/>
</div>
<textarea
id="edit-env-hawser-tls-ca"
bind:value={formTlsCa}
@@ -1927,7 +2090,7 @@
class="flex min-h-[80px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring font-mono text-xs"
disabled={formTlsSkipVerify}
></textarea>
<p class="text-xs text-muted-foreground">Paste the CA certificate if agent uses self-signed TLS (RSA or ECDSA).</p>
<p class="text-xs text-muted-foreground">Paste the CA certificate or upload a file if agent uses self-signed TLS (RSA or ECDSA).</p>
</div>
<div class="flex items-center justify-between">
<div>
@@ -2819,3 +2982,95 @@
/>
</Dialog.Content>
</Dialog.Root>
<!-- Env-rename confirmation: only fires for socket/direct envs where the
server actually moves $DATA_DIR/stacks/<oldName> → <newName>. -->
<Dialog.Root bind:open={showRenameConfirm}>
<Dialog.Content class="max-w-2xl">
<Dialog.Header>
<Dialog.Title class="flex items-center gap-2">
<AlertTriangle class="w-5 h-5 text-amber-500" />
Rename environment?
</Dialog.Title>
<Dialog.Description class="pt-2 space-y-3 text-sm">
<p>The following directories will be moved on the Dockhand host:</p>
<div class="space-y-1 text-xs font-mono bg-muted/40 rounded-md p-3 border overflow-x-auto">
<div class="flex items-center gap-2 whitespace-nowrap">
<code class="whitespace-nowrap">$DATA_DIR/stacks/{renameConfirmFrom}/</code>
<ArrowRight class="w-3.5 h-3.5 shrink-0 text-muted-foreground" />
<code class="whitespace-nowrap">$DATA_DIR/stacks/{renameConfirmTo}/</code>
</div>
<div class="flex items-center gap-2 whitespace-nowrap">
<code class="whitespace-nowrap">$DATA_DIR/git-repos/{renameConfirmFrom}/</code>
<ArrowRight class="w-3.5 h-3.5 shrink-0 text-muted-foreground" />
<code class="whitespace-nowrap">$DATA_DIR/git-repos/{renameConfirmTo}/</code>
</div>
</div>
{#if renameCountsUnknown}
<p>
Couldn't list the stacks on this environment — proceed only if
you're sure what's deployed here.
{#if renameAffectsContainers}
<strong>Any existing stacks will need to be redeployed after
the rename</strong> or their next container restart will fail.
{/if}
</p>
{:else if renameStackCount === 0 && renameGitStackCount === 0}
<p>No stacks are currently deployed on this environment, so the rename is safe.</p>
{:else if renameAffectsContainers}
<p>
{#if renameStackCount > 0 && renameGitStackCount > 0}
<strong>{renameStackCount} stack{renameStackCount === 1 ? '' : 's'}</strong>
and <strong>{renameGitStackCount} git stack{renameGitStackCount === 1 ? '' : 's'}</strong>
on this environment will need to be redeployed after the rename.
{:else if renameStackCount > 0}
<strong>{renameStackCount} stack{renameStackCount === 1 ? '' : 's'}</strong>
on this environment will need to be redeployed after the rename.
{:else}
<strong>{renameGitStackCount} git stack{renameGitStackCount === 1 ? '' : 's'}</strong>
on this environment will need to be redeployed after the rename.
{/if}
</p>
<p>
Running containers will keep working, but their compose project labels
still reference the old path. Without a redeploy, the next container
restart will fail because the old path no longer exists.
</p>
{:else}
<p>
{#if renameStackCount > 0 && renameGitStackCount > 0}
<strong>{renameStackCount} stack{renameStackCount === 1 ? '' : 's'}</strong>
and <strong>{renameGitStackCount} git stack{renameGitStackCount === 1 ? '' : 's'}</strong>
are tracked on this environment.
{:else if renameStackCount > 0}
<strong>{renameStackCount} stack{renameStackCount === 1 ? '' : 's'}</strong>
{renameStackCount === 1 ? 'is' : 'are'} tracked on this environment.
{:else}
<strong>{renameGitStackCount} git stack{renameGitStackCount === 1 ? '' : 's'}</strong>
{renameGitStackCount === 1 ? 'is' : 'are'} tracked on this environment.
{/if}
</p>
<p>
Their containers run on the Hawser agent host, where the deploy
directory doesn't include the env name — those keep working without
a redeploy. Only the local editor source and git clone caches move.
</p>
{/if}
</Dialog.Description>
</Dialog.Header>
<div class="flex justify-end gap-2 mt-4">
<Button variant="outline" onclick={() => (showRenameConfirm = false)}>
Cancel
</Button>
<Button
variant="default"
onclick={async () => {
showRenameConfirm = false;
await commitEnvironmentUpdate();
}}
>
Rename and continue
</Button>
</div>
</Dialog.Content>
</Dialog.Root>
@@ -24,8 +24,10 @@
Unplug,
CircleArrowUp,
CircleFadingArrowUp,
Clock
Clock,
AlertTriangle
} from 'lucide-svelte';
import * as Dialog from '$lib/components/ui/dialog';
import { broom, whale } from '@lucide/lab';
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
import { canAccess } from '$lib/stores/auth';
@@ -100,7 +102,13 @@
let testingEnvs = $state<Set<number>>(new Set());
let pruneStatus = $state<{ [id: number]: 'pruning' | 'success' | 'error' | null }>({});
let confirmPruneEnvId = $state<number | null>(null);
let confirmDeleteEnvId = $state<number | null>(null);
// Delete confirmation dialog state — shows the on-disk paths that will be
// wiped + the stacks-tracked counts so the user knows what they're losing.
let showDeleteConfirm = $state(false);
let deleteEnvTarget = $state<Environment | null>(null);
let deleteStackCount = $state(0);
let deleteGitStackCount = $state(0);
let deleteCountsUnknown = $state(false);
// Track which environments have scanner enabled (for shield indicator)
let envScannerStatus = $state<{ [id: number]: boolean }>({});
@@ -192,6 +200,47 @@
}
}
// Two-step delete: fetch the stack counts first (fail-closed) and pop the
// dialog that lists the on-disk paths being wiped. Only on explicit
// confirmation do we actually call deleteEnvironment().
async function requestDeleteEnvironment(id: number) {
const env = environments.find(e => e.id === id);
if (!env) return;
const [stacksRes, gitRes] = await Promise.all([
fetch(`/api/stacks?env=${id}`).catch(() => null),
fetch(`/api/git/stacks?env=${id}`).catch(() => null)
]);
let unknown = false;
let stacks: unknown[] = [];
let gitStacks: unknown[] = [];
if (stacksRes?.ok) {
try { stacks = await stacksRes.json(); } catch { unknown = true; }
} else {
unknown = true;
}
if (gitRes?.ok) {
try { gitStacks = await gitRes.json(); } catch { unknown = true; }
} else {
unknown = true;
}
deleteStackCount = Array.isArray(stacks) ? stacks.length : 0;
deleteGitStackCount = Array.isArray(gitStacks) ? gitStacks.length : 0;
deleteCountsUnknown = unknown;
deleteEnvTarget = env;
showDeleteConfirm = true;
}
async function confirmAndDelete() {
const target = deleteEnvTarget;
showDeleteConfirm = false;
deleteEnvTarget = null;
if (target) {
await deleteEnvironment(target.id);
}
}
async function testConnection(id: number) {
testingEnvs.add(id);
testingEnvs = new Set(testingEnvs);
@@ -605,27 +654,15 @@
</ConfirmPopover>
{/if}
{#if $canAccess('environments', 'delete')}
<ConfirmPopover
open={confirmDeleteEnvId === env.id}
action="Delete"
itemType="environment"
itemName={env.name}
title="Remove"
position="left"
onConfirm={() => deleteEnvironment(env.id)}
onOpenChange={(open) => confirmDeleteEnvId = open ? env.id : null}
<Button
variant="ghost"
size="sm"
class="h-7 px-2 text-muted-foreground hover:text-destructive"
title="Delete environment"
onclick={() => requestDeleteEnvironment(env.id)}
>
{#snippet children({ open })}
<Button
variant="ghost"
size="sm"
class="h-7 px-2 {open ? 'text-destructive' : 'text-muted-foreground hover:text-destructive'}"
title="Delete environment"
>
<Trash2 class="w-3.5 h-3.5" />
</Button>
{/snippet}
</ConfirmPopover>
<Trash2 class="w-3.5 h-3.5" />
</Button>
{/if}
</div>
</Table.Cell>
@@ -646,3 +683,72 @@
onSaved={handleSaved}
onScannerStatusChange={handleScannerStatusChange}
/>
<!-- Delete environment confirmation. Lists the on-disk paths that will be
wiped + the count of stacks tracked under this env. Fail-closed:
if the stack-count fetch fails, the dialog still shows but the body
warns that the count couldn't be enumerated. -->
<Dialog.Root bind:open={showDeleteConfirm}>
<Dialog.Content class="max-w-2xl">
<Dialog.Header>
<Dialog.Title class="flex items-center gap-2">
<AlertTriangle class="w-5 h-5 text-destructive" />
Delete environment?
</Dialog.Title>
<Dialog.Description class="pt-2 space-y-3 text-sm">
{#if deleteEnvTarget}
<p>
The environment
<code class="text-xs bg-muted px-1 py-0.5 rounded">{deleteEnvTarget.name}</code>
and the following directories will be permanently removed from the Dockhand host:
</p>
<div class="space-y-1 text-xs font-mono bg-muted/40 rounded-md p-3 border overflow-x-auto">
<div class="flex items-center gap-2 whitespace-nowrap">
<Trash2 class="w-3.5 h-3.5 shrink-0 text-destructive" />
<code class="whitespace-nowrap">$DATA_DIR/stacks/{deleteEnvTarget.name}/</code>
</div>
<div class="flex items-center gap-2 whitespace-nowrap">
<Trash2 class="w-3.5 h-3.5 shrink-0 text-destructive" />
<code class="whitespace-nowrap">$DATA_DIR/git-repos/{deleteEnvTarget.name}/</code>
</div>
</div>
{#if deleteCountsUnknown}
<p>
Couldn't list the stacks on this environment — proceed only
if you're sure what's deployed here.
</p>
{:else if deleteStackCount === 0 && deleteGitStackCount === 0}
<p>No stacks are currently tracked on this environment.</p>
{:else}
<p>
{#if deleteStackCount > 0 && deleteGitStackCount > 0}
<strong>{deleteStackCount} stack{deleteStackCount === 1 ? '' : 's'}</strong>
and <strong>{deleteGitStackCount} git stack{deleteGitStackCount === 1 ? '' : 's'}</strong>
tracked here will be removed from Dockhand's database.
{:else if deleteStackCount > 0}
<strong>{deleteStackCount} stack{deleteStackCount === 1 ? '' : 's'}</strong>
tracked here will be removed from Dockhand's database.
{:else}
<strong>{deleteGitStackCount} git stack{deleteGitStackCount === 1 ? '' : 's'}</strong>
tracked here will be removed from Dockhand's database.
{/if}
</p>
{/if}
<p class="text-muted-foreground">
Running containers on the Docker/Hawser host are <strong>not</strong> stopped.
You can stop or remove them separately.
</p>
{/if}
</Dialog.Description>
</Dialog.Header>
<div class="flex justify-end gap-2 mt-4">
<Button variant="outline" onclick={() => (showDeleteConfirm = false)}>
Cancel
</Button>
<Button variant="destructive" onclick={confirmAndDelete}>
<Trash2 class="w-4 h-4 mr-2" />
Delete environment
</Button>
</div>
</Dialog.Content>
</Dialog.Root>
@@ -14,6 +14,7 @@
import { canAccess, authStore } from '$lib/stores/auth';
import { toast } from 'svelte-sonner';
import ThemeSelector from '$lib/components/ThemeSelector.svelte';
import AnimateIconsToggle from '$lib/components/AnimateIconsToggle.svelte';
import * as Tooltip from '$lib/components/ui/tooltip';
// General settings state - these derive from the store
@@ -375,6 +376,7 @@ services:
<!-- Right column: Theme settings (always shown, with hint when auth enabled) -->
<div class="space-y-4">
<ThemeSelector />
<AnimateIconsToggle />
{#if $authStore.authEnabled}
<div class="text-xs text-muted-foreground flex items-start gap-1.5 mt-2 p-2 bg-muted/50 rounded-md">
<HelpCircle class="w-3.5 h-3.5 shrink-0 mt-0.5" />
@@ -159,7 +159,7 @@
}
} else {
if (!config.urls?.length) {
return 'At least one Apprise URL is required';
return 'At least one webhook URL is required';
}
}
return null;
@@ -234,7 +234,7 @@
}
} else {
if (!config.urls?.length) {
formError = 'At least one Apprise URL is required';
formError = 'At least one webhook URL is required';
return;
}
}
@@ -311,7 +311,7 @@
<Label>Type</Label>
{#if isEditing}
<Badge variant="secondary" class="h-9 flex items-center justify-center">
{formType === 'smtp' ? 'SMTP (Email)' : 'Apprise (Webhooks)'}
{formType === 'smtp' ? 'SMTP (Email)' : 'Webhooks'}
</Badge>
{:else}
<Select.Root
@@ -324,7 +324,7 @@
{#if formType === 'smtp'}
<Mail class="w-4 h-4" />SMTP (Email)
{:else}
<Zap class="w-4 h-4" />Apprise (Webhooks)
<Zap class="w-4 h-4" />Webhooks
{/if}
</span>
</Select.Trigger>
@@ -333,7 +333,7 @@
<span class="flex items-center gap-2"><Mail class="w-4 h-4" />SMTP (Email)</span>
</Select.Item>
<Select.Item value="apprise">
<span class="flex items-center gap-2"><Zap class="w-4 h-4" />Apprise (Webhooks)</span>
<span class="flex items-center gap-2"><Zap class="w-4 h-4" />Webhooks</span>
</Select.Item>
</Select.Content>
</Select.Root>
@@ -409,9 +409,9 @@
</div>
{:else}
<div class="space-y-4 border-t pt-4 min-h-[380px]">
<p class="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Apprise configuration</p>
<p class="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Webhook configuration</p>
<div class="space-y-2">
<Label for="notif-apprise-urls">Apprise URLs * (one per line)</Label>
<Label for="notif-apprise-urls">Webhook URLs * (one per line)</Label>
<textarea
id="notif-apprise-urls"
bind:value={formAppriseUrls}
@@ -430,11 +430,13 @@ workflows://hostname/workflow/signature
bark://bark_key
bark://host/bark_key
barks://host/bark_key
signal://host:8080/+sender/+recipient
apprise://host:8000/your-key
jsons://hostname/webhook/path"
class="flex min-h-[220px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
></textarea>
<p class="text-xs text-muted-foreground">
Supports Gotify (gotify:// or gotifys:// for HTTPS), Discord, Slack, Mattermost (mmost:// or mmosts://), Telegram, ntfy, Bark, Pushover, Workflows (for e.g. Microsoft Teams), and generic JSON webhooks.
Supports Discord, Slack, Mattermost, Telegram, ntfy, Gotify, Pushover, Bark, Signal (via signal-cli-rest-api), Microsoft Teams (via Workflows), and generic JSON. Or use <code>apprise://</code> to forward to a self-hosted <a href="https://github.com/caronc/apprise-api" target="_blank" rel="noopener">caronc/apprise-api</a> server for any provider Apprise upstream supports.
</p>
</div>
</div>
@@ -133,7 +133,7 @@
<div>
<p class="text-sm font-medium">Notification channels</p>
<p class="text-xs text-muted-foreground mt-1">
Configure notification channels to receive alerts about Docker events. Supports SMTP email and Apprise URLs (Discord, Slack, Telegram, ntfy, and more).
Configure notification channels to receive alerts about Docker events. Supports SMTP email and webhook URLs (Discord, Slack, Telegram, ntfy, Bark, Signal, Apprise, and more).
</p>
<p class="text-xs text-amber-600 dark:text-amber-500 mt-2 flex items-center gap-1">
<Info class="w-3 h-3" />
@@ -199,7 +199,7 @@
{#if notif.type === 'smtp'}
<span>SMTP: {notif.config.host}:{notif.config.port}</span>
{:else}
<span>Apprise: {notif.config.urls?.length || 0} URLs</span>
<span>Webhook: {notif.config.urls?.length || 0} URL{notif.config.urls?.length === 1 ? '' : 's'}</span>
{/if}
</div>
@@ -5,7 +5,7 @@
import { Button } from '$lib/components/ui/button';
import * as Card from '$lib/components/ui/card';
import { Badge } from '$lib/components/ui/badge';
import { Plus, Trash2, Pencil, Star, Key, Download, Icon } from 'lucide-svelte';
import { Plus, Trash2, Pencil, Star, Key, Download, Icon, Wifi, RefreshCw, CircleCheck, CircleX } from 'lucide-svelte';
import { whale } from '@lucide/lab';
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
import { canAccess } from '$lib/stores/auth';
@@ -38,6 +38,8 @@
let showRegModal = $state(false);
let editingReg = $state<Registry | null>(null);
let confirmDeleteRegistryId = $state<number | null>(null);
let testingRegistryId = $state<number | null>(null);
let testResults = $state<Record<number, { success: boolean; message: string }>>({});
async function fetchRegistries() {
regLoading = true;
@@ -75,6 +77,30 @@
}
}
async function testRegistry(id: number) {
testingRegistryId = id;
delete testResults[id];
try {
const response = await fetch('/api/registries/test', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ registryId: id })
});
const result = await response.json();
testResults[id] = result;
if (result.success) {
toast.success(result.message);
} else {
toast.error(result.message);
}
} catch {
testResults[id] = { success: false, message: 'Connection failed' };
toast.error('Connection test failed');
} finally {
testingRegistryId = null;
}
}
async function setRegDefault(id: number) {
try {
const response = await fetch(`/api/registries/${id}/default`, {
@@ -171,6 +197,23 @@
Set default
</Button>
{/if}
<Button
variant="outline"
size="sm"
onclick={() => testRegistry(registry.id)}
disabled={testingRegistryId === registry.id}
title="Test connectivity"
>
{#if testingRegistryId === registry.id}
<RefreshCw class="w-3 h-3 animate-spin" />
{:else if testResults[registry.id]?.success}
<CircleCheck class="w-3 h-3 text-green-500" />
{:else if testResults[registry.id] && !testResults[registry.id].success}
<CircleX class="w-3 h-3 text-red-500" />
{:else}
<Wifi class="w-3 h-3" />
{/if}
</Button>
{#if $canAccess('registries', 'edit')}
<Button
variant="outline"
@@ -3,7 +3,7 @@
import * as Dialog from '$lib/components/ui/dialog';
import { Label } from '$lib/components/ui/label';
import { Input } from '$lib/components/ui/input';
import { Plus, Check, RefreshCw } from 'lucide-svelte';
import { Plus, Check, RefreshCw, Wifi, CircleCheck, CircleX } from 'lucide-svelte';
import { focusFirstInput } from '$lib/utils';
export interface Registry {
@@ -32,6 +32,8 @@
let formPassword = $state('');
let formError = $state('');
let formSaving = $state(false);
let testResult = $state<{ success: boolean; message: string } | null>(null);
let testLoading = $state(false);
function resetForm() {
formName = '';
@@ -40,6 +42,8 @@
formPassword = '';
formError = '';
formSaving = false;
testResult = null;
testLoading = false;
}
// Initialize form when registry changes or modal opens
@@ -51,12 +55,52 @@
formUsername = registry.username || '';
formPassword = '';
formError = '';
testResult = null;
} else {
resetForm();
}
}
});
async function testConnection() {
if (!formUrl.trim()) {
formError = 'URL is required to test';
return;
}
testLoading = true;
testResult = null;
formError = '';
try {
const body: Record<string, any> = { url: formUrl.trim() };
// For edit mode with no new password, use the saved registry's credentials
if (isEditing && !formPassword && registry?.id) {
// If username present but no new password, test via registry ID to use stored creds
if (formUsername.trim()) {
body.registryId = registry.id;
delete body.url;
}
} else {
if (formUsername.trim()) body.username = formUsername.trim();
if (formPassword) body.password = formPassword;
}
const response = await fetch('/api/registries/test', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
testResult = await response.json();
} catch {
testResult = { success: false, message: 'Failed to test connection' };
} finally {
testLoading = false;
}
}
async function save() {
if (!formName.trim() || !formUrl.trim()) {
formError = 'Name and URL are required';
@@ -136,7 +180,26 @@
</div>
</div>
</div>
{#if testResult}
<div class="flex items-center gap-2 text-sm {testResult.success ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'}">
{#if testResult.success}
<CircleCheck class="w-4 h-4 shrink-0" />
{:else}
<CircleX class="w-4 h-4 shrink-0" />
{/if}
<span>{testResult.message}</span>
</div>
{/if}
<Dialog.Footer>
<Button variant="outline" onclick={testConnection} disabled={testLoading}>
{#if testLoading}
<RefreshCw class="w-4 h-4 animate-spin" />
{:else}
<Wifi class="w-4 h-4" />
{/if}
Test
</Button>
<div class="flex-1"></div>
<Button variant="outline" onclick={handleClose}>Cancel</Button>
<Button onclick={save} disabled={formSaving}>
{#if formSaving}
+1 -1
View File
@@ -2076,7 +2076,7 @@
class="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded {portUrl ? 'bg-primary/10 text-primary hover:bg-primary/20' : 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200 hover:bg-blue-200 dark:hover:bg-blue-800'} transition-colors"
title="Open {url} in new tab"
>
<code>{port.display}</code>
<code>{portParsed?.name ?? port.display}</code>
<ExternalLink class="w-2.5 h-2.5 {portUrl ? 'opacity-60' : ''}" />
</a>
{:else}
+24 -3
View File
@@ -4,6 +4,7 @@
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { goto } from '$app/navigation';
import { toast } from 'svelte-sonner';
import { Badge } from '$lib/components/ui/badge';
import { Button } from '$lib/components/ui/button';
@@ -28,7 +29,7 @@
import { EmptyState, NoEnvironment } from '$lib/components/ui/empty-state';
import { DataGrid } from '$lib/components/data-grid';
type SortField = 'name' | 'driver' | 'stack' | 'created';
type SortField = 'name' | 'driver' | 'type' | 'stack' | 'created';
type SortDirection = 'asc' | 'desc';
let volumes = $state<VolumeInfo[]>([]);
@@ -202,7 +203,10 @@
const query = searchQuery.toLowerCase();
result = result.filter(vol =>
vol.name.toLowerCase().includes(query) ||
(vol.labels['com.docker.compose.project'] || '').toLowerCase().includes(query)
(vol.labels['com.docker.compose.project'] || '').toLowerCase().includes(query) ||
// Match the driver_opts type (e.g. "nfs", "cifs") so users can
// quickly find network-mounted volumes by typing the protocol.
(vol.options?.type || '').toLowerCase().includes(query)
);
}
@@ -216,6 +220,10 @@
case 'driver':
cmp = a.driver.localeCompare(b.driver);
break;
case 'type':
// Volumes without driver_opts.type sort below those with one.
cmp = (a.options?.type || '').localeCompare(b.options?.type || '');
break;
case 'stack':
const stackA = a.labels['com.docker.compose.project'] || '';
const stackB = b.labels['com.docker.compose.project'] || '';
@@ -539,11 +547,24 @@
<code class="text-xs truncate block" title={volume.name}>{volume.name}</code>
{:else if column.id === 'driver'}
<Badge variant="outline" class="text-xs py-0 px-1.5 shadow-sm rounded-sm">{volume.driver}</Badge>
{:else if column.id === 'type'}
{#if volume.options?.type}
<Badge variant="outline" class="text-xs py-0 px-1.5 shadow-sm rounded-sm" title={Object.entries(volume.options).map(([k, v]) => `${k}=${v}`).join('\n')}>{volume.options.type}</Badge>
{:else}
<span class="text-muted-foreground text-xs">-</span>
{/if}
{:else if column.id === 'scope'}
<span class="text-xs">{volume.scope}</span>
{:else if column.id === 'stack'}
{#if stack}
<Badge variant="secondary" class="text-xs py-0 px-1.5 shadow-sm rounded-sm">{stack}</Badge>
<button
type="button"
onclick={(e) => { e.stopPropagation(); goto(appendEnvParam(`/stacks?search=${encodeURIComponent(stack)}`, envId)); }}
class="cursor-pointer"
title={`Open stack "${stack}"`}
>
<Badge variant="secondary" class="text-xs py-0 px-1.5 shadow-sm rounded-sm hover:bg-primary/10 hover:border-primary/50 transition-colors">{stack}</Badge>
</button>
{:else}
<span class="text-muted-foreground text-xs">-</span>
{/if}
+27 -2
View File
@@ -2,7 +2,9 @@
import * as Dialog from '$lib/components/ui/dialog';
import { Button } from '$lib/components/ui/button';
import { Badge } from '$lib/components/ui/badge';
import { Loader2, HardDrive } from 'lucide-svelte';
import * as Tooltip from '$lib/components/ui/tooltip';
import { Loader2, HardDrive, Layers } from 'lucide-svelte';
import { goto } from '$app/navigation';
import { currentEnvironment, appendEnvParam } from '$lib/stores/environment';
import { formatDateTime } from '$lib/stores/settings';
@@ -50,9 +52,32 @@
<Dialog.Root bind:open>
<Dialog.Content class="max-w-4xl max-h-[90vh] flex flex-col">
<Dialog.Header class="shrink-0">
<Dialog.Title class="flex items-center gap-2">
<Dialog.Title class="flex items-center gap-2 flex-wrap">
<HardDrive class="w-5 h-5" />
Volume details: <span class="text-muted-foreground font-normal break-all">{volumeName}</span>
{@const composeStack = volumeData?.Labels?.['com.docker.compose.project']}
{#if composeStack && !loading}
<Tooltip.Root>
<Tooltip.Trigger>
<button
type="button"
onclick={() => {
open = false;
goto(appendEnvParam(`/stacks?search=${encodeURIComponent(composeStack)}`, $currentEnvironment?.id ?? null));
}}
class="cursor-pointer inline-flex items-center"
>
<Badge variant="outline" class="text-xs py-0 px-1.5 hover:bg-primary/10 hover:border-primary/50 transition-colors gap-1">
<Layers class="w-3 h-3" />
{composeStack}
</Badge>
</button>
</Tooltip.Trigger>
<Tooltip.Content>
<p class="text-xs whitespace-nowrap">Open stack "{composeStack}"</p>
</Tooltip.Content>
</Tooltip.Root>
{/if}
</Dialog.Title>
</Dialog.Header>