fix(#29 review r1): stack-delete leak, rollback/retention/version tests, UX trap

F3: deleting a file-based stack now removes the stack ROOT (compose/{id}) via a
new removeStackProjectDir helper, not stack.ProjectPath (which the PR repointed to
compose/{id}/v{N}) — old version dirs + parent no longer leak. Git stacks unchanged.
F1: tests for validateRollbackTarget (rejects 0/neg/>current/hole) and the rollback
snapshot (client content ignored, target read from disk, monotonic new version, note).
F2: tests for pruneStackFileVersionDirs (deletes given dirs, swallows errors) + the
post-commit gate contract + a monotonic-version regression guard.
F4: handler tests for ?version= (negative/out-of-range -> 400, valid version served,
legacy fallback).
F5: swagger @param version on GET file; @version 2.44.0 (handler.go) + package.json
2.44.0, matching APIVersion.
F6: the version selector no longer sets rollbackTo for the current/top version and
clears it on a manual buffer edit (so edits are honored, not silently discarded);
returning to the current version restores the current content. Distinguishes real
user edits from the programmatic version-load (CodeMirror ExternalChange).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
agent_coder
2026-07-02 17:28:52 +03:00
parent d0d3c068ba
commit bb68acfbf6
8 changed files with 616 additions and 11 deletions
@@ -1,4 +1,4 @@
import { render, screen, waitFor } from '@testing-library/react';
import { act, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Formik } from 'formik';
import { vi } from 'vitest';
@@ -17,7 +17,10 @@ import { server } from '@/setup-tests/server';
import { usePreventExit } from '@@/WebEditorForm';
import { StackEditorTabInner } from './StackEditorTabInner';
import {
StackEditorTabInner,
resolveRollbackTarget,
} from './StackEditorTabInner';
import { StackEditorFormValues } from './StackEditorTab.types';
import { useVersionedStackFile } from './useVersionedStackFile';
@@ -383,6 +386,178 @@ describe('version rollback', () => {
});
});
// F6: the version selector must not silently discard manual edits. The backend
// ignores the client buffer whenever rollbackTo is set, so rollbackTo must only
// be set for a genuinely older version and must be cleared once the user either
// re-selects the current version or edits the buffer by hand.
describe('resolveRollbackTarget (F6 decision)', () => {
it('returns undefined when the current/top version is picked', () => {
// versions[0] is the latest -> picking it is not a rollback
expect(resolveRollbackTarget(3, [3, 2, 1])).toBeUndefined();
});
it('returns the version when a genuinely older version is picked', () => {
expect(resolveRollbackTarget(2, [3, 2, 1])).toBe(2);
expect(resolveRollbackTarget(1, [3, 2, 1])).toBe(1);
});
it('returns undefined when only a single version exists', () => {
expect(resolveRollbackTarget(1, [1])).toBeUndefined();
});
it('returns undefined when versions are unavailable', () => {
expect(resolveRollbackTarget(1, undefined)).toBeUndefined();
expect(resolveRollbackTarget(1, [])).toBeUndefined();
});
});
describe('version selector edit trap (F6)', () => {
// The `version` passed to useVersionedStackFile mirrors values.rollbackTo, so
// we assert on the latest call to observe how rollbackTo evolves.
function lastRollbackTo() {
const { calls } = vi.mocked(useVersionedStackFile).mock;
return calls[calls.length - 1][0].version;
}
beforeEach(() => {
vi.mocked(useVersionedStackFile).mockReturnValue({
content: '',
isLoading: false,
});
});
it('should set rollbackTo when an older version is selected', async () => {
renderComponent({ versions: [3, 2, 1] });
const user = userEvent.setup();
const versionSelect = screen.getByRole('combobox', { name: /version/i });
await user.selectOptions(versionSelect, '2');
await waitFor(() => {
expect(lastRollbackTo()).toBe(2);
});
});
it('should clear rollbackTo when the current/top version is re-selected', async () => {
renderComponent({ versions: [3, 2, 1] });
const user = userEvent.setup();
const versionSelect = screen.getByRole('combobox', { name: /version/i });
// First roll back to an older version...
await user.selectOptions(versionSelect, '2');
await waitFor(() => {
expect(lastRollbackTo()).toBe(2);
});
// ...then return to the current version: this is not a rollback, so
// rollbackTo must be cleared to restore normal edit-and-deploy.
await user.selectOptions(versionSelect, '3');
await waitFor(() => {
expect(lastRollbackTo()).toBeUndefined();
});
});
it('should clear rollbackTo when the user edits the buffer', async () => {
renderComponent(
{ versions: [3, 2, 1] },
{ initialValues: { ...defaultInitialValues, rollbackTo: 2 } }
);
const user = userEvent.setup();
// rollbackTo starts at 2 (an older version pre-selected)
expect(lastRollbackTo()).toBe(2);
const editor = screen.getByTestId('stack-editor');
await waitFor(() => {
expect(editor).not.toHaveAttribute('readonly');
});
// A genuine user edit should reset rollbackTo so the edits are honored.
await user.type(editor, ' # manual edit');
await waitFor(() => {
expect(lastRollbackTo()).toBeUndefined();
});
});
it('should NOT clear rollbackTo when a version is loaded programmatically', async () => {
let capturedOnLoad: ((content: string) => void) | undefined;
vi.mocked(useVersionedStackFile).mockImplementation(({ onLoad }) => {
capturedOnLoad = onLoad;
return { content: '', isLoading: false };
});
renderComponent(
{ versions: [3, 2, 1] },
{ initialValues: { ...defaultInitialValues, rollbackTo: 2 } }
);
expect(capturedOnLoad).toBeDefined();
// The programmatic version-load goes through handleLoadFile (setFieldValue
// on stackFileContent), NOT the CodeEditor onChange, so rollbackTo must
// stay set — otherwise the rollback would immediately cancel itself.
act(() => {
capturedOnLoad?.('version: "2"\nservices:\n db:\n image: postgres');
});
// Wait past the CodeEditor's 300ms onChange debounce: if the programmatic
// load ever leaked into handleContentChange it would clear rollbackTo only
// after the debounce fires, so asserting at t≈0 would pass vacuously. By
// waiting beyond the window we ensure the assertion fails if a load ever
// clears rollbackTo.
await act(async () => {
await new Promise((resolve) => {
setTimeout(resolve, 350);
});
});
expect(lastRollbackTo()).toBe(2);
});
it('should restore the current content when returning to the current/top version', async () => {
let capturedOnLoad: ((content: string) => void) | undefined;
vi.mocked(useVersionedStackFile).mockImplementation(({ onLoad }) => {
capturedOnLoad = onLoad;
return { content: '', isLoading: false };
});
renderComponent({ versions: [3, 2, 1] });
const user = userEvent.setup();
const editor = screen.getByTestId('stack-editor');
await waitFor(() => {
expect(editor).not.toHaveAttribute('readonly');
});
const versionSelect = screen.getByRole('combobox', { name: /version/i });
// Roll back to an older version: rollbackTo is set and its content is loaded
// into the buffer (simulating useVersionedStackFile's fetch via onLoad).
const olderContent = 'version: "2"\nservices:\n db:\n image: postgres';
await user.selectOptions(versionSelect, '2');
await waitFor(() => {
expect(lastRollbackTo()).toBe(2);
});
act(() => {
capturedOnLoad?.(olderContent);
});
await waitFor(() => {
expect(editor).toHaveValue(olderContent);
});
// Return to the current/top version: rollbackTo must clear AND the editor
// must show the current content again, not the older version's leftover
// content (which would otherwise be deployed as a brand-new version).
await user.selectOptions(versionSelect, '3');
await waitFor(() => {
expect(lastRollbackTo()).toBeUndefined();
});
expect(editor).toHaveValue(defaultInitialValues.stackFileContent);
});
});
describe('form submission', () => {
it('should enable submit button when form is valid', async () => {
renderComponent();
@@ -22,6 +22,24 @@ import { WebhookFieldset } from '../../common/WebhookFieldset';
import { StackEditorFormValues } from './StackEditorTab.types';
import { useVersionedStackFile } from './useVersionedStackFile';
/**
* Decide the `rollbackTo` value for a version chosen in the selector.
*
* `versions[0]` is the latest/current version (the list is sorted descending).
* Picking the current version is NOT a rollback, so this returns `undefined`
* to keep the normal edit-and-deploy flow; only a genuinely older version sets
* a rollback target (which the backend reads from disk, ignoring the buffer).
*/
export function resolveRollbackTarget(
newVersion: number,
versions?: Array<number>
): number | undefined {
if (!versions || versions.length <= 1) {
return undefined;
}
return newVersion < versions[0] ? newVersion : undefined;
}
interface StackEditorTabInnerProps {
stackType: StackType | undefined;
composeSyntaxMaxVersion: number;
@@ -69,6 +87,21 @@ export function StackEditorTabInner({
[setFieldValue]
);
const handleContentChange = useCallback(
(value: string) => {
setFieldValue('stackFileContent', value);
// A manual edit means the user wants a normal edit-and-deploy, not a
// rollback, so clear rollbackTo (otherwise the backend would ignore the
// edited buffer and redeploy the selected version from disk). This runs
// only on genuine user input: the programmatic version-load goes through
// handleLoadFile -> setFieldValue, which updates the editor's `value`
// prop and is skipped by CodeMirror's onChange (marked as an external
// change), so it does not clear rollbackTo.
setFieldValue('rollbackTo', undefined);
},
[setFieldValue]
);
useVersionedStackFile({
stackId,
version: values.rollbackTo,
@@ -119,7 +152,7 @@ export function StackEditorTabInner({
id="stack-editor"
textTip="Define or paste the content of your docker compose file here"
type="yaml"
onChange={(value) => setFieldValue('stackFileContent', value)}
onChange={handleContentChange}
value={values.stackFileContent}
readonly={isOrphaned || !isAuthorizedToUpdate}
schema={schema}
@@ -169,10 +202,21 @@ export function StackEditorTabInner({
async function handleVersionChange(newVersion: number) {
if (versions && versions.length > 1) {
setFieldValue(
'rollbackTo',
newVersion < versions[0] ? newVersion : versions[0]
);
// Picking the current/top version clears rollbackTo (undefined); only a
// genuinely older version sets it. See resolveRollbackTarget.
const rollbackTarget = resolveRollbackTarget(newVersion, versions);
if (rollbackTarget === undefined) {
// Returning to the current version: restore the current file content so
// the editor matches the selector. Otherwise the previously-viewed older
// version's content would remain in the buffer (useVersionedStackFile
// does not fetch when rollbackTo is undefined) and get deployed as a new
// version. initialValues.stackFileContent is the current stack file
// loaded at page init. This flows through the CodeEditor `value` prop as
// an external change, so it does not re-trigger handleContentChange and
// rollbackTo stays undefined.
setFieldValue('stackFileContent', initialValues.stackFileContent);
}
setFieldValue('rollbackTo', rollbackTarget);
}
}
}