diff --git a/.github/actions/verify/action.yml b/.github/actions/verify/action.yml index bb1531ca..47765614 100644 --- a/.github/actions/verify/action.yml +++ b/.github/actions/verify/action.yml @@ -36,8 +36,13 @@ runs: DEPLOY_DOMAIN: ${{ inputs.deploy-domain }} # No `playwright install` step: playwright.config.ts uses channel: "chrome", # which resolves to ubuntu-latest's preinstalled Google Chrome — Playwright's - # own bundled Chromium download is never used and would be wasted work. - - name: Run E2E tests + # own bundled Chromium download is never used and would be wasted work. The + # Firefox/WebKit subset runs in its own `e2e-cross-browser` job in ci.yml. + # `pnpm test:e2e` runs both Chromium projects: `chromium` against `vite dev`, and + # `chromium-preview` (e2e/*.preview.spec.ts) against `pnpm build && vite preview`, + # whose web server builds dist/ itself. Keeping both in this step covers ci.yml and + # the deploy.yml gate alike. + - name: Run E2E tests (dev server and production preview) shell: bash run: pnpm test:e2e env: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4d031dc4..3ff6b8b3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,3 +12,17 @@ jobs: with: vite-github-client-id: ${{ vars.VITE_GITHUB_CLIENT_ID }} deploy-domain: ${{ vars.DEPLOY_DOMAIN }} + # Runs the E2E tests tagged @cross-browser on Firefox and WebKit. Those use Playwright's own + # browser builds, which the Chromium-only `ci` job never needs to download. CROSS_BROWSER=1 + # leaves out the preview project and its build. + e2e-cross-browser: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: ./.github/actions/setup + - name: Install Firefox and WebKit + run: pnpm exec playwright install --with-deps firefox webkit + - name: Run cross-browser E2E tests + run: pnpm test:e2e:cross-browser + env: + VITE_GITHUB_CLIENT_ID: ${{ vars.VITE_GITHUB_CLIENT_ID }} diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index f3a45818..05932b23 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -17,6 +17,12 @@ jobs: with: ref: ${{ inputs.tag }} persist-credentials: false + # The build stamp, the Worker deploy tag and the post-deploy check must all name the + # commit that was checked out. github.sha is the caller's commit, which differs from + # inputs.tag on a manual re-deploy of an older release. + - name: Resolve deployed commit + id: rev + run: printf 'sha=%s\n' "$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" - uses: ./.github/actions/verify with: vite-github-client-id: ${{ vars.VITE_GITHUB_CLIENT_ID }} @@ -32,16 +38,29 @@ jobs: CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - run: pnpm run build env: + # GITHUB_SHA itself cannot be overridden, so the build reads this variable first. + BUILD_GIT_SHA: ${{ steps.rev.outputs.sha }} VITE_GITHUB_CLIENT_ID: ${{ vars.VITE_GITHUB_CLIENT_ID }} VITE_JIRA_CLIENT_ID: ${{ vars.VITE_JIRA_CLIENT_ID }} VITE_SENTRY_DSN: ${{ vars.VITE_SENTRY_DSN }} VITE_TURNSTILE_SITE_KEY: ${{ vars.VITE_TURNSTILE_SITE_KEY }} + # Fail before deploying if the bundle was stamped with any other commit. + - name: Verify build stamp + env: + EXPECTED_SHA: ${{ steps.rev.outputs.sha }} + run: | + expected="${EXPECTED_SHA:0:12}" + sha="$(jq -r '.sha // empty' dist/client/version.json)" + if [[ "$sha" != "$expected" ]]; then + printf 'dist/client/version.json names %s, expected %s\n' "$sha" "$expected" >&2 + exit 1 + fi - name: Deploy to Cloudflare Workers env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} LC_ALL: C.UTF-8 - DEPLOY_TAG: ${{ github.sha }} + DEPLOY_TAG: ${{ steps.rev.outputs.sha }} RAW_MSG: ${{ github.event.head_commit.message }} run: | DEPLOY_TAG="${DEPLOY_TAG:0:25}" @@ -50,3 +69,25 @@ jobs: DEPLOY_MSG="${DEPLOY_MSG:0:100}" DEPLOY_MSG="${DEPLOY_MSG:-manual deploy ${DEPLOY_TAG}}" pnpm exec wrangler deploy --tag "$DEPLOY_TAG" --message "$DEPLOY_MSG" + # Update detection ignores a /version.json that is missing or served as the SPA's HTML + # fallback, so confirm the live file is JSON and names the build that was just deployed. + - name: Verify deployed version.json + if: ${{ vars.DEPLOY_DOMAIN != '' }} + env: + DEPLOY_DOMAIN: ${{ vars.DEPLOY_DOMAIN }} + EXPECTED_SHA: ${{ steps.rev.outputs.sha }} + run: | + expected="${EXPECTED_SHA:0:12}" + for attempt in 1 2 3 4 5 6; do + out="$(curl -sS --max-time 10 -w '\n%{content_type}' "https://${DEPLOY_DOMAIN}/version.json" || true)" + ctype="${out##*$'\n'}" + json="${out%$'\n'*}" + sha="$(jq -r '.sha // empty' <<< "$json" 2>/dev/null || true)" + if [[ "$ctype" == application/json* && "$sha" == "$expected" ]]; then + printf 'version.json OK (%s)\n' "$sha" + exit 0 + fi + sleep $((attempt * 5)) + done + printf 'version.json did not report %s with a JSON content type\n' "$expected" >&2 + exit 1 diff --git a/.oxlintrc.json b/.oxlintrc.json index c9fa99f0..d0c87592 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -231,7 +231,7 @@ "group": ["*/CustomTabModal", "../shared/CustomTabModal"], "importNamePattern": "^", "allowTypeImports": true, - "message": "Lazy-load CustomTabModal via lazy(() => import('../shared/CustomTabModal')) so it is excluded from initial dashboard/settings chunks." + "message": "Lazy-load CustomTabModal via lazyWithReload(() => import('../shared/CustomTabModal')) so it is excluded from initial dashboard/settings chunks." }, { "group": ["./github-emoji-map.json", "**/github-emoji-map.json"], diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index afeafbf5..3338c162 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,7 +36,10 @@ Fine-grained PATs need Actions (read), Contents (read), Issues (read), and Pull ```bash pnpm test # unit tests (Vitest — root + mcp/) -pnpm test:e2e # Playwright E2E tests (chromium) +pnpm test:e2e # Playwright E2E tests (chromium against vite dev, plus *.preview.spec.ts against pnpm build && vite preview; rebuilds dist/) +pnpm test:e2e:preview # Only the *.preview.spec.ts E2E tests (stale-chunk and offline handling on the production build) +E2E_SERVERS=dev pnpm test:e2e # Skip the production build and preview server (dev-server specs only) +pnpm test:e2e:cross-browser # Only the @cross-browser-tagged E2E tests, on Firefox + WebKit (first run: pnpm exec playwright install firefox webkit) pnpm test:status-smoke # Live-network check that githubstatus.com still reports the tracked component names (also runs on a weekly schedule in CI) pnpm run typecheck # TypeScript validation (root + mcp/) pnpm lint # Type-aware lint check (oxlint — root + mcp/) @@ -52,7 +55,7 @@ To test MCP tools interactively, use the MCP Inspector: npx @modelcontextprotocol/inspector tsx mcp/src/index.ts ``` -CI runs typecheck, lint (`oxlint`), unit tests, and E2E tests on every PR, and lint is also enforced pre-commit via `prek` alongside typecheck and unit tests. Make sure they pass locally before pushing. +CI runs typecheck, lint (`oxlint`), unit tests, and E2E tests (Chromium, plus the `@cross-browser` subset on Firefox and WebKit in a separate job) on every PR, and lint is also enforced pre-commit via `prek` alongside typecheck and unit tests. Make sure they pass locally before pushing. To run a specific test file: @@ -76,6 +79,8 @@ pnpm test -- tests/path/to/test.ts **Validation:** Zod v4 for all runtime validation. Note that nested `.default({})` doesn't apply inner field defaults — be explicit. +**Persisted schemas (`src/shared/schemas.ts`, `src/shared/view-schema.ts`):** the build fingerprints what `ConfigSchema` and `ViewStateSchema` accept; when a deploy changes it, tabs still on the older build turn read-only until reloaded. Keys, types, enums, patterns, array limits and defaults are covered automatically. A limit enforced by `.refine()` is invisible to that, so put it in `PERSISTED_LIMITS` (or export it like `TRACKED_USER_AVATAR_PREFIX`) and let the refine read it; a test fails if a refine is added without being accounted for. Tag a new E2E test `{ tag: "@cross-browser" }` to also run it on Firefox and WebKit in CI. + ## Testing Tests live in `tests/` and mirror the `src/` directory structure. Test files end in `.test.ts` or `.test.tsx`. BDD step definitions end in `.steps.tsx` and are also picked up by Vitest automatically. diff --git a/DEPLOY.md b/DEPLOY.md index a653bff8..61293b7f 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -82,7 +82,7 @@ Cloudflare Worker secrets are set. In CI, the deploy workflow runs 5. **MCP relay** — If deploying to a custom domain, set `MCP_RELAY_ALLOWED_ORIGINS=https://YOUR-DOMAIN` when running the MCP server (`https://gh.gordoncode.dev` is allowed by default) 6. **Sentry error reporting** — Set `VITE_SENTRY_DSN` (build-time, via GitHub Actions variable) and `SENTRY_DSN` (Worker secret, via `wrangler secret put`) to the **same** DSN value. The Worker tunnel (`/api/error-reporting`) validates the incoming envelope DSN against `env.SENTRY_DSN` — different values cause all Sentry events to silently return 403. Leave both empty to disable. **Worker-only** — does not work on static deploys. 7. **Cloudflare Turnstile** — Create a widget and set `VITE_TURNSTILE_SITE_KEY` in `.env`. Only needed for the planned Jira token sealing feature. **Worker-only.** -8. **WAF smoke tests** — Set `DEPLOY_DOMAIN` as a GitHub Actions variable (e.g., `your-domain.example.com`). CI runs `pnpm test:waf https://$DEPLOY_DOMAIN` automatically. If `DEPLOY_DOMAIN` is not set, the WAF test is skipped. Run locally with: `pnpm test:waf https://YOUR-DOMAIN`. **Worker-only.** +8. **WAF smoke tests** — Set `DEPLOY_DOMAIN` as a GitHub Actions variable (e.g., `your-domain.example.com`). CI runs `pnpm test:waf https://$DEPLOY_DOMAIN` automatically. If `DEPLOY_DOMAIN` is not set, the WAF test is skipped, and so is the post-deploy `version.json` verification in `deploy.yml`. Run locally with: `pnpm test:waf https://YOUR-DOMAIN`. **Worker-only.** 9. **Social metadata** — Update `og:image` and `og:url` in `index.html` to your domain 10. **Security contact** — Update the email and scope domain in `SECURITY.md` 11. **README** — Update the "Live demo" URL in `README.md` @@ -220,6 +220,7 @@ The two tunnel endpoints (`/api/error-reporting` and `/api/csp-report`) receive - **Hashed bundles (`/_app/*`):** Vite outputs content-hashed JS and CSS bundles to `dist/client/_app/`. `public/_headers` configures `Cache-Control: public, max-age=31536000, immutable` (one year) on `/_app/*` while inheriting the global security headers from `/*`. - **Entry HTML and unhashed public assets (`index.html`, `/assets/*`):** `index.html` and unhashed images under `public/assets/*` (favicon, logos, social preview) have no custom `Cache-Control` rule in `public/_headers` and use the Cloudflare Workers Static Assets platform default (`Cache-Control: public, max-age=0, must-revalidate`), ensuring browsers revalidate `index.html` on every load. +- **Build metadata (`/version.json`):** The build emits `version.json` at the client root (`{ version, sha, builtAt, schemaFp }`; `schemaFp` fingerprints the persisted config/view schema — structure, enums, defaults and the `.refine()` limits in `PERSISTED_LIMITS` — so an open tab on an older layout turns read-only; comments and refactors don't change it). `public/_headers` serves it with `Cache-Control: no-store` so open tabs always see the latest deployment, and the WAF Path Allowlist includes it. When `DEPLOY_DOMAIN` is set, the deploy workflow's **Verify deployed version.json** step runs after `wrangler deploy` and fails the job unless the live file is served as `application/json` and its `sha` equals the first 12 characters of the deployed commit (retrying for about 105 seconds to ride out propagation). - **One-time cache miss on initial `/_app/` rollout:** Moving hashed bundles from `/assets/` to `/_app/` causes a one-time cache miss on the deployment that introduces `/_app/`. - **Stale-chunk 404 handling (`stale_asset_404`):** Under SPA `not_found_handling`, missing non-navigation requests (such as ` plus and [docs](https://evil.example/phish) ([#42](https://github.com/gordon-code/github-tracker/pull/42))", + ].join("\n"); + + const entries = parseChangelog(md); + expect(entries).toHaveLength(1); + const item = entries[0].sections[0].items[0]; + expect(item.text).toBe( + "xss: sanitize click here and plus and docs", + ); + expect(item.text).not.toContain("javascript:"); + expect(item.text).not.toContain("https://evil.example"); + expect(item.pr).toBe(42); + }); + + it("falls back to 'Changes' when bullets appear before any ### section heading, merges duplicate section headings, and filters out empty sections", () => { + const md = [ + "## 0.3.0 (2026-11-12)", + "", + "* top-level change before any section heading (#200)", + "", + "### Empty Section", + "", + "* (#201)", + "", + "### Features", + "", + "* first feature", + "", + "### Features", + "", + "* second feature under duplicate heading", + ].join("\n"); + + const entries = parseChangelog(md); + expect(entries).toEqual([ + { + version: "0.3.0", + date: "2026-11-12", + sections: [ + { + title: "Changes", + items: [ + { + text: "top-level change before any section heading", + pr: 200, + }, + ], + }, + { + title: "Features", + items: [ + { text: "first feature" }, + { text: "second feature under duplicate heading" }, + ], + }, + ], + }, + ]); + }); + + it("caps output at 20 releases and truncates bullet item text at 300 characters", () => { + const releaseBlocks: string[] = []; + for (let i = 25; i >= 1; i--) { + const longText = `item-${i}-` + "x".repeat(350); + releaseBlocks.push( + `## 0.${i}.0 (2026-10-${String((i % 28) + 1).padStart(2, "0")})\n\n### Features\n\n* ${longText} (#${i})`, + ); + } + const entries = parseChangelog(releaseBlocks.join("\n\n")); + expect(entries).toHaveLength(20); + expect(entries[0].version).toBe("0.25.0"); + expect(entries[19].version).toBe("0.6.0"); + for (const entry of entries) { + for (const section of entry.sections) { + for (const item of section.items) { + expect(item.text.length).toBeLessThanOrEqual(300); + } + } + } + }); + + it("resolves virtual:changelog and loads parsed CHANGELOG.md or returns empty array when CHANGELOG.md is absent", () => { + const [, emitPlugin] = buildMeta(); + const resolveId = emitPlugin.resolveId as unknown as (id: string) => string | null; + const load = emitPlugin.load as unknown as ( + this: { addWatchFile: (p: string) => void }, + id: string, + ) => string | null; + + expect(resolveId("virtual:changelog")).toBe("\0virtual:changelog"); + expect(resolveId("other-module")).toBeNull(); + expect(load.call({ addWatchFile: vi.fn() }, "other-id")).toBeNull(); + + // Real CHANGELOG.md exists on disk + const watchSpy = vi.fn(); + const loadedReal = load.call({ addWatchFile: watchSpy }, "\0virtual:changelog"); + expect(watchSpy).toHaveBeenCalledWith(resolve(process.cwd(), "CHANGELOG.md")); + // The committed release-please format must parse into real entries, not fall back to `[]`. + expect(loadedReal).toMatch(/^export default \[.*\];$/); + expect(loadedReal).not.toBe("export default [];"); + const realEntries = JSON.parse( + (loadedReal ?? "").replace(/^export default /, "").replace(/;$/, ""), + ) as Array<{ version: string; sections: unknown[] }>; + expect(realEntries.length).toBeGreaterThan(0); + expect(realEntries[0].version).toMatch(/^\d+\.\d+\.\d+$/); + expect(realEntries[0].sections.length).toBeGreaterThan(0); + + // Missing CHANGELOG.md returns "export default [];" + mockExistsSync.mockReturnValue(false); + const loadedMissing = load.call({ addWatchFile: vi.fn() }, "\0virtual:changelog"); + expect(loadedMissing).toBe("export default [];"); + }); + }); +}); diff --git a/tests/components/App.test.tsx b/tests/components/App.test.tsx index f1f4f363..b4c95ca6 100644 --- a/tests/components/App.test.tsx +++ b/tests/components/App.test.tsx @@ -87,6 +87,7 @@ import * as githubService from "../../src/app/services/github"; import * as cacheStore from "../../src/app/stores/cache"; import * as viewStore from "../../src/app/stores/view"; import * as sentryFacade from "../../src/app/lib/sentry-facade"; +import * as versionModule from "../../src/app/lib/version"; import App, { _resetAuthInitStartedForTests } from "../../src/app/App"; describe("App", () => { @@ -173,6 +174,37 @@ describe("App", () => { }); }); + it("starts the version watch on mount, stops it on unmount, and renders the update banner when an update is flagged", async () => { + const stopVersionWatch = vi.fn(); + const startSpy = vi + .spyOn(versionModule, "startVersionWatch") + .mockReturnValue(stopVersionWatch); + try { + const { unmount } = render(() => ); + + await waitFor(() => { + expect(startSpy).toHaveBeenCalledTimes(1); + }); + expect(screen.queryByText("A new version is available.")).toBeNull(); + + versionModule._setUpdateAvailableForTests({ + version: "0.1.2", + sha: "fedcba987654", + builtAt: "2026-01-02T00:00:00.000Z", + }); + await waitFor(() => { + screen.getByText("A new version is available."); + }); + + expect(stopVersionWatch).not.toHaveBeenCalled(); + unmount(); + expect(stopVersionWatch).toHaveBeenCalledTimes(1); + } finally { + startSpy.mockRestore(); + versionModule._resetVersionStateForTests(); + } + }); + it("redirects to /dashboard when not initially authenticated but validateToken succeeds", async () => { // Simulates cold start: localStorage has a token but user() is null // → isAuthenticated() = false → validateToken called → returns true → routes to dashboard diff --git a/tests/components/DashboardPage.test.tsx b/tests/components/DashboardPage.test.tsx index b1818bc3..cfd90b3e 100644 --- a/tests/components/DashboardPage.test.tsx +++ b/tests/components/DashboardPage.test.tsx @@ -305,6 +305,34 @@ describe("DashboardPage — tab switching", () => { }); }); +describe("DashboardPage — footer", () => { + it("renders Source, Guide, Privacy, and the v0.1.0+abcdef1 release link in the footer", () => { + render(() => ); + + const versionLink = screen.getByRole("link", { name: "v0.1.0+abcdef1" }); + expect(versionLink.getAttribute("href")).toBe( + "https://github.com/gordon-code/github-tracker/releases", + ); + expect(versionLink.getAttribute("target")).toBe("_blank"); + expect(versionLink.getAttribute("rel")).toBe("noopener noreferrer"); + + const sourceLink = screen.getByRole("link", { name: "Source" }); + expect(sourceLink.getAttribute("href")).toBe("https://github.com/gordon-code/github-tracker"); + expect(sourceLink.getAttribute("target")).toBe("_blank"); + expect(sourceLink.getAttribute("rel")).toBe("noopener noreferrer"); + + const guideLink = screen.getByRole("link", { name: "Guide" }); + expect(guideLink.getAttribute("href")).toBe( + "https://github.com/gordon-code/github-tracker/blob/main/docs/USER_GUIDE.md", + ); + expect(guideLink.getAttribute("target")).toBe("_blank"); + expect(guideLink.getAttribute("rel")).toBe("noopener noreferrer"); + + const privacyLink = screen.getByRole("link", { name: "Privacy" }); + expect(privacyLink.getAttribute("href")).toBe("/privacy"); + }); +}); + describe("DashboardPage — clock tick", () => { it("creates a 60s interval to keep relative time displays fresh", () => { const spy = vi.spyOn(globalThis, "setInterval"); diff --git a/tests/components/LoginPage.test.tsx b/tests/components/LoginPage.test.tsx index ff71a545..45e7cfed 100644 --- a/tests/components/LoginPage.test.tsx +++ b/tests/components/LoginPage.test.tsx @@ -76,6 +76,7 @@ import * as authStore from "../../src/app/stores/auth"; import * as patLib from "../../src/app/lib/pat"; import * as settingsTransfer from "../../src/app/lib/settings-transfer"; import * as proxyLib from "../../src/app/lib/proxy"; +import { _resetVersionStateForTests, _setSchemaStaleForTests } from "../../src/app/lib/version"; import * as cacheStore from "../../src/app/stores/cache"; import * as configStore from "../../src/app/stores/config"; import { ConfigSchema } from "../../src/shared/schemas"; @@ -269,6 +270,23 @@ describe("LoginPage — PAT form validation", () => { ); }); + it("a stale-schema tab refuses to sign in with a token and asks the user to reload", async () => { + vi.mocked(patLib.isValidPatFormat).mockReturnValue({ valid: true }); + mockFetchOk(); + const user = await openPatForm(); + await user.type(screen.getByLabelText("Personal access token"), "ghp_" + "a".repeat(36)); + + _setSchemaStaleForTests(true); + try { + await user.click(screen.getByRole("button", { name: "Sign in" })); + await waitFor(() => screen.getByText(/older version\. Reload this page, then sign in/i)); + expect(authStore.setAuthFromPat).not.toHaveBeenCalled(); + expect(mockNavigate).not.toHaveBeenCalled(); + } finally { + _resetVersionStateForTests(); + } + }); + it("shows 'Verifying...' and disables button while submitting", async () => { vi.mocked(patLib.isValidPatFormat).mockReturnValueOnce({ valid: true }); let resolveFetch!: (v: Response) => void; @@ -514,6 +532,32 @@ describe("LoginPage — Import from backup", () => { expect(mockNavigate).not.toHaveBeenCalled(); }); + it("a stale-schema tab refuses to commit the import and tells the user to reload", async () => { + mockValidCredsFile(); + vi.mocked(proxyLib.unsealCredentialBundle).mockResolvedValue({ ok: true, ciphertext: "CT" }); + vi.mocked(settingsTransfer.resolveImportedCredentials).mockResolvedValue({ ok: true, bundle: BUNDLE, identity: IDENTITY }); + vi.mocked(settingsTransfer.hasExistingLocalConfig).mockReturnValue(true); + vi.mocked(settingsTransfer.commitImportedSettings).mockResolvedValue({ jiraRestored: true }); + + const user = userEvent.setup(); + await openImport(user); + fireFileChange(); + await waitFor(() => screen.getByLabelText("One-time code")); + await user.type(screen.getByLabelText("One-time code"), CODE); + await user.click(screen.getByRole("button", { name: "Restore credentials" })); + await waitFor(() => screen.getByText(/sign you in as/i)); + + _setSchemaStaleForTests(true); + try { + await user.click(screen.getByRole("button", { name: "Continue" })); + await waitFor(() => screen.getByText(/older version and can't import settings/i)); + expect(settingsTransfer.commitImportedSettings).not.toHaveBeenCalled(); + expect(mockNavigate).not.toHaveBeenCalled(); + } finally { + _resetVersionStateForTests(); + } + }); + it("declining the identity dialog leaves the page in place — no navigation, no commit", async () => { mockValidCredsFile(); vi.mocked(proxyLib.unsealCredentialBundle).mockResolvedValue({ ok: true, ciphertext: "CT" }); diff --git a/tests/components/layout/Header.test.tsx b/tests/components/layout/Header.test.tsx index 019d7bab..73a3765c 100644 --- a/tests/components/layout/Header.test.tsx +++ b/tests/components/layout/Header.test.tsx @@ -53,9 +53,13 @@ import Header from "../../../src/app/components/layout/Header"; import * as authStore from "../../../src/app/stores/auth"; import * as errorsModule from "../../../src/app/lib/errors"; import * as githubStatusModule from "../../../src/app/services/github-status"; -import { render } from "@solidjs/testing-library"; +import { config, resetConfig, updateConfig } from "../../../src/app/stores/config"; +import { _resetChangelogCacheForTests, loadChangelog } from "../../../src/app/lib/changelog"; +import { render, waitFor } from "@solidjs/testing-library"; beforeEach(() => { + resetConfig(); + _resetChangelogCacheForTests(); mockNavigate.mockClear(); vi.mocked(authStore.clearAuth).mockClear(); vi.mocked(errorsModule.getUnreadCount).mockReturnValue(0); @@ -197,4 +201,90 @@ describe("Header", () => { expect(img.getAttribute("loading")).toBeNull(); vi.mocked(authStore.user).mockRestore(); }); + + it("shows the What's new unseen dot when lastSeenVersion is null or older, and hides the dot after opening WhatsNewDialog", async () => { + const user = userEvent.setup(); + render(() =>
); + + const whatsNewBtn = screen.getByLabelText("What's new"); + expect(whatsNewBtn.getAttribute("aria-expanded")).toBe("false"); + + await waitFor(() => { + expect(screen.getByTestId("whats-new-dot")).toBeDefined(); + }); + + await user.click(whatsNewBtn); + + expect(whatsNewBtn.getAttribute("aria-expanded")).toBe("true"); + expect(screen.getByText("What's New")).toBeDefined(); + expect(config.lastSeenVersion).toBe("0.1.0"); + expect(screen.queryByTestId("whats-new-dot")).toBeNull(); + }); + + it("hides the What's new dot when lastSeenVersion already matches the latest release", async () => { + updateConfig({ lastSeenVersion: "0.1.0" }); + render(() =>
); + + // Header's own load was scheduled first (setTimeout 0), so once this tick passes the entries are applied. + await loadChangelog(); + await new Promise((r) => setTimeout(r, 0)); + expect(screen.queryByTestId("whats-new-dot")).toBeNull(); + + // Control: the same loaded entries do flag an older lastSeenVersion, so the absence above + // comes from hasUnseen() and not from a changelog that never loaded. + updateConfig({ lastSeenVersion: "0.0.9" }); + expect(screen.getByTestId("whats-new-dot")).toBeDefined(); + }); + + it("announces unread release notes in the What's new button label only while the dot is shown", async () => { + render(() =>
); + + expect(screen.getByLabelText("What's new")).toBeDefined(); + + await waitFor(() => { + expect(screen.getByLabelText("What's new, unread release notes")).toBeDefined(); + }); + expect(screen.getByTestId("whats-new-dot")).toBeDefined(); + + updateConfig({ lastSeenVersion: "0.1.0" }); + expect(screen.queryByLabelText("What's new, unread release notes")).toBeNull(); + expect(screen.getByLabelText("What's new")).toBeDefined(); + }); + + it("uses requestIdleCallback when available, loads changelog on demand if clicked before idle, and calls cancelIdleCallback on unmount", async () => { + const user = userEvent.setup(); + const requestIdleSpy = vi.fn(() => 42); + const cancelIdleSpy = vi.fn(); + Object.defineProperty(window, "requestIdleCallback", { + value: requestIdleSpy, + configurable: true, + writable: true, + }); + Object.defineProperty(window, "cancelIdleCallback", { + value: cancelIdleSpy, + configurable: true, + writable: true, + }); + + try { + const { unmount } = render(() =>
); + expect(requestIdleSpy).toHaveBeenCalledTimes(1); + // Idle callback has not run yet, so dot is not shown + expect(screen.queryByTestId("whats-new-dot")).toBeNull(); + + // Clicking "What's new" before idle triggers on-demand loadChangelog() + const whatsNewBtn = screen.getByLabelText("What's new"); + await user.click(whatsNewBtn); + + await waitFor(() => { + expect(screen.getByText("v0.1.0")).toBeDefined(); + }); + + unmount(); + expect(cancelIdleSpy).toHaveBeenCalledWith(42); + } finally { + Reflect.deleteProperty(window, "requestIdleCallback"); + Reflect.deleteProperty(window, "cancelIdleCallback"); + } + }); }); diff --git a/tests/components/onboarding/OnboardingWizard.test.tsx b/tests/components/onboarding/OnboardingWizard.test.tsx index b4b7344f..0bf0cf1e 100644 --- a/tests/components/onboarding/OnboardingWizard.test.tsx +++ b/tests/components/onboarding/OnboardingWizard.test.tsx @@ -62,9 +62,11 @@ vi.mock("../../../src/app/stores/config", () => ({ CONFIG_STORAGE_KEY: "github-tracker:config", config: { selectedOrgs: [], selectedRepos: [], upstreamRepos: [], monitoredRepos: [], trackedUsers: [] }, updateConfig: vi.fn(), + flushConfigPersistence: vi.fn(), })); import * as configStore from "../../../src/app/stores/config"; +import { _resetVersionStateForTests, _setSchemaStaleForTests } from "../../../src/app/lib/version"; import * as apiModule from "../../../src/app/services/api"; import OnboardingWizard from "../../../src/app/components/onboarding/OnboardingWizard"; @@ -251,10 +253,40 @@ describe("OnboardingWizard", () => { screen.getByText(/Finish Setup \(1 repo\)/); }); await user.click(screen.getByText(/Finish Setup \(1 repo\)/)); - expect(localStorage.setItem).toHaveBeenCalledWith( - "github-tracker:config", - expect.any(String) - ); + expect(vi.mocked(configStore.flushConfigPersistence)).toHaveBeenCalledTimes(1); + + // The flush must come after the config update (so it has something to write) and + // before the page navigates away (so the write is not lost). + const updateOrder = vi.mocked(configStore.updateConfig).mock.invocationCallOrder.at(-1) ?? 0; + const flushOrder = vi.mocked(configStore.flushConfigPersistence).mock.invocationCallOrder[0]; + const replaceOrder = vi.mocked(window.location.replace).mock.invocationCallOrder[0]; + expect(updateOrder).toBeGreaterThan(0); + expect(updateOrder).toBeLessThan(flushOrder); + expect(flushOrder).toBeLessThan(replaceOrder); + }); + + it("on finish in a stale-schema tab: does not save or navigate, and asks the user to reload", async () => { + const user = userEvent.setup(); + vi.mocked(apiModule.fetchOrgs).mockResolvedValue(mockOrgs); + render(() => ); + await waitFor(() => { + screen.getByTestId("repo-selector"); + }); + await user.click(screen.getByText("Select Repo")); + await waitFor(() => { + screen.getByText(/Finish Setup \(1 repo\)/); + }); + + _setSchemaStaleForTests(true); + try { + await user.click(screen.getByText(/Finish Setup \(1 repo\)/)); + await waitFor(() => screen.getByText(/older version and can't save your choices/i)); + expect(configStore.updateConfig).not.toHaveBeenCalled(); + expect(configStore.flushConfigPersistence).not.toHaveBeenCalled(); + expect(window.location.replace).not.toHaveBeenCalledWith("/dashboard"); + } finally { + _resetVersionStateForTests(); + } }); it("on finish: navigates to /dashboard via window.location.replace", async () => { diff --git a/tests/components/settings/SettingsPage.test.tsx b/tests/components/settings/SettingsPage.test.tsx index 1778fbf3..cf2612a5 100644 --- a/tests/components/settings/SettingsPage.test.tsx +++ b/tests/components/settings/SettingsPage.test.tsx @@ -100,6 +100,7 @@ import { buildOrgAccessUrl } from "../../../src/app/lib/oauth"; import * as urlModule from "../../../src/app/lib/url"; import * as settingsTransfer from "../../../src/app/lib/settings-transfer"; import * as proxyLib from "../../../src/app/lib/proxy"; +import { _resetVersionStateForTests, _setSchemaStaleForTests } from "../../../src/app/lib/version"; // ── Helpers ─────────────────────────────────────────────────────────────────── @@ -2094,8 +2095,116 @@ describe("SettingsPage — Data: Import with encrypted credentials", () => { await user.click(screen.getByRole("button", { name: "Yes, import" })); expect(config.selectedRepos).toHaveLength(2); - // The Repositories summary is driven by the localRepos editor copy; without - // the post-import resync it would still read the stale (empty) pre-import set. await waitFor(() => screen.getByText(/2 selected/i)); }); + + it("reflects org/repo changes written to the config store after mount (as another tab's adoption does)", async () => { + updateConfig({ selectedOrgs: ["acme"], selectedRepos: [], upstreamRepos: [] }); + renderSettings(); + await waitFor(() => screen.getByText(/0 selected/i)); + + // Another tab's write is adopted into the store without this page re-mounting; + // the editors must follow it or the next edit here would save the stale list. + updateConfig({ + selectedOrgs: ["acme", "globex"], + selectedRepos: [ + { owner: "acme", name: "api", fullName: "acme/api" }, + { owner: "globex", name: "web", fullName: "globex/web" }, + ], + upstreamRepos: [{ owner: "upstream", name: "lib", fullName: "upstream/lib" }], + }); + + await waitFor(() => screen.getByText(/3 selected \(1 upstream\)/i)); + expect(screen.getByText(/^2 selected$/i)).toBeTruthy(); + }); +}); + +describe("SettingsPage — read-only while the stored-data schema is stale", () => { + afterEach(() => { + _resetVersionStateForTests(); + }); + + it("wraps the settings in a fieldset that is disabled only while the schema is stale", () => { + renderSettings(); + const signOut = screen.getByRole("button", { name: "Sign out" }); + const fieldset = signOut.closest("fieldset"); + expect(fieldset).not.toBeNull(); + expect(fieldset?.disabled).toBe(false); + + expect(fieldset?.hasAttribute("inert")).toBe(false); + + _setSchemaStaleForTests(true); + expect(fieldset?.disabled).toBe(true); + // `inert` also blocks widgets a disabled fieldset doesn't cover (custom selects, role="button"). + expect(fieldset?.hasAttribute("inert")).toBe(true); + + _setSchemaStaleForTests(false); + expect(fieldset?.disabled).toBe(false); + expect(fieldset?.hasAttribute("inert")).toBe(false); + }); + + it("disables the refresh-interval, items-per-page and default-tab selects themselves, not only the region around them", () => { + renderSettings(); + const triggers = Array.from(document.querySelectorAll("button.select")); + expect(triggers.length).toBeGreaterThanOrEqual(3); + for (const trigger of triggers) expect(trigger.disabled).toBe(false); + + _setSchemaStaleForTests(true); + for (const trigger of triggers) expect(trigger.disabled).toBe(true); + + _setSchemaStaleForTests(false); + for (const trigger of triggers) expect(trigger.disabled).toBe(false); + }); + + it("keeps the page header outside the disabled region so the back link stays usable", () => { + renderSettings(); + _setSchemaStaleForTests(true); + const back = screen.getByRole("link", { name: "Back to dashboard" }); + expect(back.closest("fieldset")).toBeNull(); + }); +}); + +describe("SettingsPage — Data: About", () => { + it("renders the About row with displayVersion() and links to Releases and Changelog", () => { + renderSettings(); + + screen.getByText("About"); + const versionLink = screen.getByRole("link", { name: "0.1.0+abcdef1" }); + expect(versionLink.getAttribute("href")).toBe( + "https://github.com/gordon-code/github-tracker/releases", + ); + expect(versionLink.getAttribute("target")).toBe("_blank"); + expect(versionLink.getAttribute("rel")).toBe("noopener noreferrer"); + + const changelogLink = screen.getByRole("link", { name: "Changelog" }); + expect(changelogLink.getAttribute("href")).toBe( + "https://github.com/gordon-code/github-tracker/blob/main/CHANGELOG.md", + ); + expect(changelogLink.getAttribute("target")).toBe("_blank"); + expect(changelogLink.getAttribute("rel")).toBe("noopener noreferrer"); + }); + + it("omits href on About links when isSafeGitHubUrl returns false", () => { + vi.mocked(urlModule.isSafeGitHubUrl).mockReturnValue(false); + renderSettings(); + + const versionEl = screen.getByText("0.1.0+abcdef1"); + expect(versionEl.getAttribute("href")).toBeNull(); + + const changelogEl = screen.getByText("Changelog"); + expect(changelogEl.getAttribute("href")).toBeNull(); + }); + + it("opens WhatsNewDialog when clicking the What's new button in the About row", async () => { + const user = userEvent.setup(); + renderSettings(); + + const whatsNewBtn = screen.getByRole("button", { name: "What's new" }); + await user.click(whatsNewBtn); + + await waitFor(() => { + expect(screen.getByText("What's New")).toBeDefined(); + expect(screen.getByText("v0.1.0")).toBeDefined(); + }); + }); }); diff --git a/tests/components/settings/ThemePicker.test.tsx b/tests/components/settings/ThemePicker.test.tsx index f7032cf7..d07ee82b 100644 --- a/tests/components/settings/ThemePicker.test.tsx +++ b/tests/components/settings/ThemePicker.test.tsx @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { render, screen } from "@solidjs/testing-library"; import userEvent from "@testing-library/user-event"; @@ -12,6 +12,7 @@ vi.mock("../../../src/app/stores/config", () => ({ })); import ThemePicker from "../../../src/app/components/settings/ThemePicker"; +import { _resetVersionStateForTests, _setSchemaStaleForTests } from "../../../src/app/lib/version"; beforeEach(() => { vi.clearAllMocks(); @@ -53,6 +54,49 @@ describe("ThemePicker", () => { expect(mockSetConfig).toHaveBeenCalledWith("theme", "dark"); }); + it("renders the Auto option as a native button so disabling and keyboard activation work", () => { + render(() => ); + const autoBtn = screen.getByRole("button", { name: "Theme: auto (follows system)" }); + expect(autoBtn.tagName).toBe("BUTTON"); + expect(autoBtn.getAttribute("type")).toBe("button"); + }); + + it("calls setConfig with 'auto' when the Auto option is clicked", async () => { + const user = userEvent.setup(); + render(() => ); + await user.click(screen.getByRole("button", { name: "Theme: auto (follows system)" })); + expect(mockSetConfig).toHaveBeenCalledWith("theme", "auto"); + }); + + describe("while the stored-data schema is stale", () => { + afterEach(() => { + _resetVersionStateForTests(); + }); + + it("disables the Auto option and every theme swatch, and clicking changes nothing", async () => { + const user = userEvent.setup(); + render(() => ); + _setSchemaStaleForTests(true); + + const buttons = screen.getAllByRole("button"); + expect(buttons).toHaveLength(9); + for (const button of buttons) expect((button as HTMLButtonElement).disabled).toBe(true); + + await user.click(screen.getByRole("button", { name: "Theme: auto (follows system)" })); + await user.click(screen.getByRole("button", { name: "Theme: dark" })); + expect(mockSetConfig).not.toHaveBeenCalled(); + }); + + it("re-enables the options once the schema matches again", () => { + render(() => ); + _setSchemaStaleForTests(true); + _setSchemaStaleForTests(false); + for (const button of screen.getAllByRole("button")) { + expect((button as HTMLButtonElement).disabled).toBe(false); + } + }); + }); + it("renders theme name as visible text in each button", () => { render(() => ); screen.getByText("light"); diff --git a/tests/components/shared/ToastContainer.test.tsx b/tests/components/shared/ToastContainer.test.tsx index 07fe94bf..fe013fad 100644 --- a/tests/components/shared/ToastContainer.test.tsx +++ b/tests/components/shared/ToastContainer.test.tsx @@ -13,6 +13,10 @@ import ToastContainer, { resetToastState, TOAST_REPEAT_COOLDOWN_MS, } from "../../../src/app/components/shared/ToastContainer"; +import { + _setUpdateAvailableForTests, + _resetVersionStateForTests, +} from "../../../src/app/lib/version"; // Mirrors the private TOASTED_MESSAGES_KEY constant in ToastContainer.tsx — // hardcoded here the same way tests/stores/config.test.ts hardcodes STORAGE_KEY. @@ -37,12 +41,14 @@ beforeEach(() => { clearNotifications(); clearMutedSources(); resetToastState(); + _resetVersionStateForTests(); vi.useFakeTimers(); // Ensure matchMedia returns non-reduced-motion vi.spyOn(window, "matchMedia").mockReturnValue({ matches: false } as MediaQueryList); }); afterEach(() => { + _resetVersionStateForTests(); vi.useRealTimers(); vi.restoreAllMocks(); }); @@ -533,4 +539,23 @@ describe("ToastContainer", () => { expect(container.firstElementChild?.getAttribute("aria-live")).toBeNull(); expect(container.firstElementChild?.getAttribute("aria-atomic")).toBeNull(); }); + + it("uses bottom-4 when updateAvailable is null and shifts to bottom-20 when updateAvailable is set", () => { + const { container } = render(() => ); + const wrapper = container.firstElementChild as HTMLElement; + expect(wrapper.className).toContain("bottom-4"); + expect(wrapper.className).not.toContain("bottom-20"); + + _setUpdateAvailableForTests({ + version: "0.1.2", + sha: "fedcba987654", + builtAt: "2026-01-02T00:00:00.000Z", + }); + expect(wrapper.className).toContain("bottom-20"); + expect(wrapper.className).not.toContain("bottom-4"); + + _setUpdateAvailableForTests(null); + expect(wrapper.className).toContain("bottom-4"); + expect(wrapper.className).not.toContain("bottom-20"); + }); }); diff --git a/tests/components/shared/UpdateBanner.test.tsx b/tests/components/shared/UpdateBanner.test.tsx new file mode 100644 index 00000000..d1765047 --- /dev/null +++ b/tests/components/shared/UpdateBanner.test.tsx @@ -0,0 +1,192 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { render, screen, fireEvent } from "@solidjs/testing-library"; +import { createRoot } from "solid-js"; +import UpdateBanner from "../../../src/app/components/shared/UpdateBanner"; +import { + _setUpdateAvailableForTests, + _setSchemaStaleForTests, + _resetVersionStateForTests, +} from "../../../src/app/lib/version"; +import { + getNotifications, + resetNotificationState, +} from "../../../src/app/lib/errors"; +import { + CONFIG_STORAGE_KEY, + updateConfig, + resetConfig, + initConfigPersistence, +} from "../../../src/app/stores/config"; +import { + VIEW_STORAGE_KEY, + updateViewState, + resetViewState, + initViewPersistence, +} from "../../../src/app/stores/view"; + +describe("UpdateBanner", () => { + const originalLocation = window.location; + let reloadMock: ReturnType; + + beforeEach(() => { + vi.useFakeTimers(); + sessionStorage.clear(); + localStorage.clear(); + _resetVersionStateForTests(); + resetNotificationState(); + resetConfig(); + resetViewState(); + + reloadMock = vi.fn(); + Object.defineProperty(window, "location", { + configurable: true, + writable: true, + value: { + reload: reloadMock, + pathname: "/", + search: "", + hash: "", + href: "", + }, + }); + }); + + afterEach(() => { + _resetVersionStateForTests(); + resetNotificationState(); + Object.defineProperty(window, "location", { + configurable: true, + writable: true, + value: originalLocation, + }); + vi.useRealTimers(); + }); + + describe("banner and app-update notification", () => { + it("is hidden when updateAvailable() is null", () => { + render(() => ); + expect(screen.queryByRole("status")).toBeNull(); + expect(getNotifications()).toHaveLength(0); + }); + + it("renders banner with Reload button and exact Changelog link when updateAvailable is set, and pushes app-update notification once", () => { + render(() => ); + + _setUpdateAvailableForTests({ + version: "0.1.2", + sha: "fedcba987654", + builtAt: "2026-01-02T00:00:00.000Z", + }); + + const banner = screen.getByRole("status"); + expect(banner.textContent).toContain("A new version is available."); + + const changelogLink = screen.getByRole("link", { name: "Changelog" }); + expect(changelogLink.getAttribute("href")).toBe( + "https://github.com/gordon-code/github-tracker/blob/main/CHANGELOG.md", + ); + expect(changelogLink.getAttribute("target")).toBe("_blank"); + expect(changelogLink.getAttribute("rel")).toBe("noopener noreferrer"); + + const notifs = getNotifications().filter((n) => n.source === "app-update"); + expect(notifs).toHaveLength(1); + expect(notifs[0].severity).toBe("info"); + expect(notifs[0].message).toBe( + "A new version of GitHub Tracker is available — reload to update.", + ); + // The banner already announces the update, so the notification must not also toast. + expect(notifs[0].silentToast).toBe(true); + + // Updating signal again must not duplicate or re-push the notification + _setUpdateAvailableForTests({ + version: "0.1.3", + sha: "111122223333", + builtAt: "2026-01-03T00:00:00.000Z", + }); + expect(getNotifications().filter((n) => n.source === "app-update")).toHaveLength(1); + }); + + it("says Settings are read-only only while the stored-data schema is stale", () => { + render(() => ); + _setUpdateAvailableForTests({ + version: "0.1.2", + sha: "fedcba987654", + builtAt: "2026-01-02T00:00:00.000Z", + }); + const banner = screen.getByRole("status"); + expect(banner.textContent).not.toContain("read-only"); + + _setSchemaStaleForTests(true); + expect(banner.textContent).toContain("A new version is available."); + expect(banner.textContent).toContain( + "This tab can't save changes, and Settings are read-only, until you reload.", + ); + + _setSchemaStaleForTests(false); + expect(banner.textContent).not.toContain("read-only"); + }); + + it("hides the banner and dismisses the app-update notification when the update clears, then re-notifies if flagged again", () => { + render(() => ); + const info = { + version: "0.1.2", + sha: "fedcba987654", + builtAt: "2026-01-02T00:00:00.000Z", + }; + + _setUpdateAvailableForTests(info); + expect(screen.getByRole("status")).toBeDefined(); + expect(getNotifications().filter((n) => n.source === "app-update")).toHaveLength(1); + + _setUpdateAvailableForTests(null); + expect(screen.queryByRole("status")).toBeNull(); + expect(getNotifications().filter((n) => n.source === "app-update")).toHaveLength(0); + + _setUpdateAvailableForTests(info); + expect(screen.getByRole("status")).toBeDefined(); + const renotified = getNotifications().filter((n) => n.source === "app-update"); + expect(renotified).toHaveLength(1); + expect(renotified[0].silentToast).toBe(true); + }); + + it("flushes pending config and viewState persistence before calling window.location.reload()", () => { + let disposePersistence!: () => void; + createRoot((d) => { + disposePersistence = d; + initConfigPersistence(); + initViewPersistence(); + }); + + _setUpdateAvailableForTests({ + version: "0.1.2", + sha: "fedcba987654", + builtAt: "2026-01-02T00:00:00.000Z", + }); + + let configAtReload: string | null = null; + let viewAtReload: string | null = null; + reloadMock.mockImplementation(() => { + configAtReload = localStorage.getItem(CONFIG_STORAGE_KEY); + viewAtReload = localStorage.getItem(VIEW_STORAGE_KEY); + }); + + render(() => ); + + updateConfig({ theme: "forest", onboardingComplete: true }); + updateViewState({ lastActiveTab: "actions" }); + + // Click Reload before the 200ms debounce timer fires + fireEvent.click(screen.getByRole("button", { name: "Reload" })); + + expect(reloadMock).toHaveBeenCalledTimes(1); + expect(configAtReload).not.toBeNull(); + expect(viewAtReload).not.toBeNull(); + expect((JSON.parse(configAtReload!) as { theme: string }).theme).toBe("forest"); + expect((JSON.parse(viewAtReload!) as { lastActiveTab: string }).lastActiveTab).toBe( + "actions", + ); + + disposePersistence(); + }); + }); +}); diff --git a/tests/components/shared/UpdateNavigator.test.tsx b/tests/components/shared/UpdateNavigator.test.tsx new file mode 100644 index 00000000..5364cbd6 --- /dev/null +++ b/tests/components/shared/UpdateNavigator.test.tsx @@ -0,0 +1,214 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { render, screen, fireEvent } from "@solidjs/testing-library"; +import { + MemoryRouter, + Route, + useNavigate, + useLocation, + createMemoryHistory, + type MemoryHistory, +} from "@solidjs/router"; +import { createRoot } from "solid-js"; +import UpdateNavigator from "../../../src/app/components/shared/UpdateNavigator"; +import { + _setUpdateAvailableForTests, + _resetVersionStateForTests, +} from "../../../src/app/lib/version"; +import { + CONFIG_STORAGE_KEY, + updateConfig, + resetConfig, + initConfigPersistence, +} from "../../../src/app/stores/config"; +import { + VIEW_STORAGE_KEY, + updateViewState, + resetViewState, + initViewPersistence, +} from "../../../src/app/stores/view"; + +const UPDATE_INFO = { + version: "0.1.2", + sha: "fedcba987654", + builtAt: "2026-01-02T00:00:00.000Z", +}; + +function NavTestHarness() { + const navigate = useNavigate(); + return ( +
+ + + + +
+ ); +} + +function PathnameProbe() { + const location = useLocation(); + return {location.pathname}; +} + +function renderWithNavigator(history: MemoryHistory) { + render(() => ( + ( + <> + + + {props.children} + + )} + > + + + + + )); +} + +describe("UpdateNavigator", () => { + const originalLocation = window.location; + let assignMock: ReturnType; + + beforeEach(() => { + vi.useFakeTimers(); + sessionStorage.clear(); + localStorage.clear(); + _resetVersionStateForTests(); + resetConfig(); + resetViewState(); + + assignMock = vi.fn(); + Object.defineProperty(window, "location", { + configurable: true, + writable: true, + value: { + reload: vi.fn(), + assign: assignMock, + pathname: "/", + search: "", + hash: "", + href: "", + }, + }); + }); + + afterEach(() => { + _resetVersionStateForTests(); + Object.defineProperty(window, "location", { + configurable: true, + writable: true, + value: originalLocation, + }); + vi.useRealTimers(); + }); + + it("navigates in-app without calling location.assign when updateAvailable is null", async () => { + const history = createMemoryHistory(); + renderWithNavigator(history); + expect(screen.getByTestId("router-pathname").textContent).toBe("/"); + + fireEvent.click(screen.getByRole("button", { name: "Go Settings" })); + await Promise.resolve(); + + expect(screen.getByTestId("router-pathname").textContent).toBe("/settings"); + expect(assignMock).not.toHaveBeenCalled(); + }); + + it("flushes debounced config and viewState persistence and calls location.assign once per target SHA on navigation", async () => { + let disposePersistence!: () => void; + createRoot((d) => { + disposePersistence = d; + initConfigPersistence(); + initViewPersistence(); + }); + + // Seed on-disk values that differ from the pending in-memory changes + localStorage.setItem( + CONFIG_STORAGE_KEY, + JSON.stringify({ theme: "corporate", onboardingComplete: false }), + ); + localStorage.setItem(VIEW_STORAGE_KEY, JSON.stringify({ lastActiveTab: "issues" })); + + let configAtAssign: string | null = null; + let viewAtAssign: string | null = null; + assignMock.mockImplementation(() => { + configAtAssign = localStorage.getItem(CONFIG_STORAGE_KEY); + viewAtAssign = localStorage.getItem(VIEW_STORAGE_KEY); + }); + + renderWithNavigator(createMemoryHistory()); + _setUpdateAvailableForTests(UPDATE_INFO); + + // Simulate commitImportedSettings mutating config + viewState right before navigating + updateConfig({ theme: "dracula", onboardingComplete: true }); + updateViewState({ lastActiveTab: "pullRequests" }); + + // Navigate before the 200ms debounce timer elapses + fireEvent.click(screen.getByRole("button", { name: "Go Settings" })); + await Promise.resolve(); + + expect(assignMock).toHaveBeenCalledTimes(1); + expect(assignMock).toHaveBeenCalledWith("/settings"); + expect(configAtAssign).not.toBeNull(); + expect(viewAtAssign).not.toBeNull(); + expect((JSON.parse(configAtAssign!) as { theme: string }).theme).toBe("dracula"); + expect( + (JSON.parse(configAtAssign!) as { onboardingComplete: boolean }).onboardingComplete, + ).toBe(true); + expect((JSON.parse(viewAtAssign!) as { lastActiveTab: string }).lastActiveTab).toBe( + "pullRequests", + ); + + // Second navigation with the same target SHA must not trigger another assign + fireEvent.click(screen.getByRole("button", { name: "Go Dashboard" })); + await Promise.resolve(); + expect(assignMock).toHaveBeenCalledTimes(1); + + disposePersistence(); + }); + + it("preserves location.search and location.hash when calling location.assign on pathname change and ignores same-path query/hash updates", async () => { + renderWithNavigator(createMemoryHistory()); + _setUpdateAvailableForTests(UPDATE_INFO); + + // Updating search/hash on the same pathname ("/") does not trigger location.assign + fireEvent.click(screen.getByRole("button", { name: "Same Path Query Change" })); + await Promise.resolve(); + expect(assignMock).not.toHaveBeenCalled(); + + // Navigating to a new pathname with search and hash passes full path + search + hash + fireEvent.click(screen.getByRole("button", { name: "Go Settings With Query And Hash" })); + await Promise.resolve(); + expect(assignMock).toHaveBeenCalledTimes(1); + expect(assignMock).toHaveBeenCalledWith("/settings?tab=general#jira"); + }); + + it("skips the reload for a protocol-relative pathname without consuming the per-target reload", async () => { + const history = createMemoryHistory(); + renderWithNavigator(history); + _setUpdateAvailableForTests(UPDATE_INFO); + + history.set({ value: "//evil.example/x" }); + await Promise.resolve(); + expect(screen.getByTestId("router-pathname").textContent).toBe("//evil.example/x"); + expect(assignMock).not.toHaveBeenCalled(); + + // The next same-origin pathname change still performs the once-per-target reload + history.set({ value: "/settings" }); + await Promise.resolve(); + expect(assignMock).toHaveBeenCalledTimes(1); + expect(assignMock).toHaveBeenCalledWith("/settings"); + }); +}); diff --git a/tests/components/shared/WhatsNewDialog.test.tsx b/tests/components/shared/WhatsNewDialog.test.tsx new file mode 100644 index 00000000..8e6ed63b --- /dev/null +++ b/tests/components/shared/WhatsNewDialog.test.tsx @@ -0,0 +1,241 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { render, screen, waitFor } from "@solidjs/testing-library"; +import WhatsNewDialog from "../../../src/app/components/shared/WhatsNewDialog"; +import { config, resetConfig, updateConfig } from "../../../src/app/stores/config"; +import * as changelogModule from "../../../src/app/lib/changelog"; +import { _resetChangelogCacheForTests } from "../../../src/app/lib/changelog"; +import { + APP_VERSION, + _resetVersionStateForTests, + _setAppVersionForTests, +} from "../../../src/app/lib/version"; +import type { ChangelogEntry } from "../../../src/shared/changelog-schema"; + +describe("WhatsNewDialog", () => { + beforeEach(() => { + resetConfig(); + _resetVersionStateForTests(); + _resetChangelogCacheForTests(); + }); + + afterEach(() => { + resetConfig(); + _resetVersionStateForTests(); + _resetChangelogCacheForTests(); + }); + + it("renders entries with version, date, section headings, items, PR link, commit SHA link, and full changelog link", () => { + const entries: ChangelogEntry[] = [ + { + version: "0.2.0", + date: "2026-11-10", + sections: [ + { + title: "Features", + items: [ + { + text: "dashboard: add keyboard navigation", + pr: 190, + sha: "1a2b3c4d5e6f", + }, + ], + }, + ], + }, + ]; + + render(() => ( + {}} entries={entries} /> + )); + + expect(screen.getByText("What's New")).toBeDefined(); + expect(screen.getByText("v0.2.0")).toBeDefined(); + expect(screen.getByText("2026-11-10")).toBeDefined(); + expect(screen.getByText("Features")).toBeDefined(); + expect(screen.getByText("dashboard: add keyboard navigation")).toBeDefined(); + + const prLink = screen.getByRole("link", { name: "#190" }); + expect(prLink.getAttribute("href")).toBe( + "https://github.com/gordon-code/github-tracker/pull/190", + ); + expect(prLink.getAttribute("target")).toBe("_blank"); + expect(prLink.getAttribute("rel")).toBe("noopener noreferrer"); + + const shaLink = screen.getByRole("link", { name: "(1a2b3c4)" }); + expect(shaLink.getAttribute("href")).toBe( + "https://github.com/gordon-code/github-tracker/commit/1a2b3c4d5e6f", + ); + expect(shaLink.getAttribute("target")).toBe("_blank"); + expect(shaLink.getAttribute("rel")).toBe("noopener noreferrer"); + + const fullLink = screen.getByRole("link", { name: "Full changelog on GitHub" }); + expect(fullLink.getAttribute("href")).toBe( + "https://github.com/gordon-code/github-tracker/blob/main/CHANGELOG.md", + ); + }); + + it("renders javascript:alert(1)", + pr: 42, + sha: "abcdef1", + }, + { + text: overlong, + // Invalid sha and negative pr should produce no link + pr: -5, + sha: "javascript:alert(1)", + }, + ], + }, + ], + }, + ]; + + render(() => ( + {}} entries={entries} /> + )); + + // XSS strings rendered literally as text nodes; no javascript:alert(1)", + ), + ).toBeDefined(); + expect(document.body.querySelectorAll("script").length).toBe(0); + expect(document.body.querySelectorAll("img").length).toBe(0); + + // 350-char string truncated to 300 chars + expect(screen.getByText("A".repeat(300))).toBeDefined(); + expect(screen.queryByText(overlong)).toBeNull(); + + // Every rendered [href] matches ^https://github\.com/gordon-code/github-tracker/ + const anchors = Array.from(document.body.querySelectorAll("a[href]")); + expect(anchors.length).toBeGreaterThan(0); + for (const a of anchors) { + expect(a.getAttribute("href")).toMatch( + /^https:\/\/github\.com\/gordon-code\/github-tracker\//, + ); + } + }); + + it("sets config.lastSeenVersion to APP_VERSION when opened with strict x.y.z APP_VERSION, and skips writing when APP_VERSION is not strict x.y.z", () => { + expect(config.lastSeenVersion).toBeNull(); + expect(APP_VERSION).toBe("0.1.0"); + + const { unmount } = render(() => ( + {}} entries={[]} /> + )); + expect(config.lastSeenVersion).toBe("0.1.0"); + unmount(); + + // Reset and test non-strict APP_VERSION + resetConfig(); + _setAppVersionForTests("0.1.0-dev"); + render(() => ( + {}} entries={[]} /> + )); + expect(config.lastSeenVersion).toBeNull(); + }); + + it("only moves lastSeenVersion forward, never back to an older build's version", () => { + updateConfig({ lastSeenVersion: "0.2.0" }); + const first = render(() => ( + {}} entries={[]} /> + )); + expect(config.lastSeenVersion).toBe("0.2.0"); + first.unmount(); + + updateConfig({ lastSeenVersion: "0.0.9" }); + render(() => ( + {}} entries={[]} /> + )); + expect(config.lastSeenVersion).toBe("0.1.0"); + }); + + it("replaces a stored lastSeenVersion that is not strict x.y.z", () => { + updateConfig({ lastSeenVersion: "garbage" }); + render(() => ( + {}} entries={[]} /> + )); + expect(config.lastSeenVersion).toBe("0.1.0"); + }); + + it("renders 'No release notes available.' empty state when entries is empty", () => { + render(() => ( + {}} entries={[]} /> + )); + + expect(screen.getByText("No release notes available.")).toBeDefined(); + }); + + it("lazily loads changelog entries via loadChangelog() when entries prop is omitted", async () => { + render(() => {}} />); + + await waitFor(() => { + expect(screen.getByText("v0.1.0")).toBeDefined(); + expect(screen.getByText("v0.0.9")).toBeDefined(); + expect( + screen.getByText( + "version: add in-app What's New dialog generated from CHANGELOG", + ), + ).toBeDefined(); + }); + }); + + it("settles an in-flight loadChangelog() after unmount without throwing or logging errors", async () => { + let resolveLoad!: (entries: ChangelogEntry[]) => void; + const loadSpy = vi.spyOn(changelogModule, "loadChangelog").mockReturnValue( + new Promise((settle) => { + resolveLoad = settle; + }), + ); + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + const { unmount } = render(() => ( + {}} /> + )); + expect(loadSpy).toHaveBeenCalledTimes(1); + + // Unmount while the load is still pending, then let it settle. + expect(() => unmount()).not.toThrow(); + resolveLoad([]); + await Promise.resolve(); + await Promise.resolve(); + + expect(errorSpy).not.toHaveBeenCalled(); + } finally { + loadSpy.mockRestore(); + errorSpy.mockRestore(); + } + }); + + it("keeps the footer Close button and full-changelog link available", () => { + render(() => {}} entries={[]} />); + + // Kobalte's CloseButton carries aria-label="Dismiss", so the footer button is found by its text. + expect(screen.getByText("Close").closest("button")).not.toBeNull(); + expect( + screen.getByRole("link", { name: "Full changelog on GitHub" }).getAttribute("href"), + ).toBe("https://github.com/gordon-code/github-tracker/blob/main/CHANGELOG.md"); + }); + + it("contains zero occurrences of innerHTML in WhatsNewDialog.tsx source", () => { + const source = readFileSync( + resolve(process.cwd(), "src/app/components/shared/WhatsNewDialog.tsx"), + "utf8", + ); + expect(source).not.toContain("innerHTML"); + }); +}); diff --git a/tests/lib/changelog.test.ts b/tests/lib/changelog.test.ts new file mode 100644 index 00000000..7302fce5 --- /dev/null +++ b/tests/lib/changelog.test.ts @@ -0,0 +1,120 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import type { ChangelogEntry } from "../../src/shared/changelog-schema"; +import { + compareSemver, + hasUnseen, + isStrictSemver, + loadChangelog, + _resetChangelogCacheForTests, +} from "../../src/app/lib/changelog"; + +const SAMPLE_ENTRIES: ChangelogEntry[] = [ + { + version: "0.10.0", + date: "2026-11-20", + sections: [{ title: "Features", items: [{ text: "feat: ten" }] }], + }, + { + version: "0.2.0", + date: "2026-11-10", + sections: [{ title: "Features", items: [{ text: "feat: two" }] }], + }, + { + version: "0.1.1", + date: "2026-11-05", + sections: [{ title: "Bug Fixes", items: [{ text: "fix: one-one" }] }], + }, + { + version: "0.1.0", + date: "2026-11-01", + sections: [{ title: "Features", items: [{ text: "feat: initial" }] }], + }, +]; + +describe("lib/changelog", () => { + beforeEach(() => { + _resetChangelogCacheForTests(); + }); + + afterEach(() => { + vi.doUnmock("virtual:changelog"); + _resetChangelogCacheForTests(); + }); + + it("validates strict x.y.z semver strings", () => { + expect(isStrictSemver("0.1.0")).toBe(true); + expect(isStrictSemver("10.20.30")).toBe(true); + expect(isStrictSemver("0.1.0-beta.1")).toBe(false); + expect(isStrictSemver("v0.1.0")).toBe(false); + expect(isStrictSemver("0.1")).toBe(false); + expect(isStrictSemver("")).toBe(false); + }); + + it("compares semver numerically across major, minor, and patch segments", () => { + expect(compareSemver("0.10.0", "0.2.0")).toBe(1); + expect(compareSemver("0.2.0", "0.10.0")).toBe(-1); + expect(compareSemver("1.0.0", "0.99.99")).toBe(1); + expect(compareSemver("0.1.2", "0.1.1")).toBe(1); + expect(compareSemver("0.1.1", "0.1.1")).toBe(0); + expect(compareSemver("invalid", "0.1.0")).toBe(0); + }); + + it("hasUnseen is true for any non-empty changelog when lastSeen is null, undefined, or not strict x.y.z", () => { + expect(hasUnseen(SAMPLE_ENTRIES, null)).toBe(true); + expect(hasUnseen(SAMPLE_ENTRIES, undefined)).toBe(true); + expect(hasUnseen(SAMPLE_ENTRIES, "")).toBe(true); + expect(hasUnseen(SAMPLE_ENTRIES, "0.1.1-test")).toBe(true); + expect(hasUnseen(SAMPLE_ENTRIES, "v0.1.1")).toBe(true); + }); + + it("hasUnseen is false for an empty changelog whatever lastSeen is", () => { + expect(hasUnseen([], null)).toBe(false); + expect(hasUnseen([], "0.1.0")).toBe(false); + }); + + it("hasUnseen is true only while a release is newer than lastSeen, comparing numerically", () => { + expect(hasUnseen(SAMPLE_ENTRIES, "0.1.1")).toBe(true); + expect(hasUnseen(SAMPLE_ENTRIES, "0.2.0")).toBe(true); + expect(hasUnseen(SAMPLE_ENTRIES, "0.9.9")).toBe(true); + expect(hasUnseen(SAMPLE_ENTRIES, "0.10.0")).toBe(false); + expect(hasUnseen(SAMPLE_ENTRIES, "1.0.0")).toBe(false); + }); + + it("loads and validates virtual:changelog and caches the result", async () => { + const first = await loadChangelog(); + const second = await loadChangelog(); + expect(first).toHaveLength(2); + expect(first[0].version).toBe("0.1.0"); + expect(second).toBe(first); + }); + + it("returns [] when virtual:changelog is invalid or rejected and recovers cleanly on subsequent loads", async () => { + // 1. Rejection: loadChangelog() catches the rejection, returns [], and clears cachedChangelogPromise + vi.resetModules(); + vi.doMock("virtual:changelog", () => { + throw new Error("chunk load failed"); + }); + const rejectedMod = await import("../../src/app/lib/changelog"); + await expect(rejectedMod.loadChangelog()).resolves.toEqual([]); + + // Without even calling _resetChangelogCacheForTests(), unmocking allows the next load to succeed + vi.doUnmock("virtual:changelog"); + const recoveredAfterReject = await rejectedMod.loadChangelog(); + expect(recoveredAfterReject).toHaveLength(2); + expect(recoveredAfterReject[0].version).toBe("0.1.0"); + + // 2. Invalid schema payload: loadChangelog() returns [] and recovers across _resetChangelogCacheForTests() + vi.resetModules(); + vi.doMock("virtual:changelog", () => ({ + default: { invalid: "not-an-array" }, + })); + const invalidMod = await import("../../src/app/lib/changelog"); + await expect(invalidMod.loadChangelog()).resolves.toEqual([]); + + vi.doUnmock("virtual:changelog"); + invalidMod._resetChangelogCacheForTests(); + const recoveredAfterInvalid = await invalidMod.loadChangelog(); + expect(recoveredAfterInvalid).toHaveLength(2); + expect(recoveredAfterInvalid[0].version).toBe("0.1.0"); + }); +}); diff --git a/tests/lib/chunk-reload.test.ts b/tests/lib/chunk-reload.test.ts new file mode 100644 index 00000000..3b155cdd --- /dev/null +++ b/tests/lib/chunk-reload.test.ts @@ -0,0 +1,373 @@ +import { readdirSync, readFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { + CHUNK_RELOAD_KEY, + CHUNK_RELOAD_MAX_AGE, + reloadOnceForStaleChunk, + installChunkReloadHandler, + lazyWithReload, +} from "../../src/app/lib/chunk-reload"; +import { + CONFIG_STORAGE_KEY, + updateConfig, + resetConfig, + initConfigPersistence, +} from "../../src/app/stores/config"; +import { + VIEW_STORAGE_KEY, + updateViewState, + resetViewState, + initViewPersistence, +} from "../../src/app/stores/view"; +import { createRoot, ErrorBoundary, Suspense } from "solid-js"; +import { render, waitFor } from "@solidjs/testing-library"; +import { + GIT_SHA, + _resetVersionStateForTests, + _setUpdateAvailableForTests, + updateAvailable, +} from "../../src/app/lib/version"; + +const NEWER_BUILD = { version: "9.9.9", sha: "fedcba987654", builtAt: "2026-01-02T00:00:00.000Z" }; + +function versionResponse(body: Record): Response { + return new Response(JSON.stringify(body), { + status: 200, + headers: { "content-type": "application/json" }, + }); +} + +describe("chunk-reload", () => { + const originalLocation = window.location; + let reloadMock: ReturnType; + + beforeEach(() => { + vi.useFakeTimers(); + sessionStorage.clear(); + localStorage.clear(); + _resetVersionStateForTests(); + resetConfig(); + resetViewState(); + + reloadMock = vi.fn(); + Object.defineProperty(window, "location", { + configurable: true, + writable: true, + value: { + reload: reloadMock, + href: "", + }, + }); + }); + + afterEach(() => { + Object.defineProperty(window, "location", { + configurable: true, + writable: true, + value: originalLocation, + }); + _resetVersionStateForTests(); + vi.unstubAllGlobals(); + vi.useRealTimers(); + }); + + describe("when no newer deployment is known yet", () => { + it("leaves the failed import to its caller and reloads only after the update check finds a newer build", async () => { + const fetchMock = vi.fn().mockResolvedValue(versionResponse(NEWER_BUILD)); + vi.stubGlobal("fetch", fetchMock); + const cleanup = installChunkReloadHandler(); + + const event = new Event("vite:preloadError", { cancelable: true }); + window.dispatchEvent(event); + expect(event.defaultPrevented).toBe(false); + expect(reloadMock).not.toHaveBeenCalled(); + + await vi.advanceTimersByTimeAsync(0); + expect(fetchMock).toHaveBeenCalledWith("/version.json", expect.objectContaining({ cache: "no-store" })); + expect(updateAvailable()).toEqual(NEWER_BUILD); + expect(reloadMock).toHaveBeenCalledTimes(1); + + cleanup(); + }); + + it("does not reload when the update check reports the running build (a blocked or flaky chunk)", async () => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue(versionResponse({ ...NEWER_BUILD, sha: GIT_SHA })), + ); + const cleanup = installChunkReloadHandler(); + + window.dispatchEvent(new Event("vite:preloadError", { cancelable: true })); + await vi.advanceTimersByTimeAsync(0); + + expect(updateAvailable()).toBeNull(); + expect(reloadMock).not.toHaveBeenCalled(); + cleanup(); + }); + + it("does not reload when the update check itself fails", async () => { + vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new TypeError("Failed to fetch"))); + const cleanup = installChunkReloadHandler(); + + window.dispatchEvent(new Event("vite:preloadError", { cancelable: true })); + await vi.advanceTimersByTimeAsync(0); + + expect(reloadMock).not.toHaveBeenCalled(); + cleanup(); + }); + }); + + it("reloads and prevents default on the first vite:preloadError once a newer build is known, suppresses within 10s, and reloads again after 10s", () => { + _setUpdateAvailableForTests(NEWER_BUILD); + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(versionResponse(NEWER_BUILD))); + const cleanup = installChunkReloadHandler(); + + const event1 = new Event("vite:preloadError", { cancelable: true }); + window.dispatchEvent(event1); + + expect(reloadMock).toHaveBeenCalledTimes(1); + expect(event1.defaultPrevented).toBe(true); + expect(sessionStorage.getItem(CHUNK_RELOAD_KEY)).not.toBeNull(); + + // Within 10s window — no reload and default not prevented + vi.advanceTimersByTime(CHUNK_RELOAD_MAX_AGE - 100); + const event2 = new Event("vite:preloadError", { cancelable: true }); + window.dispatchEvent(event2); + + expect(reloadMock).toHaveBeenCalledTimes(1); + expect(event2.defaultPrevented).toBe(false); + + // Past 10s window — reloads again + vi.advanceTimersByTime(200); + const event3 = new Event("vite:preloadError", { cancelable: true }); + window.dispatchEvent(event3); + + expect(reloadMock).toHaveBeenCalledTimes(2); + expect(event3.defaultPrevented).toBe(true); + + cleanup(); + + // After cleanup, listener is removed even after the 10s window elapses + vi.advanceTimersByTime(CHUNK_RELOAD_MAX_AGE + 100); + const event4 = new Event("vite:preloadError", { cancelable: true }); + window.dispatchEvent(event4); + expect(reloadMock).toHaveBeenCalledTimes(2); + expect(event4.defaultPrevented).toBe(false); + }); + + it("returns false and does not prevent default when sessionStorage throws", () => { + _setUpdateAvailableForTests(NEWER_BUILD); + const origGetItem = sessionStorage.getItem.bind(sessionStorage); + vi.spyOn(sessionStorage, "getItem").mockImplementation(() => { + throw new DOMException("Storage disabled", "SecurityError"); + }); + + const cleanup = installChunkReloadHandler(); + const event = new Event("vite:preloadError", { cancelable: true }); + window.dispatchEvent(event); + + expect(reloadMock).not.toHaveBeenCalled(); + expect(event.defaultPrevented).toBe(false); + + cleanup(); + vi.restoreAllMocks(); + Object.defineProperty(sessionStorage, "getItem", { + value: origGetItem, + configurable: true, + writable: true, + }); + }); + + it("flushes debounced config and viewState persistence before reloading", () => { + let dispose!: () => void; + createRoot((d) => { + dispose = d; + initConfigPersistence(); + initViewPersistence(); + }); + + updateConfig({ theme: "dracula" }); + updateViewState({ lastActiveTab: "pullRequests" }); + + // Before the 200ms debounce fires, trigger stale-chunk reload + expect(reloadOnceForStaleChunk()).toBe(true); + expect(reloadMock).toHaveBeenCalledTimes(1); + + const savedConfig = JSON.parse(localStorage.getItem(CONFIG_STORAGE_KEY) ?? "{}") as { + theme?: string; + }; + const savedView = JSON.parse(localStorage.getItem(VIEW_STORAGE_KEY) ?? "{}") as { + lastActiveTab?: string; + }; + expect(savedConfig.theme).toBe("dracula"); + expect(savedView.lastActiveTab).toBe("pullRequests"); + + dispose(); + }); + + it("lazyWithReload stays on the Suspense fallback, never reaching the ErrorBoundary, when a cancelled vite:preloadError resolves the import to undefined", async () => { + vi.useRealTimers(); + const errorBoundarySpy = vi.fn(); + + // Vite's preload helper resolves `import()` with `undefined` once a listener calls preventDefault(). + const PreventedLazy = lazyWithReload(() => Promise.resolve(undefined as never)); + const { container } = render(() => + ErrorBoundary({ + fallback: (err) => { + errorBoundarySpy(err); + return "Fallback"; + }, + get children() { + return Suspense({ + fallback: "Loading", + get children() { + return PreventedLazy({}); + }, + }); + }, + }), + ); + + await new Promise((done) => setTimeout(done, 20)); + + expect(errorBoundarySpy).not.toHaveBeenCalled(); + expect(container.textContent).toContain("Loading"); + expect(container.textContent).not.toContain("Fallback"); + }); + + it("lazyWithReload triggers reload without invoking ErrorBoundary on first rejection, and rethrows to ErrorBoundary within 10s cooldown", async () => { + vi.useRealTimers(); + const errorBoundarySpy = vi.fn(); + + const FailingLazy1 = lazyWithReload(() => Promise.reject(new Error("chunk load failed"))); + render(() => + ErrorBoundary({ + fallback: (err) => { + errorBoundarySpy(err); + return "Fallback"; + }, + get children() { + return Suspense({ + fallback: "Loading", + get children() { + return FailingLazy1({}); + }, + }); + }, + }), + ); + + await waitFor(() => { + expect(reloadMock).toHaveBeenCalledTimes(1); + }); + expect(errorBoundarySpy).not.toHaveBeenCalled(); + + // Second rejection within the 10s cooldown rethrows to ErrorBoundary + const FailingLazy2 = lazyWithReload(() => Promise.reject(new Error("chunk load failed again"))); + render(() => + ErrorBoundary({ + fallback: (err) => { + errorBoundarySpy(err); + return "Fallback"; + }, + get children() { + return Suspense({ + fallback: "Loading", + get children() { + return FailingLazy2({}); + }, + }); + }, + }), + ); + + await waitFor(() => { + expect(errorBoundarySpy).toHaveBeenCalledTimes(1); + }); + expect(reloadMock).toHaveBeenCalledTimes(1); + }); + + describe("while the browser is offline", () => { + beforeEach(() => { + _setUpdateAvailableForTests(NEWER_BUILD); + Object.defineProperty(navigator, "onLine", { + value: false, + writable: true, + configurable: true, + }); + }); + + afterEach(() => { + Reflect.deleteProperty(navigator, "onLine"); + }); + + it("does not reload, record the reload time, or prevent default on vite:preloadError, and reloads on the next failure once back online", () => { + const cleanup = installChunkReloadHandler(); + + const offlineEvent = new Event("vite:preloadError", { cancelable: true }); + window.dispatchEvent(offlineEvent); + + expect(reloadMock).not.toHaveBeenCalled(); + expect(offlineEvent.defaultPrevented).toBe(false); + expect(sessionStorage.getItem(CHUNK_RELOAD_KEY)).toBeNull(); + + Object.defineProperty(navigator, "onLine", { + value: true, + writable: true, + configurable: true, + }); + const onlineEvent = new Event("vite:preloadError", { cancelable: true }); + window.dispatchEvent(onlineEvent); + + expect(reloadMock).toHaveBeenCalledTimes(1); + expect(onlineEvent.defaultPrevented).toBe(true); + + cleanup(); + }); + + it("lazyWithReload rethrows a failed import to the ErrorBoundary without reloading", async () => { + vi.useRealTimers(); + const errorBoundarySpy = vi.fn(); + + const FailingLazy = lazyWithReload(() => Promise.reject(new Error("chunk load failed"))); + render(() => + ErrorBoundary({ + fallback: (err) => { + errorBoundarySpy(err); + return "Fallback"; + }, + get children() { + return Suspense({ + fallback: "Loading", + get children() { + return FailingLazy({}); + }, + }); + }, + }), + ); + + await waitFor(() => { + expect(errorBoundarySpy).toHaveBeenCalledTimes(1); + }); + expect(reloadMock).not.toHaveBeenCalled(); + }); + }); + + it("index.tsx installs the chunk reload handler before mounting App", () => { + const source = readFileSync(resolve(process.cwd(), "src/app/index.tsx"), "utf8"); + const installIdx = source.indexOf("installChunkReloadHandler()"); + const renderIdx = source.indexOf("render("); + expect(installIdx).toBeGreaterThan(-1); + expect(renderIdx).toBeGreaterThan(installIdx); + }); + + it("routes every lazy-loaded component in src/app through lazyWithReload", () => { + const appDir = resolve(process.cwd(), "src/app"); + const offenders = readdirSync(appDir, { encoding: "utf8", recursive: true }) + .filter((file) => /\.(ts|tsx)$/.test(file) && file !== join("lib", "chunk-reload.ts")) + .filter((file) => /\blazy\(/.test(readFileSync(join(appDir, file), "utf8"))); + expect(offenders).toEqual([]); + }); +}); diff --git a/tests/lib/field-persistence.test.ts b/tests/lib/field-persistence.test.ts new file mode 100644 index 00000000..1cd0b433 --- /dev/null +++ b/tests/lib/field-persistence.test.ts @@ -0,0 +1,415 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { createRoot, createSignal, untrack } from "solid-js"; +import { createStore, produce } from "solid-js/store"; +import { createFieldPersistence, resumePersistence, suspendPersistence } from "../../src/app/lib/field-persistence"; +import { getNotifications, resetNotificationState } from "../../src/app/lib/errors"; + +const KEY = "test:blob"; + +const localStorageMock = (() => { + let store: Record = {}; + return { + getItem: (key: string) => store[key] ?? null, + setItem: (key: string, value: string) => { + store[key] = value; + }, + removeItem: (key: string) => { + delete store[key]; + }, + clear: () => { + store = {}; + }, + }; +})(); + +Object.defineProperty(globalThis, "localStorage", { + value: localStorageMock, + writable: true, + configurable: true, +}); + +interface Fields extends Record { + a: number; + b: string[]; + c: { x: boolean }; +} + +const INITIAL: Fields = { a: 1, b: ["one"], c: { x: false } }; + +function onDisk(): Record { + return JSON.parse(localStorageMock.getItem(KEY) ?? "{}") as Record; +} + +function storageEvent(value: Record | null, storageArea: Storage | null = null): void { + window.dispatchEvent( + new StorageEvent("storage", { + key: KEY, + newValue: value === null ? null : JSON.stringify(value), + storageArea, + }), + ); +} + +function setup() { + const [store, setStore] = createStore(structuredClone(INITIAL)); + const [readOnly, setReadOnly] = createSignal(false); + const persistence = createFieldPersistence({ + storageKey: KEY, + snapshot: () => JSON.parse(JSON.stringify(untrack(() => store))) as Record, + trackedSnapshot: () => JSON.parse(JSON.stringify(store)) as Record, + validate: (parsed) => + typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) + ? (parsed as Record) + : undefined, + apply: (patch) => + setStore( + produce((draft) => { + Object.assign(draft, patch); + }), + ), + isReadOnly: () => readOnly(), + failureSource: "test:persist", + failureMessage: "Persist failed", + }); + return { store, setStore, persistence, setReadOnly }; +} + +describe("createFieldPersistence", () => { + let dispose: (() => void) | undefined; + + beforeEach(() => { + vi.useFakeTimers(); + localStorageMock.clear(); + resetNotificationState(); + }); + + afterEach(() => { + dispose?.(); + dispose = undefined; + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + function start() { + const subject = setup(); + createRoot((d) => { + dispose = d; + subject.persistence.init(); + }); + return subject; + } + + it("writes only the changed key on top of what is on disk, after the debounce", () => { + localStorageMock.setItem(KEY, JSON.stringify({ ...INITIAL, b: ["from-other-tab"] })); + const { setStore } = start(); + + setStore("a", 2); + expect(onDisk().a).toBe(1); + + vi.advanceTimersByTime(250); + expect(onDisk()).toEqual({ a: 2, b: ["from-other-tab"], c: { x: false } }); + }); + + it("flushes a pending write on dispose and cancels the timer", () => { + const { setStore } = start(); + setStore("a", 5); + dispose?.(); + dispose = undefined; + expect(onDisk().a).toBe(5); + }); + + describe("read-only mode", () => { + it("writes nothing and adopts nothing while read-only, then writes the pending change once re-enabled", () => { + const { store, setStore, persistence, setReadOnly } = start(); + setReadOnly(true); + + setStore("a", 9); + vi.advanceTimersByTime(250); + persistence.flush(); + expect(localStorageMock.getItem(KEY)).toBeNull(); + + storageEvent({ ...INITIAL, b: ["adopted?"] }); + expect(store.b).toEqual(["one"]); + + setReadOnly(false); + persistence.flush(); + expect(onDisk().a).toBe(9); + }); + + it("does not adopt what is on disk at init while read-only", () => { + localStorageMock.setItem(KEY, JSON.stringify({ ...INITIAL, a: 7 })); + const subject = setup(); + subject.setReadOnly(true); + createRoot((d) => { + dispose = d; + subject.persistence.init(); + }); + expect(subject.store.a).toBe(1); + }); + }); + + describe("suspendPersistence", () => { + afterEach(() => { + resumePersistence(); + }); + + it("blocks writes and adoption in every store until resumed, then writes the pending change", () => { + const { store, setStore, persistence } = start(); + suspendPersistence(); + + setStore("a", 2); + vi.advanceTimersByTime(250); + persistence.flush(); + expect(localStorageMock.getItem(KEY)).toBeNull(); + + storageEvent({ ...INITIAL, b: ["adopted?"] }); + expect(store.b).toEqual(["one"]); + + resumePersistence(); + persistence.flush(); + expect(onDisk().a).toBe(2); + }); + }); + + describe("catching up when persistence turns back on", () => { + afterEach(() => { + resumePersistence(); + }); + + it("resumePersistence() adopts what other tabs saved meanwhile and writes this tab's own change", () => { + const { store, setStore } = start(); + vi.advanceTimersByTime(250); + suspendPersistence(); + + setStore("a", 5); + localStorageMock.setItem(KEY, JSON.stringify({ ...INITIAL, b: ["from-other-tab"] })); + storageEvent({ ...INITIAL, b: ["from-other-tab"] }); + expect(store.b).toEqual(["one"]); + vi.advanceTimersByTime(250); + expect(onDisk().a).toBe(1); + + resumePersistence(); + expect(store.b).toEqual(["from-other-tab"]); + expect(store.a).toBe(5); + vi.advanceTimersByTime(250); + expect(onDisk()).toEqual({ a: 5, b: ["from-other-tab"], c: { x: false } }); + }); + + it("does not reconcile stores that were never initialised or have been disposed", () => { + const first = setup(); + const getItem = vi.spyOn(localStorageMock, "getItem"); + resumePersistence(); + expect(getItem).not.toHaveBeenCalled(); + expect(first.store.a).toBe(1); + + const { setStore } = start(); + vi.advanceTimersByTime(250); + dispose?.(); + dispose = undefined; + getItem.mockClear(); + setStore("a", 2); + resumePersistence(); + expect(getItem).not.toHaveBeenCalled(); + }); + + it("catches up when read-only mode ends", () => { + const { store, persistence, setReadOnly } = start(); + vi.advanceTimersByTime(250); + setReadOnly(true); + localStorageMock.setItem(KEY, JSON.stringify({ ...INITIAL, a: 9 })); + storageEvent({ ...INITIAL, a: 9 }); + expect(store.a).toBe(1); + + setReadOnly(false); + expect(store.a).toBe(9); + persistence.flush(); + expect(onDisk().a).toBe(9); + }); + }); + + describe("storage events", () => { + it("adopts a key another tab wrote and does not write it back", () => { + const { store, persistence } = start(); + vi.advanceTimersByTime(250); + const setItem = vi.spyOn(localStorageMock, "setItem"); + + storageEvent({ ...INITIAL, a: 4 }); + expect(store.a).toBe(4); + + vi.advanceTimersByTime(250); + persistence.flush(); + expect(setItem).not.toHaveBeenCalled(); + }); + + it("ignores events from a different storage area", () => { + const { store } = start(); + storageEvent({ ...INITIAL, a: 4 }, sessionStorage); + expect(store.a).toBe(1); + }); + + it("accepts events whose storage area is localStorage", () => { + const { store } = start(); + const area = localStorageMock as unknown as Storage; + storageEvent({ ...INITIAL, a: 4 }, area); + expect(store.a).toBe(4); + }); + + it("ignores removals, other keys, and unparseable or non-object values", () => { + const { store } = start(); + storageEvent(null); + window.dispatchEvent(new StorageEvent("storage", { key: "other", newValue: JSON.stringify({ a: 8 }) })); + window.dispatchEvent(new StorageEvent("storage", { key: KEY, newValue: "{broken" })); + window.dispatchEvent(new StorageEvent("storage", { key: KEY, newValue: "[1]" })); + expect(store.a).toBe(1); + }); + + it("keeps a key this tab has a pending change to", () => { + const { store, setStore } = start(); + setStore("a", 3); + storageEvent({ ...INITIAL, a: 4, b: ["other"] }); + expect(store.a).toBe(3); + expect(store.b).toEqual(["other"]); + + vi.advanceTimersByTime(250); + expect(onDisk().a).toBe(3); + }); + + it("still writes a kept local value after the user reverts it to the value last saved", () => { + const { store, setStore } = start(); + vi.advanceTimersByTime(250); + localStorageMock.setItem(KEY, JSON.stringify({ ...INITIAL, a: 4 })); + + setStore("a", 3); + storageEvent({ ...INITIAL, a: 4 }); + expect(store.a).toBe(3); + + // Back to the baseline: nothing differs from the last save, but the user's latest choice + // must still win over the value the other tab wrote. + setStore("a", 1); + vi.advanceTimersByTime(250); + expect(onDisk().a).toBe(1); + }); + + it("skips reading the stored blob when a commit has nothing pending", () => { + const { store } = start(); + vi.advanceTimersByTime(250); + const getItem = vi.spyOn(localStorageMock, "getItem"); + + storageEvent({ ...INITIAL, b: ["from-other-tab"] }); + expect(store.b).toEqual(["from-other-tab"]); + getItem.mockClear(); + + vi.advanceTimersByTime(250); + expect(getItem).not.toHaveBeenCalled(); + }); + + it("stops listening after dispose", () => { + const { store } = start(); + dispose?.(); + dispose = undefined; + storageEvent({ ...INITIAL, a: 4 }); + expect(store.a).toBe(1); + }); + }); + + describe("requestFullOverwrite", () => { + it("writes the whole snapshot and ignores other tabs' events until the write lands", () => { + const { store, setStore, persistence } = start(); + localStorageMock.setItem(KEY, JSON.stringify({ a: 99, b: ["other"], c: { x: true } })); + + persistence.requestFullOverwrite(); + setStore(produce((draft) => Object.assign(draft, INITIAL))); + persistence.schedule(); + + storageEvent({ a: 50, b: ["ignored"], c: { x: true } }); + expect(store.b).toEqual(["one"]); + + vi.advanceTimersByTime(250); + expect(onDisk()).toEqual(INITIAL); + + storageEvent({ ...INITIAL, a: 6 }); + expect(store.a).toBe(6); + }); + }); + + describe("forceKeys", () => { + it("writes a key that matches this tab's last save, and resists an incoming event", () => { + const { store, persistence } = start(); + vi.advanceTimersByTime(250); + localStorageMock.setItem(KEY, JSON.stringify({ ...INITIAL, a: 77 })); + + persistence.forceKeys(["a"]); + persistence.schedule(); + storageEvent({ ...INITIAL, a: 88 }); + expect(store.a).toBe(1); + + vi.advanceTimersByTime(250); + expect(onDisk().a).toBe(1); + }); + }); + + describe("failed writes", () => { + it("warns, keeps the change pending, and writes it on the next attempt", () => { + const { setStore, persistence } = start(); + vi.advanceTimersByTime(250); + setStore("a", 2); + + const setItem = vi.spyOn(localStorageMock, "setItem").mockImplementationOnce(() => { + throw new DOMException("QuotaExceededError", "QuotaExceededError"); + }); + persistence.flush(); + expect(getNotifications().some((n) => n.source === "test:persist")).toBe(true); + expect(onDisk().a).toBe(1); + + persistence.flush(); + expect(setItem).toHaveBeenCalledTimes(2); + expect(onDisk().a).toBe(2); + }); + + it("keeps a pending full overwrite after a failed write", () => { + const { store, setStore, persistence } = start(); + vi.advanceTimersByTime(250); + + persistence.requestFullOverwrite(); + setStore("a", 3); + vi.spyOn(localStorageMock, "setItem").mockImplementationOnce(() => { + throw new DOMException("QuotaExceededError", "QuotaExceededError"); + }); + persistence.flush(); + + storageEvent({ ...INITIAL, b: ["ignored"] }); + expect(store.b).toEqual(["one"]); + + persistence.flush(); + expect(onDisk()).toEqual({ a: 3, b: ["one"], c: { x: false } }); + }); + }); + + describe("discardPending", () => { + it("cancels the scheduled write and treats the current contents as saved", () => { + const { setStore, persistence } = start(); + vi.advanceTimersByTime(250); + localStorageMock.clear(); + + setStore("a", 2); + persistence.discardPending(); + vi.advanceTimersByTime(250); + persistence.flush(); + expect(localStorageMock.getItem(KEY)).toBeNull(); + + setStore("a", 3); + persistence.flush(); + expect(onDisk().a).toBe(3); + }); + + it("clears a pending full overwrite and forced keys", () => { + const { store, persistence } = start(); + persistence.requestFullOverwrite(); + persistence.forceKeys(["a"]); + persistence.discardPending(); + + storageEvent({ ...INITIAL, a: 4 }); + expect(store.a).toBe(4); + }); + }); +}); diff --git a/tests/lib/persisted-fields.test.ts b/tests/lib/persisted-fields.test.ts new file mode 100644 index 00000000..b43f70cc --- /dev/null +++ b/tests/lib/persisted-fields.test.ts @@ -0,0 +1,72 @@ +import { describe, it, expect } from "vitest"; +import { hasPendingFields, mergeFieldsForWrite, takeForeignFields, toFieldJson } from "../../src/app/lib/persisted-fields"; + +describe("persisted-fields", () => { + const baseline = () => toFieldJson({ a: 1, b: [1], c: { x: true } }); + + it("hasPendingFields reports a change only when a key's JSON differs from the baseline", () => { + expect(hasPendingFields({ a: 1, b: [1], c: { x: true } }, baseline())).toBe(false); + expect(hasPendingFields({ a: 2, b: [1], c: { x: true } }, baseline())).toBe(true); + }); + + it("mergeFieldsForWrite overlays only pending and missing keys onto the on-disk blob", () => { + const result = mergeFieldsForWrite({ a: 2, b: [1], c: { x: true } }, { a: 1, b: [9] }, baseline(), new Set()); + expect(result.merged).toEqual({ a: 2, b: [9], c: { x: true } }); + expect(result.writtenFields).toEqual({ a: "2", c: '{"x":true}' }); + expect(result.changed).toBe(true); + }); + + it("mergeFieldsForWrite reports no change when the overlay already matches disk", () => { + const result = mergeFieldsForWrite({ a: 2, b: [1], c: { x: true } }, { a: 2, b: [1], c: { x: true } }, baseline(), new Set()); + expect(result.changed).toBe(false); + expect(result.writtenFields).toEqual({ a: "2" }); + }); + + it("mergeFieldsForWrite writes a forced key even when it matches the baseline", () => { + const result = mergeFieldsForWrite({ a: 1, b: [1], c: { x: true } }, { a: 5, b: [1], c: { x: true } }, baseline(), new Set(["a"])); + expect(result.merged.a).toBe(1); + expect(result.writtenFields).toEqual({ a: "1" }); + expect(result.changed).toBe(true); + }); + + it("mergeFieldsForWrite reports a forced key already equal on disk as written but unchanged", () => { + const result = mergeFieldsForWrite({ a: 1, b: [1], c: { x: true } }, { a: 1, b: [1], c: { x: true } }, baseline(), new Set(["a"])); + expect(result.changed).toBe(false); + expect(result.writtenFields).toEqual({ a: "1" }); + }); + + it("mergeFieldsForWrite keeps a key that is on disk but not in the snapshot", () => { + const result = mergeFieldsForWrite({ a: 2 }, { a: 1, extra: "kept" }, toFieldJson({ a: 1 }), new Set()); + expect(result.merged).toEqual({ a: 2, extra: "kept" }); + }); + + it("mergeFieldsForWrite writes the whole snapshot when there is no on-disk blob", () => { + const snapshot = { a: 1, b: [1], c: { x: true } }; + const result = mergeFieldsForWrite(snapshot, undefined, baseline(), new Set()); + expect(result.merged).toEqual(snapshot); + expect(result.writtenFields).toEqual(toFieldJson(snapshot)); + expect(result.changed).toBe(true); + }); + + it("takeForeignFields adopts keys with no pending change and keeps pending local values", () => { + const base = baseline(); + const patch = takeForeignFields({ a: 3, b: [7], c: { x: true } }, { a: 2, b: [1], c: { x: true } }, base, new Set()); + expect(patch).toEqual({ b: [7] }); + expect(base.b).toBe("[7]"); + expect(base.a).toBe("1"); + }); + + it("takeForeignFields marks a kept pending key as forced so a later revert is still written", () => { + const forced = new Set(); + takeForeignFields({ a: 3, b: [1] }, { a: 2, b: [1], c: { x: true } }, baseline(), forced); + expect([...forced]).toEqual(["a"]); + }); + + it("takeForeignFields skips forced keys and settles a pending key whose incoming value matches", () => { + const base = baseline(); + const patch = takeForeignFields({ a: 2, b: [7] }, { a: 2, b: [1], c: { x: true } }, base, new Set(["b"])); + expect(patch).toEqual({}); + expect(base.a).toBe("2"); + expect(base.b).toBe("[1]"); + }); +}); diff --git a/tests/lib/sentry-facade.test.ts b/tests/lib/sentry-facade.test.ts index b4c77dc5..16dc10ff 100644 --- a/tests/lib/sentry-facade.test.ts +++ b/tests/lib/sentry-facade.test.ts @@ -143,6 +143,11 @@ describe("sentry-facade", () => { expect(mockSentryInit).toHaveBeenCalledOnce(); expect(mockSentryCaptureException).toHaveBeenCalledTimes(2); }); + expect(mockSentryInit).toHaveBeenCalledWith( + expect.objectContaining({ + release: "github-tracker@abcdef123456", + }), + ); expect(_getSentryQueueForTests()).toHaveLength(0); expect((mockSentryCaptureException.mock.calls[0][0] as Error).message).toBe( diff --git a/tests/lib/sentry.test.ts b/tests/lib/sentry.test.ts index 782c4768..c678e845 100644 --- a/tests/lib/sentry.test.ts +++ b/tests/lib/sentry.test.ts @@ -475,7 +475,7 @@ describe("initSdk", () => { expect(mockInit).not.toHaveBeenCalled(); }); - it("calls Sentry.init with correct DSN and enhanceFetchErrorMessages: 'report-only' when VITE_SENTRY_DSN is set", () => { + it("calls Sentry.init with correct DSN, release tag, and enhanceFetchErrorMessages: 'report-only' when VITE_SENTRY_DSN is set", () => { vi.stubEnv("DEV", false); vi.stubEnv("VITE_SENTRY_DSN", "https://test-key@o1.ingest.us.sentry.io/1"); initSdk(); @@ -483,6 +483,7 @@ describe("initSdk", () => { expect(mockInit).toHaveBeenCalledWith( expect.objectContaining({ dsn: "https://test-key@o1.ingest.us.sentry.io/1", + release: "github-tracker@abcdef123456", enhanceFetchErrorMessages: "report-only", }), ); diff --git a/tests/lib/settings-transfer.test.ts b/tests/lib/settings-transfer.test.ts index facd8927..8562e5d7 100644 --- a/tests/lib/settings-transfer.test.ts +++ b/tests/lib/settings-transfer.test.ts @@ -86,6 +86,7 @@ const EXPECTED_CONFIG_KEYS = [ "hotPollInterval", "itemsPerPage", "jira", + "lastSeenVersion", "maxRunsPerWorkflow", "maxWorkflowsPerRepo", "mcpRelayEnabled", @@ -267,6 +268,18 @@ describe("buildExportPayload", () => { expect(Object.prototype.hasOwnProperty.call(out, "mcpRelayEnabled")).toBe(true); expect(Object.prototype.hasOwnProperty.call(out, "mcpRelayPort")).toBe(true); }); + + it("round-trips lastSeenVersion through buildExportPayload and parseImportFile", () => { + const cfg = ConfigSchema.parse({ lastSeenVersion: "0.1.1" }); + const out = buildExportPayload(cfg, viewState); + expect(out.lastSeenVersion).toBe("0.1.1"); + + const parsed = parseImportFile(JSON.stringify(out)); + expect(parsed.ok).toBe(true); + if (parsed.ok) { + expect(parsed.config.lastSeenVersion).toBe("0.1.1"); + } + }); }); // ── curated, privacy-scrubbed view preferences ──────────────────────────────── diff --git a/tests/lib/version.test.ts b/tests/lib/version.test.ts new file mode 100644 index 00000000..f1a19edc --- /dev/null +++ b/tests/lib/version.test.ts @@ -0,0 +1,533 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { + APP_VERSION, + GIT_SHA, + SCHEMA_FP, + displayVersion, + getAppVersion, + schemaStale, + updateAvailable, + VERSION_CHECK_MIN_INTERVAL_MS, + _setLoadedAtForTests, + checkForUpdate, + reloadOncePerTarget, + startVersionWatch, + VERSION_WATCH_INITIAL_DELAY_MS, + _setAppVersionForTests, + _setGitShaForTests, + _resetVersionStateForTests, +} from "../../src/app/lib/version"; +import { BuildInfoSchema } from "../../src/shared/build-meta"; + +function makeJsonResponse( + body: unknown, + options?: { status?: number; contentType?: string }, +): Response { + const status = options?.status ?? 200; + const contentType = options?.contentType ?? "application/json; charset=utf-8"; + return new Response(typeof body === "string" ? body : JSON.stringify(body), { + status, + headers: { "content-type": contentType }, + }); +} + +describe("version metadata", () => { + beforeEach(() => { + _resetVersionStateForTests(); + }); + + afterEach(() => { + _resetVersionStateForTests(); + vi.useRealTimers(); + }); + + it("exposes build-time constants from Vite defines", () => { + expect(APP_VERSION).toBe("0.1.0"); + expect(GIT_SHA).toBe("abcdef123456"); + }); + + it("formats displayVersion() as +<7-char GIT_SHA>", () => { + expect(displayVersion()).toBe(`${APP_VERSION}+${GIT_SHA.slice(0, 7)}`); + expect(displayVersion()).toBe("0.1.0+abcdef1"); + }); + + it("getAppVersion() tracks the running build version and the test override resets", () => { + expect(getAppVersion()).toBe(APP_VERSION); + _setAppVersionForTests("9.9.9"); + expect(getAppVersion()).toBe("9.9.9"); + expect(displayVersion()).toBe("9.9.9+abcdef1"); + _resetVersionStateForTests(); + expect(getAppVersion()).toBe(APP_VERSION); + }); + + it("displayVersion() reflects the git SHA test override", () => { + _setGitShaForTests("1234567890ab"); + expect(displayVersion()).toBe("0.1.0+1234567"); + }); + + describe("BuildInfoSchema", () => { + it("accepts valid version metadata with hex SHA or 'dev'", () => { + const validHex = BuildInfoSchema.safeParse({ + version: "0.1.1", + sha: "1234567890ab", + builtAt: "2026-01-02T00:00:00.000Z", + }); + expect(validHex.success).toBe(true); + + const validDev = BuildInfoSchema.safeParse({ + version: "0.1.1", + sha: "dev", + builtAt: "2026-01-02T00:00:00.000Z", + }); + expect(validDev.success).toBe(true); + }); + + it("rejects oversized strings or invalid SHA formats", () => { + expect( + BuildInfoSchema.safeParse({ + version: "v".repeat(33), + sha: "1234567890ab", + builtAt: "2026-01-02T00:00:00.000Z", + }).success, + ).toBe(false); + + expect( + BuildInfoSchema.safeParse({ + version: "0.1.1", + sha: "not-a-hex-sha", + builtAt: "2026-01-02T00:00:00.000Z", + }).success, + ).toBe(false); + + expect( + BuildInfoSchema.safeParse({ + version: "0.1.1", + sha: "1234567890ab", + builtAt: "t".repeat(41), + }).success, + ).toBe(false); + }); + }); + + describe("schemaStale", () => { + const remote = { version: "0.1.1", sha: "fedcba987654", builtAt: "2026-01-02T12:00:00.000Z" }; + + it("is false by default and when the deployed schema fingerprint matches this build", async () => { + expect(schemaStale()).toBe(false); + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(makeJsonResponse({ ...remote, schemaFp: SCHEMA_FP }))); + await checkForUpdate(); + expect(updateAvailable()).toEqual({ ...remote, schemaFp: SCHEMA_FP }); + expect(schemaStale()).toBe(false); + }); + + it("is true when the deployed schema fingerprint differs from this build's", async () => { + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(makeJsonResponse({ ...remote, schemaFp: "ffffffffffff" }))); + await checkForUpdate(); + expect(schemaStale()).toBe(true); + }); + + it("stays false when the deployed version.json has no fingerprint", async () => { + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(makeJsonResponse(remote))); + await checkForUpdate(); + expect(updateAvailable()).toEqual(remote); + expect(schemaStale()).toBe(false); + }); + + it("clears when a later check reports a matching fingerprint, and survives an unusable response", async () => { + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(makeJsonResponse({ ...remote, schemaFp: "ffffffffffff" }))); + await checkForUpdate(); + expect(schemaStale()).toBe(true); + + vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new TypeError("Failed to fetch"))); + await checkForUpdate(); + expect(schemaStale()).toBe(true); + + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(makeJsonResponse({ ...remote, schemaFp: SCHEMA_FP }))); + await checkForUpdate(); + expect(schemaStale()).toBe(false); + }); + + it("is never set by a dev build", async () => { + _setGitShaForTests("dev"); + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(makeJsonResponse({ ...remote, schemaFp: "ffffffffffff" }))); + await checkForUpdate(); + expect(schemaStale()).toBe(false); + }); + + it("BuildInfoSchema accepts a 12-hex schemaFp and rejects other shapes", () => { + expect(BuildInfoSchema.safeParse({ ...remote, schemaFp: "0123456789ab" }).success).toBe(true); + expect(BuildInfoSchema.safeParse({ ...remote, schemaFp: "not-a-hash" }).success).toBe(false); + expect(BuildInfoSchema.safeParse({ ...remote, schemaFp: "ABCDEF123456" }).success).toBe(false); + }); + }); + + describe("throttled checks", () => { + const sameBuild = () => makeJsonResponse({ version: "0.1.0", sha: GIT_SHA, builtAt: "2026-01-01T00:00:00.000Z" }); + + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z")); + }); + + it("skips a throttled check during the boot window, but runs an unthrottled one", async () => { + const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(sameBuild())); + vi.stubGlobal("fetch", fetchMock); + _setLoadedAtForTests(Date.now()); + + await checkForUpdate({ throttled: true }); + expect(fetchMock).not.toHaveBeenCalled(); + + await checkForUpdate(); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it("runs a throttled check once the boot window has passed, then skips repeats inside the minimum interval", async () => { + const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(sameBuild())); + vi.stubGlobal("fetch", fetchMock); + _setLoadedAtForTests(Date.now() - VERSION_WATCH_INITIAL_DELAY_MS - 1); + + await checkForUpdate({ throttled: true }); + expect(fetchMock).toHaveBeenCalledTimes(1); + + vi.advanceTimersByTime(VERSION_CHECK_MIN_INTERVAL_MS - 1); + await checkForUpdate({ throttled: true }); + expect(fetchMock).toHaveBeenCalledTimes(1); + + vi.advanceTimersByTime(1); + await checkForUpdate({ throttled: true }); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it("lets a visibility-driven check through right after a throttled one, and counts it toward the interval", async () => { + const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(sameBuild())); + vi.stubGlobal("fetch", fetchMock); + _setLoadedAtForTests(Date.now() - VERSION_WATCH_INITIAL_DELAY_MS - 1); + + await checkForUpdate({ throttled: true }); + await checkForUpdate(); + expect(fetchMock).toHaveBeenCalledTimes(2); + + vi.advanceTimersByTime(2_000); + await checkForUpdate({ throttled: true }); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + }); + + describe("checkForUpdate", () => { + it("leaves updateAvailable null when remote SHA matches local GIT_SHA", async () => { + const fetchMock = vi.fn().mockResolvedValue( + makeJsonResponse({ + version: "0.1.0", + sha: GIT_SHA, + builtAt: "2026-01-01T00:00:00.000Z", + }), + ); + vi.stubGlobal("fetch", fetchMock); + + await checkForUpdate(); + + expect(fetchMock).toHaveBeenCalledWith("/version.json", { + cache: "no-store", + credentials: "same-origin", + }); + expect(updateAvailable()).toBeNull(); + }); + + it("sets updateAvailable when remote SHA differs from local GIT_SHA", async () => { + const remoteInfo = { + version: "0.1.1", + sha: "fedcba987654", + builtAt: "2026-01-02T12:00:00.000Z", + }; + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(makeJsonResponse(remoteInfo))); + + await checkForUpdate(); + + expect(updateAvailable()).toEqual(remoteInfo); + }); + + it("clears updateAvailable when a later check reports the running build again", async () => { + const remoteInfo = { + version: "0.1.1", + sha: "fedcba987654", + builtAt: "2026-01-02T12:00:00.000Z", + }; + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(makeJsonResponse(remoteInfo))); + await checkForUpdate(); + expect(updateAvailable()).toEqual(remoteInfo); + + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + makeJsonResponse({ + version: "0.1.0", + sha: GIT_SHA, + builtAt: "2026-01-01T00:00:00.000Z", + }), + ), + ); + await checkForUpdate(); + expect(updateAvailable()).toBeNull(); + }); + + it("keeps a flagged update when a later response is unusable", async () => { + const remoteInfo = { + version: "0.1.1", + sha: "fedcba987654", + builtAt: "2026-01-02T12:00:00.000Z", + }; + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(makeJsonResponse(remoteInfo))); + await checkForUpdate(); + + vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new TypeError("Failed to fetch"))); + await checkForUpdate(); + expect(updateAvailable()).toEqual(remoteInfo); + + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + makeJsonResponse({ version: "0.1.1", sha: "dev", builtAt: "2026-01-02T12:00:00.000Z" }), + ), + ); + await checkForUpdate(); + expect(updateAvailable()).toEqual(remoteInfo); + }); + + it("ignores non-OK HTTP responses and text/html SPA fallbacks", async () => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + makeJsonResponse( + { version: "0.1.1", sha: "fedcba987654", builtAt: "2026-01-02T12:00:00.000Z" }, + { status: 404 }, + ), + ), + ); + await checkForUpdate(); + expect(updateAvailable()).toBeNull(); + + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + makeJsonResponse("", { + status: 200, + contentType: "text/html; charset=utf-8", + }), + ), + ); + await checkForUpdate(); + expect(updateAvailable()).toBeNull(); + + const headerlessRes = new Response( + JSON.stringify({ + version: "0.1.1", + sha: "fedcba987654", + builtAt: "2026-01-02T12:00:00.000Z", + }), + { status: 200 }, + ); + headerlessRes.headers.delete("content-type"); + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(headerlessRes)); + await checkForUpdate(); + expect(updateAvailable()).toBeNull(); + }); + + it("compares 12-char SHA prefixes case-insensitively", async () => { + _setGitShaForTests("ABCDEF1234567890ABCDEF1234567890ABCDEF12"); + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + makeJsonResponse({ + version: "0.1.1", + sha: "abcdef123456", + builtAt: "2026-01-02T12:00:00.000Z", + }), + ), + ); + await checkForUpdate(); + expect(updateAvailable()).toBeNull(); + }); + + it("ignores malformed JSON, schema failures, and network errors", async () => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + makeJsonResponse("{invalid-json", { + status: 200, + contentType: "application/json", + }), + ), + ); + await checkForUpdate(); + expect(updateAvailable()).toBeNull(); + + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + makeJsonResponse({ + version: "0.1.1", + sha: "", + builtAt: "2026-01-02T12:00:00.000Z", + }), + ), + ); + await checkForUpdate(); + expect(updateAvailable()).toBeNull(); + + vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new TypeError("Failed to fetch"))); + await checkForUpdate(); + expect(updateAvailable()).toBeNull(); + }); + + it("never flags an update when local GIT_SHA or remote SHA is 'dev'", async () => { + _setGitShaForTests("dev"); + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + makeJsonResponse({ + version: "0.1.1", + sha: "fedcba987654", + builtAt: "2026-01-02T12:00:00.000Z", + }), + ), + ); + await checkForUpdate(); + expect(updateAvailable()).toBeNull(); + + _setGitShaForTests(GIT_SHA); + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue( + makeJsonResponse({ + version: "0.1.1", + sha: "dev", + builtAt: "2026-01-02T12:00:00.000Z", + }), + ), + ); + await checkForUpdate(); + expect(updateAvailable()).toBeNull(); + }); + + it("coalesces concurrent checkForUpdate() calls into a single in-flight fetch", async () => { + let resolveFetch!: (res: Response) => void; + const fetchMock = vi.fn( + () => + new Promise((resolve) => { + resolveFetch = resolve; + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const p1 = checkForUpdate(); + const p2 = checkForUpdate(); + expect(fetchMock).toHaveBeenCalledTimes(1); + + resolveFetch( + makeJsonResponse({ + version: "0.1.1", + sha: "fedcba987654", + builtAt: "2026-01-02T12:00:00.000Z", + }), + ); + await Promise.all([p1, p2]); + expect(updateAvailable()?.sha).toBe("fedcba987654"); + }); + }); + + describe("reloadOncePerTarget", () => { + it("returns true on first reload for a SHA, false on repeat for same SHA, and true for a new SHA", () => { + expect(reloadOncePerTarget("111111111111")).toBe(true); + expect(reloadOncePerTarget("111111111111")).toBe(false); + expect(reloadOncePerTarget("222222222222")).toBe(true); + expect(reloadOncePerTarget("222222222222")).toBe(false); + }); + + it("returns false for empty or 'dev' SHAs", () => { + expect(reloadOncePerTarget("")).toBe(false); + expect(reloadOncePerTarget("dev")).toBe(false); + }); + + it("normalizes SHAs to 12 characters and returns false if sessionStorage throws", () => { + expect(reloadOncePerTarget("abcdef1234567890abcdef1234567890abcdef12")).toBe(true); + expect(reloadOncePerTarget("abcdef123456")).toBe(false); + + const origGetItem = sessionStorage.getItem.bind(sessionStorage); + vi.spyOn(sessionStorage, "getItem").mockImplementation(() => { + throw new DOMException("Storage disabled", "SecurityError"); + }); + expect(reloadOncePerTarget("999999999999")).toBe(false); + vi.restoreAllMocks(); + Object.defineProperty(sessionStorage, "getItem", { + value: origGetItem, + configurable: true, + writable: true, + }); + expect(reloadOncePerTarget("999999999999")).toBe(true); + }); + }); + + describe("startVersionWatch", () => { + it("cancels the initial 30s timer if stopped before the delay elapses", async () => { + vi.useFakeTimers(); + const fetchMock = vi.fn().mockResolvedValue( + makeJsonResponse({ + version: "0.1.0", + sha: GIT_SHA, + builtAt: "2026-01-01T00:00:00.000Z", + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const stop = startVersionWatch(); + stop(); + + await vi.advanceTimersByTimeAsync(VERSION_WATCH_INITIAL_DELAY_MS * 2); + expect(fetchMock).not.toHaveBeenCalled(); + }); + it("triggers checkForUpdate after 30s and on visibilitychange to visible, and stops after cleanup", async () => { + vi.useFakeTimers(); + const fetchMock = vi.fn().mockResolvedValue( + makeJsonResponse({ + version: "0.1.0", + sha: GIT_SHA, + builtAt: "2026-01-01T00:00:00.000Z", + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const stop = startVersionWatch(); + expect(fetchMock).not.toHaveBeenCalled(); + + // Advance to 30s initial check + await vi.advanceTimersByTimeAsync(VERSION_WATCH_INITIAL_DELAY_MS); + expect(fetchMock).toHaveBeenCalledTimes(1); + + // Hidden visibilitychange should not trigger + Object.defineProperty(document, "visibilityState", { + value: "hidden", + writable: true, + configurable: true, + }); + document.dispatchEvent(new Event("visibilitychange")); + await Promise.resolve(); + expect(fetchMock).toHaveBeenCalledTimes(1); + + // Visible visibilitychange should trigger + Object.defineProperty(document, "visibilityState", { + value: "visible", + writable: true, + configurable: true, + }); + document.dispatchEvent(new Event("visibilitychange")); + await Promise.resolve(); + expect(fetchMock).toHaveBeenCalledTimes(2); + + // Cleanup removes listener + stop(); + document.dispatchEvent(new Event("visibilitychange")); + await Promise.resolve(); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + }); +}); diff --git a/tests/security/headers.test.ts b/tests/security/headers.test.ts index f097752b..8ec3ac2a 100644 --- a/tests/security/headers.test.ts +++ b/tests/security/headers.test.ts @@ -143,4 +143,9 @@ describe("public/_headers CSP validation", () => { expect(hsts).toContain("max-age="); expect(hsts).toContain("includeSubDomains"); }); + + it("serves /version.json with Cache-Control: no-store", () => { + const versionHeaders = headersMap.get("/version.json"); + expect(versionHeaders?.get("Cache-Control")).toBe("no-store"); + }); }); diff --git a/tests/services/poll-repo-scope.test.ts b/tests/services/poll-repo-scope.test.ts new file mode 100644 index 00000000..5d019478 --- /dev/null +++ b/tests/services/poll-repo-scope.test.ts @@ -0,0 +1,82 @@ +import "fake-indexeddb/auto"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +// poll.ts registers its config-change effects once, at module load. This suite keeps the real +// (reactive) config store so those effects actually run, and spies on the two resets they trigger. +const mockResetNotificationState = vi.hoisted(() => vi.fn()); +const mockResetEventsState = vi.hoisted(() => vi.fn()); + +vi.mock("../../src/app/lib/notifications", () => ({ + detectNewItems: vi.fn(() => []), + dispatchNotifications: vi.fn(), + _resetNotificationState: mockResetNotificationState, +})); + +vi.mock("../../src/app/services/events", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, resetEventsState: mockResetEventsState }; +}); + +vi.mock("../../src/app/services/github", () => ({ + getClient: vi.fn(() => null), + fetchRateLimitDetails: vi.fn(() => Promise.resolve(null)), + onApiRequest: vi.fn(), + initClientWatcher: vi.fn(), +})); + +import "../../src/app/services/poll"; +import { config, resetConfig, updateConfig } from "../../src/app/stores/config"; + +const REPO_A = { owner: "org", name: "repo-a", fullName: "org/repo-a" }; +const REPO_B = { owner: "org", name: "repo-b", fullName: "org/repo-b" }; + +async function settle(): Promise { + for (let i = 0; i < 5; i++) await Promise.resolve(); +} + +describe("poll repo-scope reset effect", () => { + beforeEach(async () => { + resetConfig(); + await settle(); + mockResetNotificationState.mockClear(); + mockResetEventsState.mockClear(); + }); + + it("resets notification and events state when a repo is added to selectedRepos", async () => { + updateConfig({ selectedRepos: [REPO_A] }); + await settle(); + + expect(mockResetNotificationState).toHaveBeenCalled(); + expect(mockResetEventsState).toHaveBeenCalled(); + }); + + it("resets when upstreamRepos change", async () => { + updateConfig({ upstreamRepos: [REPO_B] }); + await settle(); + + expect(mockResetNotificationState).toHaveBeenCalledTimes(1); + expect(mockResetEventsState).toHaveBeenCalledTimes(1); + }); + + it("does not reset when the same repos are written again in a different order", async () => { + updateConfig({ selectedRepos: [REPO_A, REPO_B] }); + await settle(); + mockResetNotificationState.mockClear(); + mockResetEventsState.mockClear(); + + updateConfig({ selectedRepos: [REPO_B, REPO_A] }); + await settle(); + + expect(config.selectedRepos).toHaveLength(2); + expect(mockResetNotificationState).not.toHaveBeenCalled(); + expect(mockResetEventsState).not.toHaveBeenCalled(); + }); + + it("does not reset for unrelated config changes", async () => { + updateConfig({ refreshInterval: 120 }); + await settle(); + + expect(mockResetNotificationState).not.toHaveBeenCalled(); + expect(mockResetEventsState).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/services/poll.test.ts b/tests/services/poll.test.ts index 2158bac8..fe1f0ea8 100644 --- a/tests/services/poll.test.ts +++ b/tests/services/poll.test.ts @@ -13,6 +13,7 @@ import { import { PR_ENRICHMENT_NOTIFICATION_SOURCE, PR_ENRICHMENT_DEGRADED_MESSAGE } from "../../src/shared/types"; import * as githubMod from "../../src/app/services/github"; import * as githubStatusMod from "../../src/app/services/github-status"; +import * as versionMod from "../../src/app/lib/version"; import { makePullRequest } from "../helpers/factories"; // Mock pushError and pushNotification so we can spy on them @@ -59,6 +60,11 @@ vi.mock("../../src/app/services/github-status", () => ({ fetchGitHubStatus: vi.fn(() => Promise.resolve()), })); +// Mock version module — checkForUpdate runs concurrently (fire-and-forget) in doFetch. +vi.mock("../../src/app/lib/version", () => ({ + checkForUpdate: vi.fn(() => Promise.resolve()), +})); + // Mock config so doFetch doesn't fail when accessing config.selectedRepos vi.mock("../../src/app/stores/config", () => ({ config: { @@ -669,6 +675,27 @@ describe("createPollCoordinator", () => { }); }); + it("checkForUpdate is called once per doFetch cycle", async () => { + const checkForUpdateSpy = vi.mocked(versionMod.checkForUpdate); + checkForUpdateSpy.mockClear(); + + const fetchAll = makeFetchAll(); + + await createRoot(async (dispose) => { + const coordinator = createPollCoordinator(makeGetInterval(0), fetchAll); + await flushPromises(); + expect(checkForUpdateSpy).toHaveBeenCalledTimes(1); + // Poll-driven checks are throttled so they stay off the boot path and don't repeat. + expect(checkForUpdateSpy).toHaveBeenCalledWith({ throttled: true }); + + coordinator.manualRefresh(); + await flushPromises(); + + expect(checkForUpdateSpy).toHaveBeenCalledTimes(2); + dispose(); + }); + }); + it("threads force = false on automatic polls and force = true on manualRefresh()", async () => { const fetchAll = makeFetchAll(); diff --git a/tests/stores/auth.test.ts b/tests/stores/auth.test.ts index 8aa744a0..1410ac74 100644 --- a/tests/stores/auth.test.ts +++ b/tests/stores/auth.test.ts @@ -1,4 +1,5 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { createRoot } from "solid-js"; // Mock cache.ts so clearAuth() doesn't try to open IndexedDB const mockClearCache = vi.fn().mockResolvedValue(undefined); @@ -535,6 +536,76 @@ describe("cross-tab auth sync", () => { expect(replaceMock).toHaveBeenCalledWith("/login"); }); + describe("unsaved config/view changes when another tab changes the signed-in identity", () => { + async function withPendingChanges(fn: (stores: { + config: typeof import("../../src/app/stores/config"); + view: typeof import("../../src/app/stores/view"); + }) => Promise | void): Promise { + const config = await import("../../src/app/stores/config"); + const view = await import("../../src/app/stores/view"); + let dispose!: () => void; + createRoot((d) => { + dispose = d; + config.initConfigPersistence(); + view.initViewPersistence(); + }); + try { + mod.setAuth({ access_token: "ghs_abc" }); + config.updateConfig({ theme: "dracula" }); + view.updateViewState({ lastActiveTab: "actions" }); + await fn({ config, view }); + // Let the debounce window pass: a discarded change must stay unwritten. + await new Promise((r) => setTimeout(r, 300)); + expect(localStorageMock.getItem("github-tracker:config")).toBeNull(); + expect(localStorageMock.getItem("github-tracker:view")).toBeNull(); + } finally { + dispose(); + } + } + + it("drops them when another tab replaces the token", async () => { + await withPendingChanges(({ config, view }) => { + window.dispatchEvent(new StorageEvent("storage", { + key: "github-tracker:auth-token", + newValue: "ghs_replacement", + })); + config.flushConfigPersistence(); + view.flushViewPersistence(); + }); + }); + + it("drops them when another tab signs out", async () => { + vi.stubGlobal("location", { href: window.location.href, replace: vi.fn() }); + await withPendingChanges(({ config, view }) => { + localStorageMock.removeItem("github-tracker:auth-token"); + window.dispatchEvent(new StorageEvent("storage", { + key: "github-tracker:auth-token", + newValue: null, + })); + config.flushConfigPersistence(); + view.flushViewPersistence(); + }); + }); + + it("keeps them when an unrelated key changes", async () => { + const config = await import("../../src/app/stores/config"); + const view = await import("../../src/app/stores/view"); + mod.setAuth({ access_token: "ghs_abc" }); + config.updateConfig({ theme: "dracula" }); + view.updateViewState({ lastActiveTab: "actions" }); + + window.dispatchEvent(new StorageEvent("storage", { + key: "github-tracker:some-other-key", + newValue: "x", + })); + config.flushConfigPersistence(); + view.flushViewPersistence(); + + expect(JSON.parse(localStorageMock.getItem("github-tracker:config") ?? "{}").theme).toBe("dracula"); + expect(JSON.parse(localStorageMock.getItem("github-tracker:view") ?? "{}").lastActiveTab).toBe("actions"); + }); + }); + it("does not call expireToken when key does not match", () => { mod.setAuth({ access_token: "ghs_abc" }); localStorageMock.removeItem("github-tracker:auth-token"); @@ -1633,6 +1704,126 @@ describe("identityEpoch and clearSnapshot integration", () => { expect(mockClearSnapshot).not.toHaveBeenCalled(); }); + describe("persistence while a cross-tab token change is being checked", () => { + const ALICE = { login: "alice", avatar_url: "https://avatars.githubusercontent.com/u/1", name: "Alice" }; + + // `userResponse` may be a factory so a rejection is only created when fetch is called. + async function setup(userResponse: Promise | (() => Promise)) { + const config = await import("../../src/app/stores/config"); + mod.setAuthFromPat("ghs_old", ALICE); + config.flushConfigPersistence(); + localStorageMock.removeItem("github-tracker:config"); + + vi.spyOn(mod.crossTabReload, "reloadForIdentitySwitch").mockImplementation(() => {}); + vi.stubGlobal( + "fetch", + vi.fn().mockImplementation(() => (typeof userResponse === "function" ? userResponse() : userResponse)), + ); + window.dispatchEvent(new StorageEvent("storage", { + key: "github-tracker:auth-token", + newValue: "ghs_rotated", + })); + + // A change made while the check is outstanding must not be written. + config.updateConfig({ theme: "dracula" }); + config.flushConfigPersistence(); + expect(localStorageMock.getItem("github-tracker:config")).toBeNull(); + return config; + } + + it("resumes writes once the /user check confirms the same user", async () => { + const okAlice = { ok: true, status: 200, json: () => Promise.resolve({ ...ALICE, login: "ALICE" }) }; + const config = await setup(Promise.resolve(okAlice)); + await new Promise((r) => setTimeout(r, 50)); + + config.updateConfig({ theme: "forest" }); + config.flushConfigPersistence(); + expect(JSON.parse(localStorageMock.getItem("github-tracker:config") ?? "{}").theme).toBe("forest"); + }); + + it("stays paused when the check finds a different identity and the tab is reloading", async () => { + const okBob = { + ok: true, + status: 200, + json: () => Promise.resolve({ login: "bob", avatar_url: "https://avatars.githubusercontent.com/u/2", name: "Bob" }), + }; + const config = await setup(Promise.resolve(okBob)); + await new Promise((r) => setTimeout(r, 50)); + + config.updateConfig({ theme: "forest" }); + config.flushConfigPersistence(); + expect(localStorageMock.getItem("github-tracker:config")).toBeNull(); + }); + + it("stays paused and warns when the /user check fails, because the account was never confirmed", async () => { + mockPushNotification.mockClear(); + const config = await setup(Promise.resolve({ ok: false, status: 403, json: () => Promise.resolve({}) })); + await new Promise((r) => setTimeout(r, 50)); + + config.updateConfig({ theme: "forest" }); + config.flushConfigPersistence(); + expect(localStorageMock.getItem("github-tracker:config")).toBeNull(); + expect(mockPushNotification).toHaveBeenCalledWith( + "auth:cross-tab-unconfirmed", + expect.stringContaining("couldn't confirm which one"), + "warning", + ); + }); + + it("stays paused and warns when the /user request errors or times out", async () => { + mockPushNotification.mockClear(); + const config = await setup(() => Promise.reject(new DOMException("timed out", "TimeoutError"))); + await new Promise((r) => setTimeout(r, 50)); + + config.updateConfig({ theme: "forest" }); + config.flushConfigPersistence(); + expect(localStorageMock.getItem("github-tracker:config")).toBeNull(); + expect(mockPushNotification).toHaveBeenCalledWith( + "auth:cross-tab-unconfirmed", + expect.any(String), + "warning", + ); + }); + + it("sends the /user check with a timeout signal", async () => { + const okAlice = { ok: true, status: 200, json: () => Promise.resolve({ ...ALICE, login: "ALICE" }) }; + await setup(Promise.resolve(okAlice)); + const init = vi.mocked(fetch).mock.calls[0][1] as RequestInit; + expect(init.signal).toBeInstanceOf(AbortSignal); + await new Promise((r) => setTimeout(r, 50)); + }); + + it("on resume, adopts what the other tab saved meanwhile and writes this tab's own change", async () => { + const configModule = await import("../../src/app/stores/config"); + let dispose!: () => void; + createRoot((d) => { + dispose = d; + configModule.initConfigPersistence(); + }); + try { + let release!: (value: unknown) => void; + const held = new Promise((resolve) => { + release = resolve; + }); + await setup(() => held); + // Another tab saves while this tab's identity check is outstanding. + localStorageMock.setItem( + "github-tracker:config", + JSON.stringify({ ...JSON.parse(JSON.stringify(configModule.config)), refreshInterval: 120 }), + ); + expect(configModule.config.refreshInterval).not.toBe(120); + + release({ ok: true, status: 200, json: () => Promise.resolve({ ...ALICE, login: "ALICE" }) }); + await new Promise((r) => setTimeout(r, 400)); + + expect(configModule.config.refreshInterval).toBe(120); + expect(JSON.parse(localStorageMock.getItem("github-tracker:config") ?? "{}").theme).toBe("dracula"); + } finally { + dispose(); + } + }); + }); + it("clearIdentityData() invokes clearSnapshot() synchronously before clearCache() resolves, awaits both, and survives either rejecting", async () => { const order: string[] = []; let resolveCache!: () => void; diff --git a/tests/stores/config.test.ts b/tests/stores/config.test.ts index ad41765d..6c4ba6bc 100644 --- a/tests/stores/config.test.ts +++ b/tests/stores/config.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, beforeEach, vi } from "vitest"; +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; vi.mock("../../src/app/lib/dashboard-snapshot", () => ({ clearSnapshot: vi.fn().mockResolvedValue(undefined), @@ -10,8 +10,11 @@ import { ConfigSchema, TrackedUserSchema, loadConfig, config, updateConfig, resetConfig, setMonitoredRepo, addCustomTab, updateCustomTab, removeCustomTab, reorderCustomTab, getCustomTab, isBuiltinTab, CustomTabSchema, updateJiraConfig, updateJiraCustomFields, updateJiraCustomScopes, - preParseConfigFixups, postParseConfigFixups, + preParseConfigFixups, postParseConfigFixups, initConfigPersistence, flushConfigPersistence, + discardPendingConfigPersistence, requestConfigFullOverwrite, setConfig, } from "../../src/app/stores/config"; +import { _resetVersionStateForTests, _setSchemaStaleForTests } from "../../src/app/lib/version"; +import { getNotifications, resetNotificationState } from "../../src/app/lib/errors"; import type { CustomTab } from "../../src/app/stores/config"; import { clearJiraAuth, clearJiraConfigFull } from "../../src/app/stores/auth"; import { JiraConfigSchema, JiraCustomFieldSchema } from "../../src/shared/schemas"; @@ -63,6 +66,7 @@ describe("ConfigSchema", () => { expect(result.onboardingComplete).toBe(false); expect(result.authMethod).toBe("oauth"); expect(result.enableActions).toBe(true); + expect(result.lastSeenVersion).toBeNull(); expect(result.dependencies.excludedOrgs).toEqual([]); expect(result.dependencies.excludedRepos).toEqual([]); }); @@ -154,6 +158,34 @@ describe("ConfigSchema", () => { expect(roundTripped.hotPollInterval).toBe(45); }); }); + + describe("lastSeenVersion", () => { + it("defaults to null and accepts valid version strings or null", () => { + expect(ConfigSchema.parse({}).lastSeenVersion).toBeNull(); + expect(ConfigSchema.parse({ lastSeenVersion: null }).lastSeenVersion).toBeNull(); + expect(ConfigSchema.parse({ lastSeenVersion: "0.1.0" }).lastSeenVersion).toBe("0.1.0"); + }); + + it("rejects strings exceeding 32 characters", () => { + expect(() => ConfigSchema.parse({ lastSeenVersion: "v".repeat(33) })).toThrow( + /lastSeenVersion|Too big|<=32/i, + ); + }); + + it("persists through loadConfig and updateConfig round-trip", () => { + const stored = ConfigSchema.parse({ lastSeenVersion: "0.1.1" }); + localStorageMock.setItem(STORAGE_KEY, JSON.stringify(stored)); + expect(loadConfig().lastSeenVersion).toBe("0.1.1"); + + createRoot((dispose) => { + resetConfig(); + expect(config.lastSeenVersion).toBeNull(); + updateConfig({ lastSeenVersion: "0.2.0" }); + expect(config.lastSeenVersion).toBe("0.2.0"); + dispose(); + }); + }); + }); }); describe("ConfigSchema — upstream repos and tracked users", () => { @@ -1609,3 +1641,581 @@ describe("clearJiraConfigFull — wipes all Jira config", () => { }); }); }); + +describe("flushConfigPersistence", () => { + beforeEach(() => { + localStorageMock.clear(); + resetConfig(); + resetNotificationState(); + }); + + it("cancels pending 200ms debounce timer and writes config synchronously once", () => { + vi.useFakeTimers(); + const setItemSpy = vi.spyOn(localStorageMock, "setItem"); + try { + let dispose!: () => void; + createRoot((d) => { + dispose = d; + initConfigPersistence(); + }); + + updateConfig({ theme: "dracula" }); + setItemSpy.mockClear(); + + flushConfigPersistence(); + expect(setItemSpy).toHaveBeenCalledTimes(1); + expect(JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}").theme).toBe("dracula"); + + // Advancing past 200ms should not fire a second debounced write + vi.advanceTimersByTime(300); + expect(setItemSpy).toHaveBeenCalledTimes(1); + + dispose(); + } finally { + setItemSpy.mockRestore(); + vi.useRealTimers(); + } + }); + + it("does not overwrite a newer config another tab saved when this tab has no changes of its own", () => { + // Establish this tab's baseline: its own config is what it last wrote. + updateConfig({ theme: "forest" }); + flushConfigPersistence(); + + // Another tab saves a different config for the same key. + const otherTabJson = JSON.stringify({ ...config, theme: "dracula" }); + localStorageMock.setItem(STORAGE_KEY, otherTabJson); + + const setItemSpy = vi.spyOn(localStorageMock, "setItem"); + try { + // This tab only reloads (e.g. for an update) without having changed anything. + flushConfigPersistence(); + expect(setItemSpy).not.toHaveBeenCalled(); + expect(localStorageMock.getItem(STORAGE_KEY)).toBe(otherTabJson); + + // Once this tab changes its config, the flush writes it. + updateConfig({ theme: "nord" }); + flushConfigPersistence(); + expect(setItemSpy).toHaveBeenCalledTimes(1); + expect(JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}").theme).toBe("nord"); + } finally { + setItemSpy.mockRestore(); + } + }); + + it("writes on flush after resetConfig + removeItem + updateConfig even when the config matches what this tab last wrote", () => { + // Establish baseline with authMethod: "pat" and default settings + updateConfig({ authMethod: "pat" }); + flushConfigPersistence(); + expect(JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}").authMethod).toBe("pat"); + + // Simulate identity switch in setAuthFromPat: resetConfig -> removeItem -> updateConfig({ authMethod: "pat" }) + resetConfig(); + localStorageMock.removeItem(STORAGE_KEY); + updateConfig({ authMethod: "pat" }); + + // resetConfig() forces the next write to replace the whole stored config, so the + // flush must write even though nothing differs from this tab's last write. + flushConfigPersistence(); + expect(localStorageMock.getItem(STORAGE_KEY)).not.toBeNull(); + expect(JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}").authMethod).toBe("pat"); + }); + + it("does not synchronously flush a stale pending write on intermediate mutations while initConfigPersistence is active, and schedules a debounced write when resetConfig matches in-memory state", () => { + vi.useFakeTimers(); + let dispose!: () => void; + createRoot((d) => { + dispose = d; + initConfigPersistence(); + }); + const setItemSpy = vi.spyOn(localStorageMock, "setItem"); + try { + // Mutate within the 200ms mount debounce window: effect re-run must NOT flush the stale initial pending write synchronously + setItemSpy.mockClear(); + updateConfig({ theme: "dracula" }); + expect(setItemSpy).not.toHaveBeenCalled(); + + // Settle the 200ms debounce + vi.advanceTimersByTime(250); + expect(setItemSpy).toHaveBeenCalledTimes(1); + expect(JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}").theme).toBe("dracula"); + + // Reset to defaults and let it settle + resetConfig(); + vi.advanceTimersByTime(250); + expect(JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}").theme).toBe("auto"); + + // Another tab writes theme: "nord" while this tab is already at defaults in memory. + // Calling resetConfig() again must still schedule a debounced write via persistTrigger. + localStorageMock.setItem(STORAGE_KEY, JSON.stringify({ ...config, theme: "nord" })); + resetConfig(); + vi.advanceTimersByTime(250); + expect(JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}").theme).toBe("auto"); + } finally { + setItemSpy.mockRestore(); + dispose(); + vi.useRealTimers(); + } + }); + + it("catches localStorage quota errors and pushes localStorage:config warning notification without throwing", () => { + updateConfig({ theme: "forest" }); + const setItemSpy = vi.spyOn(localStorageMock, "setItem").mockImplementation(() => { + throw new DOMException("QuotaExceededError", "QuotaExceededError"); + }); + try { + expect(() => flushConfigPersistence()).not.toThrow(); + const notifications = getNotifications(); + expect(notifications.some((n) => n.source === "localStorage:config")).toBe(true); + } finally { + setItemSpy.mockRestore(); + } + }); + + it("keeps a change pending after a failed write and writes it on the next flush", () => { + // Settle the full overwrite queued by beforeEach's resetConfig() so the next write is per-key. + flushConfigPersistence(); + expect(JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}").theme).toBe("auto"); + + updateConfig({ theme: "forest" }); + const setItemSpy = vi.spyOn(localStorageMock, "setItem").mockImplementationOnce(() => { + throw new DOMException("QuotaExceededError", "QuotaExceededError"); + }); + try { + flushConfigPersistence(); + expect(setItemSpy).toHaveBeenCalledTimes(1); + expect(JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}").theme).toBe("auto"); + + // The failed write must not have been recorded as saved, so this flush retries it. + flushConfigPersistence(); + expect(setItemSpy).toHaveBeenCalledTimes(2); + expect(JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}").theme).toBe("forest"); + } finally { + setItemSpy.mockRestore(); + } + }); +}); + +describe("config persistence — cross-tab sync and per-key writes", () => { + beforeEach(() => { + localStorageMock.clear(); + resetConfig(); + resetNotificationState(); + }); + + function dispatchConfigStorage(newValue: string | null): void { + window.dispatchEvent(new StorageEvent("storage", { key: STORAGE_KEY, newValue })); + } + + // Hosts initConfigPersistence() in a root with fake timers; the root is always disposed so + // its storage listener and effect never outlive the test. + function withConfigPersistence(fn: () => void): void { + vi.useFakeTimers(); + let dispose!: () => void; + createRoot((d) => { + dispose = d; + initConfigPersistence(); + }); + try { + fn(); + } finally { + dispose(); + vi.useRealTimers(); + } + } + + function configWith(overrides: Record): string { + return JSON.stringify({ ...JSON.parse(JSON.stringify(config)), ...overrides }); + } + + it("flushes a pending debounced write synchronously on disposal, and a later flush does not write again", () => { + vi.useFakeTimers(); + const setItemSpy = vi.spyOn(localStorageMock, "setItem"); + let dispose!: () => void; + try { + createRoot((d) => { + dispose = d; + initConfigPersistence(); + }); + updateConfig({ theme: "dracula" }); + expect(setItemSpy).not.toHaveBeenCalled(); + + // Dispose before the 200ms debounce timer fires. + dispose(); + expect(setItemSpy).toHaveBeenCalledTimes(1); + expect(JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}").theme).toBe("dracula"); + + flushConfigPersistence(); + vi.advanceTimersByTime(300); + expect(setItemSpy).toHaveBeenCalledTimes(1); + } finally { + setItemSpy.mockRestore(); + vi.useRealTimers(); + } + }); + + it("applies another tab's config write to the live store without writing it back", () => { + withConfigPersistence(() => { + const otherTabJson = configWith({ theme: "dracula", refreshInterval: 120 }); + localStorageMock.setItem(STORAGE_KEY, otherTabJson); + const setItemSpy = vi.spyOn(localStorageMock, "setItem"); + try { + dispatchConfigStorage(otherTabJson); + expect(config.theme).toBe("dracula"); + expect(config.refreshInterval).toBe(120); + + vi.advanceTimersByTime(250); + flushConfigPersistence(); + expect(setItemSpy).not.toHaveBeenCalled(); + expect(localStorageMock.getItem(STORAGE_KEY)).toBe(otherTabJson); + } finally { + setItemSpy.mockRestore(); + } + }); + }); + + it("keeps this tab's pending change to a key when another tab writes a different value, and writes it on top", () => { + withConfigPersistence(() => { + updateConfig({ theme: "forest" }); + const otherTabJson = configWith({ theme: "dracula", refreshInterval: 120 }); + localStorageMock.setItem(STORAGE_KEY, otherTabJson); + + dispatchConfigStorage(otherTabJson); + expect(config.theme).toBe("forest"); + expect(config.refreshInterval).toBe(120); + + vi.advanceTimersByTime(250); + const onDisk = JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}"); + expect(onDisk.theme).toBe("forest"); + expect(onDisk.refreshInterval).toBe(120); + }); + }); + + it("only writes the keys this tab changed and never reverts another tab's value on a later write", () => { + updateConfig({ theme: "forest" }); + flushConfigPersistence(); + localStorageMock.setItem( + STORAGE_KEY, + JSON.stringify({ ...JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}"), refreshInterval: 120 }), + ); + + updateConfig({ itemsPerPage: 50 }); + flushConfigPersistence(); + let onDisk = JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}"); + expect(onDisk).toMatchObject({ theme: "forest", itemsPerPage: 50, refreshInterval: 120 }); + + // A second write from this tab, which never saw the other tab's refreshInterval, must not revert it. + updateConfig({ viewDensity: "compact" }); + flushConfigPersistence(); + onDisk = JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}"); + expect(onDisk).toMatchObject({ viewDensity: "compact", itemsPerPage: 50, refreshInterval: 120 }); + }); + + it("adopts a config another tab saved between module load and initConfigPersistence(), without writing", () => { + localStorageMock.setItem(STORAGE_KEY, configWith({ theme: "dracula" })); + const setItemSpy = vi.spyOn(localStorageMock, "setItem"); + try { + withConfigPersistence(() => { + expect(config.theme).toBe("dracula"); + vi.advanceTimersByTime(250); + expect(setItemSpy).not.toHaveBeenCalled(); + }); + } finally { + setItemSpy.mockRestore(); + } + }); + + it("ignores removal, malformed, and non-object storage events, and drops individually invalid fields", () => { + withConfigPersistence(() => { + dispatchConfigStorage(null); + dispatchConfigStorage("{not valid json"); + dispatchConfigStorage("[1,2,3]"); + dispatchConfigStorage(JSON.stringify({ theme: "dracula", refreshInterval: 99999, futureKey: true })); + expect(config.theme).toBe("dracula"); + expect(config.refreshInterval).toBe(300); + expect("futureKey" in config).toBe(false); + }); + }); + + it("ignores another tab's write while a resetConfig() is waiting to be written, then fully overwrites it", () => { + withConfigPersistence(() => { + updateConfig({ selectedOrgs: ["mine"] }); + vi.advanceTimersByTime(250); + + resetConfig(); + const otherTabJson = configWith({ selectedOrgs: ["other-identity-org"] }); + localStorageMock.setItem(STORAGE_KEY, otherTabJson); + dispatchConfigStorage(otherTabJson); + expect(config.selectedOrgs).toEqual([]); + + vi.advanceTimersByTime(250); + expect(JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}").selectedOrgs).toEqual([]); + }); + }); + + afterEach(() => { + _resetVersionStateForTests(); + }); + + function readDisk(): Record { + return JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}") as Record; + } + + function configSnapshot(): Record { + return JSON.parse(JSON.stringify(config)) as Record; + } + + function throwQuotaError(): never { + throw new DOMException("QuotaExceededError", "QuotaExceededError"); + } + + const REPO_A = { owner: "alpha", name: "a", fullName: "alpha/a" }; + const REPO_B = { owner: "beta", name: "b", fullName: "beta/b" }; + + it("keeps a resetConfig() full overwrite pending after a failed write, ignoring other tabs until it lands", () => { + withConfigPersistence(() => { + updateConfig({ selectedOrgs: ["mine"] }); + vi.advanceTimersByTime(250); + + resetConfig(); + const setItemSpy = vi.spyOn(localStorageMock, "setItem").mockImplementationOnce(throwQuotaError); + try { + flushConfigPersistence(); + expect(setItemSpy).toHaveBeenCalledTimes(1); + expect(readDisk().selectedOrgs).toEqual(["mine"]); + + const otherTabJson = configWith({ selectedOrgs: ["other"], refreshInterval: 120 }); + localStorageMock.setItem(STORAGE_KEY, otherTabJson); + dispatchConfigStorage(otherTabJson); + expect(config.selectedOrgs).toEqual([]); + expect(config.refreshInterval).toBe(300); + + flushConfigPersistence(); + expect(readDisk()).toEqual(JSON.parse(JSON.stringify(ConfigSchema.parse({})))); + } finally { + setItemSpy.mockRestore(); + } + }); + }); + + it("an import that requests a full overwrite replaces a divergent on-disk value that memory and the last save already match", () => { + withConfigPersistence(() => { + vi.advanceTimersByTime(250); // settle this tab's boot write (refreshInterval 300) + localStorageMock.setItem(STORAGE_KEY, configWith({ refreshInterval: 120 })); + + requestConfigFullOverwrite(); + setConfig(ConfigSchema.parse({ refreshInterval: 300 })); + flushConfigPersistence(); + + expect(readDisk().refreshInterval).toBe(300); + }); + }); + + it("ignores another tab's write that arrives after a full-overwrite import but before its debounced write", () => { + withConfigPersistence(() => { + vi.advanceTimersByTime(250); + + requestConfigFullOverwrite(); + setConfig(ConfigSchema.parse({ refreshInterval: 300, theme: "forest" })); + const otherTabJson = configWith({ refreshInterval: 120 }); + localStorageMock.setItem(STORAGE_KEY, otherTabJson); + dispatchConfigStorage(otherTabJson); + expect(config.refreshInterval).toBe(300); + + vi.advanceTimersByTime(250); + expect(readDisk()).toMatchObject({ refreshInterval: 300, theme: "forest" }); + }); + }); + + it("schedules the full-overwrite write for an import identical to memory, so another tab's write is not ignored indefinitely", () => { + withConfigPersistence(() => { + vi.advanceTimersByTime(250); + + requestConfigFullOverwrite(); + setConfig(ConfigSchema.parse({ refreshInterval: 300 })); + const otherTabJson = configWith({ refreshInterval: 120 }); + localStorageMock.setItem(STORAGE_KEY, otherTabJson); + dispatchConfigStorage(otherTabJson); + expect(config.refreshInterval).toBe(300); + + vi.advanceTimersByTime(250); + expect(readDisk().refreshInterval).toBe(300); + }); + }); + + it("drops unknown keys and a literal __proto__ key from the on-disk blob when writing", () => { + withConfigPersistence(() => { + vi.advanceTimersByTime(250); + // A literal "__proto__" key spliced in at the JSON-text level, which JSON.parse turns + // into an own property (an object literal would set the prototype instead). + const tainted = configWith({ futureKey: "should not survive" }).slice(0, -1) + ',"__proto__":{"polluted":true}}'; + localStorageMock.setItem(STORAGE_KEY, tainted); + + updateConfig({ theme: "forest" }); + vi.advanceTimersByTime(250); + + const onDisk = readDisk(); + expect(onDisk.theme).toBe("forest"); + expect(Object.hasOwn(onDisk, "futureKey")).toBe(false); + expect(Object.hasOwn(onDisk, "__proto__")).toBe(false); + expect(Object.getPrototypeOf({})).not.toHaveProperty("polluted"); + }); + }); + + it("replaces an invalid on-disk value with this tab's value when writing", () => { + withConfigPersistence(() => { + updateConfig({ itemsPerPage: 50 }); + vi.advanceTimersByTime(250); + localStorageMock.setItem(STORAGE_KEY, configWith({ itemsPerPage: 5, refreshInterval: "fast" })); + + updateConfig({ theme: "forest" }); + vi.advanceTimersByTime(250); + + expect(readDisk()).toMatchObject({ theme: "forest", itemsPerPage: 50, refreshInterval: 300 }); + }); + }); + + it("writes this tab's value for a key missing from the on-disk blob even though it has not changed", () => { + withConfigPersistence(() => { + updateConfig({ itemsPerPage: 50 }); + vi.advanceTimersByTime(250); + const stale = readDisk(); + delete stale.itemsPerPage; + localStorageMock.setItem(STORAGE_KEY, JSON.stringify(stale)); + + updateConfig({ theme: "forest" }); + vi.advanceTimersByTime(250); + + expect(readDisk()).toMatchObject({ theme: "forest", itemsPerPage: 50 }); + }); + }); + + it.each([ + ["malformed JSON", "{not valid json"], + ["a JSON array", "[1,2,3]"], + ])("writes the full snapshot when the on-disk blob is %s", (_label, raw) => { + withConfigPersistence(() => { + updateConfig({ itemsPerPage: 50 }); + vi.advanceTimersByTime(250); + localStorageMock.setItem(STORAGE_KEY, raw); + + updateConfig({ theme: "forest" }); + vi.advanceTimersByTime(250); + + const onDisk = readDisk(); + expect(onDisk).toEqual(configSnapshot()); + expect(onDisk).toMatchObject({ theme: "forest", itemsPerPage: 50, refreshInterval: 300 }); + }); + }); + + it("repairs a stored defaultTab naming a deleted custom tab on startup and writes the repair", () => { + localStorageMock.setItem(STORAGE_KEY, JSON.stringify({ defaultTab: "deleted-tab-id", customTabs: [] })); + setConfig(loadConfig()); + withConfigPersistence(() => { + expect(config.defaultTab).toBe("issues"); + vi.advanceTimersByTime(250); + expect(readDisk().defaultTab).toBe("issues"); + }); + }); + + it("salvages the valid keys of a stored config whose blob fails whole-schema validation", () => { + localStorageMock.setItem(STORAGE_KEY, JSON.stringify({ refreshInterval: -999, itemsPerPage: 50 })); + // loadConfig() rejects the whole blob, so the store starts from defaults. + setConfig(loadConfig()); + expect(config.itemsPerPage).toBe(25); + withConfigPersistence(() => { + expect(config.itemsPerPage).toBe(50); + expect(config.refreshInterval).toBe(300); + vi.advanceTimersByTime(250); + expect(readDisk()).toMatchObject({ itemsPerPage: 50, refreshInterval: 300 }); + }); + }); + + it("keeps monitored repos and custom-tab scopes within the selected repos after adopting another tab's values", () => { + withConfigPersistence(() => { + updateConfig({ + selectedRepos: [REPO_A, REPO_B], + monitoredRepos: [REPO_A], + customTabs: [makeTab({ id: "scoped", orgScope: ["alpha", "beta"], repoScope: [REPO_A, REPO_B] })], + }); + vi.advanceTimersByTime(250); + + const otherTabJson = configWith({ selectedRepos: [REPO_A], monitoredRepos: [REPO_A, REPO_B] }); + localStorageMock.setItem(STORAGE_KEY, otherTabJson); + dispatchConfigStorage(otherTabJson); + + expect(config.selectedRepos).toEqual([REPO_A]); + expect(config.monitoredRepos).toEqual([REPO_A]); + expect(config.customTabs[0].orgScope).toEqual(["alpha"]); + expect(config.customTabs[0].repoScope).toEqual([REPO_A]); + + // The repaired values differ from what was adopted, so they are written back. + vi.advanceTimersByTime(250); + const onDisk = readDisk() as { selectedRepos: unknown; monitoredRepos: unknown; customTabs: CustomTab[] }; + expect(onDisk.selectedRepos).toEqual([REPO_A]); + expect(onDisk.monitoredRepos).toEqual([REPO_A]); + expect(onDisk.customTabs[0].orgScope).toEqual(["alpha"]); + expect(onDisk.customTabs[0].repoScope).toEqual([REPO_A]); + }); + }); + + it("falls back to the issues tab when an adopted defaultTab or customTabs leaves defaultTab naming a missing tab", () => { + withConfigPersistence(() => { + updateConfig({ customTabs: [makeTab({ id: "mine" })], defaultTab: "mine" }); + vi.advanceTimersByTime(250); + + dispatchConfigStorage(configWith({ defaultTab: "ghost" })); + expect(config.defaultTab).toBe("issues"); + vi.advanceTimersByTime(250); + expect(readDisk().defaultTab).toBe("issues"); + + updateConfig({ defaultTab: "mine" }); + vi.advanceTimersByTime(250); + dispatchConfigStorage(configWith({ customTabs: [] })); + expect(config.customTabs).toEqual([]); + expect(config.defaultTab).toBe("issues"); + }); + }); + + it("neither writes nor adopts while the stored schema is stale, then writes the pending change once it clears", () => { + withConfigPersistence(() => { + vi.advanceTimersByTime(250); + _setSchemaStaleForTests(true); + const setItemSpy = vi.spyOn(localStorageMock, "setItem"); + try { + updateConfig({ theme: "forest" }); + vi.advanceTimersByTime(250); + flushConfigPersistence(); + expect(setItemSpy).not.toHaveBeenCalled(); + + dispatchConfigStorage(configWith({ refreshInterval: 120 })); + expect(config.refreshInterval).toBe(300); + + _setSchemaStaleForTests(false); + flushConfigPersistence(); + expect(setItemSpy).toHaveBeenCalledTimes(1); + expect(readDisk()).toMatchObject({ theme: "forest", refreshInterval: 300 }); + } finally { + setItemSpy.mockRestore(); + _setSchemaStaleForTests(false); + } + }); + }); + + it("discardPendingConfigPersistence() drops this tab's unsaved change so it is never written", () => { + withConfigPersistence(() => { + vi.advanceTimersByTime(250); + const setItemSpy = vi.spyOn(localStorageMock, "setItem"); + try { + updateConfig({ theme: "forest" }); + discardPendingConfigPersistence(); + vi.advanceTimersByTime(250); + flushConfigPersistence(); + expect(setItemSpy).not.toHaveBeenCalled(); + expect(readDisk().theme).toBe("auto"); + } finally { + setItemSpy.mockRestore(); + } + }); + }); +}); diff --git a/tests/stores/view-jira-order.test.ts b/tests/stores/view-jira-order.test.ts index b76be5f9..c2b53cb7 100644 --- a/tests/stores/view-jira-order.test.ts +++ b/tests/stores/view-jira-order.test.ts @@ -174,6 +174,7 @@ describe("cross-tab sync for jiraCustomOrder", () => { beforeEach(() => { resetViewState(); + localStorage.clear(); }); afterEach(() => { @@ -220,15 +221,12 @@ describe("cross-tab sync for jiraCustomOrder", () => { expect(viewState.jiraCustomOrder).toEqual(["PROJ-1"]); }); - it("does not touch other viewState fields when syncing jiraCustomOrder", () => { + it("applies every key present in another tab's write and leaves absent keys untouched", () => { setupPersistence(); - const blob = JSON.stringify({ - lastActiveTab: "actions", - jiraCustomOrder: ["PROJ-Z"], - }); - dispatchStorageEvent(blob); + dispatchStorageEvent(JSON.stringify({ lastActiveTab: "actions", jiraCustomOrder: ["PROJ-Z"] })); expect(viewState.jiraCustomOrder).toEqual(["PROJ-Z"]); - expect(viewState.lastActiveTab).toBe("issues"); + expect(viewState.lastActiveTab).toBe("actions"); + expect(viewState.globalSort).toEqual({ field: "updatedAt", direction: "desc" }); }); it("handles malformed JSON in newValue without throwing", () => { diff --git a/tests/stores/view.test.ts b/tests/stores/view.test.ts index ed2d380d..27965cf6 100644 --- a/tests/stores/view.test.ts +++ b/tests/stores/view.test.ts @@ -31,9 +31,13 @@ import { setJiraCustomOrder, applyImportedViewState, EXPORTED_VIEW_PREF_KEYS, + flushViewPersistence, + discardPendingViewPersistence, + VIEW_STORAGE_KEY, } from "../../src/app/stores/view"; import type { IgnoredItem, TrackedItem, ViewState } from "../../src/app/stores/view"; import { getNotifications, clearNotifications } from "../../src/app/lib/errors"; +import { _resetVersionStateForTests, _setSchemaStaleForTests } from "../../src/app/lib/version"; // view.ts uses createStore — setters work outside reactive context. // We use createRoot only for initViewPersistence (which calls createEffect). @@ -404,8 +408,8 @@ describe("initViewPersistence", () => { it("drops unknown/unrecognized keys from the on-disk blob before merging (schema allowlist)", async () => { // Regression test: localStorage is writable by any same-origin script // (extensions, a stale/incompatible schema version, manual tampering). - // readOnDiskState() must filter the parsed blob down to known - // ViewStateSchema top-level keys before commitSnapshot() folds it into + // The on-disk read must filter the parsed blob down to known + // ViewStateSchema top-level keys before the commit folds it into // the merged write — otherwise unrecognized content would be perpetually // re-persisted instead of self-healing on the next write. await withViewPersistence(async (dispose) => { @@ -416,7 +420,7 @@ describe("initViewPersistence", () => { // case) rather than produce JSON text containing a "__proto__" key. JSON.parse, by // contrast, does NOT apply that special-case magic: parsing `{"__proto__":{...}}` // creates a plain OWN property literally named "__proto__" — which is the actual - // shape a tampered localStorage blob would take, and what readOnDiskState() must + // shape a tampered localStorage blob would take, and what the on-disk read must // filter out via the schema allowlist rather than relying on spread's inertness alone. const tainted = taintedJson.slice(0, -1) + ',"__proto__":{"polluted":true}}'; localStorageMock.setItem(VIEW_KEY, tainted); @@ -436,7 +440,7 @@ describe("initViewPersistence", () => { }); it("drops a known key's value from the on-disk blob when it fails that field's own schema validation", async () => { - // Regression test: the allowlist in readOnDiskState() must validate each + // Regression test: the allowlist applied to the on-disk blob must validate each // known key's VALUE against ViewStateSchema (not just its NAME) before // folding it into the merge — a structurally-valid-key-but-malformed-value // (e.g. jiraCustomOrder holding an object instead of a string array) @@ -530,18 +534,19 @@ describe("initViewPersistence", () => { it("pushes a warning notification and does not throw when localStorage.setItem fails (e.g. quota exceeded)", async () => { await withViewPersistence(async (dispose) => { clearNotifications(); - vi.spyOn(localStorageMock, "setItem").mockImplementation(() => { + const setItemSpy = vi.spyOn(localStorageMock, "setItem").mockImplementation(() => { throw new Error("QuotaExceededError"); }); + try { + setGlobalFilter("org1", "repo1"); + await Promise.resolve(); + expect(() => vi.advanceTimersByTime(200)).not.toThrow(); - setGlobalFilter("org1", "repo1"); - await Promise.resolve(); - expect(() => vi.advanceTimersByTime(200)).not.toThrow(); - - const notifications = getNotifications(); - expect(notifications.some((n) => n.source === "localStorage:view")).toBe(true); - - vi.mocked(localStorageMock.setItem).mockRestore(); + const notifications = getNotifications(); + expect(notifications.some((n) => n.source === "localStorage:view")).toBe(true); + } finally { + setItemSpy.mockRestore(); + } dispose(); }); }); @@ -560,6 +565,287 @@ describe("initViewPersistence", () => { expect(parsed.globalFilter.repo).toBe("unmount-repo"); }); }); + + function dispatchViewStorage(newValue: string | null): void { + window.dispatchEvent(new StorageEvent("storage", { key: VIEW_KEY, newValue })); + } + + it("does not revert another tab's value on a later write after merging it from disk", async () => { + await withViewPersistence(async () => { + seedOtherTabWrite({ jiraCustomOrder: ["OTHER-1"] }); + + setGlobalFilter("org1", "repo1"); + await Promise.resolve(); + vi.advanceTimersByTime(200); + expect(JSON.parse(localStorageMock.getItem(VIEW_KEY)).jiraCustomOrder).toEqual(["OTHER-1"]); + + // A second write from this tab, which still holds its own untouched [] in memory, + // must not treat jiraCustomOrder as changed. + setSortPreference("title", "asc"); + await Promise.resolve(); + vi.advanceTimersByTime(200); + const parsed = JSON.parse(localStorageMock.getItem(VIEW_KEY)); + expect(parsed.globalSort).toEqual({ field: "title", direction: "asc" }); + expect(parsed.jiraCustomOrder).toEqual(["OTHER-1"]); + + const setItemSpy = vi.spyOn(localStorageMock, "setItem"); + flushViewPersistence(); + expect(setItemSpy).not.toHaveBeenCalled(); + setItemSpy.mockRestore(); + }); + }); + + it("applies every valid key from another tab's storage event to the live store without writing it back", async () => { + await withViewPersistence(async () => { + vi.advanceTimersByTime(200); // settle this tab's boot write + const otherTabBlob = JSON.stringify({ + ...currentOnDisk(), + showPrRuns: true, + globalSort: { field: "title", direction: "asc" }, + lockedRepos: { issues: ["org/a"], pullRequests: [], actions: [], jiraAssigned: [] }, + }); + localStorageMock.setItem(VIEW_KEY, otherTabBlob); + const setItemSpy = vi.spyOn(localStorageMock, "setItem"); + + dispatchViewStorage(otherTabBlob); + expect(viewState.showPrRuns).toBe(true); + expect(viewState.globalSort).toEqual({ field: "title", direction: "asc" }); + expect(viewState.lockedRepos.issues).toEqual(["org/a"]); + + await Promise.resolve(); + vi.advanceTimersByTime(200); + flushViewPersistence(); + expect(setItemSpy).not.toHaveBeenCalled(); + expect(localStorageMock.getItem(VIEW_KEY)).toBe(otherTabBlob); + setItemSpy.mockRestore(); + }); + }); + + it("keeps this tab's pending change to a key when another tab's event carries a different value, then writes it", async () => { + await withViewPersistence(async () => { + setJiraCustomOrder(["MINE-1"]); + const otherTabBlob = JSON.stringify({ ...currentOnDisk(), jiraCustomOrder: ["OTHER-1"], showPrRuns: true }); + localStorageMock.setItem(VIEW_KEY, otherTabBlob); + + dispatchViewStorage(otherTabBlob); + expect(viewState.jiraCustomOrder).toEqual(["MINE-1"]); + expect(viewState.showPrRuns).toBe(true); + + await Promise.resolve(); + vi.advanceTimersByTime(200); + const parsed = JSON.parse(localStorageMock.getItem(VIEW_KEY)); + expect(parsed.jiraCustomOrder).toEqual(["MINE-1"]); + expect(parsed.showPrRuns).toBe(true); + }); + }); + + it("ignores removal, malformed, and non-object storage events, and drops individually invalid fields", async () => { + await withViewPersistence(async () => { + dispatchViewStorage(null); + dispatchViewStorage("{not valid json"); + dispatchViewStorage("[1,2,3]"); + dispatchViewStorage(JSON.stringify({ showPrRuns: "yes", lastActiveTab: "actions", unknownKey: 1 })); + expect(viewState.showPrRuns).toBe(false); + expect(viewState.lastActiveTab).toBe("actions"); + expect("unknownKey" in viewState).toBe(false); + }); + }); + + it("ignores another tab's storage event while a reset is waiting to be written", async () => { + await withViewPersistence(async () => { + resetViewState(); + dispatchViewStorage(JSON.stringify({ showPrRuns: true })); + expect(viewState.showPrRuns).toBe(false); + + await Promise.resolve(); + vi.advanceTimersByTime(200); + dispatchViewStorage(JSON.stringify({ showPrRuns: true })); + expect(viewState.showPrRuns).toBe(true); + }); + }); + + it("adopts another tab's write that landed between module load and initViewPersistence(), without writing", async () => { + localStorageMock.setItem(VIEW_KEY, JSON.stringify({ ...JSON.parse(JSON.stringify(viewState)), showPrRuns: true })); + const setItemSpy = vi.spyOn(localStorageMock, "setItem"); + try { + await withViewPersistence(async () => { + expect(viewState.showPrRuns).toBe(true); + await Promise.resolve(); + vi.advanceTimersByTime(200); + expect(setItemSpy).not.toHaveBeenCalled(); + }); + } finally { + setItemSpy.mockRestore(); + } + }); + + function throwQuotaError(): never { + throw new Error("QuotaExceededError"); + } + + it("keeps a resetViewState() full overwrite pending after a failed write, ignoring other tabs until it lands", async () => { + await withViewPersistence(() => { + updateViewState({ showPrRuns: true, lastActiveTab: "actions" }); + vi.advanceTimersByTime(200); + + resetViewState(); + const setItemSpy = vi.spyOn(localStorageMock, "setItem").mockImplementationOnce(throwQuotaError); + try { + flushViewPersistence(); + expect(setItemSpy).toHaveBeenCalledTimes(1); + expect(currentOnDisk().showPrRuns).toBe(true); + + const otherTabBlob = JSON.stringify({ ...currentOnDisk(), showPrRuns: true, jiraCustomOrder: ["OTHER-1"] }); + localStorageMock.setItem(VIEW_KEY, otherTabBlob); + dispatchViewStorage(otherTabBlob); + expect(viewState.showPrRuns).toBe(false); + expect(viewState.jiraCustomOrder).toEqual([]); + + flushViewPersistence(); + expect(currentOnDisk()).toEqual(JSON.parse(JSON.stringify(ViewStateSchema.parse({})))); + } finally { + setItemSpy.mockRestore(); + } + }); + }); + + it("keeps an imported key forced after a failed write, so another tab's value neither overrides it nor survives the retry", async () => { + await withViewPersistence(() => { + vi.advanceTimersByTime(200); + // Disk holds showPrRuns: true while memory and this tab's last save hold false. + seedOtherTabWrite({ showPrRuns: true }); + + applyImportedViewState({ showPrRuns: false }); + const setItemSpy = vi.spyOn(localStorageMock, "setItem").mockImplementationOnce(throwQuotaError); + try { + flushViewPersistence(); + expect(setItemSpy).toHaveBeenCalledTimes(1); + expect(currentOnDisk().showPrRuns).toBe(true); + + dispatchViewStorage(JSON.stringify({ ...currentOnDisk(), showPrRuns: true })); + expect(viewState.showPrRuns).toBe(false); + + flushViewPersistence(); + expect(currentOnDisk().showPrRuns).toBe(false); + } finally { + setItemSpy.mockRestore(); + } + }); + }); + + it("does not adopt another tab's value for an imported key equal to the last save before the debounced write lands", async () => { + await withViewPersistence(() => { + vi.advanceTimersByTime(200); + + applyImportedViewState({ jiraCustomOrder: [] }); + const otherTabBlob = JSON.stringify({ ...currentOnDisk(), jiraCustomOrder: ["OTHER-1"] }); + localStorageMock.setItem(VIEW_KEY, otherTabBlob); + dispatchViewStorage(otherTabBlob); + expect(viewState.jiraCustomOrder).toEqual([]); + + vi.advanceTimersByTime(200); + expect(currentOnDisk().jiraCustomOrder).toEqual([]); + }); + }); + + it("removes per-tab sub-keys that another tab's adopted value no longer holds", async () => { + await withViewPersistence(() => { + setCustomTabFilter("tabA", "scope", "all"); + lockRepo("tabA", "o/r"); + toggleExpandedRepo("tabA", "o/r"); + vi.advanceTimersByTime(200); + expect("tabA" in viewState.customTabFilters).toBe(true); + expect("tabA" in viewState.lockedRepos).toBe(true); + expect("tabA" in viewState.expandedRepos).toBe(true); + + const otherTabBlob = JSON.stringify({ + ...currentOnDisk(), + customTabFilters: {}, + lockedRepos: { issues: [], pullRequests: [], actions: [], jiraAssigned: [] }, + expandedRepos: { issues: {}, pullRequests: {}, actions: {}, jiraAssigned: {} }, + }); + localStorageMock.setItem(VIEW_KEY, otherTabBlob); + const setItemSpy = vi.spyOn(localStorageMock, "setItem"); + try { + dispatchViewStorage(otherTabBlob); + expect("tabA" in viewState.customTabFilters).toBe(false); + expect("tabA" in viewState.lockedRepos).toBe(false); + expect("tabA" in viewState.expandedRepos).toBe(false); + + vi.advanceTimersByTime(200); + flushViewPersistence(); + expect(setItemSpy).not.toHaveBeenCalled(); + } finally { + setItemSpy.mockRestore(); + } + }); + }); + + it("salvages the valid keys of a stored view state whose blob fails whole-schema validation", async () => { + localStorageMock.setItem( + VIEW_KEY, + JSON.stringify({ showPrRuns: "yes", lastActiveTab: "actions", hideDepDashboard: false }), + ); + // loadViewState() rejects the whole blob, so a freshly loaded store starts from defaults... + vi.resetModules(); + const fresh = await import("../../src/app/stores/view"); + expect(fresh.viewState.lastActiveTab).toBe("issues"); + expect(fresh.viewState.hideDepDashboard).toBe(true); + + // ...which this module's store also holds (beforeEach reset); init adopts the valid keys. + await withViewPersistence(() => { + expect(viewState.lastActiveTab).toBe("actions"); + expect(viewState.hideDepDashboard).toBe(false); + expect(viewState.showPrRuns).toBe(false); + + vi.advanceTimersByTime(200); + expect(currentOnDisk()).toMatchObject({ lastActiveTab: "actions", hideDepDashboard: false, showPrRuns: false }); + }); + }); + + it("neither writes nor adopts while the stored schema is stale, then writes the pending change once it clears", async () => { + await withViewPersistence(() => { + vi.advanceTimersByTime(200); + _setSchemaStaleForTests(true); + const setItemSpy = vi.spyOn(localStorageMock, "setItem"); + try { + setGlobalFilter("org1", "repo1"); + vi.advanceTimersByTime(200); + flushViewPersistence(); + expect(setItemSpy).not.toHaveBeenCalled(); + + dispatchViewStorage(JSON.stringify({ ...currentOnDisk(), showPrRuns: true })); + expect(viewState.showPrRuns).toBe(false); + + _setSchemaStaleForTests(false); + flushViewPersistence(); + expect(setItemSpy).toHaveBeenCalledTimes(1); + const onDisk = currentOnDisk(); + expect(onDisk.globalFilter).toEqual({ org: "org1", repo: "repo1" }); + expect(onDisk.showPrRuns).toBe(false); + } finally { + setItemSpy.mockRestore(); + _resetVersionStateForTests(); + } + }); + }); + + it("discardPendingViewPersistence() drops this tab's unsaved change so it is never written", async () => { + await withViewPersistence(() => { + vi.advanceTimersByTime(200); + const setItemSpy = vi.spyOn(localStorageMock, "setItem"); + try { + setGlobalFilter("org1", "repo1"); + discardPendingViewPersistence(); + vi.advanceTimersByTime(200); + flushViewPersistence(); + expect(setItemSpy).not.toHaveBeenCalled(); + expect(currentOnDisk().globalFilter).toEqual({ org: null, repo: null }); + } finally { + setItemSpy.mockRestore(); + } + }); + }); }); describe("initViewPersistence — genuine two-tab concurrency", () => { @@ -568,7 +854,7 @@ describe("initViewPersistence — genuine two-tab concurrency", () => { // representing an already-completed write), this describe block spins up // TWO fully independent module instances of stores/view.ts via // vi.resetModules() + fresh dynamic imports — each with its own in-memory - // viewState, its own commitSnapshot()/lastSyncedSnapshot closure, and its + // viewState, its own per-key persistence baseline, and its // own live createEffect/debounce timer — sharing only the same // localStorageMock (the one durable channel two real browser tabs would // actually share). This exercises the hardest case for the merge-on-write @@ -582,7 +868,7 @@ describe("initViewPersistence — genuine two-tab concurrency", () => { return import("../../src/app/stores/view"); } - it("whichever tab's commitSnapshot() actually runs last wins when both change the same field at the same tick", async () => { + it("whichever tab's debounced commit actually runs last wins when both change the same field at the same tick", async () => { vi.useFakeTimers(); const tabA = await importFreshViewModule(); const tabB = await importFreshViewModule(); @@ -871,6 +1157,37 @@ describe("resetViewState", () => { // Tab defaults reset: Jira back to expanded, GitHub tabs back to collapsed expect(viewState.expandDefault).toEqual({ jiraAssigned: true }); }); + + it("overwrites a stale on-disk value on flushViewPersistence() even when the in-memory baseline already matches the reset value", () => { + let dispose!: () => void; + createRoot((d) => { + dispose = d; + initViewPersistence(); + }); + try { + // In-memory baseline already has default globalFilter ({ org: null, repo: null }). + // Simulate another tab or prior session writing a stale globalFilter to disk. + localStorageMock.setItem( + VIEW_STORAGE_KEY, + JSON.stringify({ + ...JSON.parse(JSON.stringify(viewState)), + globalFilter: { org: "stale-org", repo: "stale-repo" }, + jiraCustomOrder: ["STALE-1"], + }), + ); + + resetViewState(); + flushViewPersistence(); + + const raw = localStorageMock.getItem(VIEW_STORAGE_KEY); + expect(raw).not.toBeNull(); + const parsed = JSON.parse(raw); + expect(parsed.globalFilter).toEqual({ org: null, repo: null }); + expect(parsed.jiraCustomOrder).toEqual([]); + } finally { + dispose(); + } + }); }); describe("resetAllTabFilters — scope reset", () => { @@ -1638,6 +1955,28 @@ describe("applyImportedViewState", () => { expect("jiraStatus" in viewState.trackedItems[0]).toBe(false); }); + it("strips htmlUrl and jiraStatus from an imported tracked item, keeping its other fields", () => { + applyImportedViewState({ + trackedItems: [ + { + id: 1, + type: "jiraIssue", + source: "jira", + repoFullName: "", + jiraKey: "PROJ-1", + addedAt: 1, + htmlUrl: "https://evil.example/x", + jiraStatus: "Done", + }, + ], + }); + expect(viewState.trackedItems).toEqual([ + { id: 1, type: "jiraIssue", source: "jira", repoFullName: "", jiraKey: "PROJ-1", addedAt: 1, title: "" }, + ]); + expect("htmlUrl" in viewState.trackedItems[0]).toBe(false); + expect("jiraStatus" in viewState.trackedItems[0]).toBe(false); + }); + it.each([null, undefined, "a string", 42, [], ["also", "an", "array"]])( "is a total silent no-op for wholly-malformed input: %p", (malformed) => { @@ -1676,4 +2015,93 @@ describe("applyImportedViewState", () => { expect(EXPORTED_VIEW_PREF_KEYS).not.toContain("globalSort"); expect(EXPORTED_VIEW_PREF_KEYS).not.toContain("globalFilter"); }); + + it("overwrites a stale on-disk value on flushViewPersistence() when an imported key matches the in-memory baseline", () => { + let dispose!: () => void; + createRoot((d) => { + dispose = d; + initViewPersistence(); + }); + try { + // In-memory baseline already has jiraCustomOrder: [] and showPrRuns: false. + // Simulate another tab or prior session writing stale values on disk. + localStorageMock.setItem( + VIEW_STORAGE_KEY, + JSON.stringify({ + ...JSON.parse(JSON.stringify(viewState)), + jiraCustomOrder: ["STALE-1"], + showPrRuns: true, + }), + ); + + applyImportedViewState({ jiraCustomOrder: [], showPrRuns: false }); + flushViewPersistence(); + + const raw = localStorageMock.getItem(VIEW_STORAGE_KEY); + expect(raw).not.toBeNull(); + const parsed = JSON.parse(raw); + expect(parsed.jiraCustomOrder).toEqual([]); + expect(parsed.showPrRuns).toBe(false); + } finally { + dispose(); + } + }); + + it("schedules a debounced write on applyImportedViewState even when imported primitive values already match in-memory viewState", () => { + vi.useFakeTimers(); + let dispose!: () => void; + createRoot((d) => { + dispose = d; + initViewPersistence(); + }); + try { + // Let initial mount persistence settle + vi.advanceTimersByTime(250); + + // Simulate another tab writing showPrRuns: true to disk while this tab still has false in memory + localStorageMock.setItem( + VIEW_STORAGE_KEY, + JSON.stringify({ + ...JSON.parse(JSON.stringify(viewState)), + showPrRuns: true, + }), + ); + + // Importing showPrRuns: false matches in-memory viewState.showPrRuns (false), + // so without persistTrigger the persistence effect would not re-run. + applyImportedViewState({ showPrRuns: false }); + vi.advanceTimersByTime(250); + + const parsed = JSON.parse(localStorageMock.getItem(VIEW_STORAGE_KEY) ?? "{}"); + expect(parsed.showPrRuns).toBe(false); + } finally { + dispose(); + vi.useRealTimers(); + } + }); + + it("does not write or strip another tab's on-disk view state on flushViewPersistence() when this tab has no changes of its own", () => { + let dispose!: () => void; + createRoot((d) => { + dispose = d; + initViewPersistence(); + }); + const setItemSpy = vi.spyOn(localStorageMock, "setItem"); + try { + const otherTabBlob = JSON.stringify({ + ...JSON.parse(JSON.stringify(viewState)), + showPrRuns: true, + futureSchemaKey: "preserved", + }); + localStorageMock.setItem(VIEW_STORAGE_KEY, otherTabBlob); + setItemSpy.mockClear(); + + flushViewPersistence(); + expect(setItemSpy).not.toHaveBeenCalled(); + expect(localStorageMock.getItem(VIEW_STORAGE_KEY)).toBe(otherTabBlob); + } finally { + setItemSpy.mockRestore(); + dispose(); + } + }); }); diff --git a/tests/stubs/build-meta-test-config.ts b/tests/stubs/build-meta-test-config.ts new file mode 100644 index 00000000..f9280c60 --- /dev/null +++ b/tests/stubs/build-meta-test-config.ts @@ -0,0 +1,22 @@ +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const stubsDir = dirname(fileURLToPath(import.meta.url)); + +/** + * Vite `resolve`/`define` settings that stand in for the build-meta plugin + * (`vite-plugins/build-meta.ts`) in every Vitest config: the `virtual:changelog` + * module is aliased to a fixture and the build constants get fixed values. + */ +export const buildMetaTestConfig = { + resolve: { + alias: { + "virtual:changelog": resolve(stubsDir, "virtual-changelog.ts"), + }, + }, + define: { + __APP_VERSION__: JSON.stringify("0.1.0"), + __GIT_SHA__: JSON.stringify("abcdef123456"), + __SCHEMA_FP__: JSON.stringify("0123456789ab"), + }, +}; diff --git a/tests/stubs/virtual-changelog.ts b/tests/stubs/virtual-changelog.ts new file mode 100644 index 00000000..ece67b7b --- /dev/null +++ b/tests/stubs/virtual-changelog.ts @@ -0,0 +1,38 @@ +import type { ChangelogEntry } from "../../src/shared/changelog-schema"; + +const entries: ChangelogEntry[] = [ + { + version: "0.1.0", + date: "2026-11-06", + sections: [ + { + title: "Features", + items: [ + { + text: "version: add in-app What's New dialog generated from CHANGELOG", + pr: 188, + sha: "abcdef1", + }, + ], + }, + ], + }, + { + version: "0.0.9", + date: "2026-11-01", + sections: [ + { + title: "Bug Fixes", + items: [ + { + text: "release: sync MCP version and automate release-please flow", + pr: 183, + sha: "97050e3", + }, + ], + }, + ], + }, +]; + +export default entries; diff --git a/vite-plugins/build-meta.ts b/vite-plugins/build-meta.ts new file mode 100644 index 00000000..ce2e2ada --- /dev/null +++ b/vite-plugins/build-meta.ts @@ -0,0 +1,268 @@ +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import type { Plugin } from "vite"; +import * as z from "zod/mini"; +import { createHash } from "node:crypto"; +import { BUILD_SHA_LENGTH, COMMIT_SHA_PATTERN, COMMIT_SHA_RE, type BuildInfo } from "../src/shared/build-meta.ts"; +import { ConfigSchema, TRACKED_USER_AVATAR_PREFIX } from "../src/shared/schemas.ts"; +import { PERSISTED_LIMITS, ViewStateSchema } from "../src/shared/view-schema.ts"; +import { + CHANGELOG_MAX_ENTRIES, + CHANGELOG_MAX_ITEM_TEXT_LENGTH, + CHANGELOG_MAX_SECTION_TITLE_LENGTH, + ChangelogSchema, + type ChangelogEntry, + type ChangelogItem, + type ChangelogSection, +} from "../src/shared/changelog-schema.ts"; + +// Case-insensitive on purpose: GITHUB_SHA and `git rev-parse` output are normalized to lowercase below. +const HEX_SHA_RE = new RegExp(COMMIT_SHA_RE.source, "i"); +const VIRTUAL_CHANGELOG_ID = "virtual:changelog"; +const RESOLVED_VIRTUAL_CHANGELOG_ID = "\0virtual:changelog"; + +const RELEASE_HEADING_RE = + /^#{2,3}\s+(?:\[v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\]\([^)]*\)|v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?))\s+\((\d{4}-\d{2}-\d{2})\)\s*$/; +const SECTION_HEADING_RE = /^###\s+(.+?)\s*$/; +const BULLET_LINE_RE = /^\s*[*-]\s+(.+?)\s*$/; +const COMMIT_LINK_RE = new RegExp( + `(?:\\(\\[(${COMMIT_SHA_PATTERN})\\]\\([^)]*\\)\\)|\\[(${COMMIT_SHA_PATTERN})\\]\\([^)]*\\))`, + "i", +); +const COMMIT_LINK_PARENS_STRIP_RE = new RegExp(`\\s*\\(\\[${COMMIT_SHA_PATTERN}\\]\\([^)]*\\)\\)`, "gi"); +const COMMIT_LINK_TRAILING_STRIP_RE = new RegExp(`\\s+\\[${COMMIT_SHA_PATTERN}\\]\\([^)]*\\)\\s*$`, "gi"); +const PR_REF_RE = /(?:\(\[#(\d+)\]\([^)]*\)\)|\[#(\d+)\]\([^)]*\)|\(#(\d+)\))/; +const MARKDOWN_LINK_RE = /!?\[([^\]]*)\]\((?:[^()\s]|\([^()\s]*\))*\)/g; + +function stripMarkdownLinks(input: string): string { + let prev = input; + for (let i = 0; i < 5; i++) { + const next = prev.replace(MARKDOWN_LINK_RE, "$1"); + if (next === prev) break; + prev = next; + } + return prev; +} + +function parseBulletLine(rawBullet: string): ChangelogItem | null { + const prMatch = PR_REF_RE.exec(rawBullet); + const parsedPr = Number.parseInt(prMatch?.[1] ?? prMatch?.[2] ?? prMatch?.[3] ?? "0", 10); + const pr = parsedPr > 0 ? parsedPr : undefined; + + const shaMatch = COMMIT_LINK_RE.exec(rawBullet); + const sha = (shaMatch?.[1] ?? shaMatch?.[2])?.toLowerCase(); + + let text = rawBullet + .replace(COMMIT_LINK_PARENS_STRIP_RE, "") + .replace(COMMIT_LINK_TRAILING_STRIP_RE, "") + .replace(/\s*\(\[#\d+\]\([^)]*\)\)/g, "") + .replace(/\s*\(#\d+\)/g, ""); + + text = stripMarkdownLinks(text) + .replace(/\*\*([^*]+)\*\*/g, "$1") + .replace(/__([^_]+)__/g, "$1") + .replace(/\s+/g, " ") + .trim() + .slice(0, CHANGELOG_MAX_ITEM_TEXT_LENGTH) + .trim(); + + if (text.length === 0) { + return null; + } + + const item: ChangelogItem = { text }; + if (pr !== undefined) item.pr = pr; + if (sha !== undefined) item.sha = sha; + return item; +} + +export function parseChangelog(markdown: string): ChangelogEntry[] { + const entries: ChangelogEntry[] = []; + let currentEntry: ChangelogEntry | null = null; + let currentSection: ChangelogSection | null = null; + + for (const rawLine of markdown.split(/\r?\n/)) { + const releaseMatch = RELEASE_HEADING_RE.exec(rawLine); + if (releaseMatch) { + const version = releaseMatch[1] ?? releaseMatch[2]; + const date = releaseMatch[3]; + if (version && date) { + currentEntry = { version, date, sections: [] }; + entries.push(currentEntry); + currentSection = null; + } + continue; + } + + if (!currentEntry) continue; + + const sectionMatch = SECTION_HEADING_RE.exec(rawLine); + if (sectionMatch) { + const title = stripMarkdownLinks(sectionMatch[1]) + .replace(/\s+/g, " ") + .trim() + .slice(0, CHANGELOG_MAX_SECTION_TITLE_LENGTH) + .trim(); + if (title.length > 0) { + const existing = currentEntry.sections.find((s) => s.title === title); + if (existing) { + currentSection = existing; + } else { + currentSection = { title, items: [] }; + currentEntry.sections.push(currentSection); + } + } + continue; + } + + const bulletMatch = BULLET_LINE_RE.exec(rawLine); + if (bulletMatch) { + const item = parseBulletLine(bulletMatch[1]); + if (!item) continue; + if (!currentSection) { + currentSection = { title: "Changes", items: [] }; + currentEntry.sections.push(currentSection); + } + currentSection.items.push(item); + } + } + + for (const entry of entries) { + entry.sections = entry.sections.filter((s) => s.items.length > 0); + } + const cleaned = entries.slice(0, CHANGELOG_MAX_ENTRIES); + + return z.parse(ChangelogSchema, cleaned); +} + +/** + * Build SHA source order: `BUILD_GIT_SHA` (set by deploy.yml to the checked-out commit, since + * GitHub Actions forbids overriding `GITHUB_SHA`), then `GITHUB_SHA`, then `git rev-parse HEAD`. + */ +export function resolveGitSha(): string { + const envSha = process.env.BUILD_GIT_SHA?.trim() || process.env.GITHUB_SHA?.trim(); + let rawSha: string; + if (envSha) { + rawSha = envSha; + } else { + try { + rawSha = execFileSync("git", ["rev-parse", "HEAD"], { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + }).trim(); + } catch { + rawSha = "dev"; + } + } + if (!HEX_SHA_RE.test(rawSha)) { + return "dev"; + } + return rawSha.toLowerCase().slice(0, BUILD_SHA_LENGTH); +} + +export function resolvePackageVersion(): string { + const pkgPath = resolve(process.cwd(), "package.json"); + const raw = JSON.parse(readFileSync(pkgPath, "utf8")) as { version?: unknown }; + return typeof raw.version === "string" && raw.version.trim() !== "" + ? raw.version.trim() + : "0.0.0"; +} + +/** + * JSON with object keys, and JSON Schema `required` lists, in a fixed order, so reordering a + * schema's keys does not change the output. + */ +function stableStringify(value: unknown): string { + return JSON.stringify(value, (key, v: unknown) => { + if (key === "required" && Array.isArray(v)) return (v as string[]).toSorted(); + if (v !== null && typeof v === "object" && !Array.isArray(v)) { + return Object.fromEntries( + Object.entries(v as Record).toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)), + ); + } + return v; + }); +} + +/** + * Fingerprint of what the persisted config and view-state blobs may contain. A tab running an + * older layout compares it with the deployed one to learn that a newer deployment stores data + * it can't safely read or write. It hashes: + * - the JSON Schema of both schemas (`io: "input"`, the stored side): keys, types, enums, + * patterns, array limits and defaults; + * - `PERSISTED_LIMITS` and `TRACKED_USER_AVATAR_PREFIX`, the rules enforced by `.refine()` + * checks that JSON Schema cannot express. + * Comments, formatting, helper code and key order don't affect it. A `.refine()` predicate that + * changes without changing one of those values is not detected, which is why every refine limit + * must live in `PERSISTED_LIMITS` (a unit test fails when a new refine appears). + */ +export function computeSchemaFingerprint(): string { + const payload = { + config: z.toJSONSchema(ConfigSchema, { unrepresentable: "any", io: "input" }), + view: z.toJSONSchema(ViewStateSchema, { unrepresentable: "any", io: "input" }), + limits: PERSISTED_LIMITS, + trackedUserAvatarPrefix: TRACKED_USER_AVATAR_PREFIX, + }; + return createHash("sha256").update(stableStringify(payload)).digest("hex").slice(0, BUILD_SHA_LENGTH); +} + +export function resolveBuildMetadata(): BuildInfo { + return { + version: resolvePackageVersion(), + sha: resolveGitSha(), + builtAt: new Date().toISOString(), + schemaFp: computeSchemaFingerprint(), + }; +} + +export function buildMeta(): Plugin[] { + const { version, sha, builtAt, schemaFp } = resolveBuildMetadata(); + + return [ + { + name: "github-tracker:build-meta-define", + config() { + return { + define: { + __APP_VERSION__: JSON.stringify(version), + __GIT_SHA__: JSON.stringify(sha), + __SCHEMA_FP__: JSON.stringify(schemaFp), + }, + }; + }, + }, + { + name: "github-tracker:build-meta-emit", + applyToEnvironment(environment) { + return environment.name === "client"; + }, + resolveId(id) { + if (id === VIRTUAL_CHANGELOG_ID) { + return RESOLVED_VIRTUAL_CHANGELOG_ID; + } + return null; + }, + load(id) { + if (id !== RESOLVED_VIRTUAL_CHANGELOG_ID) { + return null; + } + const changelogPath = resolve(process.cwd(), "CHANGELOG.md"); + this.addWatchFile(changelogPath); + if (!existsSync(changelogPath)) { + return "export default [];"; + } + const raw = readFileSync(changelogPath, "utf8"); + const entries = parseChangelog(raw); + return `export default ${JSON.stringify(entries)};`; + }, + generateBundle() { + this.emitFile({ + type: "asset", + fileName: "version.json", + source: JSON.stringify({ version, sha, builtAt, schemaFp }), + }); + }, + }, + ]; +} diff --git a/vite.config.ts b/vite.config.ts index 51ee9c25..72452f92 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -3,9 +3,11 @@ import solid from "vite-plugin-solid"; import tailwindcss from "@tailwindcss/vite"; import { cloudflare } from "@cloudflare/vite-plugin"; import { visualizer } from "rollup-plugin-visualizer"; +import { buildMeta } from "./vite-plugins/build-meta.ts"; export default defineConfig({ plugins: [ + ...buildMeta(), solid(), tailwindcss(), cloudflare(), diff --git a/vitest.config.ts b/vitest.config.ts index 5153a393..28613d63 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,12 +1,14 @@ import { defineConfig } from "vitest/config"; import solid from "vite-plugin-solid"; import tailwindcss from "@tailwindcss/vite"; +import { buildMetaTestConfig } from "./tests/stubs/build-meta-test-config.ts"; // Separate Vitest config that excludes the @cloudflare/vite-plugin. // The cloudflare plugin conflicts with Vitest's test runner environment. // vite.config.ts (with the cloudflare plugin) is used only for builds. export default defineConfig({ plugins: [solid(), tailwindcss()], + ...buildMetaTestConfig, test: { environment: "happy-dom", globals: true, diff --git a/vitest.smoke.config.ts b/vitest.smoke.config.ts index f6958173..259c558d 100644 --- a/vitest.smoke.config.ts +++ b/vitest.smoke.config.ts @@ -1,5 +1,5 @@ import { defineConfig, mergeConfig, type ViteUserConfig } from "vitest/config"; -import baseConfig from "./vitest.config"; +import baseConfig from "./vitest.config.ts"; // Standalone config for live-network smoke tests (e.g. github-status.smoke.test.ts). // These are deliberately excluded from vitest.workspace.ts's "browser" project diff --git a/vitest.workspace.ts b/vitest.workspace.ts index dd0856c7..fa80d945 100644 --- a/vitest.workspace.ts +++ b/vitest.workspace.ts @@ -2,6 +2,7 @@ import { defineConfig, defineProject } from "vitest/config"; import { cloudflareTest } from "@cloudflare/vitest-plugin"; import solid from "vite-plugin-solid"; import tailwindcss from "@tailwindcss/vite"; +import { buildMetaTestConfig } from "./tests/stubs/build-meta-test-config.ts"; export default defineConfig({ test: { @@ -11,6 +12,7 @@ export default defineConfig({ // Browser/DOM tests (stores, services, UI) defineProject({ plugins: [solid(), tailwindcss()], + ...buildMetaTestConfig, test: { name: "browser", environment: "happy-dom",