feat(stacks): live compose output and deploy history (#1499)
* feat(security): add exact-value redaction for compose output lines
* feat(stacks): emit compose output line by line via optional callback
* test(stacks): isolate collectProcess test from the DB init side effect
stacks.ts transitively imports db.ts and db/drizzle.ts, which run a
top-level seedDatabase() against better-sqlite3 -- unsupported under
Bun (oven-sh/bun#4290). Importing stacks.ts for a plain unit test
crashed at import time and, worse, leaked into unrelated test files
sharing the same bun test process (reproduced against
tests/semver-generic-v2.test.ts). Mock both modules' full export
surface before importing, mirroring tests/backups/route-guards.test.ts's
established mock.module(./db) pattern.
* refactor(stacks): extract collectProcess into a dependency-free core module
Testing it required importing stacks.ts, which transitively pulls in
db.ts and db/drizzle.ts -- both run a top-level seedDatabase() against
better-sqlite3, which does not load under Bun. That crash was cached
process-wide and broke an unrelated, previously-green test file
(tests/semver-generic-v2.test.ts) whenever the full suite ran.
Following the repo's established -core module pattern (nav-preferences-core,
ws-exec-core, etc.), collectProcess now lives in its own dependency-free
file and is re-exported from stacks.ts for its existing callers.
* feat(security): bridge line callbacks through redaction
makeLineForwarder wraps a raw line consumer with redactLine, dropping
withheld lines silently. This is the connector collectProcess-emitted
lines will pass through before reaching the job store.
* feat(stacks): thread onLine through the local compose execution path
executeLocalCompose, executeComposeViaHawser, and executeComposeCommand
all accept an optional onLine callback now, forwarded to whichever
execution path is chosen. The local path (executeLocalCompose) wires it
into collectProcess via makeLineForwarder, redacting against envVars and
secretVars -- deliberately not spawnEnv, which also carries PATH, HOME,
DOCKER_CONFIG and DOCKER_API_VERSION and would over-redact (HOME often
resolves to "/root", five characters, below the safe-replace threshold,
which would withhold every line containing it).
executeComposeViaHawser accepts the parameter for signature parity but
does not use it yet: its /_hawser/compose call is a single
request/response, not a stream, so it cannot report lines as they
happen. That lands in a follow-up task.
startStack, stopStack, restartStack, downStack, and deployStack gained
an onLine parameter (deployStack via a new DeployStackOptions field) and
pass it through to every executeComposeCommand call in their body.
redeployStackFromDir, removeStack, pullStackImages, pullStackService,
and updateStackService are deliberately left unchanged -- they don't run
behind the streaming job endpoints.
* feat(stacks): forward redacted compose output lines to the job store
Each of the five job endpoints (deploy/start/stop/restart/down) now
passes send as the onLine callback, wrapping each line in a
{type: 'line', line} progress event. The 'line' type distinguishes
these from the existing static {status} progress events the endpoints
already send.
* chore(tests): use English throughout, matching the repository language
* refactor(tests): rename identifiers to English
* feat(ui): readJobResponse forwards line messages to an optional callback
* feat(ui): show compose output while stack operations run
* feat(stacks): surface the final output block when an agent sends no lines
* feat(stacks): thread onLine through the create and compose endpoints
POST /api/stacks (create & start) and PUT /api/stacks/{name}/compose
(save & redeploy) both run deployStack inside createJobResponse but never
passed onLine, so no 'line' progress messages were emitted and any live
output view stayed empty until the job settled.
Both now forward lines exactly like the deploy endpoint does. A source-level
guard asserts every deployStack call under src/routes/api carries onLine —
the omission is invisible at runtime, so nothing else would catch the next one.
* feat(ui): show compose output for Create & Start and Save & redeploy
The five stack-row actions opened the output window; the stack modal's two
deploying paths did not, leaving the most common route after an edit —
Save & redeploy — with no visible progress.
The modal takes three optional callbacks and forwards to them. It holds no
output state and renders no window of its own: the loop stays on the page, so
closing the modal cannot tear down a running deploy. Callers that don't pass
them are unaffected.
* feat(hawser): route agent line messages to non-streaming compose requests
* feat(stacks): consume streamed compose lines from the agent
* refactor(logs): make LogViewer's title optional and path-safe
* fix(logs): strip the escape sequences compose actually emits
The first pattern accepted only digits and semicolons as CSI parameter bytes,
so it left private-mode sequences untouched -- including ESC[?25l and ESC[?25h,
which compose's progress display writes on every redraw. A stripper that misses
the sequences of the output it exists to clean does not do its job.
Match the CSI grammar instead: ESC [ , parameter bytes (0x30-0x3F, which is
where '?' lives), intermediate bytes (0x20-0x2F), one final byte (0x40-0x7E).
Also cover the backslash branch of the path-separator test, which the previous
case did not exercise.
* feat(stacks): show compose output in the full log viewer
* feat(stacks): summarise compose output into deploy facts
* feat(stacks): add a status line with duration to the compose output window
Measure wall-clock duration client-side (Date.now() at start, diff on
result) and format it with formatRunStatus() in ComposeOutputModal's
description: "Running…", "Succeeded · 6.2s", or "Failed · exit 1 · 0.9s".
Wires all five +page.svelte stack actions (start/stop/restart/redeploy/
down) plus StackModal's two own action paths (create+start, redeploy on
save) through the same startComposeOutput/finishComposeOutput state, so
every caller of the modal reports success/failure consistently. Without
the StackModal fix, its two actions would have reported every success as
"Failed" (ok defaulting to undefined).
exitCode is read defensively from the job result but StackOperationResult
carries no such field today, so it stays undefined until the server adds
one.
* feat(deploy-logs): add filesystem-backed log store for deploy runs
Provides appendRunLog/readRunLog/deleteRunLog/listRunLogIds/runLogPath
for per-run log files under DATA_DIR/deploy-logs. The run id is
validated (not sanitised) into a filename, so a route-parameter run id
can never resolve outside the log directory. usedBytes/budgetExceeded
compute directory usage against a 2 GiB budget for a later task to
enforce.
* fix(security): keep deploy logs out of the file browser
* test(fs-guard): stop the deploy-log test from leaking DATA_DIR
Bun runs every test file in one process. Setting DATA_DIR at module scope leaked
it into unrelated suites: selfhst-icons builds and creates its cache directory
under DATA_DIR, which fails when that points at a path the machine does not
have. Both selfhst tests went red once this file was added, while each file
passed on its own.
protectedPaths() reads the variable on every call rather than at import time, so
a plain import plus beforeAll/afterAll is enough -- the dynamic import was never
needed, and it was what made the leak module-scoped in the first place.
* fix(logs): let auto-scroll pause while the user reads earlier output
LogViewer's auto-scroll effect jumped to the bottom on every logs update
whenever autoScroll was true, with no way to opt out. In the compose
deploy output window autoScroll stays true for the whole run, so
scrolling up to read an earlier line got immediately overridden by the
next line arriving.
Restore the pause/resume behaviour the removed ComposeOutputModal
output pane used to have: track how close the viewport is to the
bottom on scroll, and skip the auto-scroll effect while the user is
more than 50px away from it. Scrolling back within range resumes it.
The auto-scroll effect's own scrollTop write triggers a 'scroll' event
too, so a flag suppresses handleLogScroll for the duration of that
write -- otherwise a fast enough stream of new lines could grow
scrollHeight again between the write and the event firing, misreading
our own jump as the user having scrolled up.
The distance check is extracted into isScrolledToBottom(), a pure
function, so it has a real test (including the exact-threshold
boundary case).
Also hide the Clear/Refresh buttons when no onClear/onRefresh handler
is supplied -- LogViewer's only current caller (ComposeOutputModal)
passes neither, so both buttons were rendered as inert dead clicks.
* feat(stacks): record only redacted output lines, never the result block
* fix(logs): lift a scroll-up pause when a fresh run starts
userScrolledUp was only ever set, never reset -- so scrolling up once
during a deploy paused auto-scroll for every later run of the same
page session, measured live: heights grew (392->1130px, 446->1130px)
but scrollTop stayed frozen once a prior scroll-up had set the flag,
even on a run nobody had scrolled during.
autoScroll going from false to true is the "a fresh run is starting"
signal (ComposeOutputModal's autoScroll={running} flips false->true at
the exact moment its parent clears composeOutputLines and starts a new
compose run) -- so that edge lifts the pause. Deliberately an edge, not
a level: reacting to autoScroll simply being true would re-lift the
pause on every single update while a run is already in progress,
defeating it entirely. shouldResetScrollPause() is a pure function
again, with a test for exactly that distinction (true -> true must stay
false) alongside the three other transitions.
* fix(logs): avoid state_referenced_locally on previousAutoScroll
npm run check flagged the previous run's seeding line (`let
previousAutoScroll = autoScroll`) as reading a prop in a plain
top-level initializer, which only captures its value once and usually
signals a bug. Leave it unset instead and let the effect seed it on
its first run, where reading autoScroll is tracked -- no behaviour
change, just where the initial read happens.
* feat(sse): hook an optional RunRecorder into both createJobResponse send paths
createJobResponse has two independent send() implementations: the JSON path
(Accept: application/json) and the streaming/job-poll path. A recorder wired
into only one of them would silently miss every deploy driven through the
other -- the UI keeps working, so nobody notices.
Add an optional third parameter, RunRecorder, with line() and end(). Both
send() closures now forward shouldRecord-qualifying lines to recorder.line();
end() is called on every path out of the operation (JSON: in a finally,
awaited before the response is enqueued; streaming: from the .then()/.catch()
that already drive completeJob/failJob, unawaited since the {jobId} response
already went out by the time the operation settles).
The interface is declared here, not built here: constructing a real recorder
needs db.ts, and importing that into sse.ts would make it unimportable under
Bun. Task 10 builds the recorder in the route and imports RunRecorder from
here. Until then both callers omit the third argument, which is exactly the
prior behaviour.
* feat(db): index schedule_executions by entity and environment
Powers per-stack/container deploy-run lookups without a full table scan.
* feat(schedules): register stack_deploy and deploy_log_reconcile types
Widen every schedule-type union that the run record (stack_deploy) and
the reconcile job (deploy_log_reconcile, upcoming) will need: the two
independent unions in src/lib/server/db.ts (ScheduleType) and
src/routes/api/schedules/+server.ts (ScheduleInfo.type, duplicated in
+page.svelte), plus SystemScheduleInfo.type in scheduler/index.ts so the
reconcile job can register as a system schedule alongside system_cleanup.
Give both types real labels in the schedules page instead of falling
into the generic system-job branches: the single-selected filter label,
the two new filter dropdown entries, and the execution detail dialog's
title chain. stack_deploy has no schedule until M3, so its entries are
inert until then -- added now so they aren't forgotten later.
Also cover the two places whose correct behaviour depends on treating
deploy_log_reconcile like the other system schedules: hiding it from
the filter list when "hide system jobs" is toggled, and rejecting an
attempt to pause/resume it through the per-item toggle endpoint the
same way system_cleanup already is (it's a global, settings-driven
schedule, not a per-item cron).
The manual-run endpoint's two type switches are deliberately left
untouched: stack_deploy has no schedule to run, and deploy_log_reconcile
has no trigger function yet (that lands with its own scheduler task).
Wiring a case now would either call nothing or reference a module that
doesn't exist.
npm run check: same 687 pre-existing errors/152 warnings before and
after (confirmed via git stash), only shifted line numbers where lines
were inserted -- no new problems introduced.
* fix(stacks): size the compose output window for build logs
The window was max-w-3xl (48rem) at 60vh. Compose and BuildKit lines are wide
-- step lines, image digests, container names -- so most of them wrapped or
needed horizontal scrolling, which defeats the point of showing them.
Widened to 90rem and 85vh, clamped with min() against the viewport so it still
fits on a laptop screen with a margin instead of overflowing.
* feat(schedules): record every stack_deploy run as a schedule_executions row
Add the run record that the rest of milestone 2 depends on: without it, deploy
logs land on disk with nothing pointing at them, execution history stays empty,
and the upcoming reconciler would treat every log file as orphaned and delete it.
deploy-run-record-core.ts (buildRunDetails, importfree) assembles the details
JSON -- options, summary, exit code, compose/env hash, log file name -- and
refuses to build it without a log file name, since that name is what ties the
record to its file. deploy-run-record.ts (createRunRecorder) is the
database-touching half: creates the schedule_type='stack_deploy',
schedule_id=0 row up front, chains line() calls onto appendRunLog so
concurrent writes can't scramble the log's order, and closes the row in
end() -- which must work even when no line ever arrived, since a deploy can
fail before compose produces any output.
Also switches on deploy-log-store's total-size budget (defined in an earlier
task, never called anywhere until now): once a run's log crosses it, further
lines are dropped, the file gets a line saying so, and details.truncated is
set.
Wires the recorder into both places that call deployStack from an HTTP
handler: the dedicated deploy endpoint and stack-create-with-immediate-start.
Both now read/compute the compose and effective env up front so a compose
hash, env hash, and the schedule_executions row all exist before the SSE job
stream opens -- createJobResponse takes the recorder as an already-resolved
value, not something it can await for itself.
stacks.ts gains an exitCode field on StackOperationResult, populated by the
local/direct compose path (which already had the number, just wasn't
returning it) and left unset on a timeout or over Hawser (protocol doesn't
carry one) -- the recorder falls back to a value consistent with success/
failure when it's missing.
bun test tests/: 2828 pass, 0 fail (baseline 2826 + this task's 2 new tests).
* fix(schedules): keep the deploy summary in sync with what actually got written
line() pushed its argument onto the in-memory buffer synchronously, but only
queued the file write onto the async chain. Called several times before the
chain gets to run any of them (the ordinary case -- compose output arrives in
bursts), a line already sitting in the buffer could still get skipped by the
file write once truncation kicks in partway through the queue, leaving the
eventual summary counting a line that was never actually persisted.
Move the push into the same guarded step as the write so both share one
fate: a line only ever ends up in the summary if it also ended up in the
file. Caught by re-reading the chaining logic after writing it, not by a
test -- verified instead with a live run against a real SQLite db (tsx,
temp DATA_DIR) confirming the three-line/no-line lifecycles still land
correctly. bun test tests/: still 2828 pass, 0 fail.
* feat(stacks): add deploy-run endpoints (list, single, log, delete)
Three routes under api/stacks/[name]/deploys/ each check stacks:view/edit for
themselves -- they do not inherit /api/jobs/{id}'s no-auth model. A shared
loadOwnedDeployRun helper confirms a run actually belongs to the requested
stack and checks environment access against the run's OWN environmentId
(never a caller-supplied env query param), closing the same cross-env bypass
class backups/route-guards.ts already closed for snapshot/config lookups.
getScheduleExecutions gained an entityName filter, the actual consumer of the
(entity_name, environment_id) index from the previous commit.
Also: extracted tests/helpers/db-fake.ts, a shared mock.module() registration
point for $lib/server/db, and moved tests/backups/route-guards.test.ts onto
it. Two test files each wholesale-mocking that module collided (confirmed:
whichever wins clobbers the other's needed export, deterministically) -- the
new helper avoids that by pre-declaring every export name any test needs as a
stable dispatcher, so later-registered implementations are still reachable
regardless of which file's import resolves the specifier first.
* feat(schedules): reconcile deploy-log files against stack_deploy records
Adds a dedicated deploy_log_reconcile schedule, modelled on system-cleanup.ts's
static jobs (own cron + enabled setting, own schedule_executions row) rather
than tacking it onto system_cleanup: the operator can see and disable it
independently.
planReconcile() is a pure decision core: a file with no matching record is
deleted (an orphan with nothing left to explain it); a record with no file is
only marked via details.logMissing, never deleted, since the run metadata
(when, who, what was built) stays valuable once the log text is gone. The
asymmetry is the point -- over-eager deletion here would destroy exactly the
record this job exists to protect.
run/+server.ts gained a deploy_log_reconcile case in both switches (env
resolution and dispatch) -- without it every manual trigger 400s, since both
switches already have a default that rejects unknown types.
ASSUMPTION flagged in deploy-log-reconcile.ts: the record side reads
schedule_executions rows with scheduleType 'stack_deploy' and treats
String(id) as the deploy-log run id. Nothing in this branch creates such a
row yet -- that is Task 10's createRunRecorder, not landed here (confirmed:
no t10/done ref exists). This is read-only against the existing, already
scheduled ScheduleType union, not a substitute for Task 10's write path, but
it is unverified against Task 10's actual output and needs a look once that
lands.
triggerDeployLogReconcile() is a separate function rather than a branch in
triggerSystemJob(): that function dispatches by a flat, type-less jobId
string, and DEPLOY_LOG_RECONCILE_ID (1) would otherwise collide with
SYSTEM_SCHEDULE_CLEANUP_ID (also 1, different scheduleType).
* fix(schedules): don't mark an in-progress deploy's record as logMissing
Read deploy-run-record.ts directly (Task 10's real code, in a sibling clone
not yet merged onto this branch) to check the assumption flagged in the
previous commit -- and it confirmed the record-id linkage is exactly right
(scheduleType 'stack_deploy', String(schedule_executions.id) as the deploy-log
run id), but also surfaced a race this job didn't guard against: the row is
created with status 'running' before the deploy has written a single line,
and the log file only comes into existence on the first line() call. A
reconcile firing in that window would mark an actively-running deploy as
logMissing, and nothing here ever re-checks or clears that flag once the file
does appear -- so the record would carry a false "log missing" permanently.
getScheduleExecutionIdsByType() now also returns status; records still
'queued'/'running' are excluded from markMissing candidacy (a later run will
catch them correctly once the deploy has actually finished) while remaining
in recordIds, so an already-written file for them stays protected from
deletion either way.
* test(schedules): extract the in-progress guard into a tested pure function
isEligibleForMissingMark() replaces the inline NON_TERMINAL_STATUSES array
check in deploy-log-reconcile.ts -- same decision, now importfree and covered
by its own tests (both non-terminal statuses excluded, every terminal status
included), with a mutation counter-test confirmed to go red for the right
reason before being reverted.
* fix(stacks): keep compose output visible below the editor on deploy
Save & redeploy and Create & Start used to hand live output off to a
separate window and close the stack modal immediately, so the editor
and the output were never visible at the same time -- forcing the user
to close the output window just to get back to the compose they were
editing.
The modal now keeps its own output state (lines, running, ok, ms, exit
code) and renders it inline below the editor instead of forwarding to
the page's shared ComposeOutputModal. Whether the modal closes after a
save is now a small pure function, shouldCloseAfterSave(deployed): a
plain save still closes, a deploy stays open so the output stays
visible.
Also fixes a pre-existing bug in the same code path: the error branch
called finishOutput(undefined, false) unconditionally, clobbering the
real ok/exitCode a prior successful finishOutput call had already
recorded when the job itself reported failure. Now guarded on
outputRunning so a real result from the server is never overwritten.
GitStackModal.svelte does not use the onOutput* props and needed no
changes.
* fix(stacks): clear docked deploy output when the modal reopens
StackModal is persistently mounted -- one instance is reused for every
stack. The new output* state introduced for the docked deploy output
was only ever assigned in startOutput(), so it survived close/reopen
just like the pre-existing compose-validate state does. Reopening the
modal for a different stack could show the previous stack's title,
lines and "Succeeded"/"Failed" status under the new stack's editor,
which reads as if something just ran for it.
Reset all seven output* fields in the same open-effect block that
already clears validate panel state on each open, for the same reason.
A reopen of the *same* stack while its own deploy is still running
loses the lines gathered so far, but the poll loop in sse-fetch.ts
keeps running regardless of the modal's open state (same as
ComposeOutputModal), so new lines resume arriving within one poll
interval; and if the job finishes before any new line does,
finishOutput's existing "outputLines.length === 0 && output" fallback
refills the whole transcript from the job's final output. That brief,
self-correcting gap was judged preferable to a stale result silently
misattributed to the wrong stack.
* fix(deploys): require env on the list endpoint to stop cross-environment leaks
GET /api/stacks/[name]/deploys treated `env` as optional. Omitting it left
envIdNum undefined, which skipped the enterprise environment-access check,
made auth.can() evaluate the caller's globally-merged permission instead of
their permission for one specific environment, and dropped the environment
filter from getScheduleExecutions() entirely -- returning stack_deploy runs
(timestamps, status, error text, details.userId) from every environment that
happens to have a same-named stack, regardless of what the caller's role
actually grants.
A stack name alone doesn't identify one environment, so there's no correct
behavior for a missing `env` beyond rejecting the request: parse and validate
it before the permission check runs, so auth.can() and canAccessEnvironment()
always see a definite id. Sibling routes under .../deploys already close this
class via loadOwnedDeployRun (env derived from the loaded run); this was the
one route deriving it from an optional query parameter instead.
* fix(schedules): isolate per-element failures in the reconcile job
Reproduced independently: one throwing deleteRunLog/updateScheduleExecution
call aborted the whole run -- and since the failing element is never
removed/marked, every LATER run failed at the exact same element again,
permanently. A harmless orphan file ordered before the failing one was still
removed; everything after it was not; the failed run's own `details` came
back null, so the partial progress wasn't even visible.
Both loops now wrap each element in its own try/catch (same shape as
scheduler/index.ts's scannerCleanupAllEnvs, which does this per-environment
for the same reason). Failures are counted and logged individually instead
of aborting.
Counts now reflect what actually happened, not what was planned:
deletedFiles/markedRecords only increment on success, plus a new `failed`
count. Previously markedCount was derived from plan.markMissing.length minus
skippedInProgress -- correct only by coincidence, since nothing before this
commit could fail mid-loop; a failing element would have inflated it to the
planned size.
A run with per-element failures is recorded as 'warning' rather than
'success' -- this repo's existing convention for "completed with a caveat"
(see the ScheduleStatus doc comment in db.ts), not 'failed', which stays
reserved for the run itself throwing (the outer catch, unchanged).
Tests (tests/deploy-log-reconcile-job.test.ts, new): one per loop, each with
a mutation counter-test confirmed to fail for the right reason (the element
after the failure was unreached; the reported count matched the plan instead
of the outcome), then reverted. $lib/server/db faked via
tests/helpers/db-fake.ts's shared registry (extended with the five exports
this job needs); $lib/server/deploy-log-store mocked directly since no other
test file claims it.
* fix(sse): reuse endFromResult on the streaming path so a failed run is recorded as failed
A failed docker compose run sends result:{success:false,error} and returns
normally -- it never throws. On the fire-and-forget streaming path (no Accept
header, the path every browser call takes), the .then() branch hardcoded
recorder.end(true) regardless of the result payload, so every such run was
persisted with status:"success" and errorMessage:null.
The JSON path already derives ok/error from the held-back result via
endFromResult(); reuse it here instead of duplicating success/failure logic,
using the result line the .then() branch already reads for completeJob().
* fix(deploy-run-record): redact known secret values out of the stored error text
DeployRunRecorder.end() wrote result.error verbatim into schedule_executions'
errorMessage/details on a failed run. That string is compose's raw, unredacted
stdout/stderr (deploy-recorder.ts's shouldRecord() deliberately excludes the
'result' event from the log file for this exact reason). GET
/api/schedules/executions returns errorMessage/details to every authenticated
user, with no stack/environment permission check -- so a secret that leaked
into compose's error output was readable across permission boundaries.
createRunRecorder() now takes the same merged secrets list its callers already
build for envHash, and end() runs the error text through the same redactLine()
the streamed lines already use before storing it. When redactLine withholds
the whole line (a too-short value matched), the row still closes "failed" with
a safe placeholder instead of no message at all -- a run stuck as "running"
forever is worse than one with a generic error.
* fix(stacks): auto-close after a successful deploy, stay open on failure
Operator decision (30.08.2026), after seeing the docked output live:
always keeping the modal open post-deploy was as wrong as always closing
it used to be. A plain save still closes as before. A deploy that
succeeded now closes too, just after a longer delay so the result is
still glimpsed. A deploy that failed keeps staying open.
shouldCloseAfterSave(deployed: boolean): boolean is replaced by
saveCloseTiming(deployed: boolean, ok: boolean): 'close' | 'close-delayed'
| 'stay-open', so the three operator-specified outcomes are each
individually representable and testable, instead of collapsing "closes"
into one boolean that couldn't distinguish "right away" from "after a
flash".
Verified there is no path at the two call sites where a failed deploy
resolves without throwing first: both POST /api/stacks and PUT
/api/stacks/{name}/compose always send an explicit `result` event with
success:false on failure, with an explicit `return` right after it, so
neither send() call falls through to the success path afterwards. The
'stay-open' branches at both call sites are therefore dead code today,
kept only so the switch stays exhaustive if that ever changes.
* feat(stack-modal): make the live output panel's height resizable
The output panel below the compose editor had a fixed height. Add a
horizontal drag divider (mirroring the existing vertical compose/env
split) so the panel can be resized between 15% and 70% of the combined
editor+output area, persisted to its own localStorage key.
Extract the clamp used by both splitters into clampSplitRatio() and fix
a latent bug along the way: Math.max(min, Math.min(max, value)) does
not clamp when value is NaN (Math.min/Math.max propagate NaN), which
happens for real when a container's measured size is briefly 0 during
a drag. The existing compose/env splitter had the same bug and now
uses the same fixed clamp.
* fix(stacks): record Save & redeploy (compose PUT) as a stack_deploy run
PUT /api/stacks/[name]/compose with restart:true redeployed the stack but
never built a run recorder, unlike the dedicated deploy endpoint and
stack-create-with-immediate-start. After a successful redeploy the modal
now auto-closes (recent change), so this was the only path where the
output of a successful deploy was fully lost -- no schedule_executions
row, no log file, nothing to look back at.
Wires createRunRecorder in identically to deploy/+server.ts: switches the
authoritative-paths lookup from getStackComposeFile to requireComposeFile
(same call, now also resolving secretVars/nonSecretVars), hashes the
just-submitted `content` (not a re-read off disk -- saveStackComposeFile
already wrote this exact string, and it's the same string handed to
deployStack), and hashes the merged effective env for envHash. Skipped
entirely when requireComposeFile unexpectedly fails right after a
successful save, so a run is never recorded with an empty secrets list.
restart:false (save only) is untouched -- no recorder is built, no row is
created.
Adds tests/helpers/authorize-fake.ts, mirroring db-fake.ts's dispatcher
pattern, and moves tests/deploy-endpoints.test.ts's inline authorize mock
onto it -- a second direct mock.module('$lib/server/authorize', ...) in
the new test file would have collided with that file's existing one.
bun test tests/: 2878 pass, 0 fail (baseline 2870 + this task's 8 new
tests). npm run check not yet run.
* fix(stack-modal): clamp the validate-panel width the same way, and rename accordingly
validatePanelWidth = Math.max(320, Math.min(560, w)) had the same NaN
gap as the two split-ratio clamps fixed earlier: if editorRowRef's
measured width is briefly 0 during a drag, w becomes NaN and the
"clamp" stays NaN.
clampSplitRatio never assumed a percentage, only value-vs-bounds
ordering, but its name did -- applying it to a pixel width buried that
under a misleading name. Renamed it (and its module/test file) to
clampNumber, with a doc comment that says plainly it works for both
percentage ratios and pixel distances, and a dedicated test proving
the pixel bounds (320-560) clamp exactly like the percentage bounds.
* feat(stack-modal): add a Deploys tab showing recorded run history
Adds a third history-style tab next to Backups: each recorded
stack-deploy run (GET /api/stacks/{name}/deploys, env required) as a
collapsed row -- status, relative time, duration, and a one-line
container/build summary -- expandable for the full picture: container
counts, whether the build came from cache or not, images built/pulled,
the deploy options used, a truncated-log notice, and on failure the
shortened last error line.
All of that text composition lives in deploy-run-view.ts as pure,
import-free functions (mirrors deploy-summary-core.ts's own reasoning:
no $lib/server import, so the test file runs under Bun without
dragging in better-sqlite3). The one case load-bearing enough to name
in its own doc comment: a run with no summary at all (compose produced
zero output lines) must read as "unknown", never silently as "zero
containers, nothing built" -- those are different facts.
No component test exists for DeploysPanel.svelte itself -- this repo
has no Svelte component test harness (no @testing-library/svelte, no
jsdom; @playwright/test is a dependency with zero test files). Manual
verification only for the component; the 37 new unit tests cover every
branch of the text-composition layer instead.
* perf(deploy-log-store): stop re-scanning deploy-logs/ on every appended line
DeployRunRecorder.line() called budgetExceeded() (a full readdir+stat over
every file in deploy-logs/) after every single line, so a deploy's cost grew
with both its own output AND the number of past runs' log files on disk.
Measured: 200 lines against 500 existing files took ~16.2s; against 50 files
~1.8s; with the scan removed entirely, ~49ms.
Replace that per-line full scan with SizeBudgetTracker: the directory total
excluding this run's own file is measured once, lazily, and cached; each
appended chunk's byte length is added to an in-memory running total (no
stat() involved); the cache is only re-measured once the run's own output
crosses 1 MiB since the last measurement. The budget itself is unchanged
(2 GiB, checked after each write per design doc §5) -- only how often the
directory gets re-scanned to check it.
This trades exactness for speed under concurrent writers: a run started
right after this run's baseline was measured is invisible to this run's
budget check until the next refresh. Documented on SizeBudgetTracker as an
intentional trade-off -- BUDGET_BYTES exists to catch a filled disk, not to
enforce a precise quota, and the old per-line scan had no locking against
concurrent appendRunLog() calls either.
Tests: SizeBudgetTracker's budget math (under/over/already-over-before-first-
byte), its refresh cadence (scans once for 200 small appends where the old
code would have scanned 200 times, and again once a single big append
crosses the refresh threshold), and the documented concurrent-writer gap.
Plus a DeployRunRecorder-level truncation test via an injected tiny-budget
tracker (SizeBudgetTracker now takes optional budgetBytes/measureOthers
params, DeployRunRecorder now takes an optional sizeBudget -- both test-only
seams, unused by production callers).
Refs branch-review.md H2.
* feat(stack-modal): load and show a deploy run's log on expand
Expanding a Deploys-tab row now fetches GET .../deploys/{id}/log into a
LogViewer, lazily -- never while the list itself loads. A run already
marked logMissing by deploy-log-reconcile skips the fetch entirely
instead of making a request that would just 404.
buildDeployLogPanelState (deploy-run-view.ts) turns the run into the
three independent facts the panel needs: whether the log is missing,
whether it was truncated, and whether the run has settled enough to
allow deleting it -- so a missing log never renders as an empty
viewer, and no delete action is offered while a run is still running.
* fix(deploys): scope stacks:view/edit permission checks to the run's own environment (H1)
GET/DELETE .../deploys/{runId} and GET .../deploys/{runId}/log checked
auth.can('stacks', 'view'|'edit') without an environmentId, which falls back
to the caller's globally-merged permission (OR across every role, per every
environment). A caller with stacks:view/edit scoped to environment A could
therefore read, or delete, a deploy run belonging to environment B, as long
as they also had SOME role granting stacks:view/edit somewhere -- and
loadOwnedDeployRun's own canAccessEnvironment check does not close this,
since it only confirms "has some role for this environment", not "has
stacks:view/edit specifically for this environment".
Add a second, run-scoped check via can('stacks', <action>, run.environmentId
?? undefined) AFTER loadOwnedDeployRun resolves the run -- in addition to,
not instead of, the existing un-scoped gate, so the pre-existing "no
permission anywhere" 403 tests keep their exact prior behavior. This is the
same derive-environment-then-check pattern api/git/stacks/[id]/+server.ts and
its env-files route already use for their own nullable environmentId. The
sibling list route (deploys/+server.ts) already documents and closes this
exact bug class for itself; this closes it for the three single-run routes
too.
Regression tests confirm the scoped check is what closes the gap: reverting
just the two source files turns the three "denied" tests red with the
pre-fix symptom (200 instead of 403), while the "allowed" tests stay green.
* fix(deploys): list route treats the local environment (env omitted) as reachable, not a 400 (H3)
On a single (local-only) environment install -- the normal case -- every
deploy run is recorded with environment_id = NULL: createRunRecorder()
writes it that way whenever the triggering request carried no envId, which
is always true for the local environment, because appendEnvParam()
($lib/stores/environment.ts) only appends an `env` query param when envId is
truthy. GET .../deploys required `env` as a parseable integer and 400'd
otherwise -- and there was no integer a caller could pass that matched a
NULL row (env=0 included; environment ids are never 0). The result: on a
fresh, single-environment Dockhand install, EVERY recorded deploy run was
completely unreachable through this endpoint.
The data layer already supported this -- getScheduleExecutions() maps
`environmentId: null` to `isNull(...)` -- only this route couldn't express
"give me the null-environment runs" at all.
Fix: two `env` shapes now both resolve to `environmentId: null` ("the local
environment") -- the parameter OMITTED entirely (the shape the UI actually
sends), and the literal string "null" (for direct/curl callers). Anything
else must still parse as an integer; a genuinely invalid value is still a
hard 400, so "list runs, unspecified environment" never silently means "all
environments merged". The permission check maps the null case to
`can('stacks', 'view', undefined)` -- the same "no environment context"
global-permission check api/git/stacks/[id]/+server.ts already uses for ITS
nullable environmentId -- so a caller still needs stacks:view somewhere to
see local-environment runs; canAccessEnvironment() is skipped for null (there
is no environment record to check access against).
Test coverage updated in the same file the pre-fix "missing env -> 400" and
"cross-environment leak" tests lived in, since both encoded the very
behavior this fixes (the leak test now confirms the null filter itself
still excludes a different, non-null environment's runs -- the security
property that motivated requiring `env` in the first place is unchanged).
Reverting just the route file turns the two H3-labeled tests red with the
pre-fix symptom (400 instead of 200).
* fix(openapi): move loadOwnedDeployRun-produced 400/404 into prose, closing the CI status-code-drift gate (B1)
`npm run generate:openapi:check` (.github/workflows/openapi.yml:49) failed
with 5 Gate-4 (status-code drift) issues: GET/DELETE .../deploys/{runId}
documented resp-400 and resp-404, and GET .../deploys/{runId}/log documented
resp-400, but all three of those specific codes are produced by the SHARED
loadOwnedDeployRun() helper (deploy-run-access.ts) -- not by a literal
`status: 400` / `error(400)` in the handler's OWN body text, which is all
scripts/generate-openapi.ts's static scanner (analyzeHandlerBody) can see.
statusDrift > 0 is a hard failure.
Fix: move that information into the `description:` field as prose instead of
resp-400/resp-404 lines -- the same pattern already used by
POST /api/backup/destinations/{id}/task for its own guard-produced codes.
Nothing is undocumented: the codes and their meaning are still explained,
just not as a formal schema-level response entry the generator expects to
find literally in the handler it's annotating. The log route's resp-404 line
stays as-is (its "Log not found" 404 IS literal in that handler's own body,
alongside loadOwnedDeployRun's 404 which is now covered by the same prose).
Also regenerates src/lib/openapi.generated.json and static/openapi.json
(--check writes both as a side effect of running) -- picks up this fix plus
unrelated, already-existing drift from earlier commits on this branch that
had never been regenerated (the deploy_log_reconcile schedule type additions
to two already-annotated schedule endpoints).
Verified: `npm run generate:openapi:check` was Exit 1 ("Hard failures: 1",
the 5 issues above) before this commit, at this branch's HEAD, in a fresh
clone with `npm install` -- Exit 0 ("Hard failures: 0") after.
tests/deploy-run-openapi-drift.test.ts reproduces Gate 4's own drift check
directly against these three routes' annotations (via the same
parseAnnotations/splitMethodBodies/analyzeHandlerBody the generator itself
uses) rather than shelling out to the full generator, which scans and
rewrites the entire route tree for what is a narrow, three-file regression.
Reverting just the two doc-comment edits reproduces the exact stale-code
sets from the CI report (["400","404"] and ["400"]).
* fix(stack-modal): stop duplicating a failed run's full error text
The expanded row's error box rendered the raw errorMessage (compose's
full stderr) verbatim, right above the new log panel from this same
task -- for a failed run, that meant showing almost the same text
twice. Task 17's own spec called for the shortened last error line
here (the same text the collapsed row already truncates to), not the
raw message; the box now shows view.errorSummary instead. The full
text has exactly one place now: the LogViewer beneath it.
* fix(stack-modal): fetch deploy runs for the local environment too
envId === null is not "no environment selected" -- per the list route's
H3 fix (.../deploys/+server.ts), it IS the local environment: a
single-environment install's own deploy calls never send an env param
either (appendEnvParam only appends one when envId is truthy), so
every one of its runs is recorded with environmentId === null, and the
route now resolves an omitted env to exactly that filter.
The guard that skipped the fetch and showed 'No environment selected.'
predates that fix, from when the endpoint hard-required env and would
400 without it. With the endpoint now accepting the omitted shape, the
guard silently kept the tab empty on the most common install shape
even though the API would have answered. Removed -- onMount fetches
unconditionally, appendEnvParam already produces the right URL for
both the local (null) and a specific (numeric) environment.
No pure-function decision to extract here: the branch this replaced
IS the fix, not a rule with two live outcomes -- appendEnvParam
already forms the correct request for both envId shapes, so there is
nothing left in the component to test beyond what deploy-endpoints.
test.ts already covers at the route.
* feat(git-stacks): record stack_deploy runs for every git-stack deploy trigger
deployGitStack() is the single function every git-stack deploy trigger funnels
through -- the manual Deploy button, a config-update-then-redeploy, both webhook
methods, create-and-deploy, and (via runGitStackSync) the cron scheduler and the
schedules page's "run now". Wire the stack_deploy run recorder in there, not at
a single HTTP route: wiring it only at the route level (the way compose PUT and
the non-git deploy endpoint already do it) would leave every other caller --
crucially the cron- and webhook-triggered ones, the truly unattended runs the
deploy-verlauf design doc's Meilenstein 5 is about -- unrecorded.
composeHash is taken from the content actually synced from git; envHash/secrets
mirror the same (deliberately approximate) DB-var resolution the non-git routes
already use. Every real call site now passes an explicit triggeredBy (manual/
webhook/cron) instead of the previous unconditional default, and the manual
routes forward auth.user?.id and an onLine callback so SSE progress streaming is
unchanged for HTTP callers.
Added tests/helpers/stacks-fake.ts (mirroring db-fake.ts's collision-safe
registration pattern) since syncGitStack -- deployGitStack's sync step -- is a
same-module collaborator that can't be faked via mock.module(), so the new test
drives a real git sync against a local repo served by a real `git daemon`
subprocess, faking only the $lib/server/stacks boundary (deployStack). Migrated
the existing compose-redeploy test to the same shared helper, since a second
direct mock.module('$lib/server/stacks', ...) call would have collided with it.
* docs(backups): note that a restore's redeploy has no stack_deploy run record
Backup restore's redeploy calls redeployStackFromDir directly, bypassing the
deployGitStack()/compose-route path createRunRecorder is wired into -- so it
gets no stack_deploy row and no log file. Left unrecorded on purpose (its own
piece of work, no structural blocker), but that was invisible in the code: no
comment, no marker, nothing to distinguish it from an oversight for a reader
who doesn't already know the history.
* fix(git-stacks): coerce forceRecreate to boolean for the run recorder's options
syncResult.updated is boolean | undefined; DeployRunOptions.forceRecreate wants a
strict boolean. Caught by a differential tsc run against the parent commit (the
only genuinely new type error introduced by the previous commit -- everything
else tsc reported was pre-existing, just line-shifted).
* fix(api): thread build/pull/forceRecreate through stack create & redeploy
POST /api/stacks and PUT /api/stacks/[name]/compose always deployed with
build:false and no pullPolicy, regardless of what the request sent -- a
stack whose compose declares a build: section silently never rebuilt on
"Create & Start" or "Save & redeploy" (the saved compose change just ran
against the stale local image). Both endpoints now accept pull, build,
and forceRecreate in the request body and forward them to deployStack()
and the run recorder, matching the contract the dedicated deploy endpoint
(POST /api/stacks/[name]/deploy) already uses.
PUT .../compose defaults forceRecreate to true when the field is omitted,
preserving its prior hardcoded behavior for a caller that has not been
updated to send it explicitly (env var changes need --force-recreate to
take effect). POST /api/stacks (Create & Start) has no such compatibility
concern -- there is nothing to recreate on a brand new stack -- so it
defaults all three to false when omitted.
pull:false intentionally leaves pullPolicy undefined rather than mapping
to a "never"/"missing" policy: deployStack() treats an undefined
pullPolicy as "do not pull", and its own post-deploy pending-update badge
reconciliation is gated on the same field, so unchecking Pull images also
means a stale "update available" badge on that stack will not clear until
the next pull. Documented at both call sites, not just left implicit.
Regenerated static/openapi.json and src/lib/openapi.generated.json for the
new pull/build/forceRecreate body fields on both @openapi blocks.
* feat(stacks): let Save & redeploy / Create & Start pick pull/build/force-recreate
"Save & redeploy" and "Create & Start" in the stack edit dialog silently
never rebuilt a service with a build: section (see the paired API commit).
Fixing the endpoints alone isn't enough without a way for the operator to
actually ask for a build -- both buttons are now wrapped by RedeployPopover
instead of deploying immediately, offering the same Pull/Build/Force
recreate checkboxes already used for redeploying from the stack grid.
RedeployPopover gains:
- triggerVariant="button" + triggerClass, so it can render as a full
labeled trigger styled like the shadcn Button component (buttonVariants)
instead of only the small icon-only trigger the stack grid rows use.
- defaultPull/defaultBuild/defaultForceRecreate + reason, re-seeded into
the checkboxes on every open (not just once at mount) so a caller whose
default tracks live content -- "does the compose have a build: section
right now" -- stays correct across repeated opens.
"Build images" is pre-checked whenever the compose file declares a build:
section for any service (compose-build-detect.ts, extracted as a plain
function with its own test rather than left inline in the component, the
same way save-close-policy.ts is). "Pull images" defaults to unchecked for
both buttons (unlike the grid's redeploy popover, which defaults it on) --
Save/Create already run against whatever images are already local, pulling
is an explicit extra step here. "Force recreate" defaults to checked for
Save & redeploy only, preserving its prior always-on behavior now that the
API also accepts a caller opting it off; Create & Start defaults it off
since there is nothing to recreate on a brand new stack.
pendingSaveOptions carries the chosen options through the path-change
confirmation dialog the same way pendingSaveRestart already does, so
re-entering handleSave() after the operator confirms a compose/env file
move still deploys with what they actually picked in the popover.
* chore: drop internal planning-doc references from comments
Comments and test descriptions referenced an internal milestone label and
design-doc section number that mean nothing to anyone outside this repo's
own planning process. Reworded to be self-contained -- no behavior change.
* refactor(stacks): split "Save & redeploy" / "Create & Start" into main + arrow
The previous shape had the whole button open the popover before deploying
anything -- correct behavior, wrong ergonomics. The common case (just save
and redeploy, or just create and start, with sane defaults) now takes one
click again: the label is a real, directly clickable button. A separate
small chevron button to its right opens the same Pull/Build/Force recreate
popover for the cases that need it. Two independently focusable <button>
elements sitting flush together, not one element whose behavior depends on
click position.
RedeployPopover's triggerVariant switches from 'button' (removed, was a
label-plus-icon trigger wrapping the whole action) to 'chevron' (a small
square trigger meant to sit attached to a separate main button the caller
renders itself -- the popover no longer owns the main button at all).
saveRedeployDefaults/createStartDefaults in StackModal are the single
source of truth for "what a direct click deploys with", shared between
each main button's own onclick and the popover's defaultPull/defaultBuild/
defaultForceRecreate props next to it, so the one-click path and the
pick-then-Deploy path can never quietly diverge on what "the default"
means.
The two existing icon-only redeploy triggers in the stack grid (RedeployPopover
used there via the unchanged 'icon' variant) are untouched -- they were
already the "click opens a menu" shape by design, since there is no separate
main button in a table row to split off from.
* feat(logs): follow the caller's own theme in LogViewer
LogViewer defaulted to a hardcoded dark theme regardless of the
editor's own light/dark toggle. Add a theme prop (defaulting to
'dark', so any caller that doesn't pass it renders unchanged) and
wire it through the two places that already have an editor theme in
scope: StackModal's docked output panel and, forwarded through a new
theme prop on DeploysPanel, the Deploys tab's expanded run log.
ComposeOutputModal has no editor in scope (opened straight from the
stack list) — its Dialog.Content already follows the app-wide
light/dark switch via bg-background, so it reads that switch once on
mount instead, mirroring the existing pattern in ComposeGraphViewer's
graphTheme.
Search-match highlighting gets a light-mode override, scoped to
.log-viewer-light so it doesn't touch the shared (unscoped)
.search-match rule other components such as LogsPanel still rely on:
the base rule's near-white text is illegible against the pale amber
highlight once the panel itself goes light.
* fix(stacks): pass DeploysPanel's theme prop under its own name
{editorTheme} is Svelte's shorthand for a prop literally named
editorTheme -- DeploysPanel's Props interface declares theme, not
editorTheme, so this silently passed an unknown prop and left theme
at its 'dark' default. svelte-check caught it: 'editorTheme' does not
exist in type 'Props'. bun test doesn't type-check props, which is
why it stayed green through the first commit.
* fix(sse): guard RunRecorder.end() against a second call if it throws
createJobResponse's fire-and-forget path calls recorder.end() in its
.then() branch. If that call itself throws, the rejection lands in
.catch(), which unconditionally called recorder.end() again -- breaking
the RunRecorder contract that end() runs exactly once.
Track whether the .then() branch already reached its end() call and
skip the .catch() call when it did, regardless of whether end() itself
resolved or rejected.
* test(fs-guard): remove redundant DATA_DIR assignment before the import
isProtectedPath() only reads process.env.DATA_DIR lazily inside its own
call, not at module-import time, so the beforeAll/afterAll pin already
in this file is sufficient on its own -- the extra assignment right
before the dynamic import did nothing.
Verified by measurement, not assumption: this file passes standalone,
paired with selfhst-icons.test.ts in both file orders, and as part of
the full suite, all without the removed line.
* refactor(components): move LogViewer out of the logs route
LogViewer.svelte lived under src/routes/logs/ but was never used by
that route (LogsPanel.svelte and +page.svelte render container/system
logs their own way). Its only three consumers -- ComposeOutputModal,
StackModal, and DeploysPanel, all under src/routes/stacks/ -- imported
it cross-route with a relative path, which is what shared components
under src/lib/components/ exist to avoid.
Moved it there and repointed all three imports at the $lib alias. No
internal change: every import inside LogViewer.svelte already used
$lib/... aliases, none were relative to its old location.
* test(types): fix svelte-check type errors in two test files
deploy-run-record-core.test.ts: d.summary is DeploySummary | undefined
on RunDetails, so d.summary.containersStarted possibly-undefined'd.
Switched to optional chaining -- the assertion stays just as strong
since expect(undefined).toBe(2) still fails, the RHS is a hard literal.
deploy-run-view.test.ts: both test.each((input, expected) => ...)
callbacks had their params implicitly typed 'any'. Both formatTrigger
and formatStatusLabel take/return plain strings, so annotated both
params 'string', matching the explicit-annotation style test.each
already uses elsewhere in this repo (stack-filename.test.ts).
* feat(settings): make deploy-log reconcile schedule configurable
setDeployLogReconcileCron/setDeployLogReconcileEnabled existed in db.ts
with no caller outside of it and the scheduler startup path -- there was
no way to disable or reschedule the daily reconcile job (which deletes
orphaned deploy-log files) short of writing to the settings table by
hand. Wire both into the general settings GET/POST route, the client
settings store, and a new toggle+cron block on the General settings
tab, following the existing scannerCleanupCron/scannerCleanupEnabled
pattern in the same files.
refreshSystemJobs() already read these getters before this change; it
just never had anything to react to.
* fix(format): read naive server timestamps as UTC in formatRelativeTime
formatRelativeTime() parsed its input with a bare `new Date(...)`, so a
naive PG timestamp (e.g. "2026-08-30 20:36:11.534" - no "Z"/offset, the
form Drizzle hands back for a `timestamp without time zone` column) got
read as browser-local time instead of UTC. A deploy from a couple of
minutes ago rendered as "2h ago" for anyone outside UTC.
date-format.ts already solved exactly this for formatDateTime() via
parseTimestamp() (#1183), but formatRelativeTime() lives in the
import-light utils/format module and was never switched over, even
though every caller passes the same raw server value to both functions
side by side.
Switch formatRelativeTime() to parseTimestamp() as well. Behavior is
unchanged for Date instances, epoch numbers, and already-zoned strings;
only the previously-mishandled naive-string case is fixed.
Added a TZ-forced (America/New_York) test block that reproduces the
bug and verifies the fix; reverting the change makes those three tests
fail with "in the future" (a 4h forward misinterpretation), confirming
they fail for the right reason.
* fix(tests): inject the reconcile job's log-store calls instead of mocking the module
mock.module() freezes a module's export shape for the whole test process, not
just the file that calls it. The reconcile job's test replaced
'$lib/server/deploy-log-store' with a two-export factory, so every module that
resolved the same specifier afterwards lost the other eight -- deploy-run-record.ts
imports appendRunLog, runLogFileName and SizeBudgetTracker from there and threw
"Export named ... not found".
Whether it triggered depended purely on the order bun walks tests/, which is why
the suite was green locally and red in CI.
The test's own comment reasoned that no other test file claimed that specifier.
That was the wrong question: the collision is with source modules, not test files.
runDeployLogReconcileJob() now takes its two filesystem calls as an optional deps
parameter, defaulting to the real ones. The test passes fakes and no longer
touches the module registry, so there is nothing left to collide.
* fix(deploy): redact provider-resolved secrets from stored deploy errors
Deploy run records (schedule_executions.errorMessage, readable by every
authenticated user via GET /api/schedules/executions) were redacted only
against the secret list a caller had at recorder-construction time --
DB-only nonSecretVars/secretVars, captured BEFORE deployStack() calls
resolveProviderEnvVars() and merges in the bound secret provider's
values (Bitwarden/1Password/Keepass/Proton/Vault/Infisical bulk pulls or
inline refs). A provider-resolved secret that surfaced in compose's raw
stderr therefore passed straight through DeployRunRecorder.end()'s
redaction and into errorMessage unredacted.
Add StackOperationResult.resolvedSecrets, populated once in deployStack()
(the single call site after resolveProviderEnvVars, covering both the
local and Hawser paths) from the post-resolution secretVars -- the same
set executeComposeCommand already redacts streamed lines against. Add
RunRecorder.addSecrets()/DeployRunRecorder.addSecrets() to extend the
redaction list after construction, and call it from every stack_deploy
run-record caller (the three createRunRecorder-based API routes and
deployGitStack, the funnel every git-stack deploy trigger -- including
the unattended cron/webhook ones -- goes through) right after
deployStack() returns and before the recorder is closed.
Regression tests assert on the stored value, not just field presence,
and were verified against a temporarily neutered addSecrets() (the
secret leaked verbatim, confirming they fail for the right reason)
before being restored to pass.
* fix(deploy-logs): scope deploy-log directory and size budget per environment
Before this fix, deploy-log-store.ts kept ALL environments' deploy-run log
files in a single shared deploy-logs/ directory and enforced a single
BUDGET_BYTES total across all of them (SizeBudgetTracker). A user with
deploy rights in one environment could fill that shared budget with a noisy
deploy, silently truncating deploy logs and summaries belonging to every
other environment -- a multi-tenant audit-trail integrity violation.
- deploy-log-store.ts: every path/size function now takes an `envId` and
resolves to deploy-logs/<envDirName(envId)>/ (envDirName(null) => "null").
SizeBudgetTracker measures "everything else" scoped to its own run's
environment only. Added envDirName/parseEnvDirName, listEnvDirNames() for
reconcile-job discovery, and a readRunLog() fallback to the pre-F5 flat
path (unreleased feature, no production data in that layout -- fallback
exists purely as a robustness measure).
- deploy-run-record.ts: DeployRunRecorder threads its envId through to
appendRunLog() and its default SizeBudgetTracker.
- db.ts: getScheduleExecutionIdsByType() now also returns environmentId, so
the reconcile job can group records per environment.
- deploy-log-reconcile.ts: reconciles PER ENVIRONMENT (union of directories
on disk and environments referenced by records), so an orphan file in one
environment can never be deleted -- or a record marked logMissing --
because of a same-numbered file/record in a different environment.
- Both single-run routes (GET/DELETE .../deploys/[runId], GET .../log) now
pass run.environmentId through to readRunLog()/deleteRunLog().
Tests: new cross-environment isolation coverage at the SizeBudgetTracker,
DeployRunRecorder, and reconcile-job levels, each proven against a reverted
(shared-directory) mutation to confirm it fails for the right reason before
being reverted back. Full suite: 3011 pass / 0 fail (was 2987 pass / 0 fail).
* fix(deploy): forbid deleting a non-terminal deploy run
DELETE /api/stacks/[name]/deploys/[runId] deleted the schedule_executions
row and the on-disk log file with no check on the run's status, so a
caller could delete their OWN still-running deploy's record. The
background deploy process keeps going after that: recorder.line()
recreates the just-deleted log file via appendRunLog(), recorder.end()'s
updateScheduleExecution() becomes a silent no-op (UPDATE WHERE id=x, 0
rows), and the default-enabled reconcile job then treats the recreated
file as an orphan and purges it -- erasing every trace of a deploy that
actually ran and had real host side effects.
Add isTerminalRunStatus() (deploy-run-access.ts) as an explicit allow-list
of the run-closing statuses (success/failed/skipped/warning/error/
cancelled/stale) and use it to gate the DELETE handler: a non-terminal
status (queued/running, or anything this code doesn't recognize -- the
status column is free text) now returns 409 and touches neither the log
file nor the database row. The check runs after the existing
ownership/permission checks, so an unauthorized or wrong-stack caller
still gets 403/404 rather than learning the run's status via a 409.
Deliberately its own allow-list rather than reusing
deploy-log-reconcile-core.ts's isEligibleForMissingMark(): that helper
fails OPEN for an unrecognized status because marking logMissing is
reversible metadata-only. Deleting a run is not reversible, so this
check fails CLOSED instead.
* test(deploy): guard that deployStack records the secret set it redacts against
A review found F4's single production line -- stacks.ts's
`result.resolvedSecrets = Object.values(secretVars)` -- had zero coverage:
deleting it left the whole targeted suite green. The two tests that reference
`resolvedSecrets` fake deployStack wholesale and hand-set the field, proving the
downstream recorder wiring but never that the real stacks.ts populates it.
A behaviour test of the real deployStack() is infeasible in this suite, established
empirically, not assumed:
- tests/helpers/stacks-fake.ts mock.module()s $lib/server/stacks at import time,
freezing that specifier for the whole Bun process; two suites load it, so
`import { deployStack }` resolves to the fake for the entire run, and Bun has no
per-file process isolation to escape it.
- pulling the real $lib/server/stacks into a test's import graph instantiates
better-sqlite3, which Bun does not support and crashes at load (reproduced).
So this follows the pattern the suite already uses for deployStack-internal
invariants (deploy-stack-online.test.ts, stack-create-start-build-options.test.ts):
a source guard, with comments stripped before matching and a vacuity guard. It pins
the wiring resolveProviderEnvVars -> secretVars -> executeComposeCommand (redaction)
AND -> result.resolvedSecrets (recording). Counter-tested: each assertion goes red
for its own mutation, including the exact deletion the review demonstrated.
* chore(openapi): regenerate spec after rebase onto upstream/main
* test(stacks): fake requireEnvAccess in the compose-endpoint auth stub
The old merge commit into this branch had manually patched this fake to
add requireEnvAccess (compose/+server.ts calls it, and authEnabled is
false here so the real implementation is a no-op) -- that fixup lived
only in the merge commit itself, not in any single commit, so a plain
rebase onto upstream/main dropped it. Restored; full suite is green
(3212 pass, 0 fail).
* docs(openapi): document deployLogReconcileCron/Enabled in the settings body
upstream's new Gate 7 (body-field drift check) caught that this PR's
deployLogReconcileCron/deployLogReconcileEnabled fields were read in
POST /api/settings/general but never listed in its @openapi body
annotation. Documented them and regenerated the spec; all openapi
gates and the full test suite (3221 pass, 0 fail) are green.
* fix(deploy-log-reconcile): protect an in-flight deploy's file from a TOCTOU orphan-delete
The reconcile job snapshots stack_deploy records once via
getScheduleExecutionIdsByType() before walking each environment's files.
A deploy whose record is created after that snapshot has no matching id
yet, but its log file can already exist by the time this environment's
listRunLogIds() runs -- indistinguishable from a genuine orphan by id
alone, and previously deleted on the spot while still being written to.
Add getRunLogMtimeMs() (deploy-log-store.ts) and use it as a second
signal alongside the records snapshot: a delete candidate whose file was
modified within the last 5 minutes is left alone this run instead of
deleted, since appendRunLog() keeps bumping a live deploy's mtime for as
long as it keeps writing. A later reconcile run will see the by-then-
created record and correctly never touch the file again -- nothing is
lost, it is just given one more cycle to prove itself real, the same
trade-off isEligibleForMissingMark() already makes on the other side of
this race.
* fix(git): record a stack_deploy run for the UI's manual deploy button
deployGitStack's doc comment claimed it was the single function every
git-stack deploy trigger funnels through, and wired the stack_deploy run
recorder in there on that basis. deployGitStackWithProgress -- the UI's
"Deploy" button (deploy-stream/+server.ts) -- runs its own clone/read/
deploy pipeline instead of calling deployGitStack (it needs its own
discrete onProgress stages, not deployGitStack's onLine streaming), so
it was the one caller that reached deployStack() without ever going
through createRunRecorder: webhook, cron, and config-update-triggered
deploys were recorded, the manual button was not.
Wire the same recorder setup into deployGitStackWithProgress, right
before its own deployStack() call, mirroring deployGitStack's shape
(composeHash/envHash/secrets from the DB-only vars, addSecrets() for the
provider-resolved values deployStack() only reveals after it returns,
end() closing the row on every path out). onLine mirrors output into the
run's log file without being forwarded to onProgress, so the existing
progress-stage streaming is untouched.
Corrected deployGitStack's doc comment, which is no longer accurate now
that a second call site exists, and extended the existing source-level
guard test (previously asserting exactly one createRunRecorder call in
the whole file) to check both functions individually.
This commit is contained in:
1 parent
be10bb098c
commit
b2eb0b5dcb
104 files changed
+17212
-605
No files matched your search
@@ -223,7 +223,11 @@ export const POST: RequestHandler = async (event) => {
|
||||
if (data.deployNow) {
|
||||
return createJobResponse(async (send) => {
|
||||
try {
|
||||
const deployResult = await deployGitStack(gitStack.id);
|
||||
const deployResult = await deployGitStack(gitStack.id, {
|
||||
triggeredBy: 'manual',
|
||||
userId: auth.user?.id,
|
||||
onLine: (line) => send('progress', { type: 'line', line })
|
||||
});
|
||||
await auditGitStack(event, 'deploy', gitStack.id, gitStack.stackName, gitStack.environmentId);
|
||||
send('result', {
|
||||
...gitStack,
|
||||
|
||||
@@ -217,7 +217,11 @@ export const PUT: RequestHandler = async (event) => {
|
||||
if (data.deployNow) {
|
||||
return createJobResponse(async (send) => {
|
||||
try {
|
||||
const deployResult = await deployGitStack(id);
|
||||
const deployResult = await deployGitStack(id, {
|
||||
triggeredBy: 'manual',
|
||||
userId: auth.user?.id,
|
||||
onLine: (line) => send('progress', { type: 'line', line })
|
||||
});
|
||||
await auditGitStack(event, 'deploy', updated.id, updated.stackName, updated.environmentId);
|
||||
send('result', {
|
||||
...updated,
|
||||
|
||||
@@ -34,7 +34,11 @@ export const POST: RequestHandler = async (event) => {
|
||||
|
||||
return createJobResponse(async (send) => {
|
||||
try {
|
||||
const result = await deployGitStack(id);
|
||||
const result = await deployGitStack(id, {
|
||||
triggeredBy: 'manual',
|
||||
userId: auth.user?.id,
|
||||
onLine: (line) => send('progress', { type: 'line', line })
|
||||
});
|
||||
|
||||
// Audit log
|
||||
await auditGitStack(event, 'deploy', id, gitStack.stackName, gitStack.environmentId);
|
||||
|
||||
@@ -65,7 +65,7 @@ export const POST: RequestHandler = async (event) => {
|
||||
}
|
||||
|
||||
// Deploy the git stack (syncs and deploys only if there are changes)
|
||||
const result = await deployGitStack(id, { force: false });
|
||||
const result = await deployGitStack(id, { force: false, triggeredBy: 'webhook' });
|
||||
await auditGitStack(event, 'webhook', id, gitStack.stackName, gitStack.environmentId, {
|
||||
method: 'POST', source, result: result.skipped ? 'skipped' : result.success ? 'deployed' : 'failed'
|
||||
});
|
||||
@@ -125,7 +125,7 @@ export const GET: RequestHandler = async (event) => {
|
||||
}
|
||||
|
||||
// Deploy the git stack (syncs and deploys only if there are changes)
|
||||
const result = await deployGitStack(id, { force: false });
|
||||
const result = await deployGitStack(id, { force: false, triggeredBy: 'webhook' });
|
||||
await auditGitStack(event, 'webhook', id, gitStack.stackName, gitStack.environmentId, {
|
||||
method: 'GET', source: 'get', result: result.skipped ? 'skipped' : result.success ? 'deployed' : 'failed'
|
||||
});
|
||||
|
||||
@@ -29,7 +29,7 @@ import { authorize } from '$lib/server/authorize';
|
||||
|
||||
export interface ScheduleInfo {
|
||||
id: number;
|
||||
type: 'container_update' | 'git_stack_sync' | 'system_cleanup' | 'env_update_check' | 'image_prune' | 'backup' | 'repo_prune' | 'repo_check' | 'repo_verify';
|
||||
type: 'container_update' | 'git_stack_sync' | 'system_cleanup' | 'env_update_check' | 'image_prune' | 'backup' | 'repo_prune' | 'repo_check' | 'repo_verify' | 'stack_deploy' | 'deploy_log_reconcile';
|
||||
name: string;
|
||||
entityName: string;
|
||||
description?: string;
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
* POST /api/schedules/[type]/[id]/run - Trigger a manual execution
|
||||
*
|
||||
* Path params:
|
||||
* - type: 'container_update' | 'git_stack_sync' | 'system_cleanup' | 'env_update_check' | 'image_prune'
|
||||
* - type: 'container_update' | 'git_stack_sync' | 'system_cleanup' | 'env_update_check' | 'image_prune' | 'deploy_log_reconcile'
|
||||
* - id: schedule ID
|
||||
*/
|
||||
|
||||
import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { triggerContainerUpdate, triggerGitStackSync, triggerSystemJob, triggerEnvUpdateCheck, triggerImagePrune } from '$lib/server/scheduler';
|
||||
import { triggerContainerUpdate, triggerGitStackSync, triggerSystemJob, triggerEnvUpdateCheck, triggerImagePrune, triggerDeployLogReconcile } from '$lib/server/scheduler';
|
||||
import { getBackupConfig, getBackupDestination } from '$lib/server/db';
|
||||
import { runScheduledBackup } from '$lib/server/scheduler/tasks/backup';
|
||||
import { runRepoPrune, runRepoCheck, runRepoVerify } from '$lib/server/scheduler/tasks/repo-maintenance';
|
||||
@@ -21,7 +21,7 @@ import { BACKUPS_ENABLED } from '$lib/server/features';
|
||||
/**
|
||||
* @openapi
|
||||
* summary: Manually trigger a single run of a schedule (outside its cron), by type and id
|
||||
* path: type:string! Schedule type (container_update, git_stack_sync, system_cleanup, env_update_check, image_prune, backup, repo_prune, repo_check, repo_verify)
|
||||
* path: type:string! Schedule type (container_update, git_stack_sync, system_cleanup, env_update_check, image_prune, backup, repo_prune, repo_check, repo_verify, deploy_log_reconcile)
|
||||
* path: id:integer! Schedule id (semantics depend on type) (from GET /api/schedules)
|
||||
* resp-200: {success:boolean!, message:string!}
|
||||
* resp-400: Invalid schedule id/type, or the triggered task itself reported failure
|
||||
@@ -78,6 +78,7 @@ export const POST: RequestHandler = async ({ params, cookies }) => {
|
||||
scheduleEnvId = scheduleId;
|
||||
break;
|
||||
case 'system_cleanup':
|
||||
case 'deploy_log_reconcile':
|
||||
scheduleEnvId = null;
|
||||
break;
|
||||
case 'backup': {
|
||||
@@ -117,6 +118,9 @@ export const POST: RequestHandler = async ({ params, cookies }) => {
|
||||
case 'system_cleanup':
|
||||
result = await triggerSystemJob(id);
|
||||
break;
|
||||
case 'deploy_log_reconcile':
|
||||
result = await triggerDeployLogReconcile();
|
||||
break;
|
||||
case 'env_update_check':
|
||||
result = await triggerEnvUpdateCheck(scheduleId);
|
||||
break;
|
||||
|
||||
@@ -13,10 +13,10 @@ import { auditBackup, auditBackupDestination } from '$lib/server/audit';
|
||||
/**
|
||||
* @openapi
|
||||
* summary: Toggle a schedule's enabled/disabled state (registers/unregisters the croner job accordingly)
|
||||
* path: type:string! Schedule type (container_update, git_stack_sync, env_update_check, image_prune, backup, repo_prune, repo_check, repo_verify, system_cleanup)
|
||||
* path: type:string! Schedule type (container_update, git_stack_sync, env_update_check, image_prune, backup, repo_prune, repo_check, repo_verify, system_cleanup, deploy_log_reconcile)
|
||||
* path: id:integer! Schedule id (semantics depend on type) (from GET /api/schedules)
|
||||
* resp-200: {success:boolean!, enabled:boolean!}
|
||||
* resp-400: Invalid schedule id, unsupported type, or system_cleanup (cannot be paused)
|
||||
* resp-400: Invalid schedule id, unsupported type, or system_cleanup/deploy_log_reconcile (cannot be paused)
|
||||
* resp-404: Schedule, backup config, or backup destination not found
|
||||
* resp-500: Unexpected error while toggling the schedule
|
||||
*/
|
||||
@@ -173,7 +173,11 @@ export const POST: RequestHandler = async (event) => {
|
||||
await auditBackupDestination(event, 'update', destId, dest.name, { policy: enabledKey, enabled: newEnabled });
|
||||
|
||||
return json({ success: true, enabled: newEnabled });
|
||||
} else if (type === 'system_cleanup') {
|
||||
} else if (type === 'system_cleanup' || type === 'deploy_log_reconcile') {
|
||||
// Both are global, settings-driven system schedules (own enabled flag +
|
||||
// cron, configured on the schedule settings page) -- not a per-item
|
||||
// cron the way container_update/git_stack_sync are. stack_deploy never
|
||||
// reaches here: it has no schedule to toggle (no cron, no settings row).
|
||||
return json({ error: 'System schedules cannot be paused' }, { status: 400 });
|
||||
} else {
|
||||
return json({ error: 'Invalid schedule type' }, { status: 400 });
|
||||
|
||||
@@ -18,6 +18,10 @@ import {
|
||||
setScannerCleanupCron,
|
||||
getScannerCleanupEnabled,
|
||||
setScannerCleanupEnabled,
|
||||
getDeployLogReconcileCron,
|
||||
setDeployLogReconcileCron,
|
||||
getDeployLogReconcileEnabled,
|
||||
setDeployLogReconcileEnabled,
|
||||
getDefaultTimezone,
|
||||
setDefaultTimezone,
|
||||
getEventCollectionMode,
|
||||
@@ -69,6 +73,8 @@ export interface GeneralSettings {
|
||||
eventCleanupEnabled: boolean;
|
||||
scannerCleanupCron: string;
|
||||
scannerCleanupEnabled: boolean;
|
||||
deployLogReconcileCron: string;
|
||||
deployLogReconcileEnabled: boolean;
|
||||
logBufferSizeKb: number; // legacy
|
||||
logMaxLines: number; // line-count cap for log buffer
|
||||
defaultTimezone: string;
|
||||
@@ -128,7 +134,7 @@ export interface GeneralSettings {
|
||||
defaultScannerDns: string[];
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: Omit<GeneralSettings, 'scheduleRetentionDays' | 'eventRetentionDays' | 'scheduleCleanupCron' | 'eventCleanupCron' | 'scheduleCleanupEnabled' | 'eventCleanupEnabled' | 'scannerCleanupCron' | 'scannerCleanupEnabled'> = {
|
||||
const DEFAULT_SETTINGS: Omit<GeneralSettings, 'scheduleRetentionDays' | 'eventRetentionDays' | 'scheduleCleanupCron' | 'eventCleanupCron' | 'scheduleCleanupEnabled' | 'eventCleanupEnabled' | 'scannerCleanupCron' | 'scannerCleanupEnabled' | 'deployLogReconcileCron' | 'deployLogReconcileEnabled'> = {
|
||||
confirmDestructive: true,
|
||||
showStoppedContainers: true,
|
||||
highlightUpdates: true,
|
||||
@@ -253,6 +259,8 @@ export const GET: RequestHandler = async ({ cookies }) => {
|
||||
eventCleanupEnabled,
|
||||
scannerCleanupCron,
|
||||
scannerCleanupEnabled,
|
||||
deployLogReconcileCron,
|
||||
deployLogReconcileEnabled,
|
||||
logBufferSizeKb,
|
||||
logMaxLines,
|
||||
defaultTimezone,
|
||||
@@ -305,6 +313,8 @@ export const GET: RequestHandler = async ({ cookies }) => {
|
||||
getEventCleanupEnabled(),
|
||||
getScannerCleanupCron(),
|
||||
getScannerCleanupEnabled(),
|
||||
getDeployLogReconcileCron(),
|
||||
getDeployLogReconcileEnabled(),
|
||||
getSetting('log_buffer_size_kb'),
|
||||
getSetting('log_max_lines'),
|
||||
getDefaultTimezone(),
|
||||
@@ -359,6 +369,8 @@ export const GET: RequestHandler = async ({ cookies }) => {
|
||||
eventCleanupEnabled,
|
||||
scannerCleanupCron,
|
||||
scannerCleanupEnabled,
|
||||
deployLogReconcileCron,
|
||||
deployLogReconcileEnabled,
|
||||
logBufferSizeKb: logBufferSizeKb ?? DEFAULT_SETTINGS.logBufferSizeKb,
|
||||
logMaxLines: (typeof logMaxLines === 'number' && logMaxLines > 0)
|
||||
? Math.min(2000, Math.max(100, logMaxLines))
|
||||
@@ -407,7 +419,7 @@ export const GET: RequestHandler = async ({ cookies }) => {
|
||||
* @openapi
|
||||
* summary: Update global general settings (all fields optional; only supplied keys are written)
|
||||
* description: A large flat settings bag - theme/fonts, scanner defaults, cleanup schedules, event/metrics collection, editor options (e.g. editorIndentGuides), and more.
|
||||
* body: {animateIcons:boolean, editorIndentGuides:boolean, coloredActionButtons:boolean, lightTheme:string, darkTheme:string, defaultTimezone:string, logBufferSizeKb:integer, externalStackPaths:string, actionIconSize:string, compactPorts:boolean, confirmDestructive:boolean, dateFormat:string, defaultBackupImage:string, defaultComposeTemplate:string, defaultGrypeArgs:string, defaultGrypeImage:string, defaultScannerDns:array<string>, defaultScannerNetworkMode:string, defaultTrivyArgs:string, defaultTrivyImage:string, downloadFormat:string, editorFont:string, eventCleanupCron:string, eventCleanupEnabled:boolean, eventCollectionMode:string, eventPollInterval:integer, eventRetentionDays:integer, font:string, fontSize:string, formatLogTimestamps:boolean, gridFontSize:string, highlightUpdates:boolean, honorProxyLabels:boolean, labelFilterMode:string, logMaxLines:integer, metricsCollectionInterval:integer, primaryStackLocation:string, protectScannerImages:boolean, scannerCleanupCron:string, scannerCleanupEnabled:boolean, scheduleCleanupCron:string, scheduleCleanupEnabled:boolean, scheduleRetentionDays:integer, showExposedPorts:boolean, showGitCommitHash:boolean, showImageChangelogLinks:boolean, showStoppedContainers:boolean, showWhatsNew:boolean, terminalFont:string, timeFormat:string, useSelfhstIcons:boolean}
|
||||
* body: {animateIcons:boolean, editorIndentGuides:boolean, coloredActionButtons:boolean, lightTheme:string, darkTheme:string, defaultTimezone:string, logBufferSizeKb:integer, externalStackPaths:string, actionIconSize:string, compactPorts:boolean, confirmDestructive:boolean, dateFormat:string, defaultBackupImage:string, defaultComposeTemplate:string, defaultGrypeArgs:string, defaultGrypeImage:string, defaultScannerDns:array<string>, defaultScannerNetworkMode:string, defaultTrivyArgs:string, defaultTrivyImage:string, deployLogReconcileCron:string, deployLogReconcileEnabled:boolean, downloadFormat:string, editorFont:string, eventCleanupCron:string, eventCleanupEnabled:boolean, eventCollectionMode:string, eventPollInterval:integer, eventRetentionDays:integer, font:string, fontSize:string, formatLogTimestamps:boolean, gridFontSize:string, highlightUpdates:boolean, honorProxyLabels:boolean, labelFilterMode:string, logMaxLines:integer, metricsCollectionInterval:integer, primaryStackLocation:string, protectScannerImages:boolean, scannerCleanupCron:string, scannerCleanupEnabled:boolean, scheduleCleanupCron:string, scheduleCleanupEnabled:boolean, scheduleRetentionDays:integer, showExposedPorts:boolean, showGitCommitHash:boolean, showImageChangelogLinks:boolean, showStoppedContainers:boolean, showWhatsNew:boolean, terminalFont:string, timeFormat:string, useSelfhstIcons:boolean}
|
||||
* resp-403: Permission denied (needs settings:edit)
|
||||
* resp-500: Failed to save settings
|
||||
*/
|
||||
@@ -419,7 +431,7 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { confirmDestructive, showStoppedContainers, highlightUpdates, coloredActionButtons, actionIconSize, 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, showGitCommitHash, formatLogTimestamps, externalStackPaths, primaryStackLocation, defaultGrypeImage, defaultTrivyImage, defaultComposeTemplate, labelFilterMode, defaultBackupImage, honorProxyLabels, showImageChangelogLinks, useSelfhstIcons, animateIcons, editorIndentGuides, protectScannerImages, showWhatsNew, defaultScannerNetworkMode, defaultScannerDns } = body;
|
||||
const { confirmDestructive, showStoppedContainers, highlightUpdates, coloredActionButtons, actionIconSize, timeFormat, dateFormat, downloadFormat, defaultGrypeArgs, defaultTrivyArgs, scheduleRetentionDays, eventRetentionDays, scheduleCleanupCron, eventCleanupCron, scheduleCleanupEnabled, eventCleanupEnabled, scannerCleanupCron, scannerCleanupEnabled, deployLogReconcileCron, deployLogReconcileEnabled, logBufferSizeKb, logMaxLines, defaultTimezone, eventCollectionMode, eventPollInterval, metricsCollectionInterval, lightTheme, darkTheme, font, fontSize, gridFontSize, terminalFont, editorFont, compactPorts, showExposedPorts, showGitCommitHash, formatLogTimestamps, externalStackPaths, primaryStackLocation, defaultGrypeImage, defaultTrivyImage, defaultComposeTemplate, labelFilterMode, defaultBackupImage, honorProxyLabels, showImageChangelogLinks, useSelfhstIcons, animateIcons, editorIndentGuides, protectScannerImages, showWhatsNew, defaultScannerNetworkMode, defaultScannerDns } = body;
|
||||
|
||||
if (confirmDestructive !== undefined) {
|
||||
await setSetting('confirm_destructive', confirmDestructive);
|
||||
@@ -477,6 +489,14 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
|
||||
await setScannerCleanupEnabled(scannerCleanupEnabled);
|
||||
await refreshSystemJobs();
|
||||
}
|
||||
if (deployLogReconcileCron !== undefined && typeof deployLogReconcileCron === 'string') {
|
||||
await setDeployLogReconcileCron(deployLogReconcileCron);
|
||||
await refreshSystemJobs();
|
||||
}
|
||||
if (deployLogReconcileEnabled !== undefined && typeof deployLogReconcileEnabled === 'boolean') {
|
||||
await setDeployLogReconcileEnabled(deployLogReconcileEnabled);
|
||||
await refreshSystemJobs();
|
||||
}
|
||||
if (logBufferSizeKb !== undefined && typeof logBufferSizeKb === 'number') {
|
||||
// Legacy: clamp to 100KB-5MB range.
|
||||
await setSetting('log_buffer_size_kb', Math.max(100, Math.min(5000, logBufferSizeKb)));
|
||||
|
||||
@@ -5,6 +5,9 @@ import { upsertStackSource, getStackSources, secretProviderExists } from '$lib/s
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { auditStack } from '$lib/server/audit';
|
||||
import { createJobResponse } from '$lib/server/sse';
|
||||
import { createRunRecorder } from '$lib/server/deploy-run-record';
|
||||
import { hashComposeContent, hashEnvFingerprint } from '$lib/server/deploy-run-record-core';
|
||||
import { parseEnvFileContent } from '$lib/server/git';
|
||||
import type { RequestHandler } from './$types';
|
||||
|
||||
/**
|
||||
@@ -86,7 +89,7 @@ export const GET: RequestHandler = async ({ url, cookies }) => {
|
||||
* summary: Create and (optionally) deploy a compose stack
|
||||
* description: Writes the compose + .env to the stack dir, stores secrets in the DB, and with start deploys it. Can bind a secret provider. Target environment comes from the env query param, or from envId/environmentId in the body when the query is absent.
|
||||
* query: env:integer Target environment id (takes precedence over envId/environmentId in the body)
|
||||
* body: {name:string!, compose:string!, composePath:string, envPath:string, envVars:array<object>, rawEnvContent:string, secretProviderId:integer, start:boolean, envId:integer, environmentId:integer}
|
||||
* body: {name:string!, compose:string!, composePath:string, envPath:string, envVars:array<object>, rawEnvContent:string, secretProviderId:integer, start:boolean, envId:integer, environmentId:integer, pull:boolean, build:boolean, forceRecreate:boolean}
|
||||
* resp-400: Invalid request (e.g. missing name/compose, or secretProviderId wrong type)
|
||||
* resp-403: Permission denied (needs stacks:create; binding a secret provider also needs secrets:view)
|
||||
* resp-500: Failed to create or deploy the stack
|
||||
@@ -120,7 +123,7 @@ export const POST: RequestHandler = async (event) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const { name, compose, start, envVars, rawEnvContent, composePath, envPath, secretProviderId } = body;
|
||||
const { name, compose, start, envVars, rawEnvContent, composePath, envPath, secretProviderId, pull, build, forceRecreate } = body;
|
||||
|
||||
if (!name || typeof name !== 'string') {
|
||||
return json({ error: 'Stack name is required' }, { status: 400 });
|
||||
@@ -236,6 +239,45 @@ export const POST: RequestHandler = async (event) => {
|
||||
secretProviderId
|
||||
});
|
||||
|
||||
// This endpoint has no requireComposeFile() call to hash the way the
|
||||
// dedicated deploy endpoint does -- compose and the effective env are
|
||||
// already sitting in the request body. rawEnvContent, when given, is the
|
||||
// authoritative non-secret source (see the persistence logic above); the
|
||||
// envVars array's secrets always layer on top of it.
|
||||
const effectiveEnvVars: Record<string, string> = {};
|
||||
if (rawEnvContent) {
|
||||
Object.assign(effectiveEnvVars, parseEnvFileContent(rawEnvContent, name));
|
||||
}
|
||||
if (Array.isArray(envVars)) {
|
||||
for (const v of envVars) {
|
||||
if (v && typeof v.key === 'string' && typeof v.value === 'string' && (!rawEnvContent || v.isSecret)) {
|
||||
effectiveEnvVars[v.key] = v.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build/pull/forceRecreate come from the caller (StackModal's "Create & Start"
|
||||
// popover, see RedeployPopover) -- previously this endpoint always deployed with
|
||||
// build:false and no pullPolicy regardless of what the compose file needed, so a
|
||||
// service with a `build:` section silently never built on first start.
|
||||
const pullOpt = !!pull;
|
||||
const buildOpt = !!build;
|
||||
const forceRecreateOpt = !!forceRecreate;
|
||||
|
||||
const recorder = await createRunRecorder({
|
||||
stackName: name,
|
||||
envId: envIdNum ?? null,
|
||||
userId: auth.user?.id,
|
||||
triggeredBy: 'manual',
|
||||
options: { pull: pullOpt, build: buildOpt, forceRecreate: forceRecreateOpt },
|
||||
composeHash: hashComposeContent(compose),
|
||||
envHash: hashEnvFingerprint(effectiveEnvVars),
|
||||
// Same merged set passed to envHash above -- also the redaction list end()
|
||||
// applies to the stored error text, so a leaked env value never reaches
|
||||
// errorMessage on schedule_executions.
|
||||
secrets: Object.values(effectiveEnvVars)
|
||||
});
|
||||
|
||||
// Deploy via SSE to keep connection alive during long operations
|
||||
return createJobResponse(async (send) => {
|
||||
try {
|
||||
@@ -243,24 +285,38 @@ export const POST: RequestHandler = async (event) => {
|
||||
name,
|
||||
compose,
|
||||
envId: envIdNum,
|
||||
forceRecreate: forceRecreateOpt,
|
||||
build: buildOpt,
|
||||
// pullPolicy undefined (pull unchecked) also skips deployStack's post-deploy
|
||||
// reconcileStackPendingUpdates() call -- accepted tradeoff, not a bug.
|
||||
pullPolicy: pullOpt ? 'always' : undefined,
|
||||
composePath: composePath || undefined,
|
||||
envPath: envPath || undefined
|
||||
envPath: envPath || undefined,
|
||||
onLine: (line) => send('progress', { type: 'line', line })
|
||||
});
|
||||
|
||||
// F4 fix: deployStack resolves the bound secret provider's values
|
||||
// internally, AFTER `recorder` above was already built from the DB-only
|
||||
// `effectiveEnvVars`. Feed the provider-resolved values in now, before
|
||||
// createJobResponse calls recorder.end() below -- see deploy-run-record.ts.
|
||||
recorder.addSecrets(result.resolvedSecrets ?? []);
|
||||
|
||||
if (!result.success) {
|
||||
send('result', { success: false, error: result.error, output: result.output });
|
||||
return;
|
||||
}
|
||||
|
||||
// Audit log (create + deploy in one action)
|
||||
await auditStack(event, 'deploy', name, envIdNum);
|
||||
await auditStack(event, 'deploy', name, envIdNum, {
|
||||
pull: pullOpt, build: buildOpt, forceRecreate: forceRecreateOpt
|
||||
});
|
||||
|
||||
send('result', { success: true, started: true, output: result.output });
|
||||
} catch (error: any) {
|
||||
console.error('Error deploying compose stack:', error);
|
||||
send('result', { success: false, error: error.message || 'Failed to deploy stack' });
|
||||
}
|
||||
}, request);
|
||||
}, request, recorder);
|
||||
} catch (error: any) {
|
||||
console.error('Error creating compose stack:', error);
|
||||
return json({ error: error.message || 'Failed to create stack' }, { status: 500 });
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { getStackComposeFile, deployStack, saveStackComposeFile } from '$lib/server/stacks';
|
||||
import { getStackComposeFile, deployStack, saveStackComposeFile, requireComposeFile } from '$lib/server/stacks';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { createJobResponse } from '$lib/server/sse';
|
||||
import { createRunRecorder } from '$lib/server/deploy-run-record';
|
||||
import { hashComposeContent, hashEnvFingerprint } from '$lib/server/deploy-run-record-core';
|
||||
|
||||
// GET /api/stacks/[name]/compose - Get compose file content
|
||||
/**
|
||||
@@ -58,7 +60,7 @@ export const GET: RequestHandler = async ({ params, url, cookies }) => {
|
||||
* description: Every accepted PUT persists the compose content; with restart it also redeploys. Supports moving the compose/env to a new path and binding a secret provider.
|
||||
* path: name:string The stack name
|
||||
* query: env:integer Environment id the stack belongs to
|
||||
* body: {content:string!, composePath:string, envPath:string, oldComposePath:string, oldEnvPath:string, moveFromDir:string, restart:boolean, secretProviderId:integer}
|
||||
* body: {content:string!, composePath:string, envPath:string, oldComposePath:string, oldEnvPath:string, moveFromDir:string, restart:boolean, secretProviderId:integer, pull:boolean, build:boolean, forceRecreate:boolean}
|
||||
* resp-400: Invalid request (e.g. missing content, or secretProviderId wrong type)
|
||||
* resp-403: Permission denied (needs stacks:edit; binding a secret provider also needs secrets:view)
|
||||
* resp-500: Failed to save or deploy the compose file
|
||||
@@ -79,7 +81,7 @@ export const PUT: RequestHandler = async ({ params, request, url, cookies }) =>
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { content, restart = false, composePath, envPath, moveFromDir, oldComposePath, oldEnvPath, secretProviderId } = body;
|
||||
const { content, restart = false, composePath, envPath, moveFromDir, oldComposePath, oldEnvPath, secretProviderId, pull, build, forceRecreate } = body;
|
||||
|
||||
if (!content || typeof content !== 'string') {
|
||||
return json({ error: 'Compose file content is required' }, { status: 400 });
|
||||
@@ -120,10 +122,57 @@ export const PUT: RequestHandler = async ({ params, request, url, cookies }) =>
|
||||
}
|
||||
|
||||
if (restart) {
|
||||
// Deploy with docker compose up -d --force-recreate.
|
||||
// Force recreate ensures env var changes are applied.
|
||||
// Get authoritative paths from DB/filesystem for deploy (now reflects the saved content).
|
||||
const composeInfo = await getStackComposeFile(name, envIdNum);
|
||||
// Build/pull/force-recreate come from the caller (StackModal's "Save & redeploy"
|
||||
// popover, see RedeployPopover) -- previously this branch always deployed with
|
||||
// build:false and pull skipped regardless of what the compose file needed, so a
|
||||
// service with a `build:` section silently never rebuilt (the change was saved,
|
||||
// but `docker compose up` just reused the stale local image). forceRecreate
|
||||
// defaults to true when the caller omits it, preserving the prior hardcoded
|
||||
// behavior for any caller that hasn't been updated to send it explicitly -- env
|
||||
// var changes need --force-recreate to take effect.
|
||||
const pullOpt = !!pull;
|
||||
const buildOpt = !!build;
|
||||
const forceRecreateOpt = forceRecreate === undefined ? true : !!forceRecreate;
|
||||
|
||||
// Get authoritative paths AND effective env vars from DB/filesystem for deploy
|
||||
// (now reflects the saved content). requireComposeFile() wraps
|
||||
// getStackComposeFile() and additionally resolves secretVars/nonSecretVars --
|
||||
// the same DB-sourced values deployStack itself resolves again internally
|
||||
// at deploy time (stacks.ts), and the same shape deploy/+server.ts already
|
||||
// merges for ITS run record below.
|
||||
const composeInfo = await requireComposeFile(name, envIdNum);
|
||||
|
||||
// Same run record as the dedicated deploy endpoint (deploy/+server.ts:75) --
|
||||
// built up front since createJobResponse takes the recorder as an
|
||||
// already-resolved value, not something it can await for itself.
|
||||
//
|
||||
// composeHash is hashed off the just-submitted `content`, NOT
|
||||
// composeInfo.content: saveStackComposeFile() above wrote this exact string
|
||||
// verbatim (no reformatting, see stacks.ts), and it's the same string handed
|
||||
// to the deployStack call below -- hashing it directly ties the recorded hash to
|
||||
// precisely what gets deployed, instead of a redundant re-read off disk that
|
||||
// could only ever produce the same bytes anyway.
|
||||
//
|
||||
// Skipped entirely when composeInfo.success is false (the compose file is
|
||||
// unexpectedly unreadable right here, immediately after we just wrote it) --
|
||||
// the deploy below proceeds unchanged either way (composePath/envPath already
|
||||
// tolerate this via `|| undefined`), but recording a run without secretVars
|
||||
// would mean the recorder's end() redacts against an empty secrets list,
|
||||
// risking a leaked secret value in the stored error text.
|
||||
let recorder: Awaited<ReturnType<typeof createRunRecorder>> | undefined;
|
||||
if (composeInfo.success) {
|
||||
const effectiveEnvVars = { ...(composeInfo.nonSecretVars ?? {}), ...(composeInfo.secretVars ?? {}) };
|
||||
recorder = await createRunRecorder({
|
||||
stackName: name,
|
||||
envId: envIdNum ?? null,
|
||||
userId: auth.user?.id,
|
||||
triggeredBy: 'manual',
|
||||
options: { pull: pullOpt, build: buildOpt, forceRecreate: forceRecreateOpt },
|
||||
composeHash: hashComposeContent(content),
|
||||
envHash: hashEnvFingerprint(effectiveEnvVars),
|
||||
secrets: Object.values(effectiveEnvVars)
|
||||
});
|
||||
}
|
||||
|
||||
// Deploy via SSE to keep connection alive during long operations
|
||||
return createJobResponse(async (send) => {
|
||||
@@ -132,11 +181,26 @@ export const PUT: RequestHandler = async ({ params, request, url, cookies }) =>
|
||||
name,
|
||||
compose: content,
|
||||
envId: envIdNum,
|
||||
forceRecreate: true,
|
||||
forceRecreate: forceRecreateOpt,
|
||||
build: buildOpt,
|
||||
// pullPolicy undefined (pull unchecked) means deployStack's post-deploy
|
||||
// reconcileStackPendingUpdates() call is skipped too -- a stale "update
|
||||
// available" badge on this stack won't clear until the next pull. Accepted
|
||||
// tradeoff, not a bug.
|
||||
pullPolicy: pullOpt ? 'always' : undefined,
|
||||
composePath: composeInfo.composePath || undefined,
|
||||
envPath: composeInfo.envPath || undefined
|
||||
envPath: composeInfo.envPath || undefined,
|
||||
onLine: (line) => send('progress', { type: 'line', line })
|
||||
});
|
||||
|
||||
// F4 fix: deployStack resolves the bound secret provider's values
|
||||
// internally, AFTER `recorder` above was already built from
|
||||
// composeInfo's DB-only vars. Feed the provider-resolved values in
|
||||
// now, before createJobResponse calls recorder.end() below -- see
|
||||
// deploy-run-record.ts. recorder may be undefined (composeInfo
|
||||
// wasn't readable), matching its optional-recorder construction above.
|
||||
recorder?.addSecrets(result.resolvedSecrets ?? []);
|
||||
|
||||
if (!result.success) {
|
||||
send('result', { success: false, error: result.error });
|
||||
return;
|
||||
@@ -146,7 +210,7 @@ export const PUT: RequestHandler = async ({ params, request, url, cookies }) =>
|
||||
console.error(`Error deploying stack ${name}:`, error);
|
||||
send('result', { success: false, error: error.message || 'Failed to deploy stack' });
|
||||
}
|
||||
}, request);
|
||||
}, request, recorder);
|
||||
}
|
||||
|
||||
// No restart: the content is already persisted above.
|
||||
|
||||
@@ -3,6 +3,8 @@ import { deployStack, requireComposeFile, ComposeFileNotFoundError } from '$lib/
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { auditStack } from '$lib/server/audit';
|
||||
import { createJobResponse } from '$lib/server/sse';
|
||||
import { createRunRecorder } from '$lib/server/deploy-run-record';
|
||||
import { hashComposeContent, hashEnvFingerprint } from '$lib/server/deploy-run-record-core';
|
||||
import type { RequestHandler } from './$types';
|
||||
|
||||
/**
|
||||
@@ -39,23 +41,50 @@ export const POST: RequestHandler = async (event) => {
|
||||
forceRecreate?: boolean;
|
||||
};
|
||||
|
||||
const stackName = decodeURIComponent(params.name);
|
||||
|
||||
// Read up-front (not inside createJobResponse's callback, as before): the run
|
||||
// record needs a compose/env hash and a schedule_executions row BEFORE the job
|
||||
// stream opens, since createJobResponse takes the recorder as a plain (already
|
||||
// resolved) argument, not something it can await for itself.
|
||||
let composeResult: Awaited<ReturnType<typeof requireComposeFile>>;
|
||||
try {
|
||||
composeResult = await requireComposeFile(stackName, envIdNum);
|
||||
} catch (error) {
|
||||
const message = error instanceof ComposeFileNotFoundError
|
||||
? error.message
|
||||
: 'Failed to deploy compose stack';
|
||||
return createJobResponse(async (send) => {
|
||||
send('result', { success: false, error: message });
|
||||
}, event.request);
|
||||
}
|
||||
|
||||
if (!composeResult.success) {
|
||||
const message = composeResult.needsFileLocation
|
||||
? 'Stack compose file location not configured'
|
||||
: composeResult.error || 'Compose file not found';
|
||||
return createJobResponse(async (send) => {
|
||||
send('result', { success: false, error: message });
|
||||
}, event.request);
|
||||
}
|
||||
|
||||
// Same merged set used for envHash below -- also the redaction list end() applies
|
||||
// to the stored error text, so a leaked env value never reaches errorMessage.
|
||||
const effectiveEnvVars = { ...(composeResult.nonSecretVars ?? {}), ...(composeResult.secretVars ?? {}) };
|
||||
|
||||
const recorder = await createRunRecorder({
|
||||
stackName,
|
||||
envId: envIdNum ?? null,
|
||||
userId: auth.user?.id,
|
||||
triggeredBy: 'manual',
|
||||
options: { pull: !!pull, build: !!build, forceRecreate: !!forceRecreate },
|
||||
composeHash: hashComposeContent(composeResult.content!),
|
||||
envHash: hashEnvFingerprint(effectiveEnvVars),
|
||||
secrets: Object.values(effectiveEnvVars)
|
||||
});
|
||||
|
||||
return createJobResponse(async (send) => {
|
||||
try {
|
||||
const stackName = decodeURIComponent(params.name);
|
||||
|
||||
send('progress', { status: 'Reading compose file...' });
|
||||
const composeResult = await requireComposeFile(stackName, envIdNum);
|
||||
|
||||
if (!composeResult.success) {
|
||||
send('result', {
|
||||
success: false,
|
||||
error: composeResult.needsFileLocation
|
||||
? 'Stack compose file location not configured'
|
||||
: composeResult.error || 'Compose file not found'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
send('progress', { status: 'Deploying stack...' });
|
||||
const result = await deployStack({
|
||||
name: stackName,
|
||||
@@ -65,9 +94,18 @@ export const POST: RequestHandler = async (event) => {
|
||||
build,
|
||||
forceRecreate,
|
||||
composePath: composeResult.composePath,
|
||||
envPath: composeResult.envPath
|
||||
envPath: composeResult.envPath,
|
||||
onLine: (line) => send('progress', { type: 'line', line })
|
||||
});
|
||||
|
||||
// F4 fix: deployStack resolves the bound secret provider's values
|
||||
// internally, AFTER `recorder` above was already built from the DB-only
|
||||
// `effectiveEnvVars`. Feed the provider-resolved values in now, before
|
||||
// createJobResponse calls recorder.end() below (on both the JSON and the
|
||||
// streaming path) -- otherwise a provider secret leaking into result.error
|
||||
// would bypass end()'s redaction entirely. See deploy-run-record.ts.
|
||||
recorder.addSecrets(result.resolvedSecrets ?? []);
|
||||
|
||||
// Audit log
|
||||
await auditStack(event, 'deploy', stackName, envIdNum, {
|
||||
pull, build, forceRecreate
|
||||
@@ -86,5 +124,5 @@ export const POST: RequestHandler = async (event) => {
|
||||
console.error('Error deploying compose stack:', error);
|
||||
send('result', { success: false, error: 'Failed to deploy compose stack' });
|
||||
}
|
||||
}, event.request);
|
||||
}, event.request, recorder);
|
||||
};
|
||||
@@ -0,0 +1,138 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import { getScheduleExecutions } from '$lib/server/db';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import type { RequestHandler } from './$types';
|
||||
|
||||
/**
|
||||
* GET /api/stacks/[name]/deploys?env=X
|
||||
*
|
||||
* List of deploy runs recorded for this stack. No log text here — the log
|
||||
* lives in a file (Task 5), not in this response; fetch it separately via
|
||||
* GET .../deploys/{runId}/log.
|
||||
*
|
||||
* This route does NOT inherit the no-auth model of /api/jobs/{id}: a job id
|
||||
* is an unguessable UUID that lives ten minutes in memory, while a schedule
|
||||
* execution id is a small sequential integer that persists forever. Every
|
||||
* route under .../deploys checks stacks:view for itself.
|
||||
*
|
||||
* `env` identifies WHICH environment's runs to list, unlike the other two
|
||||
* routes under .../deploys (which derive the environment from the loaded run
|
||||
* itself via loadOwnedDeployRun). A stack NAME alone is not unique -- the
|
||||
* same name can exist in more than one environment -- so a list without a
|
||||
* definite environment would either merge runs from unrelated environments
|
||||
* into one response, or get evaluated against the caller's globally-merged
|
||||
* permission instead of their permission for one specific environment:
|
||||
* `auth.can(..., undefined)` checks the OR of every role's grant across all
|
||||
* environments, not "does this caller have stacks:view for env X". A caller
|
||||
* with stacks:view scoped to exactly one environment could otherwise get
|
||||
* runs -- including timestamps, status, error text and details.userId --
|
||||
* from every environment that happens to have a same-named stack.
|
||||
*
|
||||
* Two `env` shapes both resolve to the LOCAL environment (environmentId ===
|
||||
* NULL in schedule_executions): the parameter OMITTED entirely, and the
|
||||
* literal string "null". This is not a relaxation of the paragraph above --
|
||||
* it is the environment id createRunRecorder() actually writes for a deploy
|
||||
* triggered without an explicit envId, which is the case on a single
|
||||
* (local-only) environment install: appendEnvParam() in
|
||||
* $lib/stores/environment.ts only appends `env` to the request when envId is
|
||||
* truthy, so the UI's own "deploy this stack" call for the local environment
|
||||
* NEVER sends an `env` param in the first place. Before this NULL shape was
|
||||
* recognized here, EVERY recorded run on a single-environment install was
|
||||
* unreachable through this endpoint: any non-null `env` value matches zero
|
||||
* rows (`env=0` included -- environment ids are never 0), and omitting `env`
|
||||
* was a hard 400. There is no legitimate case where "list runs, no env
|
||||
* specified" should silently mean "all environments, merged" -- an explicit,
|
||||
* distinguishable id (a real integer, or the NULL/local shape) is still
|
||||
* required for every request; only what counts as that definite id changed.
|
||||
* Anything that is neither a parseable integer nor the omitted/"null" shape
|
||||
* remains a hard 400: parsing happens before the permission check, so
|
||||
* `can()` and `canAccessEnvironment()` always see a definite id (a number,
|
||||
* or `undefined` for the local case -- never an ambiguous "no filter").
|
||||
*/
|
||||
/**
|
||||
* @openapi
|
||||
* summary: List deploy runs recorded for a stack (no log text -- see GET .../{runId}/log)
|
||||
* path: name:string! Stack name (from GET /api/stacks)
|
||||
* query: env:integer Environment id the stack belongs to (from GET /api/environments). Omit, or pass the literal string "null", for the local/default environment (deploys triggered without an explicit env, the normal shape on a single-environment install).
|
||||
* resp-200: {runs:array<{id:integer!, environmentId:integer, triggeredBy:string!, triggeredAt:string!, startedAt:string, completedAt:string, duration:integer, status:string!, errorMessage:string, details:{}}>!}
|
||||
* resp-400: env query parameter must be an integer, or omitted/"null" for the local environment
|
||||
* resp-401: Authentication required
|
||||
* resp-403: Permission denied (needs stacks:view), or access denied to this environment
|
||||
*/
|
||||
export const GET: RequestHandler = async ({ params, url, cookies }) => {
|
||||
const auth = await authorize(cookies);
|
||||
|
||||
// Authentication gate first, checked BEFORE anything else runs: a caller
|
||||
// without a session gets 401 here, not a 403 indistinguishable from "logged
|
||||
// in but lacking the permission", and not some later error from touching the
|
||||
// database without a user.
|
||||
if (auth.authEnabled && !auth.isAuthenticated) {
|
||||
return json({ error: 'Authentication required' }, { status: 401 });
|
||||
}
|
||||
|
||||
// env is resolved to a definite id -- a real integer, or `null` for the
|
||||
// local environment (see the module doc comment above) -- BEFORE the
|
||||
// permission check below, so `can()` never falls back to the caller's
|
||||
// globally-merged permission across all environments. NEVER left
|
||||
// `undefined` past this point: passed straight through to
|
||||
// getScheduleExecutions(), where `environmentId: undefined` means "do not
|
||||
// filter on environment at all" (every environment's runs), while
|
||||
// `environmentId: null` means "only NULL-environment runs" -- the two are
|
||||
// not interchangeable, and only the second is what "local environment"
|
||||
// must mean here.
|
||||
const envIdParam = url.searchParams.get('env');
|
||||
let envIdNum: number | null;
|
||||
if (envIdParam === null || envIdParam === 'null') {
|
||||
envIdNum = null;
|
||||
} else {
|
||||
const parsed = parseInt(envIdParam, 10);
|
||||
if (isNaN(parsed)) {
|
||||
return json(
|
||||
{ error: 'env query parameter must be an integer, or omitted/"null" for the local environment' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
envIdNum = parsed;
|
||||
}
|
||||
|
||||
// `?? undefined` maps the local environment (null) to the same "no
|
||||
// environment context" global-permission check `can()` performs for
|
||||
// git-stack routes with a nullable environmentId (`gitStack.environmentId
|
||||
// || undefined` in api/git/stacks/[id]/+server.ts) -- there is no
|
||||
// per-environment role to scope against for a run that was never
|
||||
// attributed to one.
|
||||
if (auth.authEnabled && !(await auth.can('stacks', 'view', envIdNum ?? undefined))) {
|
||||
return json({ error: 'Permission denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
// The local environment has no environment record to check access
|
||||
// against -- canAccessEnvironment() takes a required numeric id and would
|
||||
// throw or misbehave on null/undefined, and there is nothing to be denied
|
||||
// access TO for a run that isn't attributed to any environment.
|
||||
if (envIdNum !== null && auth.isEnterprise && !(await auth.canAccessEnvironment(envIdNum))) {
|
||||
return json({ error: 'Access denied to this environment' }, { status: 403 });
|
||||
}
|
||||
|
||||
const stackName = decodeURIComponent(params.name);
|
||||
const { executions } = await getScheduleExecutions({
|
||||
scheduleType: 'stack_deploy',
|
||||
entityName: stackName,
|
||||
environmentId: envIdNum,
|
||||
limit: 100
|
||||
});
|
||||
|
||||
return json({
|
||||
runs: executions.map((e) => ({
|
||||
id: e.id,
|
||||
environmentId: e.environmentId,
|
||||
triggeredBy: e.triggeredBy,
|
||||
triggeredAt: e.triggeredAt,
|
||||
startedAt: e.startedAt,
|
||||
completedAt: e.completedAt,
|
||||
duration: e.duration,
|
||||
status: e.status,
|
||||
errorMessage: e.errorMessage,
|
||||
details: e.details
|
||||
}))
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,141 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import { deleteScheduleExecution } from '$lib/server/db';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { deleteRunLog } from '$lib/server/deploy-log-store';
|
||||
import { loadOwnedDeployRun, isTerminalRunStatus } from '$lib/server/deploy-run-access';
|
||||
import type { RequestHandler } from './$types';
|
||||
|
||||
/**
|
||||
* GET /api/stacks/[name]/deploys/[runId]
|
||||
*
|
||||
* A single deploy run with all its metadata (no log text -- see .../log).
|
||||
*/
|
||||
/**
|
||||
* @openapi
|
||||
* summary: Get a single deploy run's metadata (no log text -- see GET .../{runId}/log)
|
||||
* description: 400 ("Invalid run id") and 404 ("Deploy run not found", also returned for a run that belongs to a different stack) are produced by the shared loadOwnedDeployRun() helper (deploy-run-access.ts), not literally in this handler's body -- the openapi generator's static scanner cannot see status()/error() calls in a different file, hence the prose here instead of resp-400/resp-404 lines (same pattern as POST /api/backup/destinations/{id}/task's description).
|
||||
* path: name:string! Stack name (from GET /api/stacks)
|
||||
* path: runId:integer! Run id (from GET /api/stacks/{name}/deploys)
|
||||
* resp-200: {id:integer!, environmentId:integer, triggeredBy:string!, triggeredAt:string!, startedAt:string, completedAt:string, duration:integer, status:string!, errorMessage:string, details:{}}
|
||||
* resp-401: Authentication required
|
||||
* resp-403: Permission denied (needs stacks:view for the run's own environment), or access denied to this environment
|
||||
*/
|
||||
export const GET: RequestHandler = async ({ params, cookies }) => {
|
||||
const auth = await authorize(cookies);
|
||||
|
||||
// Authentication gate first: a caller without a session gets 401 here, not
|
||||
// a 403 indistinguishable from "logged in but lacking the permission".
|
||||
if (auth.authEnabled && !auth.isAuthenticated) {
|
||||
return json({ error: 'Authentication required' }, { status: 401 });
|
||||
}
|
||||
// Coarse gate: reject a caller who lacks stacks:view EVERYWHERE, before
|
||||
// even touching the database. This does not by itself scope to the run's
|
||||
// environment (see the check below) -- it only screens out someone with
|
||||
// no stacks:view grant on any role at all.
|
||||
if (auth.authEnabled && !(await auth.can('stacks', 'view'))) {
|
||||
return json({ error: 'Permission denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
const stackName = decodeURIComponent(params.name);
|
||||
const loaded = await loadOwnedDeployRun(stackName, params.runId, auth);
|
||||
if ('response' in loaded) return loaded.response;
|
||||
|
||||
const { run } = loaded;
|
||||
|
||||
// Scoped to the RUN's OWN environment, checked ADDITIONALLY and AFTER the
|
||||
// coarse gate above -- it needs run.environmentId, which only exists once
|
||||
// loadOwnedDeployRun has resolved it. Without this, a caller with
|
||||
// stacks:view for SOME environment (which already satisfied the coarse
|
||||
// gate above via the global OR-across-roles merge) but not for THIS run's
|
||||
// environment could read a run from an environment they have no
|
||||
// stacks:view grant on at all. Same idea the sibling list route
|
||||
// (deploys/+server.ts) already documents for itself, and the same pattern
|
||||
// api/git/stacks/[id]/+server.ts and env-files/+server.ts use: derive the
|
||||
// environment from the loaded entity, then check permission against THAT.
|
||||
// `?? undefined` maps a local run (NULL environmentId) to the same
|
||||
// "no environment context" global-permission check those routes use for
|
||||
// their own nullable environmentId (`gitStack.environmentId || undefined`).
|
||||
if (auth.authEnabled && !(await auth.can('stacks', 'view', run.environmentId ?? undefined))) {
|
||||
return json({ error: 'Permission denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
return json({
|
||||
id: run.id,
|
||||
environmentId: run.environmentId,
|
||||
triggeredBy: run.triggeredBy,
|
||||
triggeredAt: run.triggeredAt,
|
||||
startedAt: run.startedAt,
|
||||
completedAt: run.completedAt,
|
||||
duration: run.duration,
|
||||
status: run.status,
|
||||
errorMessage: run.errorMessage,
|
||||
details: run.details
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* DELETE /api/stacks/[name]/deploys/[runId]
|
||||
*
|
||||
* Removes both the database record AND the on-disk log file. Deleting only
|
||||
* one half would either leave an orphaned log file nobody can reach (record
|
||||
* gone), or a record that 404s the moment someone tries to read its log (file
|
||||
* gone) -- so both happen together, file first: if the file delete throws,
|
||||
* the record still exists and a retry can clean up the rest; the reverse
|
||||
* order would leave a log file with no record pointing at it, findable only
|
||||
* by scanning the log directory.
|
||||
*/
|
||||
/**
|
||||
* @openapi
|
||||
* summary: Delete a deploy run's database record and its on-disk log file
|
||||
* description: 400 ("Invalid run id") and 404 ("Deploy run not found", also returned for a run that belongs to a different stack) are produced by the shared loadOwnedDeployRun() helper (deploy-run-access.ts), not literally in this handler's body -- see GET .../{runId}'s description for why that means prose here instead of resp-400/resp-404 lines.
|
||||
* path: name:string! Stack name (from GET /api/stacks)
|
||||
* path: runId:integer! Run id (from GET /api/stacks/{name}/deploys)
|
||||
* resp-200: {success:boolean!}
|
||||
* resp-401: Authentication required
|
||||
* resp-403: Permission denied (needs stacks:edit for the run's own environment), or access denied to this environment
|
||||
* resp-409: The run has not finished yet (status is not a terminal one) -- deleting a
|
||||
* still-running run would let its background deploy process keep writing to a log
|
||||
* file with no record behind it, which the deploy-log reconcile job then purges as an
|
||||
* orphan, erasing every trace that the deploy ever happened. Retry once it finishes.
|
||||
*/
|
||||
export const DELETE: RequestHandler = async ({ params, cookies }) => {
|
||||
const auth = await authorize(cookies);
|
||||
|
||||
if (auth.authEnabled && !auth.isAuthenticated) {
|
||||
return json({ error: 'Authentication required' }, { status: 401 });
|
||||
}
|
||||
// Coarse gate -- see the identical comment on GET above.
|
||||
if (auth.authEnabled && !(await auth.can('stacks', 'edit'))) {
|
||||
return json({ error: 'Permission denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
const stackName = decodeURIComponent(params.name);
|
||||
const loaded = await loadOwnedDeployRun(stackName, params.runId, auth);
|
||||
if ('response' in loaded) return loaded.response;
|
||||
|
||||
const { run } = loaded;
|
||||
|
||||
// Scoped to the RUN's OWN environment -- see the identical comment on GET
|
||||
// above for why this is checked in addition to, and after, the coarse
|
||||
// gate. Checked before either delete happens: neither the log file nor
|
||||
// the database record is touched if this denies.
|
||||
if (auth.authEnabled && !(await auth.can('stacks', 'edit', run.environmentId ?? undefined))) {
|
||||
return json({ error: 'Permission denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
// Finding B fix: refuse to delete a run that has not finished yet. Checked AFTER
|
||||
// the ownership/permission checks above (a caller who is not allowed to see this
|
||||
// run at all must not learn its status via a 409 either -- 404/403 still win), and
|
||||
// BEFORE either delete happens below, same as the permission check it follows. See
|
||||
// isTerminalRunStatus()'s doc comment (deploy-run-access.ts) for why an unrecognized
|
||||
// status is treated as NOT finished rather than assumed safe to delete.
|
||||
if (!isTerminalRunStatus(run.status)) {
|
||||
return json({ error: 'Cannot delete a running deploy run' }, { status: 409 });
|
||||
}
|
||||
|
||||
// F5 fix: scoped to the run's OWN environment directory (deploy-log-store.ts).
|
||||
await deleteRunLog(run.environmentId, String(run.id));
|
||||
await deleteScheduleExecution(run.id);
|
||||
|
||||
return json({ success: true });
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { loadOwnedDeployRun } from '$lib/server/deploy-run-access';
|
||||
import { readRunLog } from '$lib/server/deploy-log-store';
|
||||
import type { RequestHandler } from './$types';
|
||||
|
||||
/**
|
||||
* GET /api/stacks/[name]/deploys/[runId]/log
|
||||
*
|
||||
* The run's protocol text, straight from the file (Task 5) as text/plain.
|
||||
*
|
||||
* This is the most sensitive of the four operations -- it is the one that can
|
||||
* actually carry secrets that survived redaction -- so it MUST NOT come out
|
||||
* looking safe just because a file path happened to be unresolvable. Every
|
||||
* check below runs BEFORE the file is ever touched: authentication, then
|
||||
* stacks:view, then ownership+environment access via loadOwnedDeployRun (the
|
||||
* exact same helper GET/DELETE .../deploys/{runId} use, so this route can
|
||||
* never drift into trusting a run it shouldn't). Only once all of that has
|
||||
* passed does readRunLog() run at all.
|
||||
*/
|
||||
/**
|
||||
* @openapi
|
||||
* summary: Get a deploy run's log text (text/plain, from the on-disk file)
|
||||
* description: 400 ("Invalid run id") is produced by the shared loadOwnedDeployRun() helper (deploy-run-access.ts), not literally in this handler's body -- the openapi generator's static scanner cannot see status()/error() calls in a different file, hence the prose here instead of a resp-400 line (same pattern as POST /api/backup/destinations/{id}/task's description). The 404 below covers BOTH loadOwnedDeployRun's "run not found / belongs to a different stack" AND this handler's own "log file missing" -- the latter IS literal in this file's body, which is why it can stay a resp-404 line.
|
||||
* path: name:string! Stack name (from GET /api/stacks)
|
||||
* path: runId:integer! Run id (from GET /api/stacks/{name}/deploys)
|
||||
* resp-200: Plain-text log content
|
||||
* resp-401: Authentication required
|
||||
* resp-403: Permission denied (needs stacks:view for the run's own environment), or access denied to this environment
|
||||
* resp-404: Deploy run not found (also returned for a run that belongs to a different stack), or log file missing
|
||||
*/
|
||||
export const GET: RequestHandler = async ({ params, cookies }) => {
|
||||
const auth = await authorize(cookies);
|
||||
|
||||
if (auth.authEnabled && !auth.isAuthenticated) {
|
||||
return json({ error: 'Authentication required' }, { status: 401 });
|
||||
}
|
||||
// Coarse gate -- see the identical comment in
|
||||
// .../deploys/[runId]/+server.ts's GET handler.
|
||||
if (auth.authEnabled && !(await auth.can('stacks', 'view'))) {
|
||||
return json({ error: 'Permission denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
const stackName = decodeURIComponent(params.name);
|
||||
const loaded = await loadOwnedDeployRun(stackName, params.runId, auth);
|
||||
if ('response' in loaded) return loaded.response;
|
||||
|
||||
const { run } = loaded;
|
||||
|
||||
// Scoped to the RUN's OWN environment -- see the identical comment in
|
||||
// .../deploys/[runId]/+server.ts's GET handler for why this runs in
|
||||
// addition to, and after, the coarse gate above. This is the MOST
|
||||
// sensitive of the three routes (it is the one that can carry secrets
|
||||
// that survived redaction, see the module doc comment below), so this
|
||||
// check runs BEFORE readRunLog() ever touches the file.
|
||||
if (auth.authEnabled && !(await auth.can('stacks', 'view', run.environmentId ?? undefined))) {
|
||||
return json({ error: 'Permission denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
// F5 fix: scoped to the run's OWN environment directory (deploy-log-store.ts) --
|
||||
// readRunLog() only reaches a file another environment's run wrote.
|
||||
const log = await readRunLog(run.environmentId, String(run.id));
|
||||
if (log === null) {
|
||||
return json({ error: 'Log not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
return new Response(log, { headers: { 'content-type': 'text/plain' } });
|
||||
};
|
||||
@@ -46,7 +46,7 @@ export const POST: RequestHandler = async (event) => {
|
||||
return createJobResponse(async (send) => {
|
||||
try {
|
||||
const stackName = decodeURIComponent(params.name);
|
||||
const result = await downStack(stackName, envIdNum, removeVolumes);
|
||||
const result = await downStack(stackName, envIdNum, removeVolumes, (line) => send('progress', { type: 'line', line }));
|
||||
|
||||
// Audit log
|
||||
await auditStack(event, 'down', stackName, envIdNum, { removeVolumes });
|
||||
|
||||
@@ -37,7 +37,7 @@ export const POST: RequestHandler = async (event) => {
|
||||
return createJobResponse(async (send) => {
|
||||
try {
|
||||
const stackName = decodeURIComponent(params.name);
|
||||
const result = await restartStack(stackName, envIdNum, mode);
|
||||
const result = await restartStack(stackName, envIdNum, mode, (line) => send('progress', { type: 'line', line }));
|
||||
|
||||
// Audit log
|
||||
await auditStack(event, 'restart', stackName, envIdNum);
|
||||
|
||||
@@ -35,7 +35,7 @@ export const POST: RequestHandler = async (event) => {
|
||||
return createJobResponse(async (send) => {
|
||||
try {
|
||||
const stackName = decodeURIComponent(params.name);
|
||||
const result = await startStack(stackName, envIdNum);
|
||||
const result = await startStack(stackName, envIdNum, (line) => send('progress', { type: 'line', line }));
|
||||
|
||||
// Audit log
|
||||
await auditStack(event, 'start', stackName, envIdNum);
|
||||
|
||||
@@ -35,7 +35,7 @@ export const POST: RequestHandler = async (event) => {
|
||||
return createJobResponse(async (send) => {
|
||||
try {
|
||||
const stackName = decodeURIComponent(params.name);
|
||||
const result = await stopStack(stackName, envIdNum);
|
||||
const result = await stopStack(stackName, envIdNum, (line) => send('progress', { type: 'line', line }));
|
||||
|
||||
// Audit log
|
||||
await auditStack(event, 'stop', stackName, envIdNum);
|
||||
|
||||
@@ -1,374 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { RefreshCw, Copy, Download, WrapText, ArrowDownToLine, Search, ChevronUp, ChevronDown, X, Type, Eraser, Filter, Hash } from 'lucide-svelte';
|
||||
import { wrapHtmlLines } from '$lib/utils/log-lines';
|
||||
import { copyToClipboard } from '$lib/utils/clipboard';
|
||||
import * as Select from '$lib/components/ui/select';
|
||||
import { appSettings, formatLogTimestamps } from '$lib/stores/settings';
|
||||
import { themeStore } from '$lib/stores/theme';
|
||||
import { getMonospaceFont } from '$lib/themes';
|
||||
import { AnsiUp } from 'ansi_up';
|
||||
const ansiUp = new AnsiUp();
|
||||
ansiUp.use_classes = true;
|
||||
|
||||
interface Props {
|
||||
logs: string;
|
||||
containerName: string;
|
||||
loading?: boolean;
|
||||
autoRefresh?: boolean;
|
||||
autoScroll?: boolean;
|
||||
onRefresh?: () => void;
|
||||
onClear?: () => void;
|
||||
onAutoRefreshChange?: (value: boolean) => void;
|
||||
onAutoScrollChange?: (value: boolean) => void;
|
||||
class?: string;
|
||||
}
|
||||
|
||||
let {
|
||||
logs,
|
||||
containerName,
|
||||
loading = false,
|
||||
autoRefresh = true,
|
||||
autoScroll = true,
|
||||
onRefresh,
|
||||
onClear,
|
||||
onAutoRefreshChange,
|
||||
onAutoScrollChange,
|
||||
class: className = ''
|
||||
}: Props = $props();
|
||||
|
||||
let logsRef: HTMLDivElement;
|
||||
let wordWrap = $state(true);
|
||||
let showLineNumbers = $state(typeof window !== 'undefined' && localStorage.getItem('dockhand-log-line-numbers') === 'true');
|
||||
let fontSize = $state(12);
|
||||
|
||||
// RAF-based auto-scroll
|
||||
let scrollRafPending = false;
|
||||
|
||||
// Search state
|
||||
let logSearchActive = $state(false);
|
||||
let logSearchQuery = $state('');
|
||||
let logSearchFilterMode = $state(typeof window !== 'undefined' && localStorage.getItem('dockhand-log-filter-mode') === 'true');
|
||||
let currentMatchIndex = $state(0);
|
||||
let matchCount = $state(0);
|
||||
let logSearchInputRef: HTMLInputElement;
|
||||
|
||||
const fontSizeOptions = [10, 12, 14, 16];
|
||||
|
||||
// Get terminal font family from theme preferences
|
||||
let terminalFontFamily = $derived(() => {
|
||||
const fontMeta = getMonospaceFont($themeStore.terminalFont);
|
||||
return fontMeta?.family || 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace';
|
||||
});
|
||||
|
||||
// Auto-scroll when logs change
|
||||
$effect(() => {
|
||||
if (autoScroll && logsRef && logs) {
|
||||
if (!scrollRafPending) {
|
||||
scrollRafPending = true;
|
||||
requestAnimationFrame(() => {
|
||||
if (logsRef) logsRef.scrollTop = logsRef.scrollHeight;
|
||||
scrollRafPending = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Copy logs to clipboard
|
||||
async function copyLogs() {
|
||||
if (logs) {
|
||||
await copyToClipboard(logs);
|
||||
}
|
||||
}
|
||||
|
||||
// Download logs as txt file
|
||||
function downloadLogs() {
|
||||
if (logs && containerName) {
|
||||
const blob = new Blob([logs], { type: 'text/plain' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${containerName}-logs.txt`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
}
|
||||
|
||||
// Search functions
|
||||
function toggleLogSearch() {
|
||||
logSearchActive = !logSearchActive;
|
||||
if (logSearchActive) {
|
||||
setTimeout(() => logSearchInputRef?.focus(), 50);
|
||||
} else {
|
||||
logSearchQuery = '';
|
||||
currentMatchIndex = 0;
|
||||
matchCount = 0;
|
||||
}
|
||||
}
|
||||
|
||||
function closeLogSearch() {
|
||||
logSearchActive = false;
|
||||
logSearchQuery = '';
|
||||
logSearchFilterMode = false;
|
||||
currentMatchIndex = 0;
|
||||
matchCount = 0;
|
||||
}
|
||||
|
||||
function toggleSearchFilterMode() {
|
||||
logSearchFilterMode = !logSearchFilterMode;
|
||||
localStorage.setItem('dockhand-log-filter-mode', String(logSearchFilterMode));
|
||||
}
|
||||
|
||||
function navigateMatch(direction: 'prev' | 'next') {
|
||||
if (!logsRef || matchCount === 0) return;
|
||||
|
||||
const matches = logsRef.querySelectorAll('.search-match');
|
||||
if (matches.length === 0) return;
|
||||
|
||||
matches[currentMatchIndex]?.classList.remove('current-match');
|
||||
|
||||
if (direction === 'next') {
|
||||
currentMatchIndex = (currentMatchIndex + 1) % matches.length;
|
||||
} else {
|
||||
currentMatchIndex = (currentMatchIndex - 1 + matches.length) % matches.length;
|
||||
}
|
||||
|
||||
const currentEl = matches[currentMatchIndex];
|
||||
if (currentEl) {
|
||||
currentEl.classList.add('current-match');
|
||||
currentEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
}
|
||||
}
|
||||
|
||||
function handleLogSearchKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (e.shiftKey) {
|
||||
navigateMatch('prev');
|
||||
} else {
|
||||
navigateMatch('next');
|
||||
}
|
||||
} else if (e.key === 'Escape') {
|
||||
closeLogSearch();
|
||||
}
|
||||
}
|
||||
|
||||
// Highlighted logs with search matches and ANSI color support
|
||||
let highlightedLogs = $derived(() => {
|
||||
let text = logs || '';
|
||||
if ($appSettings.formatLogTimestamps) {
|
||||
text = formatLogTimestamps(text);
|
||||
}
|
||||
|
||||
const query = logSearchQuery.trim();
|
||||
|
||||
// Filter lines before ANSI conversion (plain text matching)
|
||||
if (logSearchFilterMode && query) {
|
||||
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const filterRegex = new RegExp(escapedForRegex, 'i');
|
||||
const lines = text.split('\n');
|
||||
text = lines.filter(line => filterRegex.test(line)).join('\n');
|
||||
}
|
||||
|
||||
const withAnsi = ansiUp.ansi_to_html(text);
|
||||
if (!query) return withAnsi;
|
||||
|
||||
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const escapedQuery = escapedForRegex.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
|
||||
// Split by HTML tags and only process text parts
|
||||
const parts = withAnsi.split(/(<[^>]*>)/);
|
||||
return parts.map(part => {
|
||||
if (part.startsWith('<')) return part;
|
||||
return part.replace(new RegExp(`(${escapedQuery})`, 'gi'), '<mark class="search-match">$1</mark>');
|
||||
}).join('');
|
||||
});
|
||||
|
||||
// Update match count after render
|
||||
$effect(() => {
|
||||
const html = highlightedLogs();
|
||||
|
||||
if (logSearchQuery && logsRef) {
|
||||
setTimeout(() => {
|
||||
const matches = logsRef.querySelectorAll('.search-match');
|
||||
matchCount = matches.length;
|
||||
currentMatchIndex = 0;
|
||||
if (matches.length > 0) {
|
||||
matches[0].classList.add('current-match');
|
||||
matches[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
}
|
||||
}, 100);
|
||||
} else {
|
||||
matchCount = 0;
|
||||
currentMatchIndex = 0;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col bg-zinc-950 rounded-lg border border-zinc-800 overflow-hidden {className}">
|
||||
<!-- Header bar -->
|
||||
<div class="flex items-center justify-between px-3 py-1.5 border-b border-zinc-800 bg-zinc-900/50 shrink-0">
|
||||
<div class="flex items-center gap-2">
|
||||
{#if loading}
|
||||
<RefreshCw class="w-3 h-3 text-zinc-500 animate-spin" />
|
||||
{/if}
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<!-- Auto-refresh button -->
|
||||
<button
|
||||
onclick={() => onAutoRefreshChange?.(!autoRefresh)}
|
||||
class="flex items-center gap-1 px-1.5 py-0.5 rounded text-xs transition-colors {autoRefresh ? 'bg-amber-500/20 ring-1 ring-amber-500/50 text-amber-400' : 'text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800'}"
|
||||
title="Toggle auto-refresh"
|
||||
>
|
||||
<RefreshCw class="w-3 h-3" />
|
||||
</button>
|
||||
<!-- Auto-scroll button -->
|
||||
<button
|
||||
onclick={() => onAutoScrollChange?.(!autoScroll)}
|
||||
class="flex items-center gap-1 px-1.5 py-0.5 rounded text-xs transition-colors {autoScroll ? 'bg-amber-500/20 ring-1 ring-amber-500/50 text-amber-400' : 'text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800'}"
|
||||
title="Toggle auto-scroll"
|
||||
>
|
||||
<ArrowDownToLine class="w-3 h-3" />
|
||||
</button>
|
||||
<!-- Font size -->
|
||||
<Select.Root type="single" value={String(fontSize)} onValueChange={(v) => fontSize = Number(v)}>
|
||||
<Select.Trigger class="h-6 w-16 bg-zinc-800 border-zinc-700 text-xs text-zinc-300 px-1.5">
|
||||
<Type class="w-3 h-3 mr-1 text-zinc-400" />
|
||||
<span>{fontSize}px</span>
|
||||
</Select.Trigger>
|
||||
<Select.Content>
|
||||
{#each fontSizeOptions as size}
|
||||
<Select.Item value={String(size)} label="{size}px">
|
||||
<Type class="w-3 h-3 mr-1.5 text-muted-foreground" />
|
||||
{size}px
|
||||
</Select.Item>
|
||||
{/each}
|
||||
</Select.Content>
|
||||
</Select.Root>
|
||||
<!-- Word wrap -->
|
||||
<button
|
||||
onclick={() => wordWrap = !wordWrap}
|
||||
class="p-1 rounded hover:bg-zinc-800 transition-colors {wordWrap ? 'bg-amber-500/20 ring-1 ring-amber-500/50' : ''}"
|
||||
title="Toggle word wrap"
|
||||
>
|
||||
<WrapText class="w-3 h-3 transition-colors {wordWrap ? 'text-amber-400' : 'text-zinc-500 hover:text-zinc-300'}" />
|
||||
</button>
|
||||
<!-- Line numbers -->
|
||||
<button
|
||||
onclick={() => { showLineNumbers = !showLineNumbers; localStorage.setItem('dockhand-log-line-numbers', String(showLineNumbers)); }}
|
||||
class="p-1 rounded hover:bg-zinc-800 transition-colors {showLineNumbers ? 'bg-amber-500/20 ring-1 ring-amber-500/50' : ''}"
|
||||
title={showLineNumbers ? 'Hide line numbers' : 'Show line numbers'}
|
||||
>
|
||||
<Hash class="w-3 h-3 transition-colors {showLineNumbers ? 'text-amber-400' : 'text-zinc-500 hover:text-zinc-300'}" />
|
||||
</button>
|
||||
<!-- Search -->
|
||||
{#if logSearchActive}
|
||||
<div class="flex items-center gap-1 bg-zinc-800 rounded px-1.5 py-0.5">
|
||||
<Search class="w-3 h-3 text-amber-400" />
|
||||
<input
|
||||
bind:this={logSearchInputRef}
|
||||
type="text"
|
||||
placeholder="Search..."
|
||||
bind:value={logSearchQuery}
|
||||
onkeydown={handleLogSearchKeydown}
|
||||
class="bg-transparent border-none outline-none text-xs text-zinc-200 w-20 placeholder:text-zinc-500"
|
||||
/>
|
||||
<button
|
||||
onclick={toggleSearchFilterMode}
|
||||
class="p-0.5 rounded transition-colors {logSearchFilterMode ? 'bg-amber-500/20 ring-1 ring-amber-500/50' : 'hover:bg-zinc-700'}"
|
||||
title={logSearchFilterMode ? 'Show all lines (filter mode active)' : 'Hide non-matching lines'}
|
||||
>
|
||||
<Filter class="w-3 h-3 transition-colors {logSearchFilterMode ? 'text-amber-400' : 'text-zinc-400'}" />
|
||||
</button>
|
||||
{#if matchCount > 0}
|
||||
<span class="text-xs text-zinc-400">{currentMatchIndex + 1}/{matchCount}</span>
|
||||
{:else if logSearchQuery}
|
||||
<span class="text-xs text-zinc-500">0/0</span>
|
||||
{/if}
|
||||
<button onclick={() => navigateMatch('prev')} class="p-0.5 rounded hover:bg-zinc-700" title="Previous">
|
||||
<ChevronUp class="w-3 h-3 text-zinc-400" />
|
||||
</button>
|
||||
<button onclick={() => navigateMatch('next')} class="p-0.5 rounded hover:bg-zinc-700" title="Next">
|
||||
<ChevronDown class="w-3 h-3 text-zinc-400" />
|
||||
</button>
|
||||
<button onclick={closeLogSearch} class="p-0.5 rounded hover:bg-zinc-700" title="Close">
|
||||
<X class="w-3 h-3 text-zinc-400" />
|
||||
</button>
|
||||
</div>
|
||||
{:else}
|
||||
<button
|
||||
onclick={toggleLogSearch}
|
||||
class="p-1 rounded hover:bg-zinc-800 transition-colors"
|
||||
title="Search logs"
|
||||
>
|
||||
<Search class="w-3 h-3 text-zinc-500 hover:text-zinc-300" />
|
||||
</button>
|
||||
{/if}
|
||||
<!-- Copy -->
|
||||
<button
|
||||
onclick={copyLogs}
|
||||
class="p-1 rounded hover:bg-zinc-800 transition-colors"
|
||||
title="Copy logs"
|
||||
>
|
||||
<Copy class="w-3 h-3 text-zinc-500 hover:text-zinc-300" />
|
||||
</button>
|
||||
<!-- Download -->
|
||||
<button
|
||||
onclick={downloadLogs}
|
||||
class="p-1 rounded hover:bg-zinc-800 transition-colors"
|
||||
title="Download logs"
|
||||
>
|
||||
<Download class="w-3 h-3 text-zinc-500 hover:text-zinc-300" />
|
||||
</button>
|
||||
<!-- Clear -->
|
||||
<button
|
||||
onclick={() => onClear?.()}
|
||||
class="p-1 rounded hover:bg-zinc-800 transition-colors"
|
||||
title="Clear logs"
|
||||
>
|
||||
<Eraser class="w-3 h-3 text-zinc-500 hover:text-zinc-300" />
|
||||
</button>
|
||||
<!-- Refresh -->
|
||||
<button
|
||||
onclick={() => onRefresh?.()}
|
||||
class="p-1 rounded hover:bg-zinc-800 transition-colors"
|
||||
title="Refresh logs"
|
||||
>
|
||||
<RefreshCw class="w-3 h-3 text-zinc-500 hover:text-zinc-300" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Logs content -->
|
||||
<div bind:this={logsRef} class="flex-1 overflow-auto p-4">
|
||||
{#if logs}
|
||||
<pre class="text-zinc-50 {wordWrap ? 'whitespace-pre-wrap' : 'whitespace-pre'} {showLineNumbers ? 'show-line-numbers' : ''}" style="font-size: {fontSize}px; font-family: {terminalFontFamily()};">{@html wrapHtmlLines(highlightedLogs())}</pre>
|
||||
{:else if loading}
|
||||
<div class="flex items-center justify-center h-full text-muted-foreground">
|
||||
<RefreshCw class="w-5 h-5 animate-spin mr-2" />
|
||||
Loading logs...
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-zinc-500 text-sm">No logs available</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
:global(.search-match) {
|
||||
background-color: rgba(234, 179, 8, 0.4);
|
||||
color: #fef3c7;
|
||||
border-radius: 2px;
|
||||
padding: 1px 2px;
|
||||
box-shadow: 0 0 4px rgba(234, 179, 8, 0.5);
|
||||
}
|
||||
:global(.search-match.current-match) {
|
||||
background-color: rgba(234, 179, 8, 0.8);
|
||||
color: #1a1a1a;
|
||||
font-weight: 600;
|
||||
box-shadow: 0 0 8px rgba(234, 179, 8, 0.9), 0 0 16px rgba(234, 179, 8, 0.5);
|
||||
outline: 2px solid rgb(250, 204, 21);
|
||||
}
|
||||
|
||||
</style>
|
||||
@@ -163,7 +163,7 @@
|
||||
|
||||
interface ScheduleExecution {
|
||||
id: number;
|
||||
scheduleType: 'container_update' | 'git_stack_sync' | 'system_cleanup' | 'env_update_check' | 'image_prune' | 'backup' | 'repo_prune' | 'repo_check' | 'repo_verify';
|
||||
scheduleType: 'container_update' | 'git_stack_sync' | 'system_cleanup' | 'env_update_check' | 'image_prune' | 'backup' | 'repo_prune' | 'repo_check' | 'repo_verify' | 'stack_deploy' | 'deploy_log_reconcile';
|
||||
scheduleId: number;
|
||||
environmentId: number | null;
|
||||
entityName: string;
|
||||
@@ -182,7 +182,7 @@
|
||||
interface Schedule {
|
||||
key: string; // Unique key: type-id
|
||||
id: number;
|
||||
type: 'container_update' | 'git_stack_sync' | 'system_cleanup' | 'env_update_check' | 'image_prune' | 'backup' | 'repo_prune' | 'repo_check' | 'repo_verify';
|
||||
type: 'container_update' | 'git_stack_sync' | 'system_cleanup' | 'env_update_check' | 'image_prune' | 'backup' | 'repo_prune' | 'repo_check' | 'repo_verify' | 'stack_deploy' | 'deploy_log_reconcile';
|
||||
name: string;
|
||||
entityName: string;
|
||||
description?: string;
|
||||
@@ -508,9 +508,10 @@
|
||||
|
||||
async function toggleHideSystemJobs() {
|
||||
hideSystemJobs = !hideSystemJobs;
|
||||
// Remove system_cleanup from filter if hiding system jobs
|
||||
if (hideSystemJobs && filterTypes.includes('system_cleanup')) {
|
||||
filterTypes = filterTypes.filter(t => t !== 'system_cleanup');
|
||||
// Remove system_cleanup and deploy_log_reconcile from filter if hiding system jobs
|
||||
// (both are system schedules -- isSystem: true -- so they're gone from the list too)
|
||||
if (hideSystemJobs && (filterTypes.includes('system_cleanup') || filterTypes.includes('deploy_log_reconcile'))) {
|
||||
filterTypes = filterTypes.filter(t => t !== 'system_cleanup' && t !== 'deploy_log_reconcile');
|
||||
}
|
||||
// Save preference in background
|
||||
try {
|
||||
@@ -975,6 +976,10 @@
|
||||
Repo check
|
||||
{:else if filterTypes[0] === 'repo_verify'}
|
||||
Data verify
|
||||
{:else if filterTypes[0] === 'stack_deploy'}
|
||||
Stack deploy
|
||||
{:else if filterTypes[0] === 'deploy_log_reconcile'}
|
||||
Deploy log reconcile
|
||||
{:else}
|
||||
System jobs
|
||||
{/if}
|
||||
@@ -1009,6 +1014,10 @@
|
||||
<Trash2 class="w-4 h-4 mr-2 inline text-amber-500 drop-shadow-[0_0_3px_rgba(245,158,11,0.4)]" />
|
||||
Image prune
|
||||
</Select.Item>
|
||||
<Select.Item value="stack_deploy">
|
||||
<Server class="w-4 h-4 mr-2 inline text-indigo-500 drop-shadow-[0_0_3px_rgba(99,102,241,0.4)]" />
|
||||
Stack deploy
|
||||
</Select.Item>
|
||||
<!-- BETA GATE: backup schedule filters hidden unless FEAT_BACKUPS_ENABLED (see features.ts) -->
|
||||
{#if $page.data.backupsEnabled}
|
||||
<Select.Item value="backup">
|
||||
@@ -1033,6 +1042,10 @@
|
||||
<Wrench class="w-4 h-4 mr-2 inline text-amber-500 drop-shadow-[0_0_3px_rgba(245,158,11,0.4)]" />
|
||||
System jobs
|
||||
</Select.Item>
|
||||
<Select.Item value="deploy_log_reconcile">
|
||||
<FileText class="w-4 h-4 mr-2 inline text-amber-500 drop-shadow-[0_0_3px_rgba(245,158,11,0.4)]" />
|
||||
Deploy log reconcile
|
||||
</Select.Item>
|
||||
{/if}
|
||||
</Select.Content>
|
||||
</Select.Root>
|
||||
@@ -1604,7 +1617,7 @@
|
||||
Execution details
|
||||
{#if selectedExecution}
|
||||
<span class="text-muted-foreground font-normal">
|
||||
({#if selectedExecution.scheduleType === 'container_update'}Container update{:else if selectedExecution.scheduleType === 'env_update_check'}Environment update{:else if selectedExecution.scheduleType === 'git_stack_sync'}Git stack sync{:else if selectedExecution.scheduleType === 'backup'}Backup{:else if selectedExecution.scheduleType === 'repo_prune'}Repo prune{:else if selectedExecution.scheduleType === 'repo_check'}Repo check{:else if selectedExecution.scheduleType === 'repo_verify'}Data verify{:else}System job{/if})
|
||||
({#if selectedExecution.scheduleType === 'container_update'}Container update{:else if selectedExecution.scheduleType === 'env_update_check'}Environment update{:else if selectedExecution.scheduleType === 'git_stack_sync'}Git stack sync{:else if selectedExecution.scheduleType === 'backup'}Backup{:else if selectedExecution.scheduleType === 'repo_prune'}Repo prune{:else if selectedExecution.scheduleType === 'repo_check'}Repo check{:else if selectedExecution.scheduleType === 'repo_verify'}Data verify{:else if selectedExecution.scheduleType === 'stack_deploy'}Stack deploy{:else if selectedExecution.scheduleType === 'deploy_log_reconcile'}Deploy log reconcile{:else}System job{/if})
|
||||
</span>
|
||||
{/if}
|
||||
</Dialog.Title>
|
||||
|
||||
@@ -91,6 +91,8 @@ services:
|
||||
let eventCleanupEnabled = $derived($appSettings.eventCleanupEnabled);
|
||||
let scannerCleanupCron = $derived($appSettings.scannerCleanupCron);
|
||||
let scannerCleanupEnabled = $derived($appSettings.scannerCleanupEnabled);
|
||||
let deployLogReconcileCron = $derived($appSettings.deployLogReconcileCron);
|
||||
let deployLogReconcileEnabled = $derived($appSettings.deployLogReconcileEnabled);
|
||||
let logMaxLines = $derived($appSettings.logMaxLines);
|
||||
let formatLogTimestamps = $derived($appSettings.formatLogTimestamps);
|
||||
let defaultTimezone = $derived($appSettings.defaultTimezone);
|
||||
@@ -187,6 +189,17 @@ services:
|
||||
toast.success(newState ? 'Scanner cleanup enabled' : 'Scanner cleanup disabled');
|
||||
}
|
||||
|
||||
function handleDeployLogReconcileCronChange(cron: string) {
|
||||
appSettings.setDeployLogReconcileCron(cron);
|
||||
toast.success('Deploy log reconcile cron updated');
|
||||
}
|
||||
|
||||
function handleDeployLogReconcileEnabledChange() {
|
||||
const newState = !deployLogReconcileEnabled;
|
||||
appSettings.setDeployLogReconcileEnabled(newState);
|
||||
toast.success(newState ? 'Deploy log reconcile enabled' : 'Deploy log reconcile disabled');
|
||||
}
|
||||
|
||||
function handleGrypeImageBlur(e: Event) {
|
||||
const value = (e.target as HTMLInputElement).value.trim();
|
||||
if (value && value !== defaultGrypeImage) {
|
||||
@@ -1121,6 +1134,26 @@ services:
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="space-y-1 pt-2 border-t">
|
||||
<div class="flex items-center gap-3">
|
||||
<Label>Deploy log reconcile</Label>
|
||||
<TogglePill
|
||||
checked={deployLogReconcileEnabled}
|
||||
onchange={handleDeployLogReconcileEnabledChange}
|
||||
disabled={!$canAccess('settings', 'edit')}
|
||||
/>
|
||||
</div>
|
||||
<p class="text-xs text-muted-foreground">Delete deploy-log files that no longer have a matching deploy record; deploy records that lost their log file are only flagged, never deleted</p>
|
||||
{#if deployLogReconcileEnabled}
|
||||
<div class="mt-2">
|
||||
<CronEditor
|
||||
value={deployLogReconcileCron}
|
||||
onchange={handleDeployLogReconcileCronChange}
|
||||
disabled={!$canAccess('settings', 'edit')}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="space-y-1 pt-2 border-t">
|
||||
<div class="flex items-center gap-3">
|
||||
<Label>Protect scanner images from prune</Label>
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
import type { ComposeStackInfo, ContainerStats, StackContainer } from '$lib/types';
|
||||
import StackModal from './StackModal.svelte';
|
||||
import DeleteStackModal from './DeleteStackModal.svelte';
|
||||
import ComposeOutputModal from './ComposeOutputModal.svelte';
|
||||
import GitSourceBadge from './GitSourceBadge.svelte';
|
||||
import GitStackModal from './GitStackModal.svelte';
|
||||
import ImportStackModal from './ImportStackModal.svelte';
|
||||
@@ -520,6 +521,52 @@
|
||||
let restartPopoverOpen = $state<Record<string, boolean>>({});
|
||||
let stackDownLoading = $state<string | null>(null);
|
||||
|
||||
// Live compose output window: shown while a stack action (start/stop/restart/
|
||||
// redeploy/down) runs, fed line-by-line via readJobResponse's onLine callback.
|
||||
let composeOutputOpen = $state(false);
|
||||
let composeOutputTitle = $state('');
|
||||
let composeOutputLines = $state<string[]>([]);
|
||||
let composeOutputRunning = $state(false);
|
||||
// Status-line inputs, measured here in the browser (wall-clock incl. the round
|
||||
// trip through fetch/polling) — NOT the server-side execution time recorded
|
||||
// separately for the deploy-history dataset (Task 10). Different path, different
|
||||
// number; don't conflate the two.
|
||||
let composeOutputStartedAt = 0;
|
||||
let composeOutputOk = $state<boolean | undefined>(undefined);
|
||||
let composeOutputMs = $state<number | undefined>(undefined);
|
||||
let composeOutputExitCode = $state<number | undefined>(undefined);
|
||||
|
||||
function startComposeOutput(title: string) {
|
||||
composeOutputTitle = title;
|
||||
composeOutputLines = [];
|
||||
composeOutputRunning = true;
|
||||
composeOutputOpen = true;
|
||||
composeOutputStartedAt = Date.now();
|
||||
composeOutputOk = undefined;
|
||||
composeOutputMs = undefined;
|
||||
composeOutputExitCode = undefined;
|
||||
}
|
||||
|
||||
function appendComposeOutputLine(line: string) {
|
||||
composeOutputLines = [...composeOutputLines, line];
|
||||
}
|
||||
|
||||
// Called once the job settles. Older agent versions (pre line-streaming, see Task 5)
|
||||
// only return a batched `output` string — show it if nothing arrived incrementally.
|
||||
// `ok`/`exitCode` come from the job result (or `false`/undefined on a thrown
|
||||
// network error, from the catch blocks below) — the payload does not carry an
|
||||
// exit code today (StackOperationResult has no such field, see stacks.ts), so
|
||||
// `exitCode` stays undefined in practice until the server starts sending one.
|
||||
function finishComposeOutput(output: string | undefined, ok: boolean, exitCode?: number) {
|
||||
composeOutputRunning = false;
|
||||
composeOutputOk = ok;
|
||||
composeOutputMs = Date.now() - composeOutputStartedAt;
|
||||
composeOutputExitCode = exitCode;
|
||||
if (composeOutputLines.length === 0 && output) {
|
||||
composeOutputLines = output.split('\n');
|
||||
}
|
||||
}
|
||||
|
||||
// Container-level confirmation popover state
|
||||
let confirmStopContainerId = $state<string | null>(null);
|
||||
let confirmRestartContainerId = $state<string | null>(null);
|
||||
@@ -965,9 +1012,15 @@
|
||||
async function startStack(name: string) {
|
||||
operationError = null;
|
||||
stackActionLoading = name;
|
||||
startComposeOutput(`Starting ${name}`);
|
||||
try {
|
||||
const response = await fetch(appendEnvParam(`/api/stacks/${encodeURIComponent(name)}/start`, envId), { method: 'POST' });
|
||||
const data = await readJobResponse(response);
|
||||
const data = await readJobResponse(response, appendComposeOutputLine);
|
||||
finishComposeOutput(
|
||||
typeof data.output === 'string' ? data.output : undefined,
|
||||
Boolean(data.success),
|
||||
typeof data.exitCode === 'number' ? data.exitCode : undefined
|
||||
);
|
||||
if (!data.success) {
|
||||
showErrorDialog(`Failed to start ${name}`, data.error || 'Failed to start stack');
|
||||
return;
|
||||
@@ -975,6 +1028,7 @@
|
||||
toast.success(`Started ${name}`);
|
||||
await fetchStacks();
|
||||
} catch (error) {
|
||||
finishComposeOutput(undefined, false);
|
||||
console.error('Failed to start stack:', error);
|
||||
const errorMsg = error instanceof Error ? error.message : 'Failed to start stack';
|
||||
showErrorDialog(`Failed to start ${name}`, errorMsg);
|
||||
@@ -986,9 +1040,15 @@
|
||||
async function stopStack(name: string) {
|
||||
operationError = null;
|
||||
stackActionLoading = name;
|
||||
startComposeOutput(`Stopping ${name}`);
|
||||
try {
|
||||
const response = await fetch(appendEnvParam(`/api/stacks/${encodeURIComponent(name)}/stop`, envId), { method: 'POST' });
|
||||
const data = await readJobResponse(response);
|
||||
const data = await readJobResponse(response, appendComposeOutputLine);
|
||||
finishComposeOutput(
|
||||
typeof data.output === 'string' ? data.output : undefined,
|
||||
Boolean(data.success),
|
||||
typeof data.exitCode === 'number' ? data.exitCode : undefined
|
||||
);
|
||||
if (!data.success) {
|
||||
showErrorDialog(`Failed to stop ${name}`, data.error || 'Failed to stop stack');
|
||||
return;
|
||||
@@ -996,6 +1056,7 @@
|
||||
toast.success(`Stopped ${name}`);
|
||||
await fetchStacks();
|
||||
} catch (error) {
|
||||
finishComposeOutput(undefined, false);
|
||||
console.error('Failed to stop stack:', error);
|
||||
const errorMsg = error instanceof Error ? error.message : 'Failed to stop stack';
|
||||
showErrorDialog(`Failed to stop ${name}`, errorMsg);
|
||||
@@ -1007,13 +1068,19 @@
|
||||
async function restartStack(name: string, mode: 'restart' | 'ordered' | 'recreate' = 'restart') {
|
||||
operationError = null;
|
||||
stackActionLoading = name;
|
||||
startComposeOutput(mode === 'recreate' ? `Recreating ${name}` : `Restarting ${name}`);
|
||||
try {
|
||||
let url = appendEnvParam(`/api/stacks/${encodeURIComponent(name)}/restart`, envId);
|
||||
if (mode === 'recreate' || mode === 'ordered') {
|
||||
url += (url.includes('?') ? '&' : '?') + `mode=${mode}`;
|
||||
}
|
||||
const response = await fetch(url, { method: 'POST' });
|
||||
const data = await readJobResponse(response);
|
||||
const data = await readJobResponse(response, appendComposeOutputLine);
|
||||
finishComposeOutput(
|
||||
typeof data.output === 'string' ? data.output : undefined,
|
||||
Boolean(data.success),
|
||||
typeof data.exitCode === 'number' ? data.exitCode : undefined
|
||||
);
|
||||
if (!data.success) {
|
||||
showErrorDialog(`Failed to restart ${name}`, data.error || 'Failed to restart stack');
|
||||
return;
|
||||
@@ -1021,6 +1088,7 @@
|
||||
toast.success(mode === 'recreate' ? `Recreated ${name}` : `Restarted ${name}`);
|
||||
await fetchStacks();
|
||||
} catch (error) {
|
||||
finishComposeOutput(undefined, false);
|
||||
console.error('Failed to restart stack:', error);
|
||||
const errorMsg = error instanceof Error ? error.message : 'Failed to restart stack';
|
||||
showErrorDialog(`Failed to restart ${name}`, errorMsg);
|
||||
@@ -1032,13 +1100,19 @@
|
||||
async function redeployStack(name: string, options: { pull: boolean; build: boolean; forceRecreate: boolean }) {
|
||||
operationError = null;
|
||||
stackActionLoading = name;
|
||||
startComposeOutput(`Redeploying ${name}`);
|
||||
try {
|
||||
const response = await fetch(appendEnvParam(`/api/stacks/${encodeURIComponent(name)}/deploy`, envId), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(options)
|
||||
});
|
||||
const data = await readJobResponse(response);
|
||||
const data = await readJobResponse(response, appendComposeOutputLine);
|
||||
finishComposeOutput(
|
||||
typeof data.output === 'string' ? data.output : undefined,
|
||||
Boolean(data.success),
|
||||
typeof data.exitCode === 'number' ? data.exitCode : undefined
|
||||
);
|
||||
if (!data.success) {
|
||||
showErrorDialog(`Failed to redeploy ${name}`, data.error || 'Failed to redeploy stack');
|
||||
return;
|
||||
@@ -1046,6 +1120,7 @@
|
||||
toast.success(`Redeployed ${name}`);
|
||||
await fetchStacks();
|
||||
} catch (error) {
|
||||
finishComposeOutput(undefined, false);
|
||||
console.error('Failed to redeploy stack:', error);
|
||||
const errorMsg = error instanceof Error ? error.message : 'Failed to redeploy stack';
|
||||
showErrorDialog(`Failed to redeploy ${name}`, errorMsg);
|
||||
@@ -1058,9 +1133,15 @@
|
||||
operationError = null;
|
||||
stackActionLoading = name;
|
||||
stackDownLoading = name;
|
||||
startComposeOutput(`Bringing down ${name}`);
|
||||
try {
|
||||
const response = await fetch(appendEnvParam(`/api/stacks/${encodeURIComponent(name)}/down`, envId), { method: 'POST' });
|
||||
const data = await readJobResponse(response);
|
||||
const data = await readJobResponse(response, appendComposeOutputLine);
|
||||
finishComposeOutput(
|
||||
typeof data.output === 'string' ? data.output : undefined,
|
||||
Boolean(data.success),
|
||||
typeof data.exitCode === 'number' ? data.exitCode : undefined
|
||||
);
|
||||
if (!data.success) {
|
||||
showErrorDialog(`Failed to bring down ${name}`, data.error || 'Failed to bring down stack');
|
||||
return;
|
||||
@@ -1068,6 +1149,7 @@
|
||||
toast.success(`Brought down ${name}`);
|
||||
await fetchStacks();
|
||||
} catch (error) {
|
||||
finishComposeOutput(undefined, false);
|
||||
console.error('Failed to bring down stack:', error);
|
||||
const errorMsg = error instanceof Error ? error.message : 'Failed to bring down stack';
|
||||
showErrorDialog(`Failed to bring down ${name}`, errorMsg);
|
||||
@@ -2764,6 +2846,16 @@
|
||||
onConfirm={(opts) => removeStack(deleteStackName, opts)}
|
||||
/>
|
||||
|
||||
<ComposeOutputModal
|
||||
bind:open={composeOutputOpen}
|
||||
title={composeOutputTitle}
|
||||
lines={composeOutputLines}
|
||||
running={composeOutputRunning}
|
||||
ok={composeOutputOk}
|
||||
ms={composeOutputMs}
|
||||
exitCode={composeOutputExitCode}
|
||||
/>
|
||||
|
||||
<ContainerInspectModal
|
||||
bind:open={showInspectModal}
|
||||
containerId={inspectContainerId}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import * as Dialog from '$lib/components/ui/dialog';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { Loader2 } from 'lucide-svelte';
|
||||
import LogViewer from '$lib/components/LogViewer.svelte';
|
||||
import { formatRunStatus } from '$lib/utils/run-status';
|
||||
|
||||
// A plain display window for compose output. It owns none of the polling —
|
||||
// the parent pushes lines in as they arrive via readJobResponse's onLine callback
|
||||
// and flips `running` to false once the job settles, at which point it also
|
||||
// supplies `ok`/`ms`/`exitCode` for the status line below.
|
||||
interface Props {
|
||||
open: boolean;
|
||||
title: string;
|
||||
lines: string[];
|
||||
running: boolean;
|
||||
ok?: boolean;
|
||||
ms?: number;
|
||||
exitCode?: number;
|
||||
}
|
||||
|
||||
let { open = $bindable(false), title, lines, running, ok, ms, exitCode }: Props = $props();
|
||||
|
||||
let statusLine = $derived(formatRunStatus({ running, ok, ms, exitCode }));
|
||||
|
||||
// This modal is opened straight from the stack list, with no editor in scope to
|
||||
// borrow a theme from (unlike the docked panel and Deploys tab inside StackModal,
|
||||
// which both follow `dockhand-editor-theme`). Its Dialog.Content already tracks
|
||||
// the app-wide light/dark switch via bg-background, so the log viewer inside
|
||||
// follows the same switch instead of introducing a third, unrelated toggle.
|
||||
// Same read-once-on-mount + system-preference-fallback pattern as
|
||||
// ComposeGraphViewer's graphTheme -- this component is mounted once at the page
|
||||
// root and toggled via `open`, so onMount runs once per page load.
|
||||
let outputTheme = $state<'light' | 'dark'>('dark');
|
||||
|
||||
onMount(() => {
|
||||
const appTheme = localStorage.getItem('theme');
|
||||
if (appTheme === 'dark' || appTheme === 'light') {
|
||||
outputTheme = appTheme;
|
||||
} else {
|
||||
outputTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
});
|
||||
|
||||
function handleClose() {
|
||||
// Closing only hides this window. The operation it is watching keeps running
|
||||
// against the server regardless (watchJob's poll loop in sse-fetch.ts has no
|
||||
// abort mechanism and isn't meant to gain one here) — never stop it on close.
|
||||
open = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<Dialog.Root bind:open>
|
||||
<!-- Build output is line-oriented and often wide (BuildKit step lines, image digests).
|
||||
A narrow window forces wrapping or horizontal scrolling on every other line, so this
|
||||
one is sized generously -- but clamped to the viewport so it never overflows on a
|
||||
laptop screen: min() picks the smaller of the two, and the 4rem keeps a margin. -->
|
||||
<Dialog.Content class="max-w-[min(90rem,calc(100vw-4rem))] h-[85vh] overflow-hidden flex flex-col">
|
||||
<Dialog.Header class="shrink-0">
|
||||
<Dialog.Title class="flex items-center gap-2">
|
||||
{#if running}
|
||||
<Loader2 class="w-4 h-4 animate-spin text-muted-foreground" />
|
||||
{/if}
|
||||
{title}
|
||||
</Dialog.Title>
|
||||
<Dialog.Description>
|
||||
{statusLine}
|
||||
</Dialog.Description>
|
||||
</Dialog.Header>
|
||||
|
||||
<LogViewer
|
||||
logs={lines.join('\n')}
|
||||
{title}
|
||||
autoRefresh={false}
|
||||
autoScroll={running}
|
||||
class="flex-1 min-h-0"
|
||||
theme={outputTheme}
|
||||
/>
|
||||
|
||||
<Dialog.Footer class="shrink-0">
|
||||
<Button variant="outline" onclick={handleClose}>Close</Button>
|
||||
</Dialog.Footer>
|
||||
</Dialog.Content>
|
||||
</Dialog.Root>
|
||||
@@ -0,0 +1,355 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* Deploys tab: the recorded history of deploy runs for this stack (GET
|
||||
* /api/stacks/{name}/deploys). Each run is a collapsed row by default --
|
||||
* status, relative time, duration, and a one-line summary -- expandable for the
|
||||
* full picture (containers, build/cache, images, options, a truncated notice,
|
||||
* and on failure the shortened last error line). All of that text composition
|
||||
* lives in deploy-run-view.ts, not here -- this component only fetches and binds.
|
||||
*
|
||||
* Mirrors BackupPanel/ExecutionHistoryList's shape (loading / empty / list),
|
||||
* the sibling tab in this same modal -- see StackModal.svelte's Backups tab
|
||||
* for the tab-gating convention this one follows.
|
||||
*
|
||||
* Expanding a row additionally loads that run's full protocol text (GET
|
||||
* .../deploys/{id}/log) into the same LogViewer the live output window and
|
||||
* the docked panel use -- but only on expand, never while the list itself
|
||||
* loads: a run's log can be large, and the list is meant to stay quick.
|
||||
* buildDeployLogPanelState (deploy-run-view.ts) decides what that fetch
|
||||
* should even attempt: a run already known to be missing its log file
|
||||
* (reconciled by deploy-log-reconcile) never triggers the request at all,
|
||||
* since it would just 404.
|
||||
*
|
||||
* `envId === null` is NOT "nothing to ask for" -- it is the LOCAL
|
||||
* environment (see the list route's own doc comment, `.../deploys/+server.ts`):
|
||||
* appendEnvParam() only appends `env` when envId is truthy, so a
|
||||
* single-environment install's own "deploy" calls never send one either,
|
||||
* and every one of ITS runs is recorded with environmentId === null. The
|
||||
* route now resolves an omitted `env` to exactly that filter. onMount
|
||||
* below fetches unconditionally for that reason -- there is no longer a
|
||||
* distinct "no environment selected" state to guard against here; the
|
||||
* type this component receives (number | null) has no third value that
|
||||
* could mean anything else.
|
||||
*/
|
||||
import { onMount } from 'svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import {
|
||||
Loader2,
|
||||
ChevronDown,
|
||||
Check,
|
||||
X,
|
||||
Clock,
|
||||
Hand,
|
||||
Timer,
|
||||
Webhook,
|
||||
Power,
|
||||
AlertTriangle,
|
||||
Trash2
|
||||
} from 'lucide-svelte';
|
||||
import { formatRelativeTime, formatDateTime } from '$lib/stores/settings';
|
||||
import { appendEnvParam } from '$lib/stores/environment';
|
||||
import { buildDeployRunView, buildDeployLogPanelState, type DeployRun } from '$lib/utils/deploy-run-view';
|
||||
import LogViewer from '$lib/components/LogViewer.svelte';
|
||||
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
|
||||
|
||||
interface Props {
|
||||
stackName: string;
|
||||
envId: number | null;
|
||||
// Forwarded to LogViewer so an expanded run's log follows the caller's editor
|
||||
// theme toggle instead of LogViewer's own 'dark' default.
|
||||
theme?: 'light' | 'dark';
|
||||
}
|
||||
let { stackName, envId, theme = 'dark' }: Props = $props();
|
||||
|
||||
let runs = $state<DeployRun[]>([]);
|
||||
let loading = $state(true);
|
||||
let loadError = $state<string | null>(null);
|
||||
let expanded = $state<Set<number>>(new Set());
|
||||
|
||||
/** One entry per run whose log has been requested. 'loading'/'loaded'/'missing'/'error'
|
||||
* -- deliberately not reused for "not yet requested" (absent from the map), so a
|
||||
* fresh row doesn't render as if a fetch had already failed. */
|
||||
interface LogFetch {
|
||||
status: 'loading' | 'loaded' | 'missing' | 'error';
|
||||
text?: string;
|
||||
error?: string;
|
||||
}
|
||||
let logs = $state<Map<number, LogFetch>>(new Map());
|
||||
let confirmDeleteId = $state<number | null>(null);
|
||||
let deletingIds = $state<Set<number>>(new Set());
|
||||
|
||||
function toggle(run: DeployRun) {
|
||||
const s = new Set(expanded);
|
||||
if (s.has(run.id)) {
|
||||
s.delete(run.id);
|
||||
} else {
|
||||
s.add(run.id);
|
||||
void loadLog(run);
|
||||
}
|
||||
expanded = s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches a run's protocol text the first time its row opens. A prior 'error'
|
||||
* result is retried on the next open (transient network failures shouldn't
|
||||
* require a page reload to recover from); 'loading'/'loaded'/'missing' are all
|
||||
* left alone -- there is nothing a second fetch would tell us that the first
|
||||
* one (or the run's own details.logMissing) didn't already establish.
|
||||
*/
|
||||
async function loadLog(run: DeployRun) {
|
||||
const existing = logs.get(run.id);
|
||||
if (existing && existing.status !== 'error') return;
|
||||
|
||||
if (buildDeployLogPanelState(run).logMissing) {
|
||||
logs = new Map(logs).set(run.id, { status: 'missing' });
|
||||
return;
|
||||
}
|
||||
|
||||
logs = new Map(logs).set(run.id, { status: 'loading' });
|
||||
try {
|
||||
const res = await fetch(`/api/stacks/${encodeURIComponent(stackName)}/deploys/${run.id}/log`);
|
||||
if (res.status === 404) {
|
||||
logs = new Map(logs).set(run.id, { status: 'missing' });
|
||||
return;
|
||||
}
|
||||
if (!res.ok) {
|
||||
logs = new Map(logs).set(run.id, { status: 'error', error: `Failed to load log (${res.status})` });
|
||||
return;
|
||||
}
|
||||
const text = await res.text();
|
||||
logs = new Map(logs).set(run.id, { status: 'loaded', text });
|
||||
} catch {
|
||||
logs = new Map(logs).set(run.id, { status: 'error', error: 'Failed to load log.' });
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes both the database record and the on-disk log file (see the DELETE
|
||||
* route's own doc comment) -- there is no "delete just the log" option, so a
|
||||
* removed run disappears from the list entirely rather than turning into a
|
||||
* metadata-only row nobody can act on. */
|
||||
async function deleteRun(run: DeployRun) {
|
||||
deletingIds = new Set(deletingIds).add(run.id);
|
||||
try {
|
||||
const res = await fetch(`/api/stacks/${encodeURIComponent(stackName)}/deploys/${run.id}`, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => null);
|
||||
toast.error(data?.error || 'Failed to delete deploy run');
|
||||
return;
|
||||
}
|
||||
runs = runs.filter((r) => r.id !== run.id);
|
||||
const s = new Set(expanded);
|
||||
s.delete(run.id);
|
||||
expanded = s;
|
||||
const l = new Map(logs);
|
||||
l.delete(run.id);
|
||||
logs = l;
|
||||
toast.success('Deploy run deleted');
|
||||
} catch {
|
||||
toast.error('Failed to delete deploy run');
|
||||
} finally {
|
||||
const d = new Set(deletingIds);
|
||||
d.delete(run.id);
|
||||
deletingIds = d;
|
||||
confirmDeleteId = null;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
const res = await fetch(appendEnvParam(`/api/stacks/${encodeURIComponent(stackName)}/deploys`, envId));
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => null);
|
||||
loadError = data?.error || `Failed to load deploy history (${res.status})`;
|
||||
return;
|
||||
}
|
||||
const data = await res.json();
|
||||
runs = Array.isArray(data?.runs) ? data.runs : [];
|
||||
} catch {
|
||||
loadError = 'Failed to load deploy history.';
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
});
|
||||
|
||||
function statusBadge(status: string) {
|
||||
switch (status) {
|
||||
case 'success':
|
||||
return { cls: 'bg-emerald-500/15 text-emerald-500', icon: Check };
|
||||
case 'failed':
|
||||
return { cls: 'bg-red-500/15 text-red-500', icon: X };
|
||||
case 'running':
|
||||
return { cls: 'bg-sky-500/15 text-sky-500', icon: Loader2 };
|
||||
default:
|
||||
return { cls: 'bg-muted text-muted-foreground', icon: AlertTriangle };
|
||||
}
|
||||
}
|
||||
|
||||
function triggerIcon(triggeredBy: string) {
|
||||
switch (triggeredBy) {
|
||||
case 'cron':
|
||||
return Timer;
|
||||
case 'webhook':
|
||||
return Webhook;
|
||||
case 'startup':
|
||||
return Power;
|
||||
default:
|
||||
return Hand;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if loading}
|
||||
<div class="flex justify-center py-8"><Loader2 class="h-5 w-5 animate-spin text-muted-foreground" /></div>
|
||||
{:else if loadError}
|
||||
<div class="flex min-h-[40vh] flex-col items-center justify-center py-10 text-center">
|
||||
<AlertTriangle class="mb-3 h-10 w-10 text-muted-foreground/40" />
|
||||
<p class="text-sm text-muted-foreground">{loadError}</p>
|
||||
</div>
|
||||
{:else if runs.length === 0}
|
||||
<div class="flex min-h-[40vh] flex-col items-center justify-center py-10 text-center">
|
||||
<Clock class="mb-3 h-10 w-10 text-muted-foreground/40" />
|
||||
<p class="text-sm text-muted-foreground">No deploy runs yet.</p>
|
||||
<p class="mt-1 text-xs text-muted-foreground">Deploy this stack — its run history appears here.</p>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="space-y-1.5">
|
||||
{#each runs as run (run.id)}
|
||||
{@const view = buildDeployRunView(run)}
|
||||
{@const badge = statusBadge(run.status)}
|
||||
{@const BadgeIcon = badge.icon}
|
||||
{@const TrigIcon = triggerIcon(run.triggeredBy)}
|
||||
{@const isOpen = expanded.has(run.id)}
|
||||
{@const panelState = buildDeployLogPanelState(run)}
|
||||
{@const logEntry = logs.get(run.id)}
|
||||
<div class="rounded-md border border-zinc-200 dark:border-zinc-700">
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2.5 px-3 py-2 text-left text-xs hover:bg-muted/30"
|
||||
onclick={() => toggle(run)}
|
||||
>
|
||||
<ChevronDown class="h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform {isOpen ? '' : '-rotate-90'}" />
|
||||
<span class="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded {badge.cls}" title={view.statusLabel}>
|
||||
<BadgeIcon class="h-3 w-3 {run.status === 'running' ? 'animate-spin' : ''}" />
|
||||
</span>
|
||||
<span class="shrink-0" title={run.startedAt ? formatDateTime(run.startedAt, true) : ''}>
|
||||
{run.startedAt ? formatRelativeTime(run.startedAt) : '—'}
|
||||
</span>
|
||||
<span class="shrink-0 text-muted-foreground">{view.duration}</span>
|
||||
<span class="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded bg-muted text-muted-foreground" title={view.trigger}>
|
||||
<TrigIcon class="h-3 w-3" />
|
||||
</span>
|
||||
<span class="min-w-0 flex-1 truncate text-muted-foreground">
|
||||
{view.containerSummary} · {view.buildStatus}
|
||||
</span>
|
||||
{#if view.errorSummary}
|
||||
<span class="max-w-[300px] shrink truncate text-destructive" title={run.errorMessage || ''}>{view.errorSummary}</span>
|
||||
{/if}
|
||||
</button>
|
||||
{#if isOpen}
|
||||
<div class="border-t border-zinc-200 px-3 py-2.5 text-xs dark:border-zinc-700">
|
||||
<div class="grid grid-cols-2 gap-x-4 gap-y-1.5 sm:grid-cols-3">
|
||||
<div>
|
||||
<div class="text-muted-foreground">Containers</div>
|
||||
<div>{view.containerSummary}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-muted-foreground">Build</div>
|
||||
<div>{view.buildStatus}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-muted-foreground">Triggered by</div>
|
||||
<div>{view.trigger}</div>
|
||||
</div>
|
||||
</div>
|
||||
{#if view.optionChips.length > 0}
|
||||
<div class="mt-2 flex flex-wrap gap-1">
|
||||
{#each view.optionChips as chip}
|
||||
<span class="rounded-full bg-muted px-2 py-0.5 text-[10px] font-medium text-muted-foreground">{chip}</span>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
{#if view.imagesBuilt.length > 0 || view.imagesPulled.length > 0}
|
||||
<div class="mt-2 space-y-1">
|
||||
{#if view.imagesBuilt.length > 0}
|
||||
<div><span class="text-muted-foreground">Built:</span> {view.imagesBuilt.join(', ')}</div>
|
||||
{/if}
|
||||
{#if view.imagesPulled.length > 0}
|
||||
<div><span class="text-muted-foreground">Pulled:</span> {view.imagesPulled.join(', ')}</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{#if view.errorSummary}
|
||||
<!-- The task-17 spec called for the shortened last error line here (same
|
||||
text the collapsed row already truncates to) -- not the raw errorMessage,
|
||||
which is compose's full stderr and, for a failed run, duplicates almost
|
||||
everything the log panel below shows. One line of "what went wrong" is a
|
||||
useful recap next to the run's other details; the full text belongs in
|
||||
exactly one place, the LogViewer beneath it. -->
|
||||
<div class="mt-2 rounded-md border border-l-[3px] border-destructive/40 border-l-destructive bg-destructive/5 px-2 py-1.5">
|
||||
<span class="font-mono text-[11px] text-destructive/90">{view.errorSummary}</span>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="mt-3">
|
||||
<div class="mb-1 flex items-center justify-between">
|
||||
<span class="text-muted-foreground">Log</span>
|
||||
{#if panelState.deletable}
|
||||
<ConfirmPopover
|
||||
open={confirmDeleteId === run.id}
|
||||
action="Delete"
|
||||
itemType="deploy run"
|
||||
title="Delete this run"
|
||||
position="left"
|
||||
disabled={deletingIds.has(run.id)}
|
||||
onConfirm={() => deleteRun(run)}
|
||||
onOpenChange={(open) => (confirmDeleteId = open ? run.id : null)}
|
||||
>
|
||||
{#snippet children({ open })}
|
||||
{#if deletingIds.has(run.id)}
|
||||
<Loader2 class="h-3 w-3 animate-spin text-muted-foreground" />
|
||||
{:else}
|
||||
<Trash2 class="h-3 w-3 {open ? 'text-destructive' : 'text-muted-foreground hover:text-destructive'}" />
|
||||
{/if}
|
||||
{/snippet}
|
||||
</ConfirmPopover>
|
||||
{/if}
|
||||
</div>
|
||||
{#if panelState.truncated}
|
||||
<!-- The notice belongs directly above the viewer it describes, not
|
||||
among the run's other metadata -- it says something about the
|
||||
text below it, not about the run as a whole. -->
|
||||
<div class="mb-1 inline-flex items-center gap-1 rounded-full bg-amber-500/15 px-2 py-0.5 text-[10px] font-medium text-amber-600 dark:text-amber-400">
|
||||
<AlertTriangle class="h-2.5 w-2.5" /> Log truncated
|
||||
</div>
|
||||
{/if}
|
||||
{#if panelState.logMissing || logEntry?.status === 'missing'}
|
||||
<!-- A confirmed-gone log file reads the same as an empty one if it's
|
||||
just handed to LogViewer with logs="" -- the two mean opposite
|
||||
things (nothing happened vs. the record of what happened is
|
||||
gone), so this case gets its own, unambiguous message instead. -->
|
||||
<div class="rounded-md border border-dashed border-zinc-300 px-3 py-6 text-center text-muted-foreground dark:border-zinc-700">
|
||||
Protocol no longer available.
|
||||
</div>
|
||||
{:else if logEntry?.status === 'error'}
|
||||
<div class="rounded-md border border-dashed border-destructive/40 px-3 py-6 text-center text-destructive">
|
||||
{logEntry.error}
|
||||
</div>
|
||||
{:else}
|
||||
<LogViewer
|
||||
logs={logEntry?.text ?? ''}
|
||||
loading={logEntry?.status !== 'loaded'}
|
||||
title={`${stackName}-deploy-${run.id}`}
|
||||
autoRefresh={false}
|
||||
autoScroll={false}
|
||||
class="h-64"
|
||||
{theme}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -1,10 +1,11 @@
|
||||
<script lang="ts">
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { Button, buttonVariants } from '$lib/components/ui/button';
|
||||
import * as Popover from '$lib/components/ui/popover';
|
||||
import { Checkbox } from '$lib/components/ui/checkbox';
|
||||
import { Label } from '$lib/components/ui/label';
|
||||
import { Loader2 } from 'lucide-svelte';
|
||||
import type { Snippet } from 'svelte';
|
||||
import { cn } from '$lib/utils';
|
||||
|
||||
interface Props {
|
||||
stackName: string;
|
||||
@@ -12,6 +13,33 @@
|
||||
disabled?: boolean;
|
||||
side?: 'top' | 'bottom';
|
||||
align?: 'start' | 'center' | 'end';
|
||||
/**
|
||||
* 'icon' (default): small icon-only trigger, as used standalone in the stack
|
||||
* grid rows -- the icon itself IS the action, there is no separate main button.
|
||||
* 'chevron': a small square trigger meant to sit flush against a separate,
|
||||
* directly-clickable main button (a split button), as used next to
|
||||
* "Save & redeploy" / "Create & Start" in StackModal. The main button is NOT
|
||||
* part of this component -- the caller renders it, wraps both in one flex
|
||||
* container, and gives the main button `rounded-r-none` / this trigger
|
||||
* `rounded-l-none` so they read as one control with two separate, independently
|
||||
* reachable click/focus targets (never one element that does different things
|
||||
* depending on where exactly it's clicked).
|
||||
*/
|
||||
triggerVariant?: 'icon' | 'chevron';
|
||||
/** Extra classes merged onto the trigger. */
|
||||
triggerClass?: string;
|
||||
/**
|
||||
* Initial state of the "Pull images" / "Build images" / "Force recreate"
|
||||
* checkboxes each time the popover opens. Re-read on every open (not just once
|
||||
* at mount) so a caller whose default is derived from live content (e.g. "does
|
||||
* the compose have a build: section right now") stays correct across repeated
|
||||
* opens.
|
||||
*/
|
||||
defaultPull?: boolean;
|
||||
defaultBuild?: boolean;
|
||||
defaultForceRecreate?: boolean;
|
||||
/** Short note shown under the checkboxes, e.g. explaining why Build is pre-checked. */
|
||||
reason?: string;
|
||||
onDeploy: (options: { pull: boolean; build: boolean; forceRecreate: boolean }) => Promise<void>;
|
||||
children: Snippet;
|
||||
}
|
||||
@@ -22,14 +50,20 @@
|
||||
disabled = false,
|
||||
side = 'top',
|
||||
align = 'end',
|
||||
triggerVariant = 'icon',
|
||||
triggerClass = '',
|
||||
defaultPull = true,
|
||||
defaultBuild = false,
|
||||
defaultForceRecreate = false,
|
||||
reason,
|
||||
onDeploy,
|
||||
children
|
||||
}: Props = $props();
|
||||
|
||||
let open = $state(false);
|
||||
let pull = $state(true);
|
||||
let build = $state(false);
|
||||
let forceRecreate = $state(false);
|
||||
let pull = $state(defaultPull);
|
||||
let build = $state(defaultBuild);
|
||||
let forceRecreate = $state(defaultForceRecreate);
|
||||
let deploying = $state(false);
|
||||
|
||||
async function handleDeploy() {
|
||||
@@ -45,6 +79,14 @@
|
||||
function handleTriggerClick(e: MouseEvent) {
|
||||
e.stopPropagation();
|
||||
if (disabled) return;
|
||||
if (!open) {
|
||||
// Re-seed from the current defaults on every open, not just once at mount --
|
||||
// defaultBuild in particular tracks the live compose content and can change
|
||||
// between two opens of the same popover.
|
||||
pull = defaultPull;
|
||||
build = defaultBuild;
|
||||
forceRecreate = defaultForceRecreate;
|
||||
}
|
||||
open = !open;
|
||||
}
|
||||
</script>
|
||||
@@ -54,10 +96,16 @@
|
||||
{#snippet child({ props })}
|
||||
<button
|
||||
type="button"
|
||||
title="Redeploy"
|
||||
title={triggerVariant === 'icon' ? 'Redeploy' : 'More deploy options'}
|
||||
{...props}
|
||||
onclick={handleTriggerClick}
|
||||
class="p-1 rounded hover:bg-muted transition-colors opacity-70 hover:opacity-100 cursor-pointer inline-flex items-center"
|
||||
{disabled}
|
||||
class={triggerVariant === 'chevron'
|
||||
? cn(buttonVariants({ variant: 'default', size: 'icon' }), 'rounded-l-none border-l border-primary-foreground/20', triggerClass)
|
||||
: cn(
|
||||
'p-1 rounded hover:bg-muted transition-colors opacity-70 hover:opacity-100 cursor-pointer inline-flex items-center',
|
||||
triggerClass
|
||||
)}
|
||||
>
|
||||
{@render children()}
|
||||
</button>
|
||||
@@ -80,6 +128,9 @@
|
||||
<Checkbox bind:checked={build} disabled={deploying} />
|
||||
<span class="text-xs">Build images</span>
|
||||
</label>
|
||||
{#if reason}
|
||||
<p class="text-2xs text-muted-foreground pl-6 -mt-1">{reason}</p>
|
||||
{/if}
|
||||
<label class="flex items-center gap-2 cursor-pointer">
|
||||
<Checkbox bind:checked={forceRecreate} disabled={deploying} />
|
||||
<span class="text-xs">Force recreate</span>
|
||||
|
||||
@@ -11,9 +11,10 @@
|
||||
import { SELECTOR_VARS } from '$lib/utils/bulk-selector';
|
||||
import { classifyMarker, resolvedRefVarNames } from '$lib/utils/invault-markers';
|
||||
import { applyQuickFix, findingKey } from '$lib/utils/compose-quick-fix';
|
||||
import { Layers, Save, Play, Code, GitGraph, GitBranch, GitCommitHorizontal, Github, Loader2, AlertCircle, X, Sun, Moon, TriangleAlert, GripVertical, FolderOpen, Copy, Check, XCircle, MapPin, ArrowRight, ArrowDown, Info, Box, FolderSync, Archive, ListChecks } from 'lucide-svelte';
|
||||
import { Layers, Save, Play, Code, GitGraph, GitBranch, GitCommitHorizontal, Github, Loader2, AlertCircle, X, Sun, Moon, TriangleAlert, GripVertical, GripHorizontal, FolderOpen, Copy, Check, XCircle, MapPin, ArrowRight, ArrowDown, Info, Box, FolderSync, Archive, ListChecks, History, ChevronDown } from 'lucide-svelte';
|
||||
import ComposeValidatePanel from './ComposeValidatePanel.svelte';
|
||||
import BackupPanel from '../containers/BackupPanel.svelte';
|
||||
import DeploysPanel from './DeploysPanel.svelte';
|
||||
import { volumesForStack, type VolumeInfo } from '$lib/utils/mounts';
|
||||
import { fetchBackupExecutions } from '$lib/utils/backup';
|
||||
import type { Component } from 'svelte';
|
||||
@@ -32,12 +33,33 @@
|
||||
import * as Alert from '$lib/components/ui/alert';
|
||||
import { ErrorDialog } from '$lib/components/ui/error-dialog';
|
||||
import { readJobResponse } from '$lib/utils/sse-fetch';
|
||||
import { saveCloseTiming } from '$lib/utils/save-close-policy';
|
||||
import { clampNumber } from '$lib/utils/clamp-number';
|
||||
import LogViewer from '$lib/components/LogViewer.svelte';
|
||||
import { formatRunStatus } from '$lib/utils/run-status';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import ComposeGraphViewer from './ComposeGraphViewer.svelte';
|
||||
import RedeployPopover from './RedeployPopover.svelte';
|
||||
import { hasBuildSection as detectBuildSection } from '$lib/utils/compose-build-detect';
|
||||
|
||||
|
||||
// localStorage key for persisted split ratio
|
||||
const STORAGE_KEY_SPLIT = 'dockhand-stack-modal-split';
|
||||
// Own key: this ratio has nothing to do with the compose/env split ratio above --
|
||||
// reusing STORAGE_KEY_SPLIT would mean resizing the editor/env divider also resizes
|
||||
// the unrelated output panel on the next load.
|
||||
const STORAGE_KEY_OUTPUT_SPLIT = 'dockhand-stack-modal-output-split';
|
||||
|
||||
// How long a successful deploy leaves the modal open before auto-closing, so the
|
||||
// operator still glimpses the success and the compose output before it goes away
|
||||
// (operator decision, 30.08.2026 -- see save-close-policy.ts). The plain-save flash-
|
||||
// then-close delay (500ms, below) predates this and is left as it was.
|
||||
const DEPLOY_SUCCESS_CLOSE_DELAY_MS = 1500;
|
||||
|
||||
// Options picked in the RedeployPopover next to "Save & redeploy" / "Create & Start"
|
||||
// (see the pull/build/forceRecreate contract RedeployPopover.svelte already uses for
|
||||
// the stack-grid redeploy actions).
|
||||
type DeployOptions = { pull: boolean; build: boolean; forceRecreate: boolean };
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
@@ -115,7 +137,29 @@
|
||||
let loadError = $state<string | null>(null);
|
||||
let errors = $state<{ stackName?: string; compose?: string }>({});
|
||||
let composeContent = $state('');
|
||||
let activeTab = $state<'editor' | 'graph' | 'backups'>('editor');
|
||||
// Whether the current compose content declares a build: section for any service --
|
||||
// pre-checks "Build images" in the Save & redeploy / Create & Start popover
|
||||
// (RedeployPopover's defaultBuild). Logic lives in compose-build-detect.ts, not
|
||||
// inline, so it has its own unit test independent of mounting this component.
|
||||
let hasBuildSection = $derived(detectBuildSection(composeContent));
|
||||
// Single source of truth for "what does a direct click on the main button do",
|
||||
// shared between the button's own onclick AND the split-button popover's
|
||||
// defaultPull/defaultBuild/defaultForceRecreate props next to it -- so the two
|
||||
// paths (one-click vs pick-then-Deploy) can never drift into deploying with
|
||||
// different options for what looks like the same defaults.
|
||||
//
|
||||
// pull is always false on both: Save/Create already run against whatever images
|
||||
// are already local, pulling is an explicit extra step the operator reaches for
|
||||
// via the popover, not something either main button does silently.
|
||||
//
|
||||
// forceRecreate differs: Save & redeploy defaults to true, preserving the
|
||||
// endpoint's prior always-on behavior (env var changes need --force-recreate to
|
||||
// take effect) now that it's a real choice instead of hardcoded. Create & Start
|
||||
// defaults to false -- there is nothing to recreate on a stack that doesn't exist
|
||||
// yet.
|
||||
let saveRedeployDefaults = $derived<DeployOptions>({ pull: false, build: hasBuildSection, forceRecreate: true });
|
||||
let createStartDefaults = $derived<DeployOptions>({ pull: false, build: hasBuildSection, forceRecreate: false });
|
||||
let activeTab = $state<'editor' | 'graph' | 'backups' | 'deploys'>('editor');
|
||||
let backupCount = $state(0);
|
||||
let backupTally = $state<{ ok: number; failed: number }>({ ok: 0, failed: 0 });
|
||||
let showConfirmClose = $state(false);
|
||||
@@ -174,6 +218,47 @@
|
||||
// Error dialog state
|
||||
let operationError = $state<{ title: string; message: string; details?: string } | null>(null);
|
||||
|
||||
// Live compose output for deploying operations (Create & Start, Save & redeploy),
|
||||
// rendered inline below the editor instead of in a separate window -- the modal
|
||||
// stays open while it runs, and afterwards for exactly as long as saveCloseTiming
|
||||
// (see save-close-policy.ts) says it should, so the output stays visible where the
|
||||
// result or the error it might explain also lives.
|
||||
let outputTitle = $state('');
|
||||
let outputLines = $state<string[]>([]);
|
||||
let outputRunning = $state(false);
|
||||
let outputOk = $state<boolean | undefined>(undefined);
|
||||
let outputMs = $state<number | undefined>(undefined);
|
||||
let outputExitCode = $state<number | undefined>(undefined);
|
||||
let outputStartedAt = 0;
|
||||
|
||||
function startOutput(title: string) {
|
||||
outputTitle = title;
|
||||
outputLines = [];
|
||||
outputRunning = true;
|
||||
outputStartedAt = Date.now();
|
||||
outputOk = undefined;
|
||||
outputMs = undefined;
|
||||
outputExitCode = undefined;
|
||||
}
|
||||
|
||||
function appendOutputLine(line: string) {
|
||||
outputLines = [...outputLines, line];
|
||||
}
|
||||
|
||||
function finishOutput(output: string | undefined, ok: boolean, exitCode?: number) {
|
||||
outputRunning = false;
|
||||
outputOk = ok;
|
||||
outputMs = Date.now() - outputStartedAt;
|
||||
outputExitCode = exitCode;
|
||||
if (outputLines.length === 0 && output) {
|
||||
outputLines = output.split('\n');
|
||||
}
|
||||
}
|
||||
|
||||
const outputStatusLine = $derived(
|
||||
formatRunStatus({ running: outputRunning, ok: outputOk, ms: outputMs, exitCode: outputExitCode })
|
||||
);
|
||||
|
||||
// Stack exists warning dialog state
|
||||
let showExistsWarning = $state(false);
|
||||
|
||||
@@ -395,6 +480,11 @@
|
||||
let pathChangeOldDir = $state<string | null>(null); // Old directory to move files from
|
||||
let pathChangeFileCount = $state(0); // Number of files in old directory
|
||||
let pendingSaveRestart = $state(false); // Whether user clicked "Save & restart" vs "Save"
|
||||
// Pull/build/forceRecreate chosen in the "Save & redeploy" RedeployPopover (see
|
||||
// handleSave below) -- carried across the path-change confirmation dialog the same
|
||||
// way pendingSaveRestart is, so re-entering handleSave() after the user confirms a
|
||||
// path move still deploys with the options they actually picked.
|
||||
let pendingSaveOptions = $state<DeployOptions | undefined>(undefined);
|
||||
|
||||
// Browse confirmation dialog state (when selecting different file would replace content)
|
||||
let showBrowseConfirm = $state(false);
|
||||
@@ -892,6 +982,18 @@
|
||||
let isDraggingSplit = $state(false);
|
||||
let containerRef: HTMLDivElement | null = $state(null);
|
||||
|
||||
// Resizable output-panel split state -- height (not width) of the live output
|
||||
// panel below the editor, as a percentage of the combined editor+output area.
|
||||
// Bounds (15/70, default 30): the editor must stay usable even at the output
|
||||
// panel's largest size (30% left for the editor is several lines, not one), and
|
||||
// the output panel must stay usable even at its smallest (15% is enough for the
|
||||
// status line plus a handful of log lines).
|
||||
const OUTPUT_SPLIT_MIN = 15;
|
||||
const OUTPUT_SPLIT_MAX = 70;
|
||||
let outputSplitRatio = $state(30); // percentage of the editor+output area given to output
|
||||
let isDraggingOutputSplit = $state(false);
|
||||
let outputAreaRef: HTMLDivElement | null = $state(null);
|
||||
|
||||
// Debounce timer for validation
|
||||
let validateTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
@@ -1076,6 +1178,15 @@
|
||||
}
|
||||
}
|
||||
|
||||
// Load saved output-panel split ratio
|
||||
const savedOutputSplit = localStorage.getItem(STORAGE_KEY_OUTPUT_SPLIT);
|
||||
if (savedOutputSplit) {
|
||||
const ratio = parseFloat(savedOutputSplit);
|
||||
if (!isNaN(ratio) && ratio >= OUTPUT_SPLIT_MIN && ratio <= OUTPUT_SPLIT_MAX) {
|
||||
outputSplitRatio = ratio;
|
||||
}
|
||||
}
|
||||
|
||||
// Add global mouse event listeners for split dragging
|
||||
window.addEventListener('mousemove', handleMouseMove);
|
||||
window.addEventListener('mouseup', handleMouseUp);
|
||||
@@ -1105,6 +1216,12 @@
|
||||
isDraggingSplit = true;
|
||||
}
|
||||
|
||||
// Output-panel split drag handler (vertical drag -- resizes height, not width).
|
||||
function startOutputSplitDrag(e: MouseEvent) {
|
||||
e.preventDefault();
|
||||
isDraggingOutputSplit = true;
|
||||
}
|
||||
|
||||
// Validate side-panel width (px), drag-resizable, persisted.
|
||||
const STORAGE_KEY_VALIDATE_W = 'dockhand-validate-panel-width';
|
||||
let validatePanelWidth = $state(
|
||||
@@ -1123,7 +1240,7 @@
|
||||
if (isDraggingSplit && containerRef) {
|
||||
const rect = containerRef.getBoundingClientRect();
|
||||
const newRatio = ((e.clientX - rect.left) / rect.width) * 100;
|
||||
splitRatio = Math.max(30, Math.min(80, newRatio));
|
||||
splitRatio = clampNumber(newRatio, 30, 80);
|
||||
}
|
||||
if (isDraggingValidate && editorRowRef) {
|
||||
const rect = editorRowRef.getBoundingClientRect();
|
||||
@@ -1131,7 +1248,14 @@
|
||||
const w = rect.right - e.clientX;
|
||||
// Floor at 320px: below that the header's title + count chips + re-check button
|
||||
// no longer fit on one line and start clipping.
|
||||
validatePanelWidth = Math.max(320, Math.min(560, w));
|
||||
validatePanelWidth = clampNumber(w, 320, 560);
|
||||
}
|
||||
if (isDraggingOutputSplit && outputAreaRef) {
|
||||
const rect = outputAreaRef.getBoundingClientRect();
|
||||
// output panel is on the bottom: its height = distance from cursor to the
|
||||
// area's bottom edge, as a percentage of the whole editor+output area.
|
||||
const newRatio = ((rect.bottom - e.clientY) / rect.height) * 100;
|
||||
outputSplitRatio = clampNumber(newRatio, OUTPUT_SPLIT_MIN, OUTPUT_SPLIT_MAX);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1145,6 +1269,10 @@
|
||||
isDraggingValidate = false;
|
||||
localStorage.setItem(STORAGE_KEY_VALIDATE_W, String(validatePanelWidth));
|
||||
}
|
||||
if (isDraggingOutputSplit) {
|
||||
isDraggingOutputSplit = false;
|
||||
localStorage.setItem(STORAGE_KEY_OUTPUT_SPLIT, outputSplitRatio.toString());
|
||||
}
|
||||
}
|
||||
|
||||
// Populate the backup picker's volume/bind list from this stack's containers'
|
||||
@@ -1333,7 +1461,7 @@
|
||||
composeContent = newContent;
|
||||
}
|
||||
|
||||
async function handleCreate(start: boolean = false, persistenceAcked = false) {
|
||||
async function handleCreate(start: boolean = false, persistenceAcked = false, deployOptions?: DeployOptions) {
|
||||
errors = {};
|
||||
let hasErrors = false;
|
||||
|
||||
@@ -1355,7 +1483,7 @@
|
||||
|
||||
// Warn if the chosen compose path won't survive a recreate (#1524) - before creating.
|
||||
if (!persistenceAcked && workingComposePath.trim()) {
|
||||
return guardComposePersistence(workingComposePath.trim(), () => handleCreate(start, true));
|
||||
return guardComposePersistence(workingComposePath.trim(), () => handleCreate(start, true, deployOptions));
|
||||
}
|
||||
|
||||
const envId = $currentEnvironment?.id ?? null;
|
||||
@@ -1414,6 +1542,16 @@
|
||||
|
||||
requestBody.secretProviderId = formSecretProviderId;
|
||||
|
||||
// Only meaningful when start is true -- deployOptions is undefined for the
|
||||
// plain "Create" button, which never reaches deployStack server-side anyway.
|
||||
if (start && deployOptions) {
|
||||
requestBody.pull = deployOptions.pull;
|
||||
requestBody.build = deployOptions.build;
|
||||
requestBody.forceRecreate = deployOptions.forceRecreate;
|
||||
}
|
||||
|
||||
if (start) startOutput(`Starting ${newStackName.trim()}`);
|
||||
|
||||
// Create the stack
|
||||
response = await fetch(appendEnvParam('/api/stacks', envId), {
|
||||
method: 'POST',
|
||||
@@ -1422,7 +1560,14 @@
|
||||
});
|
||||
|
||||
// When start=true, response is a job or JSON; when start=false, it's plain JSON
|
||||
const data = start ? await readJobResponse(response) : await response.json();
|
||||
const data = start
|
||||
? await readJobResponse(response, (line) => appendOutputLine(line))
|
||||
: await response.json();
|
||||
if (start) finishOutput(
|
||||
typeof data.output === 'string' ? data.output : undefined,
|
||||
Boolean(data.success),
|
||||
typeof data.exitCode === 'number' ? data.exitCode : undefined
|
||||
);
|
||||
|
||||
if (!response.ok && !data.success) {
|
||||
throw new Error((typeof data.error === 'string' ? data.error : data.message) || 'Failed to create stack');
|
||||
@@ -1435,8 +1580,28 @@
|
||||
|
||||
toast.success(`Created stack "${newStackName.trim()}"`);
|
||||
onSuccess();
|
||||
handleClose();
|
||||
switch (saveCloseTiming(start, Boolean(data.success))) {
|
||||
case 'close':
|
||||
handleClose();
|
||||
break;
|
||||
case 'close-delayed':
|
||||
setTimeout(() => handleClose(), DEPLOY_SUCCESS_CLOSE_DELAY_MS);
|
||||
break;
|
||||
case 'stay-open':
|
||||
// Reachable only if a future change to the create/deploy endpoint ever
|
||||
// resolves without throwing on failure -- today both throw checks above
|
||||
// always catch a failed deploy first, so this case is currently dead code
|
||||
// at this exact call site. Kept so the switch stays exhaustive and this
|
||||
// call site doesn't silently start closing on failure if that changes.
|
||||
break;
|
||||
}
|
||||
} catch (e: any) {
|
||||
// The success path above already calls finishOutput with the server's real
|
||||
// ok/exitCode before it throws (a deploy that ran but reported failure).
|
||||
// Only mark the run failed here if it never got that far -- overwriting a
|
||||
// real exit code with `undefined` would erase the very thing the docked
|
||||
// output panel exists to show.
|
||||
if (start && outputRunning) finishOutput(undefined, false);
|
||||
operationError = {
|
||||
title: 'Failed to create stack',
|
||||
message: e.message || 'An error occurred while creating the stack',
|
||||
@@ -1455,7 +1620,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSave(restart = false, moveFromDir: string | null | undefined = undefined, persistenceAcked = false) {
|
||||
async function handleSave(restart = false, moveFromDir: string | null | undefined = undefined, persistenceAcked = false, deployOptions?: DeployOptions) {
|
||||
errors = {};
|
||||
|
||||
// Validate compose content (unless file location is needed and we have a path)
|
||||
@@ -1493,7 +1658,7 @@
|
||||
// Non-persisted path is the more serious warning - surface it first (#1524).
|
||||
if (checkData.persistenceWarning && !persistenceAcked) {
|
||||
persistenceWarnText = checkData.persistenceWarning;
|
||||
persistenceWarnProceed = () => handleSave(restart, moveFromDir, true);
|
||||
persistenceWarnProceed = () => handleSave(restart, moveFromDir, true, deployOptions);
|
||||
showPersistenceWarn = true;
|
||||
return;
|
||||
}
|
||||
@@ -1502,6 +1667,7 @@
|
||||
pathChangeOldDir = checkData.oldDir;
|
||||
pathChangeFileCount = checkData.fileCount;
|
||||
pendingSaveRestart = restart;
|
||||
pendingSaveOptions = deployOptions;
|
||||
showPathChangeConfirm = true;
|
||||
return;
|
||||
}
|
||||
@@ -1556,6 +1722,14 @@
|
||||
|
||||
requestBody.secretProviderId = formSecretProviderId;
|
||||
|
||||
// Only meaningful when restart is true -- deployOptions is undefined for the
|
||||
// plain "Save" button, which never reaches deployStack server-side anyway.
|
||||
if (restart && deployOptions) {
|
||||
requestBody.pull = deployOptions.pull;
|
||||
requestBody.build = deployOptions.build;
|
||||
requestBody.forceRecreate = deployOptions.forceRecreate;
|
||||
}
|
||||
|
||||
// Save env files BEFORE compose to ensure deploy reads fresh values
|
||||
// Save raw content to .env file (non-secrets only, comments preserved)
|
||||
const rawEnvResponse = await fetch(
|
||||
@@ -1601,6 +1775,8 @@
|
||||
);
|
||||
}
|
||||
|
||||
if (restart) startOutput(`Redeploying ${stackName}`);
|
||||
|
||||
// Save compose file (with optional paths) - after env so deploy reads fresh .env
|
||||
const response = await fetch(
|
||||
appendEnvParam(`/api/stacks/${encodeURIComponent(stackName)}/compose`, envId),
|
||||
@@ -1612,7 +1788,14 @@
|
||||
);
|
||||
|
||||
// When restart=true, response is a job or JSON; when restart=false, it's plain JSON
|
||||
const data = restart ? await readJobResponse(response) : await response.json();
|
||||
const data = restart
|
||||
? await readJobResponse(response, (line) => appendOutputLine(line))
|
||||
: await response.json();
|
||||
if (restart) finishOutput(
|
||||
typeof data.output === 'string' ? data.output : undefined,
|
||||
Boolean(data.success),
|
||||
typeof data.exitCode === 'number' ? data.exitCode : undefined
|
||||
);
|
||||
|
||||
if (!response.ok && !data.success) {
|
||||
throw new Error((typeof data.error === 'string' ? data.error : data.message) || 'Failed to save compose file');
|
||||
@@ -1625,13 +1808,26 @@
|
||||
toast.success(restart ? 'Stack applied' : 'Stack saved');
|
||||
onSuccess();
|
||||
|
||||
if (!restart) {
|
||||
// Show success briefly then close
|
||||
setTimeout(() => handleClose(), 500);
|
||||
} else {
|
||||
handleClose();
|
||||
switch (saveCloseTiming(restart, Boolean(data.success))) {
|
||||
case 'close':
|
||||
// Show success briefly then close.
|
||||
setTimeout(() => handleClose(), 500);
|
||||
break;
|
||||
case 'close-delayed':
|
||||
setTimeout(() => handleClose(), DEPLOY_SUCCESS_CLOSE_DELAY_MS);
|
||||
break;
|
||||
case 'stay-open':
|
||||
// Reachable only if a future change to the compose/deploy endpoint ever
|
||||
// resolves without throwing on failure -- today both throw checks above
|
||||
// always catch a failed deploy first, so this case is currently dead code
|
||||
// at this exact call site. Kept so the switch stays exhaustive and this
|
||||
// call site doesn't silently start closing on failure if that changes.
|
||||
break;
|
||||
}
|
||||
} catch (e: any) {
|
||||
// Same reasoning as handleCreate's catch block: don't clobber a real
|
||||
// ok/exitCode that finishOutput already recorded before this throw.
|
||||
if (restart && outputRunning) finishOutput(undefined, false);
|
||||
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'),
|
||||
@@ -1645,14 +1841,14 @@
|
||||
// Handle path change confirmation - move files to new location and proceed
|
||||
function confirmPathChangeAndMove() {
|
||||
showPathChangeConfirm = false;
|
||||
handleSave(pendingSaveRestart, pathChangeOldDir);
|
||||
handleSave(pendingSaveRestart, pathChangeOldDir, false, pendingSaveOptions);
|
||||
}
|
||||
|
||||
// Handle path change - keep old files and proceed (just save without moving)
|
||||
function confirmPathChangeKeepFiles() {
|
||||
showPathChangeConfirm = false;
|
||||
// Pass empty string to skip move check (undefined means "not checked yet")
|
||||
handleSave(pendingSaveRestart, '');
|
||||
handleSave(pendingSaveRestart, '', false, pendingSaveOptions);
|
||||
}
|
||||
|
||||
function tryClose() {
|
||||
@@ -1706,6 +1902,7 @@
|
||||
pathChangeOldDir = null;
|
||||
pathChangeFileCount = 0;
|
||||
pendingSaveRestart = false;
|
||||
pendingSaveOptions = undefined;
|
||||
// Reset browse confirmation state
|
||||
showBrowseConfirm = false;
|
||||
pendingBrowsePath = null;
|
||||
@@ -1734,6 +1931,23 @@
|
||||
validateLoading = false;
|
||||
validateActiveLine = null;
|
||||
validateSeq++;
|
||||
// Same reasoning for the docked deploy output: without this, reopening the
|
||||
// modal for a *different* stack would still show the previous stack's title,
|
||||
// lines and status ("Redeploying A" / "Succeeded" while looking at stack B).
|
||||
// A reopen of the *same* stack while its own deploy is still running loses the
|
||||
// lines accumulated so far, but only until the next line arrives (the poll loop
|
||||
// in sse-fetch.ts keeps running regardless of this modal's open state, same as
|
||||
// ComposeOutputModal) or the job finishes -- finishOutput's `outputLines.length
|
||||
// === 0 && output` fallback then refills the whole transcript from the job's
|
||||
// final output. That brief, self-correcting gap is preferable to a stale result
|
||||
// silently misattributed to the wrong stack.
|
||||
outputTitle = '';
|
||||
outputLines = [];
|
||||
outputRunning = false;
|
||||
outputOk = undefined;
|
||||
outputMs = undefined;
|
||||
outputExitCode = undefined;
|
||||
outputStartedAt = 0;
|
||||
if (mode === 'edit' && stackName) {
|
||||
loadComposeFile().then(() => {
|
||||
// Auto-validate after loading
|
||||
@@ -1953,8 +2167,28 @@
|
||||
{#if backupTally.failed > 0}<span class="inline-flex items-center gap-0.5 rounded-full bg-red-500/15 px-1.5 text-[10px] font-semibold text-red-500"><X class="w-2.5 h-2.5" />{backupTally.failed}</span>{/if}
|
||||
</button>
|
||||
{/if}
|
||||
<!-- Deploys tab: recorded run history for this stack (Task 17). Same gate
|
||||
shape as Backups above minus the beta flag -- hidden for untracked
|
||||
stacks (no compose file means no deploy history either) and only in
|
||||
edit mode, where stackName/envId are actually known. -->
|
||||
{#if mode === 'edit' && !needsFileLocation}
|
||||
<button
|
||||
type="button"
|
||||
class="relative -mb-px flex items-center gap-1.5 border-b-2 px-3 py-2 text-sm transition-colors {activeTab === 'deploys' ? 'border-primary text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'}"
|
||||
onclick={() => activeTab = 'deploys'}
|
||||
>
|
||||
<History class="h-3.5 w-3.5" /> Deploys
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Wrapper spanning the editor area + the live output panel below it, so the
|
||||
output panel's height can be a percentage of THIS combined space rather than
|
||||
of the whole dialog (which also includes the fixed header/tabs/footer). -->
|
||||
<div
|
||||
bind:this={outputAreaRef}
|
||||
class="flex-1 min-h-0 flex flex-col {isDraggingOutputSplit ? 'select-none' : ''}"
|
||||
>
|
||||
<div class="flex-1 overflow-hidden flex flex-col min-h-0">
|
||||
{#if errors.compose}
|
||||
<Alert.Root variant="destructive" class="mx-6 mt-4">
|
||||
@@ -2288,11 +2522,53 @@
|
||||
onTally={(t) => (backupTally = t)}
|
||||
/>
|
||||
</div>
|
||||
{:else if activeTab === 'deploys' && !needsFileLocation}
|
||||
<!-- Deploys tab (never for untracked stacks — same reasoning as Backups above) -->
|
||||
<div class="h-full flex-1 overflow-auto p-4">
|
||||
<DeploysPanel {stackName} envId={$currentEnvironment?.id ?? null} theme={editorTheme} />
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Live output for Create & Start / Save & redeploy, rendered below the editor instead
|
||||
of handing the user off to a separate window (see save-close-policy.ts for how long
|
||||
the dialog then stays open). Only takes up space once there is something to show,
|
||||
and only then does its resize divider exist -- a handle that drags nothing is worse
|
||||
than no handle. -->
|
||||
{#if outputRunning || outputLines.length > 0}
|
||||
<!-- Resizable divider (height, not width -- drag up/down to resize the output panel) -->
|
||||
<div
|
||||
class="h-1 shrink-0 bg-zinc-200 dark:bg-zinc-700 hover:bg-blue-400 dark:hover:bg-blue-500 cursor-row-resize transition-colors flex items-center justify-center group {isDraggingOutputSplit ? 'bg-blue-500 dark:bg-blue-400' : ''}"
|
||||
onmousedown={startOutputSplitDrag}
|
||||
role="separator"
|
||||
aria-orientation="horizontal"
|
||||
tabindex="0"
|
||||
>
|
||||
<div class="w-8 h-4 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity {isDraggingOutputSplit ? 'opacity-100' : ''}">
|
||||
<GripHorizontal class="w-3 h-3 text-white" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="shrink-0 flex flex-col min-h-0" style="height: {outputSplitRatio}%">
|
||||
<div class="px-5 py-1.5 text-xs text-zinc-500 dark:text-zinc-400 flex items-center gap-2 flex-shrink-0">
|
||||
{#if outputRunning}
|
||||
<Loader2 class="w-3 h-3 animate-spin" />
|
||||
{/if}
|
||||
{outputTitle} — {outputStatusLine}
|
||||
</div>
|
||||
<LogViewer
|
||||
logs={outputLines.join('\n')}
|
||||
title={outputTitle}
|
||||
autoRefresh={false}
|
||||
autoScroll={outputRunning}
|
||||
class="flex-1 min-h-0"
|
||||
theme={editorTheme}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<div class="px-5 py-2.5 border-t border-zinc-200 dark:border-zinc-700 flex items-center justify-between flex-shrink-0">
|
||||
<div class="text-xs text-zinc-500 dark:text-zinc-400">
|
||||
@@ -2325,15 +2601,41 @@
|
||||
Create
|
||||
{/if}
|
||||
</Button>
|
||||
<Button onclick={() => handleCreate(true)} disabled={saving}>
|
||||
{#if saving}
|
||||
<Loader2 class="w-4 h-4 animate-spin" />
|
||||
Starting...
|
||||
{:else}
|
||||
<Play class="w-4 h-4" />
|
||||
Create & Start
|
||||
{/if}
|
||||
</Button>
|
||||
<!-- Split button: the label itself stays a direct, one-click action (the
|
||||
common case) with the current defaults baked in; the chevron opens a
|
||||
popover to override pull/build/forceRecreate before deploying. Two
|
||||
separate <button> elements, both independently reachable by keyboard --
|
||||
never one element whose behavior depends on click position. -->
|
||||
<div class="inline-flex">
|
||||
<Button
|
||||
class="rounded-r-none"
|
||||
onclick={() => handleCreate(true, false, createStartDefaults)}
|
||||
disabled={saving}
|
||||
>
|
||||
{#if saving}
|
||||
<Loader2 class="w-4 h-4 animate-spin" />
|
||||
Starting...
|
||||
{:else}
|
||||
<Play class="w-4 h-4" />
|
||||
Create & Start
|
||||
{/if}
|
||||
</Button>
|
||||
<RedeployPopover
|
||||
stackName={newStackName}
|
||||
envId={$currentEnvironment?.id ?? null}
|
||||
disabled={saving}
|
||||
triggerVariant="chevron"
|
||||
defaultPull={createStartDefaults.pull}
|
||||
defaultBuild={createStartDefaults.build}
|
||||
defaultForceRecreate={createStartDefaults.forceRecreate}
|
||||
reason={hasBuildSection ? 'Auto-checked: this compose file has a build: section' : undefined}
|
||||
onDeploy={(options) => handleCreate(true, false, options)}
|
||||
>
|
||||
{#snippet children()}
|
||||
<ChevronDown class="w-4 h-4" />
|
||||
{/snippet}
|
||||
</RedeployPopover>
|
||||
</div>
|
||||
{:else if !readonly}
|
||||
<!-- Edit mode buttons -->
|
||||
<Button variant="outline" class="w-24" onclick={() => handleSave(false)} disabled={saving || loading || (needsFileLocation && !workingComposePath.trim())}>
|
||||
@@ -2345,15 +2647,37 @@
|
||||
Save
|
||||
{/if}
|
||||
</Button>
|
||||
<Button class="w-36" onclick={() => handleSave(true)} disabled={saving || loading || (needsFileLocation && !workingComposePath.trim())}>
|
||||
{#if saving && savingWithRestart}
|
||||
<Loader2 class="w-4 h-4 animate-spin" />
|
||||
Deploying...
|
||||
{:else}
|
||||
<Play class="w-4 h-4" />
|
||||
Save & redeploy
|
||||
{/if}
|
||||
</Button>
|
||||
<!-- Same split-button shape as Create & Start above. -->
|
||||
<div class="inline-flex">
|
||||
<Button
|
||||
class="w-36 rounded-r-none"
|
||||
onclick={() => handleSave(true, undefined, false, saveRedeployDefaults)}
|
||||
disabled={saving || loading || (needsFileLocation && !workingComposePath.trim())}
|
||||
>
|
||||
{#if saving && savingWithRestart}
|
||||
<Loader2 class="w-4 h-4 animate-spin" />
|
||||
Deploying...
|
||||
{:else}
|
||||
<Play class="w-4 h-4" />
|
||||
Save & redeploy
|
||||
{/if}
|
||||
</Button>
|
||||
<RedeployPopover
|
||||
{stackName}
|
||||
envId={$currentEnvironment?.id ?? null}
|
||||
disabled={saving || loading || (needsFileLocation && !workingComposePath.trim())}
|
||||
triggerVariant="chevron"
|
||||
defaultPull={saveRedeployDefaults.pull}
|
||||
defaultBuild={saveRedeployDefaults.build}
|
||||
defaultForceRecreate={saveRedeployDefaults.forceRecreate}
|
||||
reason={hasBuildSection ? 'Auto-checked: this compose file has a build: section' : undefined}
|
||||
onDeploy={(options) => handleSave(true, undefined, false, options)}
|
||||
>
|
||||
{#snippet children()}
|
||||
<ChevronDown class="w-4 h-4" />
|
||||
{/snippet}
|
||||
</RedeployPopover>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user