Files
kandev/apps/web/e2e/fixtures/test-base.ts
T
João Salavisa bb36cb9e01 refactor: move integrations to top-level settings with install-wide configs (#787)
* refactor: move integrations to top-level settings with install-wide configs

Jira and Linear configurations are now install-wide singletons rather than
per-workspace duplicates, and the GitHub/Jira/Linear settings pages live
under /settings/integrations instead of being nested inside each workspace.
Issue and PR watchers stay per-workspace via a workspace switcher inside
each integration page. Backend ships one-shot migrations that promote the
most-recently-updated row and copy its secret onto the new global key.

* fix: address review feedback on integrations refactor

Fix migration crash on installs whose jira_configs predate the auth-health
columns by selecting only guaranteed-present legacy columns and falling back
to defaults for the rest. Cover the empty-legacy-table and pre-health-columns
upgrade paths with new store tests.

On the frontend, refactor useIntegrationEnabled to take string parameters
instead of an inline options object so getSnapshot stays referentially stable
across renders, and stop dispatching a misleading no-op sync event when
localStorage.setItem fails in private mode.

* fix: hydrate workspace list on integration settings pages

The integration pages wrapped their content in a fresh StateProvider, which
created a nested store scope with an empty initial state and shadowed the
settings layout's hydrated workspace list. WorkspaceScopedSection then saw
zero workspaces and rendered the "Create a workspace to configure this
integration" empty state even when the user had workspaces.

Drop the redundant StateProvider from the jira and linear pages so they share
the layout's store. The github page switches to StateHydrator so it can still
seed the GitHub OAuth status without resetting the rest of the store.

* refactor(integrations): flatten watcher tables, pick workspace in create dialog

Hiding watchers behind a workspace switcher made the list invisible at a
glance — a user with multiple workspaces had to flip between each one to
see what was configured. Replace the switcher with a flat table that lists
every watch across every workspace, with a Workspace column for context, and
move workspace selection into the create dialog so the user picks once when
the watcher is born.

Backend: jira list-issue-watches and github list-review-watches /
list-issue-watches accept the workspace_id query param as optional; when
omitted, the corresponding store ListAll* method returns rows across every
workspace. Per-row mutations still require workspace_id as the IDOR guard.

Frontend: useReviewWatches / useIssueWatches / useJiraIssueWatches gain a
three-state contract — string for one workspace, undefined for all
workspaces, null to skip fetching. Watch tables grow an optional
showWorkspace column. Watch dialogs accept an optional workspaceId prop;
when absent, the dialog renders a workspace dropdown for the create flow
(disabled when editing existing rows so refs aren't orphaned). Github
review-watch-dialog crossed the 600-line lint cap so the prompt editor
moved to review-watch-prompt-field.tsx.

* fix(integrations): make watcher step dropdown reactive across workspace switches

Switching to a workspace whose workflows had to be fetched left the workflow
step dropdown stuck — the user could pick a workflow but the step Select
either showed the previous workflow's steps or appeared inert. The cause was
the per-dialog useWorkflowSteps hook deferring its empty-state reset via
Promise.resolve().then(() => setSteps([])) to dodge a setState-in-effect
lint rule, which let stale steps survive into the next render and gave Radix
nothing to anchor the popover to during the in-flight fetch.

Hoist the hook into a shared useWorkflowSteps that resets via React's
official setState-during-render pattern, exposes a loading flag, and returns
a stepPlaceholder helper so the Select can render "Loading steps…" or "No
steps in this workflow" instead of an empty popover. The Step Select is now
also disabled while loading or when there are no steps, making the state of
the dropdown unambiguous.

* fix: address PR review feedback on integrations refactor

Backend:
- linear migration: add column-presence guard mirroring the Jira fix so
  installs that upgraded from the original Linear schema (without org_slug
  / last_checked_at / last_ok / last_error) don't crash startup with
  "no such column"; add TestStore_MigrateLegacyPerWorkspaceTable_PreHealthColumns
- jira/handlers.go: drop the now-unused errMsgWorkspaceIDRequired constant
  that was failing golangci-lint
- jira/mock_controller_test.go (new): cover setAuthHealth happy-path and
  invalid-JSON-rejection so the singleton-shaped payload is locked in

Frontend:
- useIntegrationAvailable: gate the auth-health probe on loaded && enabled
  so disabled integrations don't poll /config every 90s
- use-workflow-steps: initialize loading to !!workflowId so edit-mode opens
  show "Loading steps…" instead of "No steps in this workflow" before the
  first fetch lands
- use-workflow-steps.test.ts (new): cover the empty/non-empty workflowId,
  workflow switch, fetch error, and stepPlaceholder branches
- use-linear-enabled.test: tighten the legacy-key migration assertion to
  pin the migrated value rather than just verifying key cleanup

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-03 10:22:57 +01:00

174 lines
6.7 KiB
TypeScript

import { type Page } from "@playwright/test";
import { execSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { backendFixture, type BackendContext } from "./backend";
import { ApiClient } from "../helpers/api-client";
import { PrAssetCapture } from "../helpers/pr-asset-capture";
import { makeGitEnv } from "../helpers/git-helper";
import type { WorkflowStep } from "../../lib/types/http";
export type SeedData = {
workspaceId: string;
workflowId: string;
startStepId: string;
steps: WorkflowStep[];
repositoryId: string;
agentProfileId: string;
/** Executor profile ID for the worktree executor — use to create tasks with git worktree isolation. */
worktreeExecutorProfileId: string;
};
export const test = backendFixture.extend<
{
testPage: Page;
prCapture: PrAssetCapture;
/**
* Auto fixture that resets integration mock state and any persisted
* Jira/Linear configs at the top of every test. Auto fixtures run
* automatically — unlike a top-level `test.beforeEach` registered in this
* module, which Playwright only fires for tests defined in the same file.
*/
integrationCleanup: void;
},
{ apiClient: ApiClient; seedData: SeedData }
>({
// Worker-scoped API client
apiClient: [
async ({ backend }, use) => {
const client = new ApiClient(backend.baseUrl);
await use(client);
},
{ scope: "worker" },
],
// Worker-scoped seed data: creates workspace, workflow (from template), discovers steps,
// and sets up a local git repository for agent execution workspace.
// The repo is created inside backend.tmpDir (the backend's HOME) so that
// discoveryRoots() allows branch listing (isPathAllowed check).
seedData: [
async ({ apiClient, backend }, use) => {
const workspace = await apiClient.createWorkspace("E2E Workspace");
const workflow = await apiClient.createWorkflow(workspace.id, "E2E Workflow", "simple");
const { steps } = await apiClient.listWorkflowSteps(workflow.id);
const sorted = steps.sort((a, b) => a.position - b.position);
const startStep = sorted.find((s) => s.is_start_step) ?? sorted[0];
// Create a minimal git repository inside backend.tmpDir (the backend's HOME).
// This ensures discoveryRoots() allows the path for branch listing.
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
fs.mkdirSync(repoDir, { recursive: true });
const gitEnv = makeGitEnv(backend.tmpDir);
execSync("git init -b main", { cwd: repoDir, env: gitEnv });
execSync('git commit --allow-empty -m "init"', { cwd: repoDir, env: gitEnv });
const repo = await apiClient.createRepository(workspace.id, repoDir);
const { agents } = await apiClient.listAgents();
const agentProfileId = agents[0]?.profiles[0]?.id;
if (!agentProfileId) {
throw new Error("E2E seed failed: no agent profile available");
}
// Find the worktree executor's profile so tests can opt in to worktree-based sessions.
const { executors } = await apiClient.listExecutors();
const worktreeExec = executors.find((e) => e.type === "worktree");
const worktreeExecutorProfileId = worktreeExec?.profiles?.[0]?.id;
if (!worktreeExecutorProfileId) {
throw new Error("E2E seed failed: no worktree executor profile available");
}
await use({
workspaceId: workspace.id,
workflowId: workflow.id,
startStepId: startStep.id,
steps: sorted,
repositoryId: repo.id,
agentProfileId,
worktreeExecutorProfileId,
});
},
{ scope: "worker" },
],
// Per-test page with baseURL pointing to worker's frontend.
// Resets user settings to the E2E workspace/workflow before each test so that
// SSR always resolves to the correct workspace regardless of what commitSettings
// may have written during previous tests.
testPage: async ({ browser, backend, apiClient, seedData }, use) => {
// Clean up tasks, test-created workflows, and extra agent profiles from
// previous tests in this worker. Keep the seeded workflow and the seed
// agent profile so the worker-scoped seedData fixture remains valid.
await apiClient.e2eReset(seedData.workspaceId, [seedData.workflowId]);
await apiClient.cleanupTestProfiles([seedData.agentProfileId]);
await apiClient.saveUserSettings({
workspace_id: seedData.workspaceId,
workflow_filter_id: seedData.workflowId,
keyboard_shortcuts: {},
enable_preview_on_click: false,
sidebar_views: [],
});
const context = await browser.newContext({
baseURL: backend.frontendUrl,
});
const page = await context.newPage();
await setupPage(page, backend, seedData);
await use(page);
await context.close();
},
// PR asset capture — gated behind CAPTURE_PR_ASSETS env var.
// When enabled, provides screenshot/recording helpers for PR descriptions.
// Destructure in tests that need it: { testPage, prCapture }
prCapture: async ({ testPage }, use, testInfo) => {
const capture = new PrAssetCapture(testPage, testInfo.file);
await use(capture);
capture.flush();
},
integrationCleanup: [
async ({ apiClient }, use) => {
await apiClient.rawRequest("DELETE", `/api/v1/jira/config`).catch(() => undefined);
await apiClient.rawRequest("DELETE", `/api/v1/linear/config`).catch(() => undefined);
await Promise.all([
apiClient.mockJiraReset().catch(() => undefined),
apiClient.mockLinearReset().catch(() => undefined),
]);
await use();
},
{ auto: true },
],
});
export { expect } from "@playwright/test";
async function setupPage(page: Page, backend: BackendContext, seedData: SeedData): Promise<void> {
await page.addInitScript(
({
backendPort,
repositoryId,
agentProfileId,
}: {
backendPort: string;
repositoryId: string;
agentProfileId: string;
}) => {
localStorage.setItem("kandev.onboarding.completed", "true");
// Pre-seed dialog selections so auto-select effects resolve on their
// first render cycle instead of waiting for async API chains.
localStorage.setItem("kandev.dialog.lastRepositoryId", JSON.stringify(repositoryId));
localStorage.setItem("kandev.dialog.lastAgentProfileId", JSON.stringify(agentProfileId));
localStorage.setItem("kandev.dialog.lastBranch", JSON.stringify("main"));
// Set the window global that getBackendConfig() reads for API/WS connections
// (e2e tests run frontend and backend on separate ports, like dev mode)
window.__KANDEV_API_PORT = backendPort;
},
{
backendPort: String(backend.port),
repositoryId: seedData.repositoryId,
agentProfileId: seedData.agentProfileId,
},
);
}