Files
sencho/e2e/anatomy-resize.spec.ts
Anso ab6e4940e7 feat(ui): add resizable sidebar and Anatomy pane (#1902)
* feat(db): per-user preference store with versioned revision contract

Add the user_preferences table (per user and domain, with a strictly
advancing integer revision and schema_version) plus the atomic
persistence methods behind it:

- getUserPreferenceDomain returns a transport envelope with corrupt-row
  reporting (the revision stays intact so clients can repair)
- mutateUserPreferenceDomain applies a document mutation inside a single
  transaction under an expectedRevision or create-if-absent
  precondition; two competing writers cannot both succeed
- resetUserPreferenceDomain writes a tombstone (schema_version 0) under
  the same precondition contract, so a post-reset edit can
  conditionally un-tombstone while a stale pre-reset edit conflicts
- deleteUserPreferenceDomains removes every row on account deletion
  (foreign keys are declarative only in this codebase, so deleteUser
  runs the cleanup explicitly in its transaction)

* feat(preferences): per-user preference API with conditional writes

Add the /api/user-preferences router: collection GET, per-domain PUT
and DELETE (reset to tombstone), and a migrate endpoint for the
create-if-absent first-run race.

- Every operation is identity-guarded: the x-sencho-pref-user header
  must match the authenticated user before any persistence access, so
  a stale tab can never read or write another account's rows. A
  mismatch is a 409 IDENTITY_CHANGED with no current envelope, kept
  distinct from the revision-conflict 409 CONFLICT which carries one.
- Writes are conditional (expectedRevision or absent: true); there is
  no unguarded write path. Stale preconditions return the fresh
  envelope so clients reconcile instead of retrying blind.
- Documents are validated server-side with strict Zod schemas mirroring
  the frontend field guards; legacy navigation mode values are rejected
- Machine identities (node proxy, pilot tunnel) are rejected and API
  tokens lack the required scope
- The route is hub-only: a remote x-node-id targeting it gets an
  explicit 403, since account-owned state lives on the hub
- Audit summaries cover migrate, update, reset, and failed attempts

* feat(preferences): parity script pinning server enums to frontend registries

The server-side enum tables duplicate the frontend's field guards, and
nothing in the TypeScript compilation boundary links the two (backend
and frontend compile separately). Add a standalone check script that
extracts both value sets from source text and fails on drift, wired as
the pretest step for backend and frontend so a mismatch surfaces in
the ordinary test run instead of as a 400 at write time.

* feat(preferences): frontend preference domains, sync bus, and identity guards

Introduce the client half of server-backed per-user preferences: the
existing localStorage hooks remain the owners of state and DOM
application; a thin sync layer carries their documents to and from the
per-user preference API.

- preferenceEvents: the leaf module with write notifications (dirty
  field attribution), the identity-generation counter, the
  eligibility-readiness store with ownership-captured publications,
  and the unsaved-episode failure surface
- preferencesDocuments: build and per-field sanitize of appearance and
  navigation documents, tombstone-aware hydration, and the owner
  marker that wipes cached values when another account claims the
  browser
- syncBus: the single write choke point. Per-domain serialization,
  same-kind coalescing, reset-cancels-prior-puts chronology, debounced
  trailing writes, conditional PUTs with 409 reconciliation (reset
  conflicts re-queue the DELETE once on the adopted revision),
  keepalive flush on page hide, and pump-level identity guards that
  drop operations captured by a superseded account or generation
- useUserPreferencesSync: the always-mounted sync owner. Hydrates on
  identity resolution, reconciles late GETs against dirty fields
  (server wins untouched fields), adopts remote resets by observable
  revision, repairs corrupt rows with a conditional PUT, and surfaces
  failures as a single unsaved episode per domain
- AuthContext: sequenced identity transitions and a cross-tab storage
  signal so a login or logout in one tab re-checks auth in the others
- the localStorage hooks gain apply/current exports for the hydration
  path; user-facing setters notify the bus, hydration and derived
  seeding paths deliberately do not

* feat(preferences): reset actions, account-scope copy, and frontend tests

Wire the per-domain reset actions into the settings surface: the
appearance section footer and navigation section each offer a
complete-domain reset, and the recovery section's interface reset
runs both domains through the shared handler with a reload only after
both tombstones settle successfully.

- Settings registry: appearance scope moves from browser to account,
  with copy that states where preferences now live
- ThemeQuickSwitch: the save-location line reflects account syncing
- Tests: dirty-field merge against a late hydration GET, identity
  guards (cache ownership, queue invalidation on account switch,
  loading-state no-op), corrupt-row repair through the hook path,
  remote-reset precedence, reset settle/failure handling, registry
  scope assertions, and the eligibility readiness bridge

* test(e2e): cross-browser preference convergence suite

Add the end-to-end spec covering the promise the feature makes: two
browser contexts on the same account converge (appearance fields,
density, navigation mode and pin order), a reset in one context
reaches the other on reload, an account switch renders the new
account's state rather than the previous account's cache, and a
pending write captured before the switch is rejected server-side
without touching either account's rows.

The existing navigation, motion, and effects suites seed a known
server-side preference baseline per suite account so the new
hydration layer cannot overwrite their localStorage-only setups.

* docs: appearance and navigation preferences are account-scoped

Rewrite the user-facing pages that described browser-only
personalization: the appearance feature page (including the quick
switcher, troubleshooting entries, and screenshot description), the
settings reference scope legend, and the multi-node and overview
pages that stated preferences stay per browser. The recovery page's
emergency-reset entry now explains that clearing site data only
drops the local cache, not the saved preferences.

* test(preferences): mint API tokens through the shared test helper

Replace the duplicated token-minting code with the existing
createTestApiToken helper so the file leans on the repo-standard
scaffolding and CodeQL stops flagging the inline sha256 hashing
as new alerts on this diff.

* feat(preferences): sidebar mode and width in the appearance document

Extend the appearance preference domain with sidebarMode (fixed or
resizable) and sidebarWidth (224 to 440 px, default 256), the persisted
contract for the upcoming desktop sidebar resize feature.

Frontend: a use-sidebar-layout hook modeled on the density hook (guarded
localStorage cache, settings-changed broadcast, per-field dirty-field
notification), the new fields in the appearance document builder,
hydration with default fallbacks for older documents, both keys in the
identity-clear cache key list, and a targeted sidebar-layout reset that
puts defaults without tombstoning the domain. The theme cache document
excludes the new fields so pre-paint cache rewrites stay consistent.

Backend: the strict appearance schema gains both fields with defaults, so
an older writer's 16-field document parses and is stored normalized
instead of being rejected; out-of-bounds, fractional, and unknown mode
values still fail validation. The preference parity script now compares
the mode enum across backend and frontend.

Tests: backend normalization (PUT and migrate) plus boundary rejection
cases, and a frontend hook suite covering sanitization, cached reads,
write-path attribution, cross-tab sync, and cache key registration.

* feat(shell): resizable stacks sidebar

Add a desktop resize boundary for the stacks sidebar. When the sidebar
mode preference is resizable, the shell wraps the sidebar in a width-
owned pane with a draggable separator: pointer drag updates the pane
live and persists one sanitized width on release; pointercancel, lost
pointer capture, and unmount clean up without committing. The separator
is keyboard accessible (arrows, Home, End) and exposes role=separator
ARIA values that track the effective bounds.

The effective width clamps to the viewport through a ResizeObserver on
the shell flex row (sidebar plus workspace), reserving a minimum
workspace width. Narrowing the window shrinks the pane live without
rewriting the stored preference; widening restores the preferred width.
Fixed mode (the default) renders the original shell DOM unchanged, and
mobile is untouched.

* fix(shell): harden sidebar resize drag teardown

The resize separator now ignores a second pointerdown while a drag is
in progress, so an extra touch or mouse button cannot steal or corrupt
an active drag. The commit on pointerup releases the drag state in a
finally block, so teardown (body cursor, user-select, capture release)
always runs even if a consumer's commit handler throws. The drag
teardown helper drops its unused commit flag: cancellation paths never
commit, and the single pointerup commit now owns that decision
explicitly.

Covered by three new pane tests: keyboard End clamping to the
viewport-limited max, sub-minimum drags clamping to the minimum
without a sub-minimum commit, and interleaved second-pointer
pointerdowns being ignored.

* feat(settings): sidebar layout preference

Add a Sidebar layout section to Settings > Appearance with a
Fixed/Resizable mode control, a width slider (224 to 440 px, step 4),
and a targeted reset that restores the defaults without touching other
appearance values.

The sidebar layout hook now broadcasts the settings-changed event when
one of its setter writes actually changes localStorage, so every mounted
instance (the shell separator, the Settings slider, other tabs) converges
on the commit instead of holding a stale draft.

Settings search keywords gain sidebar/resize/layout aliases, and the
preference sync tests cover the targeted reset path: local defaults apply
immediately, one bus op carries both dirty fields, and the write degrades
to a migrate POST when no preference row exists yet.

* fix(shell): review cleanup for the resizable sidebar

Restore the Fixed-mode main column class exactly as before (min-w-0 is
now applied only in Resizable mode, so the desktop default DOM stays
byte-identical), drop the unused committed drag flag, remove a stray
blank line and the redundant width-commit wrapper, and align the
separator keyboard step on the 8 px used by the file explorer pane.

* test(e2e): sidebar resize journeys

Cover the resizable stacks sidebar end to end: Fixed default with no
separator, the Settings opt-in writing one preference PUT, drag and
keyboard resize with release as the persistence boundary, viewport
clamping that never persists the clamped width, mode-toggle retention,
a targeted reset that leaves other appearance values untouched,
per-account scoping, and an unchanged phone layout. The shared
preference GET helper now retries briefly on rate-limit responses so a
burst of suite traffic cannot fail an assertion read.

* docs(preferences): sidebar layout docs and E2E polling hardening

User-facing docs for the sidebar layout preference: a Display bullet and
new Sidebar section in the Appearance feature page (with screenshot), a
Display row in the settings reference, and an appearance row update on
the multi-node page stating that sidebar layout is account-scoped.

E2E: every server-state assertion now polls (expectStoredAppearance
helper over GET user-preferences) instead of relying on a fixed sleep,
the dead flushPreferenceWrite/DEBOUNCE_MS pair is removed, the
targeted-reset seed uses non-default theme and density so the
"untouched" assertion is meaningful, and serial hand-off points gained
storage boundary proofs. Helper retry comment now states the 429 retry
window explicitly.

* feat: add resizable Anatomy pane

* fix: expand Anatomy resize range

* test: build storage events without the two-arg constructor

Static analysis models StorageEvent as one-argument only. The tests
still need key and newValue, so those fields are defined on a
generic storage Event.

* ci: give Playwright E2E thirty minutes on PRs

The pane-layout journeys pushed the chromium suite past the old
twenty-minute job limit, so the run was cancelled mid-suite.
2026-09-18 01:19:15 -04:00

186 lines
7.7 KiB
TypeScript

import { test, expect, type APIRequestContext, type Page } from '@playwright/test';
import { loginAs, waitForShellReady, TEST_PASSWORD } from './helpers';
import {
APPEARANCE_DOC, adminApiContext, disposePrefUser, getPreferences, putDomain, seedPrefUser,
} from './preferences-helpers';
const SUITE_USER = 'anatomy-resize-e2e';
const STACK_NAME = 'anatomy-resize-e2e-stack';
function pane(page: Page) {
return page.getByTestId('anatomy-resize-pane');
}
function separator(page: Page) {
return page.getByTestId('anatomy-resize-separator');
}
function anatomyModeOption(page: Page, name: 'Fixed' | 'Resizable') {
return page.getByRole('radiogroup', { name: 'Anatomy panel mode' }).getByRole('radio', { name });
}
async function openStack(page: Page, slug: string): Promise<void> {
await page.goto(`/nodes/local/stacks/${encodeURIComponent(slug)}`);
await waitForShellReady(page);
await expect(page.getByRole('tab', { name: 'Anatomy' })).toBeVisible();
}
async function openAppearanceSettings(page: Page): Promise<void> {
await page.getByRole('button', { name: /profile/i }).click();
await page.getByRole('button', { name: 'Settings', exact: true }).click();
await page.getByRole('button', { name: 'Appearance', exact: true }).click();
await expect(page.getByRole('heading', { name: 'Stack detail layout' })).toBeVisible();
}
async function expectStoredAppearance(
request: APIRequestContext,
userId: number,
expected: Record<string, unknown>,
): Promise<void> {
await expect.poll(async () => {
const rows = await getPreferences(request, userId);
return rows.preferences.appearance?.data ?? null;
}, { timeout: 15_000 }).toMatchObject(expected);
}
test.describe('Resizable Anatomy panel', () => {
test.describe.configure({ mode: 'serial' });
let prefUser: Awaited<ReturnType<typeof seedPrefUser>> | undefined;
let admin: Awaited<ReturnType<typeof adminApiContext>> | undefined;
test.beforeAll(async () => {
prefUser = await seedPrefUser(SUITE_USER, TEST_PASSWORD, 'viewer');
admin = await adminApiContext();
const priorDelete = await admin.delete(`/api/stacks/${STACK_NAME}`);
if (!priorDelete.ok() && priorDelete.status() !== 404) {
throw new Error(`delete prior ${STACK_NAME} failed with ${priorDelete.status()}`);
}
const create = await admin.post('/api/stacks', { data: { stackName: STACK_NAME } });
if (!create.ok()) throw new Error(`create ${STACK_NAME} failed with ${create.status()}`);
await putDomain(prefUser.request, prefUser.userId, 'appearance', {
...APPEARANCE_DOC,
anatomyWidth: 480,
});
});
test.afterAll(async () => {
try {
if (admin) {
const cleanup = await admin.delete(`/api/stacks/${STACK_NAME}`);
if (!cleanup.ok() && cleanup.status() !== 404) {
throw new Error(`delete ${STACK_NAME} failed with ${cleanup.status()}`);
}
}
} finally {
await disposePrefUser(prefUser, admin);
}
});
test('Fixed preserves the existing stack detail split without a separator', async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await loginAs(page, SUITE_USER, TEST_PASSWORD, { viewerSafe: true });
await waitForShellReady(page);
await openStack(page, STACK_NAME);
await expect(separator(page)).toHaveCount(0);
await expect(pane(page)).toHaveCount(0);
await context.close();
});
test('Resizable drags the right pane, commits on release, and survives reload', async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await loginAs(page, SUITE_USER, TEST_PASSWORD, { viewerSafe: true });
await waitForShellReady(page);
await openAppearanceSettings(page);
await anatomyModeOption(page, 'Resizable').click();
await expectStoredAppearance(page.request, prefUser!.userId, { anatomyMode: 'resizable', anatomyWidth: 480 });
await openStack(page, STACK_NAME);
await expect(pane(page)).toHaveAttribute('style', /width: 480px/);
let widthWrites = 0;
page.on('request', (request) => {
if (request.method() === 'PUT' && request.url().includes('/api/user-preferences/appearance')
&& (request.postDataJSON() as Record<string, unknown>).anatomyWidth !== undefined) {
widthWrites += 1;
}
});
const box = await separator(page).boundingBox();
expect(box).not.toBeNull();
const startX = box!.x + box!.width / 2;
const startY = box!.y + box!.height / 2;
await page.mouse.move(startX, startY);
await page.mouse.down();
await page.mouse.move(startX + 48, startY, { steps: 4 });
expect(widthWrites).toBe(0);
await page.mouse.up();
await expect(pane(page)).toHaveAttribute('style', /width: 432px/);
await expect.poll(() => widthWrites).toBe(1);
await expectStoredAppearance(page.request, prefUser!.userId, { anatomyMode: 'resizable', anatomyWidth: 432 });
await page.reload();
await waitForShellReady(page);
await expect(pane(page)).toHaveAttribute('style', /width: 432px/);
await context.close();
});
test('keyboard bounds and targeted reset leave the sidebar preference untouched', async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await loginAs(page, SUITE_USER, TEST_PASSWORD, { viewerSafe: true });
await waitForShellReady(page);
await openStack(page, STACK_NAME);
await separator(page).focus();
await page.keyboard.press('Home');
await expect(pane(page)).toHaveAttribute('style', /width: 320px/);
await expectStoredAppearance(page.request, prefUser!.userId, { anatomyWidth: 320 });
const gridBox = await separator(page).locator('..').boundingBox();
const separatorBox = await separator(page).boundingBox();
expect(gridBox).not.toBeNull();
expect(separatorBox).not.toBeNull();
const expectedMaximum = Math.floor(gridBox!.width - 320 - separatorBox!.width);
await page.keyboard.press('End');
await expect(pane(page)).toHaveAttribute('style', new RegExp(`width: ${expectedMaximum}px`));
await expectStoredAppearance(page.request, prefUser!.userId, { anatomyWidth: expectedMaximum });
const primaryPaneBox = await page.getByTestId('stack-detail-primary-pane').boundingBox();
expect(primaryPaneBox).not.toBeNull();
expect(Math.abs(primaryPaneBox!.width - 320)).toBeLessThanOrEqual(1);
await putDomain(page.request, prefUser!.userId, 'appearance', {
...APPEARANCE_DOC,
sidebarMode: 'resizable',
sidebarWidth: 400,
anatomyMode: 'resizable',
anatomyWidth: 800,
});
await page.reload();
await waitForShellReady(page);
await openAppearanceSettings(page);
await page.getByRole('button', { name: 'Reset Anatomy panel layout' }).click();
await expectStoredAppearance(page.request, prefUser!.userId, {
anatomyMode: 'fixed', anatomyWidth: 640, sidebarMode: 'resizable', sidebarWidth: 400,
});
await context.close();
});
test('phone stack detail never renders the desktop Anatomy separator', async ({ browser }) => {
await putDomain(prefUser!.request, prefUser!.userId, 'appearance', {
...APPEARANCE_DOC,
anatomyMode: 'resizable',
anatomyWidth: 720,
});
const context = await browser.newContext();
const page = await context.newPage();
await loginAs(page, SUITE_USER, TEST_PASSWORD, { viewerSafe: true });
await page.setViewportSize({ width: 390, height: 844 });
await page.goto(`/nodes/local/stacks/${encodeURIComponent(STACK_NAME)}`);
await expect(page.getByRole('tablist', { name: 'Stack detail sections' })).toBeVisible({ timeout: 15_000 });
await expect(separator(page)).toHaveCount(0);
await expect(pane(page)).toHaveCount(0);
await context.close();
});
});