Files
sencho/e2e/editor-save-deploy.spec.ts
T
Anso 7c84969b31 fix(editor): harden save-deploy, node-switch, delete, and stats reactivity (#1188)
* fix(stacks): validate input, bound YAML parses, and reorder delete steps

Backend hardening covering three editor-served routes:

- `/:stackName/containers` GET adds an explicit `isValidStackName` guard so
  bad input is rejected at the call site even if the router-level param
  validator changes in future.
- `MAX_COMPOSE_PARSE_BYTES` (1 MiB) bounds the two `YAML.parse` callsites
  (`resolveAllEnvFilePaths`, `/services`) so a malformed or oversize compose
  cannot exhaust heap during routine env/service lookups.
- `DELETE /:stackName` is reordered to abort before any database cleanup
  if `FileSystemService.deleteStack` throws, keeping DB and FS in sync.
  Partial-failure responses now describe the resulting state in human
  terms instead of returning a generic 500.

Adds debug-mode entry-point traces (`[Stacks:debug] ...`) on save / down /
restart / delete handlers, all sanitised through `sanitizeForLog`. New
vitest covers the containers validator, the YAML size guard, and the
small-compose happy path.

* fix(editor): gate save-and-deploy on save success, abort stale loads

`saveFile` now returns a boolean: true on a successful PUT, false on any
failure. `handleSaveAndDeploy` short-circuits when save fails so a backend
500 on the compose write no longer slips through to a deploy with the
unsaved in-memory content. The diff-preview confirm path in ShellOverlays
applies the same guard.

`loadFile` now drives a per-hook `AbortController`. A stack switch, a
node switch (via `resetEditorState`), or hook unmount aborts the in-flight
GET chain so a late compose / env / containers / backup response from the
previous selection never overwrites freshly-loaded state.

`hasUnsavedChanges` is exported so EditorLayout can check it during the
node-switch lifecycle. New unit tests cover the boolean save contract and
the save-fail-blocks-deploy invariant.

* fix(editor): prompt on node switch when the editor has unsaved changes

Switching the active node previously called `resetEditorState()` without
checking the editor's dirty state, silently dropping in-progress edits.
The post-auth shell now intercepts the node-change effect: if the editor
is dirty, the attempted node is stashed via the existing
`pendingUnsavedNode` field, `pendingUnsavedLoad` is set to a sentinel
that routes `discardAndLoadPending` to `setActiveNode`, and `activeNode`
is reverted to the previous node so the dialog can be resolved without
losing content.

A re-entrant switch (clicking a third node while the dialog is still
open) is now ignored — the second switch reverts silently so the
dialog's anchor stays on the first attempt. When the previous node is no
longer in the registry and cannot be reverted to, the operator gets a
warning toast before the wipe so the loss is at least visible.

* fix(editor): split delete and deploy permission gates in the action bar

The action bar previously wrapped every affordance — including the Delete
menu item — in a single `can('stack:deploy')` check, even though the
backend route requires `stack:delete`. A user with `stack:deploy` only
saw a Delete button that 403'd, and a user with `stack:delete` only saw
no menu at all.

Each affordance now renders against its own permission: deploy / stop /
restart / update on `stack:deploy`, delete on `stack:delete`, rollback on
`canDeploy + isPaid + backupInfo.exists`, scan on `isAdmin +
trivy.available`. The overflow menu appears if any of {rollback, scan,
delete} is granted, so a delete-only operator still has a way to remove
the stack.

Adds a Monaco model dispose on EditorView unmount via the existing
editor ref, and a compact `Stats unavailable` chip in the CONTAINERS
header that lights up when the live-stats WebSocket reports a persistent
failure.

* fix(editor): make container-stats hook reactive to the active node

`useContainerStats` previously read the active node id from
`localStorage` on each WebSocket open, with a deps array of `[containers]`
only. After a node switch the stats stream stayed pointed at the
previous node's `/ws` endpoint until the containers array refreshed.

The hook now accepts `activeNodeId` as a second argument, depends on
`[containers, activeNodeId]`, and drops the localStorage read. The
return shape is `{ stats, error }`: the error field carries a string
when the stream fails, surfaced by EditorView as a small chip in the
CONTAINERS header. A per-WS `warnedOnce` set ensures a flaky daemon
emits at most one console.warn per stream lifetime, never at message
rate. Close codes 1000 / 1001 stay silent (normal teardown, navigation).

The error reset (`setError(null)`) is split into its own effect keyed on
`activeNodeId` so the banner does not flap on every containers-array
refresh tick against a persistently-flaky daemon. Tests cover the new
shape, the node-id reactivity, and the abnormal-close warn behaviour.

* docs(editor): describe new gate split and add troubleshooting entries

Updates the editor cockpit page to reflect that the action bar now
gates each affordance on its own permission (deploy / delete), and that
the bar appears for delete-only users so a stack can still be removed.

Adds three troubleshooting accordions covering the new behaviours: a
failed save that blocks the subsequent deploy, the unsaved-changes
prompt on node switch, and the live-stats chip when the daemon is
unreachable.

Adds an E2E spec verifying that a forced PUT 500 on the compose write
surfaces the failure toast and prevents the deploy POST from firing.

* fix(stacks): use printf-style format for compose-down warn

`console.warn` treats arg-1 as a printf format string when subsequent
args follow. The template literal here interpolated a sanitized but
not %-escaped stackName into arg-1 alongside an error argument, so a
stackName containing a `%s` placeholder could theoretically swallow
the error in the substitution. Switch to the file's established
`'... %s ...', value, err` pattern.

* test(editor): fix save-deploy spec; click both edit buttons, drop Monaco fill

The editor has two edit affordances: a lowercase 'edit' in the Anatomy
panel header that swaps the right column to the editor tabs, and a
capital 'Edit' in the editor toolbar that flips Monaco from read-only
into edit mode. The spec previously matched both with a case-insensitive
regex and only fired one click, so Monaco never entered edit mode.

It also tried to fill .monaco-editor textarea — that element is Monaco's
IME accessibility helper, hard-coded readonly; the real editable surface
is a contenteditable div.

`saveFile()` does not gate on a dirty buffer, so the spec does not need
to modify Monaco at all. Click both edit buttons with case-anchored
regexes and drop the fill step.

* test(editor): disambiguate Save & Deploy locator from sidebar row

The TEST_STACK fixture is named 'e2e-save-deploy-stack'. The sidebar
renders each stack into a div with role=button whose accessible name
includes the stack slug, so the regex /save.*deploy/i matches both the
sidebar row ('e2e-save-deploy-stack') and the editor toolbar's actual
Save & Deploy button — strict-mode bails. Anchor the locator to the
literal button text with exact:true.
2026-05-24 15:18:47 -04:00

79 lines
3.1 KiB
TypeScript

/**
* EditorView save-and-deploy: a failed PUT must abort the deploy. Verified by
* intercepting the PUT with a forced 500 and asserting that no POST to /deploy
* is observed, plus a "Failed to save file" toast surfaces.
*/
import { test, expect } from '@playwright/test';
import { loginAs, waitForStacksLoaded } from './helpers';
const TEST_STACK = 'e2e-save-deploy-stack';
async function deleteTestStack(page: import('@playwright/test').Page) {
await page.evaluate(async (name) => {
await fetch(`/api/stacks/${name}`, { method: 'DELETE', credentials: 'include' }).catch(() => { });
}, TEST_STACK);
}
async function createTestStack(page: import('@playwright/test').Page) {
await page.getByRole('button', { name: 'Create Stack' }).click();
await expect(page.getByRole('dialog')).toBeVisible({ timeout: 5_000 });
await page.locator('#create-stack-name').fill(TEST_STACK);
await page.locator('[role="dialog"]').getByRole('button', { name: 'Create' }).click();
await expect(page.getByRole('dialog')).toBeHidden({ timeout: 8_000 });
}
test.describe('EditorView save-and-deploy', () => {
test.beforeEach(async ({ page }) => {
await loginAs(page);
await waitForStacksLoaded(page);
await deleteTestStack(page);
await page.waitForTimeout(300);
await page.reload();
await loginAs(page);
await waitForStacksLoaded(page);
await createTestStack(page);
// Open the new stack in the editor.
await page.locator('[role="listbox"]').getByText(TEST_STACK, { exact: true }).click();
});
test.afterEach(async ({ page }) => {
await deleteTestStack(page);
});
test('does NOT deploy when the save PUT fails', async ({ page }) => {
// Force the compose-save PUT to fail.
await page.route(`**/api/stacks/${TEST_STACK}`, async (route, req) => {
if (req.method() === 'PUT') {
await route.fulfill({ status: 500, body: 'forced save failure' });
return;
}
await route.continue();
});
// Track whether the deploy POST is ever attempted.
let deployAttempts = 0;
await page.route(`**/api/stacks/${TEST_STACK}/deploy*`, async (route, req) => {
if (req.method() === 'POST') deployAttempts += 1;
await route.continue();
});
// The editor surface has two distinct edit affordances. First click swaps
// the right panel from Anatomy to the editor tabs (Monaco mounts read-only);
// second click flips Monaco into edit mode and reveals Save & Deploy.
await page.getByRole('button', { name: /^edit$/ }).click();
await page.getByRole('button', { name: /^Edit$/ }).click();
// No need to modify Monaco content: saveFile fires the PUT regardless of
// dirty state. The route interceptor forces it to 500; the gated handler
// then must not call POST /deploy.
await page.getByRole('button', { name: 'Save & Deploy', exact: true }).click();
// Failure toast must appear.
await expect(page.getByText(/failed to save file/i)).toBeVisible({ timeout: 5_000 });
// Give the UI a beat to (incorrectly) fire a deploy if the guard is broken.
await page.waitForTimeout(1_000);
expect(deployAttempts).toBe(0);
});
});