Files
sencho/frontend/src/components/stack/GitSourcePanel.test.tsx
T
Anso f23b7e1bac feat: ordered multi-file Compose for Git sources (#1380)
* feat: ordered multi-file Compose for Git sources

Extend Git sources to deploy an ordered list of compose files merged with
docker compose -f base.yaml -f override.yaml ..., plus an optional project
directory.

- Pick and reorder compose files from the repository tree (drag to reorder on
  desktop, up/down arrows on phones); manual path entry is also supported.
- The ordered set drives every stack-scoped compose command (deploy, update,
  start/stop/restart/down, image scans, Compose Doctor) and the container
  lookup, so a service or image declared only in an override is handled too.
- Runtime keys off the materialized set, not the saved configuration: saving a
  source does not change deploy args until the pull is applied, and apply
  materializes from the pending snapshot rather than live config.
- The project directory is passed as --project-directory, with -p <stack>
  pinning the Compose project so container labels stay stable.
- The Mesh override is layered last; single-file sources are byte-identical to
  before, and existing rows keep working via the single-path fallback.

Docs cover the picker, ordering, project directory, and the new troubleshooting
and limitations (referenced files are not materialized; the dependency graph,
drift, and networking views read the primary file).

* fix: harden multi-file Git source (hash, unlink, collisions, node id)

- hashContent folds ordered file CONTENTS (not paths) so a clean multi-file
  stack is not flagged as locally edited: create/apply hash the fetched files
  (repo paths) while pull hashes the on-disk files (materialized paths), which
  previously disagreed and showed a false "local edits detected".
- Block unlinking a multi-file or project-directory Git source (409): the deploy
  spec lives on the source row, so removing it would silently revert deploys to
  root compose.yaml. Single-file sources still unlink.
- Reject materialized-path collisions in the selection validator: an additional
  file equal to or nested under compose.yaml, an ancestor/descendant overlap
  between selected files, and a project directory nested under a compose file
  (previously a 500 at materialization).
- DockerController.getContainersByStack uses the controller's node compose dir
  and passes its node id to the authored prefix, instead of the process default.

* fix: CI failures on multi-file Git source (test crash, aria query, path barrier)

- GitSourceFields no longer crashes when repoUrl/branch are falsy: the canBrowse
  trim() is optional-chained, so a reusable field component tolerates partial
  props. Fixes the apply-binding panel test, which feeds a minimal source object.
- GitSourcePanel tests query the footer Remove button by its exact name, so the
  picker's per-file "Remove <path>" buttons no longer collide with the broad
  /remove/i match (the test intent, footer Remove present/absent, is unchanged).
- validateCompose uses an inline resolve + startsWith barrier at the context-dir
  mkdir sink (CodeQL does not credit the wrapped isPathWithinBase helper),
  clearing the js/path-injection alert. The containment check is equivalent and
  contextDir is also validated upstream.

* test: update Git source E2E spec for the multi-file compose picker

The compose-file picker replaced the single #git-source-path input and added
per-file Remove buttons, so the E2E spec drove selectors that no longer exist:

- Drop the redundant compose.yaml fills (the picker defaults to compose.yaml).
- Select the footer Remove button by exact name so the picker's per-file
  "Remove <path>" buttons no longer make the locator ambiguous.
- Set a custom compose path through the picker (add via the manual input, press
  Enter, then remove the default compose.yaml).

* test: match the footer Remove button with an exact Playwright name

Playwright's getByRole name option is a substring match by default, so
{ name: 'Remove' } also matched the picker's "Remove <path>" buttons. Require an
exact match so only the footer Remove button is selected.
2026-06-17 13:24:55 -04:00

140 lines
4.9 KiB
TypeScript

/**
* Covers the panel's load path for the unlinked-stack contract: when the
* backend answers 200 { linked: false } (an existing stack with no Git source
* attached), the form must land in the empty/unlinked state rather than
* treating the sentinel as a configured source.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
// Mutable controls so a deploy-mode test can set the active node and capture the
// runWithLog params, while the load tests keep the default (no active node).
const nodeCtl = vi.hoisted(() => ({ activeNode: null as { id: number; type?: string } | null }));
const dfCtl = vi.hoisted(() => ({ params: null as null | { stackName: string; action: string; nodeId: number | null } }));
vi.mock('@/lib/api', () => ({ apiFetch: vi.fn() }));
vi.mock('@/context/DeployFeedbackContext', () => ({
useDeployFeedback: () => ({
runWithLog: vi.fn(
async (
params: { stackName: string; action: string; nodeId: number | null },
run: (started: Promise<void>) => Promise<{ ok: boolean }>,
) => {
dfCtl.params = params;
return run(Promise.resolve());
},
),
}),
}));
vi.mock('@/context/NodeContext', () => ({
useNodes: () => ({ activeNode: nodeCtl.activeNode }),
}));
// Drive applyPull(commitSha, deploy=true) directly without standing up the real
// diff UI; the panel passes applyPull as onApply.
vi.mock('./GitSourceDiffDialog', () => ({
GitSourceDiffDialog: ({ onApply }: { onApply: (sha: string, deploy: boolean) => void }) => (
<button data-testid="apply-deploy" onClick={() => onApply('sha-123', true)}>apply</button>
),
}));
vi.mock('@/components/ui/toast-store', () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
loading: vi.fn(() => 'toast-id'),
dismiss: vi.fn(),
},
}));
import { apiFetch } from '@/lib/api';
import { GitSourcePanel } from './GitSourcePanel';
function jsonRes(body: unknown, ok = true, status = 200) {
return { ok, status, json: async () => body, text: async () => '' } as unknown as Response;
}
const LINKED_SOURCE = {
id: 1,
stack_name: 'web',
repo_url: 'https://github.com/org/repo.git',
branch: 'main',
compose_path: 'compose.yaml',
sync_env: false,
env_path: null,
auth_type: 'none' as const,
has_token: false,
auto_apply_on_webhook: false,
auto_deploy_on_apply: false,
last_applied_commit_sha: null,
pending_commit_sha: null,
pending_fetched_at: null,
created_at: 0,
updated_at: 0,
};
function panel() {
return (
<GitSourcePanel
open
onOpenChange={vi.fn()}
stackName="web"
canEdit
isDarkMode={false}
/>
);
}
beforeEach(() => {
vi.mocked(apiFetch).mockReset();
nodeCtl.activeNode = null;
dfCtl.params = null;
});
describe('GitSourcePanel load', () => {
it('treats a 200 { linked: false } response as the empty/unlinked state', async () => {
vi.mocked(apiFetch).mockResolvedValue(jsonRes({ linked: false }));
render(panel());
// Save (not Update) and no Pull now / Remove affordances means the panel
// did not mistake the { linked: false } sentinel for a configured source.
await screen.findByRole('button', { name: /^save$/i });
expect(screen.queryByRole('button', { name: /update/i })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /pull now/i })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Remove' })).not.toBeInTheDocument();
expect(screen.getByLabelText(/repository url/i)).toHaveValue('');
});
it('renders the configured source when one is attached', async () => {
vi.mocked(apiFetch).mockResolvedValue(jsonRes(LINKED_SOURCE));
render(panel());
// A real source flips the primary action to Update and exposes Pull now / Remove.
await screen.findByRole('button', { name: /update/i });
expect(screen.getByRole('button', { name: /pull now/i })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Remove' })).toBeInTheDocument();
await waitFor(() =>
expect(screen.getByLabelText(/repository url/i)).toHaveValue('https://github.com/org/repo.git'),
);
});
});
describe('GitSourcePanel deploy-mode apply node binding', () => {
beforeEach(() => {
nodeCtl.activeNode = { id: 4, type: 'local' };
vi.mocked(apiFetch).mockResolvedValue(jsonRes({ applied: true, deployed: true }));
});
it('binds both runWithLog and the apply POST to the captured node when deploying', async () => {
render(panel());
fireEvent.click(await screen.findByTestId('apply-deploy'));
await waitFor(() => {
const applyCall = vi.mocked(apiFetch).mock.calls.find(c => String(c[0]).includes('/git-source/apply'));
expect(applyCall?.[1]).toEqual(expect.objectContaining({ nodeId: 4 }));
});
expect(dfCtl.params).toEqual(expect.objectContaining({ action: 'deploy', nodeId: 4 }));
});
});