From a0bd74621ca20485398434a3df9dc9b8f8240fc3 Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Fri, 6 Nov 2026 10:06:18 -0500 Subject: [PATCH 01/11] feat(version): stamp build metadata, serve version.json, show version --- docs/USER_GUIDE.md | 2 +- package.json | 4 +- public/_headers | 3 + .../components/dashboard/DashboardPage.tsx | 13 ++ src/app/components/settings/SettingsPage.tsx | 29 +++ src/app/lib/sentry-init.ts | 2 + src/app/lib/version.ts | 7 + src/types/build-meta.d.ts | 4 + tests/build/build-meta.test.ts | 202 ++++++++++++++++++ tests/components/DashboardPage.test.tsx | 28 +++ .../components/settings/SettingsPage.test.tsx | 32 +++ tests/lib/sentry-facade.test.ts | 5 + tests/lib/sentry.test.ts | 3 +- tests/lib/version.test.ts | 20 ++ tests/security/headers.test.ts | 5 + vite-plugins/build-meta.ts | 81 +++++++ vite.config.ts | 2 + vitest.config.ts | 5 + vitest.workspace.ts | 5 + 19 files changed, 448 insertions(+), 4 deletions(-) create mode 100644 src/app/lib/version.ts create mode 100644 src/types/build-meta.d.ts create mode 100644 tests/build/build-meta.test.ts create mode 100644 tests/lib/version.test.ts create mode 100644 vite-plugins/build-meta.ts diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index 0be99dbb..23b8b7cc 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -710,7 +710,7 @@ The header shrinks as you scroll to maximize content space. ## Settings Reference -Settings are saved automatically to `localStorage` and persist across sessions. All settings can be exported as a JSON file via **Settings > Data > Export**. +Settings are saved automatically to `localStorage` and persist across sessions. All settings can be exported as a JSON file via **Settings > Data > Export**. The current build version (`+`) is shown in **Settings > Data > About** (alongside a link to the changelog) and in the dashboard footer, both linking to the GitHub Releases page. ### Config Settings diff --git a/package.json b/package.json index 7159fabd..979897d4 100644 --- a/package.json +++ b/package.json @@ -12,8 +12,8 @@ "test:watch": "vitest --config vitest.workspace.ts", "deploy": "wrangler deploy", "typecheck": "tsc --build src/shared/tsconfig.json && tsc --build mcp/tsconfig.json && tsc -p tsconfig.lint.json", - "lint": "oxlint --type-aware --tsconfig tsconfig.lint.json --deny-warnings src tests e2e mcp/tests vite.config.ts vitest.config.ts vitest.smoke.config.ts vitest.workspace.ts playwright.config.ts playwright.config.screenshot.ts mcp/tsup.config.ts mcp/vitest.config.ts && oxlint --type-aware --tsconfig mcp/tsconfig.json --deny-warnings mcp/src", - "lint:fix": "oxlint --type-aware --tsconfig tsconfig.lint.json --fix src tests e2e mcp/tests vite.config.ts vitest.config.ts vitest.smoke.config.ts vitest.workspace.ts playwright.config.ts playwright.config.screenshot.ts mcp/tsup.config.ts mcp/vitest.config.ts && oxlint --type-aware --tsconfig mcp/tsconfig.json --fix mcp/src", + "lint": "oxlint --type-aware --tsconfig tsconfig.lint.json --deny-warnings src tests e2e mcp/tests vite.config.ts vitest.config.ts vitest.smoke.config.ts vitest.workspace.ts playwright.config.ts playwright.config.screenshot.ts mcp/tsup.config.ts mcp/vitest.config.ts vite-plugins && oxlint --type-aware --tsconfig mcp/tsconfig.json --deny-warnings mcp/src", + "lint:fix": "oxlint --type-aware --tsconfig tsconfig.lint.json --fix src tests e2e mcp/tests vite.config.ts vitest.config.ts vitest.smoke.config.ts vitest.workspace.ts playwright.config.ts playwright.config.screenshot.ts mcp/tsup.config.ts mcp/vitest.config.ts vite-plugins && oxlint --type-aware --tsconfig mcp/tsconfig.json --fix mcp/src", "test:e2e": "E2E_PORT=$(node -e \"const s=require('net').createServer();s.listen(0,()=>{console.log(s.address().port);s.close()})\") playwright test", "test:waf": "bash scripts/waf-smoke-test.sh", "test:status-smoke": "vitest run --config vitest.smoke.config.ts", diff --git a/public/_headers b/public/_headers index ce8bf8cf..f0a87ecd 100644 --- a/public/_headers +++ b/public/_headers @@ -9,3 +9,6 @@ /_app/* Cache-Control: public, max-age=31536000, immutable + +/version.json + Cache-Control: no-store diff --git a/src/app/components/dashboard/DashboardPage.tsx b/src/app/components/dashboard/DashboardPage.tsx index 0e926a1b..be95ed82 100644 --- a/src/app/components/dashboard/DashboardPage.tsx +++ b/src/app/components/dashboard/DashboardPage.tsx @@ -51,8 +51,12 @@ import { isUserInvolved } from "../../lib/grouping"; import { KNOWN_CONCLUSIONS, KNOWN_EVENTS } from "../shared/filterTypes"; import { loadEmojiMap } from "../../lib/emoji"; import { mergeActiveFilters } from "../../lib/tabFilters"; +import { isSafeGitHubUrl } from "../../lib/url"; +import { displayVersion } from "../../lib/version"; import type { CustomTab } from "../../stores/config"; +const RELEASES_URL = "https://github.com/gordon-code/github-tracker/releases"; + const CustomTabModal = lazy(() => import("../shared/CustomTabModal")); // Hoisted to module scope — these are constant values (Zod schema defaults). @@ -2162,6 +2166,15 @@ export default function DashboardPage() { > Privacy + + + v{displayVersion()} +
diff --git a/src/app/components/settings/SettingsPage.tsx b/src/app/components/settings/SettingsPage.tsx index abfcbfb7..de964f8a 100644 --- a/src/app/components/settings/SettingsPage.tsx +++ b/src/app/components/settings/SettingsPage.tsx @@ -21,6 +21,7 @@ import { pushNotification, dismissNotificationBySource } from "../../lib/errors" import { buildOrgAccessUrl, buildJiraAuthorizeUrl } from "../../lib/oauth"; import { sealApiToken } from "../../lib/proxy"; import { isSafeGitHubUrl, openGitHubUrl } from "../../lib/url"; +import { displayVersion } from "../../lib/version"; import { relativeTime, formatScopeSummary } from "../../lib/format"; import { fetchOrgs } from "../../services/api"; import { getClient } from "../../services/github"; @@ -47,6 +48,8 @@ import type { RepoRef } from "../../services/api"; const VALID_JIRA_CLIENT_ID_RE = /^[A-Za-z0-9_-]+$/; const VALID_JIRA_SITE_URL_RE = /^https:\/\/[a-z0-9-]+\.atlassian\.net$/i; const VALID_JIRA_CLOUD_ID_RE = /^[a-zA-Z0-9-]+$/; +const RELEASES_URL = "https://github.com/gordon-code/github-tracker/releases"; +const CHANGELOG_URL = "https://github.com/gordon-code/github-tracker/blob/main/CHANGELOG.md"; interface NumberSelectOption { value: number; @@ -2122,6 +2125,32 @@ export default function SettingsPage() { Sign out + + {/* About */} + + +
diff --git a/src/app/lib/sentry-init.ts b/src/app/lib/sentry-init.ts index f9e7814a..eb1489b9 100644 --- a/src/app/lib/sentry-init.ts +++ b/src/app/lib/sentry-init.ts @@ -1,5 +1,6 @@ import { captureException, init } from "@sentry/solid"; import { beforeBreadcrumbHandler, beforeSendHandler } from "./sentry"; +import { GIT_SHA } from "./version"; export interface SentrySdkClient { captureException: typeof captureException; @@ -11,6 +12,7 @@ export function initSdk(): SentrySdkClient { init({ dsn, + release: `github-tracker@${GIT_SHA}`, tunnel: "/api/error-reporting", environment: import.meta.env.MODE, enhanceFetchErrorMessages: "report-only", diff --git a/src/app/lib/version.ts b/src/app/lib/version.ts new file mode 100644 index 00000000..42b2835c --- /dev/null +++ b/src/app/lib/version.ts @@ -0,0 +1,7 @@ +export const APP_VERSION: string = __APP_VERSION__; +export const GIT_SHA: string = __GIT_SHA__; +export const BUILD_TIME: string = __BUILD_TIME__; + +export function displayVersion(): string { + return `${APP_VERSION}+${GIT_SHA.slice(0, 7)}`; +} diff --git a/src/types/build-meta.d.ts b/src/types/build-meta.d.ts new file mode 100644 index 00000000..ec149957 --- /dev/null +++ b/src/types/build-meta.d.ts @@ -0,0 +1,4 @@ +// Build-time metadata constants injected via Vite `define`. +declare const __APP_VERSION__: string; +declare const __GIT_SHA__: string; +declare const __BUILD_TIME__: string; diff --git a/tests/build/build-meta.test.ts b/tests/build/build-meta.test.ts new file mode 100644 index 00000000..58af5a27 --- /dev/null +++ b/tests/build/build-meta.test.ts @@ -0,0 +1,202 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; + +const mockExecFileSync = vi.hoisted(() => vi.fn()); +const mockReadFileSync = vi.hoisted(() => vi.fn()); + +vi.mock("node:child_process", () => ({ + execFileSync: (...args: unknown[]) => mockExecFileSync(...args), +})); + +vi.mock("node:fs", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + readFileSync: (...args: Parameters) => + mockReadFileSync.getMockImplementation() + ? mockReadFileSync(...args) + : actual.readFileSync(...args), + }; +}); + +import { + buildMeta, + resolveBuildMetadata, + resolveGitSha, + resolvePackageVersion, +} from "../../vite-plugins/build-meta"; + +const pkgVersion = ( + JSON.parse( + readFileSync(resolve(process.cwd(), "package.json"), "utf8"), + ) as { version: string } +).version; + +describe("buildMeta Vite plugin", () => { + const originalGithubSha = process.env.GITHUB_SHA; + + beforeEach(() => { + mockExecFileSync.mockReset(); + mockReadFileSync.mockReset(); + delete process.env.GITHUB_SHA; + }); + + afterEach(() => { + if (originalGithubSha === undefined) { + delete process.env.GITHUB_SHA; + } else { + process.env.GITHUB_SHA = originalGithubSha; + } + vi.useRealTimers(); + }); + + it("prefers GITHUB_SHA over git rev-parse HEAD and slices to 12 hex characters", () => { + process.env.GITHUB_SHA = " 1234567890ABCDEF1234567890abcdef12345678\n"; + mockExecFileSync.mockReturnValue("ffffffffffffffffffffffffffffffffffffffff\n"); + + const sha = resolveGitSha(); + expect(sha).toBe("1234567890ab"); + expect(mockExecFileSync).not.toHaveBeenCalled(); + }); + + it("falls back to git rev-parse HEAD when GITHUB_SHA is unset or blank and slices to 12 chars", () => { + process.env.GITHUB_SHA = " "; + mockExecFileSync.mockReturnValue("fedcba9876543210fedcba9876543210fedcba98\n"); + + const sha = resolveGitSha(); + expect(sha).toBe("fedcba987654"); + expect(mockExecFileSync).toHaveBeenCalledWith( + "git", + ["rev-parse", "HEAD"], + expect.objectContaining({ + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + }), + ); + }); + + it("falls back to 'dev' when git rev-parse HEAD throws or returns non-hex output", () => { + mockExecFileSync.mockImplementationOnce(() => { + throw new Error("fatal: not a git repository"); + }); + expect(resolveGitSha()).toBe("dev"); + + mockExecFileSync.mockReturnValueOnce("not-a-valid-sha\n"); + expect(resolveGitSha()).toBe("dev"); + + mockExecFileSync.mockReturnValueOnce("\n"); + expect(resolveGitSha()).toBe("dev"); + }); + + it("validates GITHUB_SHA length and hex characters and accepts 7-char short SHAs", () => { + process.env.GITHUB_SHA = "123456"; // < 7 chars + expect(resolveGitSha()).toBe("dev"); + expect(mockExecFileSync).not.toHaveBeenCalled(); + + process.env.GITHUB_SHA = "a".repeat(41); // > 40 chars + expect(resolveGitSha()).toBe("dev"); + expect(mockExecFileSync).not.toHaveBeenCalled(); + + process.env.GITHUB_SHA = "1234567g"; // non-hex character + expect(resolveGitSha()).toBe("dev"); + expect(mockExecFileSync).not.toHaveBeenCalled(); + + process.env.GITHUB_SHA = "ABCDEF1"; // minimum valid 7-char short SHA + expect(resolveGitSha()).toBe("abcdef1"); + }); + + it("resolves trimmed package.json version and falls back to '0.0.0' when missing, blank, or non-string", () => { + expect(resolvePackageVersion()).toBe(pkgVersion); + + mockReadFileSync.mockImplementation(() => JSON.stringify({ version: " 2.3.4-beta.1 " })); + expect(resolvePackageVersion()).toBe("2.3.4-beta.1"); + + mockReadFileSync.mockImplementation(() => JSON.stringify({})); + expect(resolvePackageVersion()).toBe("0.0.0"); + + mockReadFileSync.mockImplementation(() => JSON.stringify({ version: " " })); + expect(resolvePackageVersion()).toBe("0.0.0"); + + mockReadFileSync.mockImplementation(() => JSON.stringify({ version: 123 })); + expect(resolvePackageVersion()).toBe("0.0.0"); + }); + + it("resolveBuildMetadata() combines package version, resolved git SHA, and ISO timestamp", () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-04-14T12:34:56.789Z")); + process.env.GITHUB_SHA = "abcdef0123456789abcdef0123456789abcdef01"; + + expect(resolveBuildMetadata()).toEqual({ + version: pkgVersion, + sha: "abcdef012345", + builtAt: "2026-04-14T12:34:56.789Z", + }); + }); + + it("returns define plugin that sets JSON-encoded __APP_VERSION__, __GIT_SHA__, and __BUILD_TIME__", () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-04-14T12:34:56.789Z")); + process.env.GITHUB_SHA = "abcdef0123456789abcdef0123456789abcdef01"; + + const [definePlugin] = buildMeta(); + expect(definePlugin.name).toBe("github-tracker:build-meta-define"); + + const configFn = definePlugin.config as unknown as () => { + define: Record; + }; + const result = configFn(); + + expect(result).toEqual({ + define: { + __APP_VERSION__: JSON.stringify(pkgVersion), + __GIT_SHA__: JSON.stringify("abcdef012345"), + __BUILD_TIME__: JSON.stringify("2026-04-14T12:34:56.789Z"), + }, + }); + }); + + it("scopes the emit plugin to the client environment only", () => { + mockExecFileSync.mockReturnValue("abcdef0123456789abcdef0123456789abcdef01\n"); + const [, emitPlugin] = buildMeta(); + expect(emitPlugin.name).toBe("github-tracker:build-meta-emit"); + + const applyToEnvironment = emitPlugin.applyToEnvironment as unknown as (env: { + name: string; + }) => boolean; + expect(applyToEnvironment({ name: "client" })).toBe(true); + expect(applyToEnvironment({ name: "ssr" })).toBe(false); + expect(applyToEnvironment({ name: "worker" })).toBe(false); + }); + + it("emits version.json at the client root with exact keys ['version', 'sha', 'builtAt']", () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-04-14T12:34:56.789Z")); + process.env.GITHUB_SHA = "abcdef0123456789abcdef0123456789abcdef01"; + + const [, emitPlugin] = buildMeta(); + const emitFile = vi.fn(); + const generateBundle = emitPlugin.generateBundle as unknown as (this: { + emitFile: typeof emitFile; + }) => void; + + generateBundle.call({ emitFile }); + + expect(emitFile).toHaveBeenCalledOnce(); + const emitted = emitFile.mock.calls[0][0] as { + type: string; + fileName: string; + source: string; + }; + expect(emitted.type).toBe("asset"); + expect(emitted.fileName).toBe("version.json"); + + const parsed = JSON.parse(emitted.source) as Record; + expect(Object.keys(parsed)).toEqual(["version", "sha", "builtAt"]); + expect(parsed).toEqual({ + version: pkgVersion, + sha: "abcdef012345", + builtAt: "2026-04-14T12:34:56.789Z", + }); + }); +}); diff --git a/tests/components/DashboardPage.test.tsx b/tests/components/DashboardPage.test.tsx index b1818bc3..e630688e 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-test+abcdef1 release link in the footer", () => { + render(() => ); + + const versionLink = screen.getByRole("link", { name: "v0.1.0-test+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/settings/SettingsPage.test.tsx b/tests/components/settings/SettingsPage.test.tsx index 1778fbf3..5ed9d239 100644 --- a/tests/components/settings/SettingsPage.test.tsx +++ b/tests/components/settings/SettingsPage.test.tsx @@ -2099,3 +2099,35 @@ describe("SettingsPage — Data: Import with encrypted credentials", () => { await waitFor(() => screen.getByText(/2 selected/i)); }); }); + +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-test+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-test+abcdef1"); + expect(versionEl.getAttribute("href")).toBeNull(); + + const changelogEl = screen.getByText("Changelog"); + expect(changelogEl.getAttribute("href")).toBeNull(); + }); +}); 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/version.test.ts b/tests/lib/version.test.ts new file mode 100644 index 00000000..36bc1234 --- /dev/null +++ b/tests/lib/version.test.ts @@ -0,0 +1,20 @@ +import { describe, it, expect } from "vitest"; +import { + APP_VERSION, + GIT_SHA, + BUILD_TIME, + displayVersion, +} from "../../src/app/lib/version"; + +describe("version metadata", () => { + it("exposes build-time constants from Vite defines", () => { + expect(APP_VERSION).toBe("0.1.0-test"); + expect(GIT_SHA).toBe("abcdef123456"); + expect(BUILD_TIME).toBe("2026-01-01T00:00:00.000Z"); + }); + + it("formats displayVersion() as +<7-char GIT_SHA>", () => { + expect(displayVersion()).toBe(`${APP_VERSION}+${GIT_SHA.slice(0, 7)}`); + expect(displayVersion()).toBe("0.1.0-test+abcdef1"); + }); +}); 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/vite-plugins/build-meta.ts b/vite-plugins/build-meta.ts new file mode 100644 index 00000000..c919df1f --- /dev/null +++ b/vite-plugins/build-meta.ts @@ -0,0 +1,81 @@ +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import type { Plugin } from "vite"; + +const HEX_SHA_RE = /^[0-9a-f]{7,40}$/i; + +export interface BuildMetadata { + version: string; + sha: string; + builtAt: string; +} + +export function resolveGitSha(): string { + const envSha = 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, 12); +} + +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"; +} + +export function resolveBuildMetadata(): BuildMetadata { + return { + version: resolvePackageVersion(), + sha: resolveGitSha(), + builtAt: new Date().toISOString(), + }; +} + +export function buildMeta(): Plugin[] { + const { version, sha, builtAt } = resolveBuildMetadata(); + + return [ + { + name: "github-tracker:build-meta-define", + config() { + return { + define: { + __APP_VERSION__: JSON.stringify(version), + __GIT_SHA__: JSON.stringify(sha), + __BUILD_TIME__: JSON.stringify(builtAt), + }, + }; + }, + }, + { + name: "github-tracker:build-meta-emit", + applyToEnvironment(environment) { + return environment.name === "client"; + }, + generateBundle() { + this.emitFile({ + type: "asset", + fileName: "version.json", + source: JSON.stringify({ version, sha, builtAt }), + }); + }, + }, + ]; +} 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..89e07f08 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -7,6 +7,11 @@ import tailwindcss from "@tailwindcss/vite"; // vite.config.ts (with the cloudflare plugin) is used only for builds. export default defineConfig({ plugins: [solid(), tailwindcss()], + define: { + __APP_VERSION__: JSON.stringify("0.1.0-test"), + __GIT_SHA__: JSON.stringify("abcdef123456"), + __BUILD_TIME__: JSON.stringify("2026-01-01T00:00:00.000Z"), + }, test: { environment: "happy-dom", globals: true, diff --git a/vitest.workspace.ts b/vitest.workspace.ts index dd0856c7..f9428a4a 100644 --- a/vitest.workspace.ts +++ b/vitest.workspace.ts @@ -11,6 +11,11 @@ export default defineConfig({ // Browser/DOM tests (stores, services, UI) defineProject({ plugins: [solid(), tailwindcss()], + define: { + __APP_VERSION__: JSON.stringify("0.1.0-test"), + __GIT_SHA__: JSON.stringify("abcdef123456"), + __BUILD_TIME__: JSON.stringify("2026-01-01T00:00:00.000Z"), + }, test: { name: "browser", environment: "happy-dom", From 4a49686f7abf17c6c4463039b64cfee746e16a42 Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Fri, 6 Nov 2026 11:40:11 -0500 Subject: [PATCH 02/11] feat(version): detect updates, show banner, reload on navigation --- docs/USER_GUIDE.md | 11 + e2e/update.spec.ts | 73 ++++ src/app/App.tsx | 41 ++- src/app/components/shared/ToastContainer.tsx | 5 +- src/app/components/shared/UpdateBanner.tsx | 61 +++ src/app/index.tsx | 2 + src/app/lib/chunk-reload.ts | 35 ++ src/app/lib/sentry-init.ts | 3 +- src/app/lib/version.ts | 103 ++++++ src/app/services/poll.ts | 2 + src/app/stores/config.ts | 20 +- src/app/stores/view.ts | 137 +++---- .../components/shared/ToastContainer.test.tsx | 25 ++ tests/components/shared/UpdateBanner.test.tsx | 306 ++++++++++++++++ tests/lib/chunk-reload.test.ts | 137 +++++++ tests/lib/version.test.ts | 346 +++++++++++++++++- tests/services/poll.test.ts | 25 ++ 17 files changed, 1251 insertions(+), 81 deletions(-) create mode 100644 e2e/update.spec.ts create mode 100644 src/app/components/shared/UpdateBanner.tsx create mode 100644 src/app/lib/chunk-reload.ts create mode 100644 tests/components/shared/UpdateBanner.test.tsx create mode 100644 tests/lib/chunk-reload.test.ts diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index 23b8b7cc..a5a59c93 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -837,6 +837,17 @@ Encrypted credentials are sealed by this deployment's server and can only be imp --- +## Updates & What's New + +GitHub Tracker checks `/version.json` in the background (30 seconds after load, when returning to a tab, and on each full poll cycle) to detect when a new build has been deployed. + +- **Update Banner:** When a newer deployment is detected, a banner appears at the bottom of the screen (*"A new version is available."*) with a **Reload** button and a link to the **Changelog**, and an informational entry is added to the Notification Drawer. +- **Automatic Reload on Navigation:** If an update is waiting when you navigate between pages (for example, opening **Settings** or returning to the **Dashboard**), the app flushes any pending configuration or view-state changes to `localStorage` and performs a full page reload into the new build automatically. +- **Stale Chunk Recovery:** If a lazy-loaded page chunk from a previous deployment is no longer available before a background check runs, the app automatically flushes pending state and reloads once to load the current bundle. +- **Version & Changelog:** You can view the running build version (`+`) and open the [Changelog](https://github.com/gordon-code/github-tracker/blob/main/CHANGELOG.md) or [GitHub Releases](https://github.com/gordon-code/github-tracker/releases) at any time from **Settings > Data > About** or the dashboard footer. + +--- + ## Troubleshooting **Items I expect to see are not showing up.** diff --git a/e2e/update.spec.ts b/e2e/update.spec.ts new file mode 100644 index 00000000..ff377168 --- /dev/null +++ b/e2e/update.spec.ts @@ -0,0 +1,73 @@ +import { execFileSync } from "node:child_process"; +import { test, expect } from "@playwright/test"; +import { setupAuth } from "./helpers"; + +const rawSha = ( + process.env.GITHUB_SHA ?? + execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }) +) + .trim() + .toLowerCase(); +const currentSha = rawSha.slice(0, 12); +const differentSha = + currentSha === "111111111111" ? "222222222222" : "111111111111"; + +test("shows update banner when version.json reports a new SHA and triggers full reload on navigation", async ({ + page, +}) => { + await setupAuth(page); + await page.route("**/version.json", (route) => + route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify({ + version: "9.9.9", + sha: differentSha, + builtAt: "2026-01-02T00:00:00.000Z", + }), + }), + ); + + await page.goto("/dashboard"); + + const banner = page + .getByRole("status") + .filter({ hasText: "A new version is available." }); + await expect(banner).toBeVisible(); + await expect(banner.getByRole("button", { name: "Reload" })).toBeVisible(); + await expect(banner.getByRole("link", { name: "Changelog" })).toBeVisible(); + + const loadPromise = page.waitForEvent("load"); + await page.getByRole("link", { name: "Settings" }).click(); + await loadPromise; + await expect(page).toHaveURL(/\/settings$/); +}); + +test("does not show update banner when version.json matches the running build SHA", async ({ + page, +}) => { + await setupAuth(page); + let versionFetched = false; + await page.route("**/version.json", (route) => { + versionFetched = true; + return route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify({ + version: "0.1.1", + sha: currentSha, + builtAt: "2026-01-01T00:00:00.000Z", + }), + }); + }); + + await page.goto("/dashboard"); + await expect(page.getByRole("tablist")).toBeVisible(); + await expect.poll(() => versionFetched).toBe(true); + + await expect( + page + .getByRole("status") + .filter({ hasText: "A new version is available." }), + ).toHaveCount(0); +}); diff --git a/src/app/App.tsx b/src/app/App.tsx index df768615..4d02f939 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -1,10 +1,13 @@ import { createSignal, createEffect, on, onMount, onCleanup, getOwner, runWithOwner, Show, ErrorBoundary, Suspense, lazy, type JSX } from "solid-js"; import { reportBoundaryError } from "./lib/sentry-facade"; -import { Router, Route, Navigate, useNavigate } from "@solidjs/router"; +import { reloadOnceForStaleChunk } from "./lib/chunk-reload"; +import { updateAvailable, reloadOncePerTarget, startVersionWatch } from "./lib/version"; +import { Router, Route, Navigate, useNavigate, useLocation } from "@solidjs/router"; import { isAuthenticated, validateToken, AUTH_STORAGE_KEY } from "./stores/auth"; -import { config, initConfigPersistence, resolveTheme } from "./stores/config"; -import { initViewPersistence, pruneStaleIgnoredItems } from "./stores/view"; +import { config, initConfigPersistence, flushConfigPersistence, resolveTheme } from "./stores/config"; +import { initViewPersistence, flushViewPersistence, pruneStaleIgnoredItems } from "./stores/view"; import { evictStaleEntries, evictKeysWithPrefix } from "./stores/cache"; +import UpdateBanner from "./components/shared/UpdateBanner"; import LoginPage from "./pages/LoginPage"; import OAuthCallback from "./pages/OAuthCallback"; import JiraCallback from "./pages/JiraCallback"; @@ -19,16 +22,10 @@ export function _resetAuthInitStartedForTests(): void { authInitGen++; } -const CHUNK_RELOAD_KEY = "github-tracker:chunk-reload"; -const CHUNK_RELOAD_MAX_AGE = 10_000; - function lazyWithReload(loader: Parameters[0]) { return lazy(() => loader().catch((err) => { - const last = sessionStorage.getItem(CHUNK_RELOAD_KEY); - if (!last || Date.now() - Number(last) > CHUNK_RELOAD_MAX_AGE) { - sessionStorage.setItem(CHUNK_RELOAD_KEY, String(Date.now())); - window.location.reload(); + if (reloadOnceForStaleChunk()) { return new Promise(() => {}); } throw err; @@ -36,6 +33,25 @@ function lazyWithReload(loader: Parameters[0]) { ); } +export function UpdateNavigator() { + const location = useLocation(); + createEffect( + on( + () => location.pathname, + (path, prev) => { + if (prev === undefined || path === prev) return; + const info = updateAvailable(); + if (info && reloadOncePerTarget(info.sha)) { + flushConfigPersistence(); + flushViewPersistence(); + window.location.assign(path + location.search + location.hash); + } + }, + ), + ); + return null; +} + const DashboardPage = lazyWithReload(() => import("./components/dashboard/DashboardPage")); const OnboardingWizard = lazyWithReload(() => import("./components/onboarding/OnboardingWizard")); const SettingsPage = lazyWithReload(() => import("./components/settings/SettingsPage")); @@ -238,6 +254,8 @@ export default function App() { initConfigPersistence(); initViewPersistence(); pruneStaleIgnoredItems(); + const stopVersionWatch = startVersionWatch(); + onCleanup(stopVersionWatch); const staleCacheMaxAgeMs = 24 * 60 * 60 * 1000; const staleEvictionIntervalMs = 60 * 60 * 1000; @@ -269,12 +287,13 @@ export default function App() { return handleRouteError(err); }} > + }> - + <>{props.children}}> diff --git a/src/app/components/shared/ToastContainer.tsx b/src/app/components/shared/ToastContainer.tsx index 4a827a4e..77c159f4 100644 --- a/src/app/components/shared/ToastContainer.tsx +++ b/src/app/components/shared/ToastContainer.tsx @@ -7,6 +7,7 @@ import { type NotificationSeverity, } from "../../lib/errors"; import { onAuthCleared } from "../../stores/auth"; +import { updateAvailable } from "../../lib/version"; export interface SeverityConfig { path: string; @@ -315,7 +316,9 @@ export default function ToastContainer() { }); return ( -
+
{(item) => { const cfg = severityConfig(item.notification.severity); diff --git a/src/app/components/shared/UpdateBanner.tsx b/src/app/components/shared/UpdateBanner.tsx new file mode 100644 index 00000000..c047c520 --- /dev/null +++ b/src/app/components/shared/UpdateBanner.tsx @@ -0,0 +1,61 @@ +import { createEffect, Show } from "solid-js"; +import { updateAvailable } from "../../lib/version"; +import { pushNotification } from "../../lib/errors"; +import { isSafeGitHubUrl } from "../../lib/url"; +import { flushConfigPersistence } from "../../stores/config"; +import { flushViewPersistence } from "../../stores/view"; + +export const CHANGELOG_URL = "https://github.com/gordon-code/github-tracker/blob/main/CHANGELOG.md"; + +export default function UpdateBanner() { + let notified = false; + + createEffect(() => { + const info = updateAvailable(); + if (info && !notified) { + notified = true; + pushNotification( + "app-update", + "A new version of GitHub Tracker is available — reload to update.", + "info", + ); + } + }); + + const handleReload = () => { + flushConfigPersistence(); + flushViewPersistence(); + window.location.reload(); + }; + + return ( + +
+ A new version is available. +
+ + + Changelog + + + +
+
+
+ ); +} diff --git a/src/app/index.tsx b/src/app/index.tsx index 4f3fc146..cfa08e91 100644 --- a/src/app/index.tsx +++ b/src/app/index.tsx @@ -1,11 +1,13 @@ import "./index.css"; import { render } from "solid-js/web"; import { installEarlyErrorCapture, startSentryLoad } from "./lib/sentry-facade"; +import { installChunkReloadHandler } from "./lib/chunk-reload"; import App from "./App"; // Capture early errors synchronously before first paint, then lazy-load the // Sentry SDK on idle after render. No-ops in dev/test or without DSN. installEarlyErrorCapture(); +installChunkReloadHandler(); render(() => , document.getElementById("app")!); diff --git a/src/app/lib/chunk-reload.ts b/src/app/lib/chunk-reload.ts new file mode 100644 index 00000000..53023db5 --- /dev/null +++ b/src/app/lib/chunk-reload.ts @@ -0,0 +1,35 @@ +import { flushConfigPersistence } from "../stores/config"; +import { flushViewPersistence } from "../stores/view"; + +export const CHUNK_RELOAD_KEY = "github-tracker:chunk-reload"; +export const CHUNK_RELOAD_MAX_AGE = 10_000; + +export function reloadOnceForStaleChunk(): boolean { + const now = Date.now(); + try { + const last = sessionStorage.getItem(CHUNK_RELOAD_KEY); + if (!last || now - Number(last) > CHUNK_RELOAD_MAX_AGE) { + sessionStorage.setItem(CHUNK_RELOAD_KEY, String(now)); + flushConfigPersistence(); + flushViewPersistence(); + window.location.reload(); + return true; + } + } catch { + return false; + } + return false; +} + +export function handleVitePreloadError(event: Event): void { + if (reloadOnceForStaleChunk()) { + event.preventDefault(); + } +} + +export function installChunkReloadHandler(): () => void { + window.addEventListener("vite:preloadError", handleVitePreloadError); + return () => { + window.removeEventListener("vite:preloadError", handleVitePreloadError); + }; +} diff --git a/src/app/lib/sentry-init.ts b/src/app/lib/sentry-init.ts index eb1489b9..4404bffa 100644 --- a/src/app/lib/sentry-init.ts +++ b/src/app/lib/sentry-init.ts @@ -1,6 +1,5 @@ import { captureException, init } from "@sentry/solid"; import { beforeBreadcrumbHandler, beforeSendHandler } from "./sentry"; -import { GIT_SHA } from "./version"; export interface SentrySdkClient { captureException: typeof captureException; @@ -12,7 +11,7 @@ export function initSdk(): SentrySdkClient { init({ dsn, - release: `github-tracker@${GIT_SHA}`, + release: `github-tracker@${__GIT_SHA__}`, tunnel: "/api/error-reporting", environment: import.meta.env.MODE, enhanceFetchErrorMessages: "report-only", diff --git a/src/app/lib/version.ts b/src/app/lib/version.ts index 42b2835c..b8300dfa 100644 --- a/src/app/lib/version.ts +++ b/src/app/lib/version.ts @@ -1,3 +1,6 @@ +import { createSignal } from "solid-js"; +import * as z from "zod/mini"; + export const APP_VERSION: string = __APP_VERSION__; export const GIT_SHA: string = __GIT_SHA__; export const BUILD_TIME: string = __BUILD_TIME__; @@ -5,3 +8,103 @@ export const BUILD_TIME: string = __BUILD_TIME__; export function displayVersion(): string { return `${APP_VERSION}+${GIT_SHA.slice(0, 7)}`; } + +export const VersionInfoSchema = z.object({ + version: z.string().check(z.maxLength(32)), + sha: z.string().check(z.regex(/^[0-9a-f]{7,40}$|^dev$/)), + builtAt: z.string().check(z.maxLength(40)), +}); + +export type VersionInfo = z.infer; + +export const UPDATE_RELOADED_SHA_KEY = "github-tracker:update-reloaded-sha"; +export const VERSION_WATCH_INITIAL_DELAY_MS = 30_000; + +const [updateAvailable, setUpdateAvailable] = createSignal(null); +export { updateAvailable }; + +let currentGitSha: string = GIT_SHA; +let checkInFlight: Promise | null = null; + +export function checkForUpdate(): Promise { + if (checkInFlight) return checkInFlight; + checkInFlight = (async () => { + try { + const res = await fetch("/version.json", { + cache: "no-store", + credentials: "same-origin", + }); + if (!res.ok) return; + const contentType = (res.headers.get("content-type") ?? "").toLowerCase(); + if (!contentType.includes("application/json")) return; + const raw: unknown = await res.json(); + const parsed = VersionInfoSchema.safeParse(raw); + if (!parsed.success) return; + if ( + currentGitSha !== "dev" && + parsed.data.sha !== "dev" && + parsed.data.sha.slice(0, 12) !== currentGitSha.toLowerCase().slice(0, 12) + ) { + setUpdateAvailable(parsed.data); + } + } catch { + // Best-effort — network errors or non-JSON bodies are ignored silently. + } finally { + checkInFlight = null; + } + })(); + return checkInFlight; +} + +export function reloadOncePerTarget(targetSha: string): boolean { + const normalized = targetSha.slice(0, 12); + if (!normalized || normalized === "dev") return false; + try { + if (sessionStorage.getItem(UPDATE_RELOADED_SHA_KEY) === normalized) { + return false; + } + sessionStorage.setItem(UPDATE_RELOADED_SHA_KEY, normalized); + return true; + } catch { + return false; + } +} + +export function startVersionWatch(): () => void { + const handleVisibilityChange = () => { + if (document.visibilityState === "visible") { + void checkForUpdate(); + } + }; + document.addEventListener("visibilitychange", handleVisibilityChange); + const timerId = setTimeout(() => { + void checkForUpdate(); + }, VERSION_WATCH_INITIAL_DELAY_MS); + + return () => { + document.removeEventListener("visibilitychange", handleVisibilityChange); + clearTimeout(timerId); + }; +} + +/** @internal Test-only helper to set updateAvailable signal directly */ +export function _setUpdateAvailableForTest(info: VersionInfo | null): void { + setUpdateAvailable(info); +} + +/** @internal Test-only helper to override local build GIT_SHA */ +export function _setGitShaForTest(sha: string): void { + currentGitSha = sha; +} + +/** @internal Test-only helper to reset version checker state */ +export function _resetVersionStateForTest(): void { + setUpdateAvailable(null); + currentGitSha = GIT_SHA; + checkInFlight = null; + try { + sessionStorage.removeItem(UPDATE_RELOADED_SHA_KEY); + } catch { + // Ignore storage errors in restricted environments + } +} diff --git a/src/app/services/poll.ts b/src/app/services/poll.ts index e405db5e..8e630064 100644 --- a/src/app/services/poll.ts +++ b/src/app/services/poll.ts @@ -2,6 +2,7 @@ import { createSignal, createEffect, createRoot, untrack, onCleanup } from "soli import { captureException } from "../lib/sentry-facade"; import { getClient, fetchRateLimitDetails } from "./github"; import { fetchGitHubStatus } from "./github-status"; +import { checkForUpdate } from "../lib/version"; import { config } from "../stores/config"; import { user, onAuthCleared, expireToken, identityEpoch } from "../stores/auth"; import { checkAndResetIfExpired } from "./api-usage"; @@ -464,6 +465,7 @@ export function createPollCoordinator( // own notification push/dismiss) — no interaction with this cycle's error // handling or the fetchAll() try/catch below. void fetchGitHubStatus(); + void checkForUpdate(); // Snapshot sources of notifications from previous cycle (for reconciliation) const previousSources = new Set( diff --git a/src/app/stores/config.ts b/src/app/stores/config.ts index 5966013f..a8de310c 100644 --- a/src/app/stores/config.ts +++ b/src/app/stores/config.ts @@ -1,5 +1,5 @@ import { createStore, produce } from "solid-js/store"; -import { createEffect, onCleanup } from "solid-js"; +import { createEffect, onCleanup, untrack } from "solid-js"; import { pushNotification } from "../lib/errors"; import { viewState, updateViewState } from "./view"; import { ConfigSchema, type RepoRefSchema, THEME_OPTIONS, BUILTIN_TAB_IDS, CustomTabSchema } from "../../shared/schemas"; @@ -228,9 +228,22 @@ export function reorderCustomTab(id: string, direction: "up" | "down"): void { ); } +let debounceTimer: ReturnType | undefined; +let pendingJson: string | undefined; + +export function flushConfigPersistence(): void { + clearTimeout(debounceTimer); + debounceTimer = undefined; + pendingJson = undefined; + try { + const json = JSON.stringify(untrack(() => config)); + localStorage.setItem(CONFIG_STORAGE_KEY, json); + } catch { + pushNotification("localStorage:config", "Config write failed — storage may be full", "warning"); + } +} + export function initConfigPersistence(): void { - let debounceTimer: ReturnType | undefined; - let pendingJson: string | undefined; createEffect(() => { const snapshot = JSON.parse(JSON.stringify(config)) as Config; const json = JSON.stringify(snapshot); @@ -246,6 +259,7 @@ export function initConfigPersistence(): void { }, 200); onCleanup(() => { clearTimeout(debounceTimer); + debounceTimer = undefined; if (pendingJson !== undefined) { try { localStorage.setItem(CONFIG_STORAGE_KEY, pendingJson); } catch { /* best-effort */ } pendingJson = undefined; diff --git a/src/app/stores/view.ts b/src/app/stores/view.ts index 0e101ef9..5def84ab 100644 --- a/src/app/stores/view.ts +++ b/src/app/stores/view.ts @@ -847,6 +847,78 @@ export function pruneClosedTrackedItems(pruneKeys: Set): void { ); } +// Baseline snapshot of what this tab last knew to be persisted to localStorage +// (starts at the state this tab loaded at boot). Used by commitSnapshot() to work +// out which top-level fields THIS tab actually changed, so a debounced write only +// overlays those fields onto whatever is CURRENTLY on disk instead of blindly +// overwriting with this tab's full (possibly stale) in-memory snapshot. Without +// this, a full-object overwrite from Tab A could silently revert a newer value +// Tab B wrote for some other field (e.g. jiraCustomOrder) in the gap between when +// Tab A's debounce timer started and when it actually fires. +let lastSyncedSnapshot: Record = JSON.parse(JSON.stringify(untrack(() => viewState))); +let debounceTimer: ReturnType | undefined; +let pendingSnapshot: Record | undefined; + +function readOnDiskState(): Record | undefined { + try { + const raw = localStorage.getItem(VIEW_STORAGE_KEY); + if (raw === null) return undefined; + const parsed = JSON.parse(raw) as unknown; + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return undefined; + // Only trust keys that are part of the current ViewState schema AND whose value + // passes that field's own Zod validation. localStorage is writable by any + // same-origin script (extensions, a stale/incompatible schema version, manual + // tampering), and commitSnapshot() below folds this content into every future + // write for fields this tab doesn't happen to touch itself — without both the + // key-name allowlist and per-field value validation, unrecognized or malformed + // on-disk content would be perpetually re-persisted instead of self-healing on + // the next write, as it did before the merge-on-write logic existed. Validated + // one key at a time (not a single ViewStateSchema.pick(...).safeParse() over the + // whole object) so one malformed field can't cause every other valid field to be + // dropped too. + const filtered: Record = {}; + for (const [key, value] of Object.entries(parsed as Record)) { + if (!VIEW_STATE_KEYS.has(key)) continue; + const validated = validateViewStateField(key as keyof ViewState, value); + if (validated !== undefined) filtered[key] = validated; + } + return filtered; + } catch { + return undefined; + } +} + +function commitSnapshot(snapshot: Record): void { + const onDisk = readOnDiskState(); + // Start from whatever is currently on disk (may include newer values another tab + // wrote); fall back to this tab's own snapshot if disk is unreadable/absent. + const merged: Record = { ...(onDisk ?? snapshot) }; + for (const key of Object.keys(snapshot)) { + // Always include a key this tab knows about but that's missing from the on-disk + // blob entirely (stale/corrupted/version-skewed data) — no legitimate flow ever + // produces a ViewState with a top-level key truly absent, so treat that as + // recoverable staleness rather than silently dropping this tab's known value + // (which Zod's .default() would otherwise backfill on the next load). + if (!(key in merged) || JSON.stringify(snapshot[key]) !== JSON.stringify(lastSyncedSnapshot[key])) { + merged[key] = snapshot[key]; + } + } + try { + localStorage.setItem(VIEW_STORAGE_KEY, JSON.stringify(merged)); + lastSyncedSnapshot = merged; + } catch { + pushNotification("localStorage:view", "View state write failed — storage may be full", "warning"); + } +} + +export function flushViewPersistence(): void { + clearTimeout(debounceTimer); + debounceTimer = undefined; + pendingSnapshot = undefined; + const snapshot = JSON.parse(JSON.stringify(untrack(() => viewState))) as Record; + commitSnapshot(snapshot); +} + export function initViewPersistence(): void { if (typeof window !== "undefined") { const handleViewStorage = (e: StorageEvent) => { @@ -872,70 +944,8 @@ export function initViewPersistence(): void { onCleanup(() => window.removeEventListener("storage", handleViewStorage)); } - // Baseline snapshot of what this tab last knew to be persisted to localStorage - // (starts at the state this tab loaded at boot). Used by commitSnapshot() to work - // out which top-level fields THIS tab actually changed, so a debounced write only - // overlays those fields onto whatever is CURRENTLY on disk instead of blindly - // overwriting with this tab's full (possibly stale) in-memory snapshot. Without - // this, a full-object overwrite from Tab A could silently revert a newer value - // Tab B wrote for some other field (e.g. jiraCustomOrder) in the gap between when - // Tab A's debounce timer started and when it actually fires. - let lastSyncedSnapshot: Record = JSON.parse(JSON.stringify(untrack(() => viewState))); - - function readOnDiskState(): Record | undefined { - try { - const raw = localStorage.getItem(VIEW_STORAGE_KEY); - if (raw === null) return undefined; - const parsed = JSON.parse(raw) as unknown; - if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return undefined; - // Only trust keys that are part of the current ViewState schema AND whose value - // passes that field's own Zod validation. localStorage is writable by any - // same-origin script (extensions, a stale/incompatible schema version, manual - // tampering), and commitSnapshot() below folds this content into every future - // write for fields this tab doesn't happen to touch itself — without both the - // key-name allowlist and per-field value validation, unrecognized or malformed - // on-disk content would be perpetually re-persisted instead of self-healing on - // the next write, as it did before the merge-on-write logic existed. Validated - // one key at a time (not a single ViewStateSchema.pick(...).safeParse() over the - // whole object) so one malformed field can't cause every other valid field to be - // dropped too. - const filtered: Record = {}; - for (const [key, value] of Object.entries(parsed as Record)) { - if (!VIEW_STATE_KEYS.has(key)) continue; - const validated = validateViewStateField(key as keyof ViewState, value); - if (validated !== undefined) filtered[key] = validated; - } - return filtered; - } catch { - return undefined; - } - } - - function commitSnapshot(snapshot: Record): void { - const onDisk = readOnDiskState(); - // Start from whatever is currently on disk (may include newer values another tab - // wrote); fall back to this tab's own snapshot if disk is unreadable/absent. - const merged: Record = { ...(onDisk ?? snapshot) }; - for (const key of Object.keys(snapshot)) { - // Always include a key this tab knows about but that's missing from the on-disk - // blob entirely (stale/corrupted/version-skewed data) — no legitimate flow ever - // produces a ViewState with a top-level key truly absent, so treat that as - // recoverable staleness rather than silently dropping this tab's known value - // (which Zod's .default() would otherwise backfill on the next load). - if (!(key in merged) || JSON.stringify(snapshot[key]) !== JSON.stringify(lastSyncedSnapshot[key])) { - merged[key] = snapshot[key]; - } - } - try { - localStorage.setItem(VIEW_STORAGE_KEY, JSON.stringify(merged)); - lastSyncedSnapshot = merged; - } catch { - pushNotification("localStorage:view", "View state write failed — storage may be full", "warning"); - } - } + lastSyncedSnapshot = JSON.parse(JSON.stringify(untrack(() => viewState))); - let debounceTimer: ReturnType | undefined; - let pendingSnapshot: Record | undefined; createEffect(() => { const json = JSON.stringify(viewState); // synchronous read → tracked by SolidJS const snapshot = JSON.parse(json) as Record; @@ -958,6 +968,7 @@ export function initViewPersistence(): void { // describes. onCleanup(() => { clearTimeout(debounceTimer); + debounceTimer = undefined; // Flush pending write synchronously so HMR doesn't lose state if (pendingSnapshot !== undefined) { commitSnapshot(pendingSnapshot); diff --git a/tests/components/shared/ToastContainer.test.tsx b/tests/components/shared/ToastContainer.test.tsx index 07fe94bf..755428b5 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 { + _setUpdateAvailableForTest, + _resetVersionStateForTest, +} 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(); + _resetVersionStateForTest(); vi.useFakeTimers(); // Ensure matchMedia returns non-reduced-motion vi.spyOn(window, "matchMedia").mockReturnValue({ matches: false } as MediaQueryList); }); afterEach(() => { + _resetVersionStateForTest(); 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"); + + _setUpdateAvailableForTest({ + 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"); + + _setUpdateAvailableForTest(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..9f9805fb --- /dev/null +++ b/tests/components/shared/UpdateBanner.test.tsx @@ -0,0 +1,306 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { render, screen, fireEvent } from "@solidjs/testing-library"; +import { MemoryRouter, Route, useNavigate, createMemoryHistory } from "@solidjs/router"; +import { createRoot } from "solid-js"; +import UpdateBanner, { CHANGELOG_URL } from "../../../src/app/components/shared/UpdateBanner"; +import { UpdateNavigator } from "../../../src/app/App"; +import { + _setUpdateAvailableForTest, + _resetVersionStateForTest, +} 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 & UpdateNavigator", () => { + const originalLocation = window.location; + let reloadMock: ReturnType; + let assignMock: ReturnType; + + beforeEach(() => { + vi.useFakeTimers(); + sessionStorage.clear(); + localStorage.clear(); + _resetVersionStateForTest(); + resetNotificationState(); + resetConfig(); + resetViewState(); + + reloadMock = vi.fn(); + assignMock = vi.fn(); + Object.defineProperty(window, "location", { + configurable: true, + writable: true, + value: { + reload: reloadMock, + assign: assignMock, + pathname: "/", + search: "", + hash: "", + href: "", + }, + }); + }); + + afterEach(() => { + _resetVersionStateForTest(); + resetNotificationState(); + Object.defineProperty(window, "location", { + configurable: true, + writable: true, + value: originalLocation, + }); + vi.useRealTimers(); + }); + + describe("UpdateBanner", () => { + 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(() => ); + + _setUpdateAvailableForTest({ + 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(CHANGELOG_URL); + 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.", + ); + + // Updating signal again must not duplicate or re-push the notification + _setUpdateAvailableForTest({ + version: "0.1.3", + sha: "111122223333", + builtAt: "2026-01-03T00:00:00.000Z", + }); + expect(getNotifications().filter((n) => n.source === "app-update")).toHaveLength(1); + }); + + it("flushes pending config and viewState persistence before calling window.location.reload()", () => { + let disposePersistence!: () => void; + createRoot((d) => { + disposePersistence = d; + initConfigPersistence(); + initViewPersistence(); + }); + + _setUpdateAvailableForTest({ + 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(); + }); + }); + + describe("UpdateNavigator", () => { + function NavTestHarness() { + const navigate = useNavigate(); + return ( +
+ + + + +
+ ); + } + + it("does not call location.assign when navigating with updateAvailable null", async () => { + const history = createMemoryHistory(); + render(() => ( + ( + <> + + {props.children} + + )} + > + + + + + )); + + fireEvent.click(screen.getByRole("button", { name: "Go Settings" })); + await Promise.resolve(); + 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 stale previous-identity values in localStorage + 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); + }); + + const history = createMemoryHistory(); + render(() => ( + ( + <> + + {props.children} + + )} + > + + + + + )); + + _setUpdateAvailableForTest({ + version: "0.1.2", + sha: "fedcba987654", + builtAt: "2026-01-02T00:00:00.000Z", + }); + + // 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 () => { + const history = createMemoryHistory(); + render(() => ( + ( + <> + + {props.children} + + )} + > + + + + + )); + + _setUpdateAvailableForTest({ + version: "0.1.2", + sha: "fedcba987654", + builtAt: "2026-01-02T00:00:00.000Z", + }); + + // 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"); + }); + }); +}); diff --git a/tests/lib/chunk-reload.test.ts b/tests/lib/chunk-reload.test.ts new file mode 100644 index 00000000..e40c4682 --- /dev/null +++ b/tests/lib/chunk-reload.test.ts @@ -0,0 +1,137 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { + CHUNK_RELOAD_KEY, + CHUNK_RELOAD_MAX_AGE, + reloadOnceForStaleChunk, + installChunkReloadHandler, +} 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 } from "solid-js"; + +describe("chunk-reload", () => { + const originalLocation = window.location; + let reloadMock: ReturnType; + + beforeEach(() => { + vi.useFakeTimers(); + sessionStorage.clear(); + localStorage.clear(); + 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, + }); + vi.useRealTimers(); + }); + + it("reloads and prevents default on the first vite:preloadError, suppresses within 10s, and reloads again after 10s", () => { + 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", () => { + 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(); + }); +}); diff --git a/tests/lib/version.test.ts b/tests/lib/version.test.ts index 36bc1234..fccccd85 100644 --- a/tests/lib/version.test.ts +++ b/tests/lib/version.test.ts @@ -1,12 +1,41 @@ -import { describe, it, expect } from "vitest"; +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { APP_VERSION, GIT_SHA, BUILD_TIME, displayVersion, + VersionInfoSchema, + updateAvailable, + checkForUpdate, + reloadOncePerTarget, + startVersionWatch, + VERSION_WATCH_INITIAL_DELAY_MS, + _setGitShaForTest, + _resetVersionStateForTest, } from "../../src/app/lib/version"; +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(() => { + _resetVersionStateForTest(); + }); + + afterEach(() => { + _resetVersionStateForTest(); + vi.useRealTimers(); + }); + it("exposes build-time constants from Vite defines", () => { expect(APP_VERSION).toBe("0.1.0-test"); expect(GIT_SHA).toBe("abcdef123456"); @@ -17,4 +46,319 @@ describe("version metadata", () => { expect(displayVersion()).toBe(`${APP_VERSION}+${GIT_SHA.slice(0, 7)}`); expect(displayVersion()).toBe("0.1.0-test+abcdef1"); }); + + describe("VersionInfoSchema", () => { + it("accepts valid version metadata with hex SHA or 'dev'", () => { + const validHex = VersionInfoSchema.safeParse({ + version: "0.1.1", + sha: "1234567890ab", + builtAt: "2026-01-02T00:00:00.000Z", + }); + expect(validHex.success).toBe(true); + + const validDev = VersionInfoSchema.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( + VersionInfoSchema.safeParse({ + version: "v".repeat(33), + sha: "1234567890ab", + builtAt: "2026-01-02T00:00:00.000Z", + }).success, + ).toBe(false); + + expect( + VersionInfoSchema.safeParse({ + version: "0.1.1", + sha: "not-a-hex-sha", + builtAt: "2026-01-02T00:00:00.000Z", + }).success, + ).toBe(false); + + expect( + VersionInfoSchema.safeParse({ + version: "0.1.1", + sha: "1234567890ab", + builtAt: "t".repeat(41), + }).success, + ).toBe(false); + }); + }); + + describe("checkForUpdate", () => { + it("leaves updateAvailable null when remote SHA matches local GIT_SHA", async () => { + const fetchMock = vi.fn().mockResolvedValue( + makeJsonResponse({ + version: "0.1.0-test", + 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("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 () => { + _setGitShaForTest("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 () => { + _setGitShaForTest("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(); + + _setGitShaForTest(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-test", + 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-test", + 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/services/poll.test.ts b/tests/services/poll.test.ts index 2158bac8..4cb6010b 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,25 @@ 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); + + 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(); From f3a00f24287de3e24da32472d189735b21d19f4e Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Fri, 6 Nov 2026 12:54:10 -0500 Subject: [PATCH 03/11] feat(version): add in-app What's New dialog generated from CHANGELOG --- docs/USER_GUIDE.md | 3 +- src/app/components/layout/Header.tsx | 80 ++++++- src/app/components/settings/SettingsPage.tsx | 15 ++ src/app/components/shared/WhatsNewDialog.tsx | 179 +++++++++++++++ src/app/lib/changelog.ts | 68 ++++++ src/app/lib/version.ts | 8 +- src/shared/changelog-schema.ts | 28 +++ src/shared/schemas.ts | 1 + src/types/build-meta.d.ts | 6 + tests/build/build-meta.test.ts | 209 ++++++++++++++++++ tests/components/DashboardPage.test.tsx | 4 +- tests/components/layout/Header.test.tsx | 33 ++- .../components/settings/SettingsPage.test.tsx | 17 +- .../components/shared/WhatsNewDialog.test.tsx | 180 +++++++++++++++ tests/lib/changelog.test.ts | 91 ++++++++ tests/lib/settings-transfer.test.ts | 13 ++ tests/lib/version.test.ts | 10 +- tests/stores/config.test.ts | 29 +++ tests/stubs/virtual-changelog.ts | 38 ++++ vite-plugins/build-meta.ts | 158 ++++++++++++- vite.config.ts | 2 +- vitest.config.ts | 11 +- vitest.workspace.ts | 11 +- 23 files changed, 1177 insertions(+), 17 deletions(-) create mode 100644 src/app/components/shared/WhatsNewDialog.tsx create mode 100644 src/app/lib/changelog.ts create mode 100644 src/shared/changelog-schema.ts create mode 100644 tests/components/shared/WhatsNewDialog.test.tsx create mode 100644 tests/lib/changelog.test.ts create mode 100644 tests/stubs/virtual-changelog.ts diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index a5a59c93..1f6ffad4 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -710,7 +710,7 @@ The header shrinks as you scroll to maximize content space. ## Settings Reference -Settings are saved automatically to `localStorage` and persist across sessions. All settings can be exported as a JSON file via **Settings > Data > Export**. The current build version (`+`) is shown in **Settings > Data > About** (alongside a link to the changelog) and in the dashboard footer, both linking to the GitHub Releases page. +Settings are saved automatically to `localStorage` and persist across sessions. All settings can be exported as a JSON file via **Settings > Data > Export**. The current build version (`+`) is shown in **Settings > Data > About** (alongside a **What's new** button and a link to the changelog) and in the dashboard footer, both linking to the GitHub Releases page. ### Config Settings @@ -844,6 +844,7 @@ GitHub Tracker checks `/version.json` in the background (30 seconds after load, - **Update Banner:** When a newer deployment is detected, a banner appears at the bottom of the screen (*"A new version is available."*) with a **Reload** button and a link to the **Changelog**, and an informational entry is added to the Notification Drawer. - **Automatic Reload on Navigation:** If an update is waiting when you navigate between pages (for example, opening **Settings** or returning to the **Dashboard**), the app flushes any pending configuration or view-state changes to `localStorage` and performs a full page reload into the new build automatically. - **Stale Chunk Recovery:** If a lazy-loaded page chunk from a previous deployment is no longer available before a background check runs, the app automatically flushes pending state and reloads once to load the current bundle. +- **What's New Dialog:** Click the **What's new** star icon in the dashboard header (or **What's new** in **Settings > Data > About**) to view recent release notes directly in the app. A small unread indicator dot appears on the header icon whenever a newer release has shipped since you last opened the dialog, and clears automatically once opened. - **Version & Changelog:** You can view the running build version (`+`) and open the [Changelog](https://github.com/gordon-code/github-tracker/blob/main/CHANGELOG.md) or [GitHub Releases](https://github.com/gordon-code/github-tracker/releases) at any time from **Settings > Data > About** or the dashboard footer. --- diff --git a/src/app/components/layout/Header.tsx b/src/app/components/layout/Header.tsx index f68eb706..c2e40137 100644 --- a/src/app/components/layout/Header.tsx +++ b/src/app/components/layout/Header.tsx @@ -1,16 +1,61 @@ -import { createSignal, Show } from "solid-js"; +import { createMemo, createSignal, onCleanup, onMount, Show } from "solid-js"; import { useNavigate } from "@solidjs/router"; import { user, clearAuth } from "../../stores/auth"; +import { config } from "../../stores/config"; import { getUnreadCount, markAllAsRead } from "../../lib/errors"; +import { hasUnseen, loadChangelog } from "../../lib/changelog"; +import type { ChangelogEntry } from "../../../shared/changelog-schema"; import { sizedAvatarUrl } from "../../lib/url"; import NotificationDrawer from "../shared/NotificationDrawer"; import ToastContainer from "../shared/ToastContainer"; import { Tooltip } from "../shared/Tooltip"; import GitHubStatusBadge from "../shared/GitHubStatusBadge"; +import WhatsNewDialog from "../shared/WhatsNewDialog"; export default function Header() { const navigate = useNavigate(); const [drawerOpen, setDrawerOpen] = createSignal(false); + const [whatsNewOpen, setWhatsNewOpen] = createSignal(false); + const [changelogEntries, setChangelogEntries] = createSignal([]); + + onMount(() => { + let cancelled = false; + const load = () => { + void (async () => { + const entries = await loadChangelog(); + if (!cancelled) setChangelogEntries(entries); + })(); + }; + if (typeof window !== "undefined" && typeof window.requestIdleCallback === "function") { + const idleId = window.requestIdleCallback(load); + onCleanup(() => { + cancelled = true; + if (typeof window.cancelIdleCallback === "function") { + window.cancelIdleCallback(idleId); + } + }); + } else { + const timerId = setTimeout(load, 0); + onCleanup(() => { + cancelled = true; + clearTimeout(timerId); + }); + } + }); + + const showWhatsNewDot = createMemo(() => + hasUnseen(changelogEntries(), config.lastSeenVersion), + ); + + function handleWhatsNewClick() { + if (changelogEntries().length === 0) { + void (async () => { + const entries = await loadChangelog(); + setChangelogEntries(entries); + })(); + } + setWhatsNewOpen(true); + } function handleLogout() { clearAuth(); @@ -109,6 +154,34 @@ export default function Header() { + {/* What's new button with unseen dot */} + + + + +
+ + setShowDependencyExclusionModal(false)} diff --git a/src/app/components/shared/WhatsNewDialog.tsx b/src/app/components/shared/WhatsNewDialog.tsx new file mode 100644 index 00000000..6c314400 --- /dev/null +++ b/src/app/components/shared/WhatsNewDialog.tsx @@ -0,0 +1,179 @@ +import { createEffect, createSignal, For, Show, untrack } from "solid-js"; +import { Dialog } from "@kobalte/core/dialog"; +import type { ChangelogEntry } from "../../../shared/changelog-schema"; +import { isStrictSemver, loadChangelog } from "../../lib/changelog"; +import { isSafeGitHubUrl } from "../../lib/url"; +import { APP_VERSION } from "../../lib/version"; +import { config, updateConfig } from "../../stores/config"; + +const REPO_BASE_URL = "https://github.com/gordon-code/github-tracker"; +const CHANGELOG_URL = `${REPO_BASE_URL}/blob/main/CHANGELOG.md`; +const HEX_SHA_RE = /^[0-9a-f]{7,40}$/; + +function buildPrUrl(pr: number | undefined): string | undefined { + if (typeof pr !== "number" || !Number.isInteger(pr) || pr <= 0) return undefined; + const url = `${REPO_BASE_URL}/pull/${pr}`; + return isSafeGitHubUrl(url) ? url : undefined; +} + +function buildCommitUrl(sha: string | undefined): string | undefined { + if (typeof sha !== "string" || !HEX_SHA_RE.test(sha)) return undefined; + const url = `${REPO_BASE_URL}/commit/${sha}`; + return isSafeGitHubUrl(url) ? url : undefined; +} + +export interface WhatsNewDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + entries?: readonly ChangelogEntry[]; +} + +export default function WhatsNewDialog(props: WhatsNewDialogProps) { + const [loadedEntries, setLoadedEntries] = createSignal([]); + + createEffect(() => { + if (!props.open) return; + if (isStrictSemver(APP_VERSION) && untrack(() => config.lastSeenVersion) !== APP_VERSION) { + updateConfig({ lastSeenVersion: APP_VERSION }); + } + if (props.entries === undefined) { + void (async () => { + const data = await loadChangelog(); + setLoadedEntries(data); + })(); + } + }); + + const entries = () => props.entries ?? loadedEntries(); + const fullChangelogHref = () => (isSafeGitHubUrl(CHANGELOG_URL) ? CHANGELOG_URL : undefined); + + return ( + + + + + + Recent release notes and changelog entries for GitHub Tracker + + + {/* Header */} +
+ + What's New + + + + +
+ + {/* Body */} +
+ + {/* Footer */} + + {(href) => ( + + )} + + + + + ); +} diff --git a/src/app/lib/changelog.ts b/src/app/lib/changelog.ts new file mode 100644 index 00000000..2e14026d --- /dev/null +++ b/src/app/lib/changelog.ts @@ -0,0 +1,68 @@ +import * as z from "zod/mini"; +import { ChangelogSchema, type ChangelogEntry } from "../../shared/changelog-schema"; + +const STRICT_SEMVER_RE = /^\d+\.\d+\.\d+$/; +const BASE_SEMVER_RE = /^(\d+)\.(\d+)\.(\d+)/; + +let cachedChangelogPromise: Promise | null = null; + +export function isStrictSemver(version: string): boolean { + return STRICT_SEMVER_RE.test(version); +} + +function parseSemverTuple(version: string): [number, number, number] | null { + const match = BASE_SEMVER_RE.exec(version); + if (!match) return null; + return [ + Number.parseInt(match[1], 10), + Number.parseInt(match[2], 10), + Number.parseInt(match[3], 10), + ]; +} + +export function compareSemver(a: string, b: string): number { + const tupleA = parseSemverTuple(a); + const tupleB = parseSemverTuple(b); + if (!tupleA || !tupleB) return 0; + for (let i = 0; i < 3; i++) { + if (tupleA[i] !== tupleB[i]) { + return tupleA[i] > tupleB[i] ? 1 : -1; + } + } + return 0; +} + +export function loadChangelog(): Promise { + if (!cachedChangelogPromise) { + cachedChangelogPromise = import("virtual:changelog") + .then((mod) => { + const parsed = z.safeParse(ChangelogSchema, mod.default); + return parsed.success ? parsed.data : []; + }) + .catch(() => []); + } + return cachedChangelogPromise; +} + +export function unseenEntries( + entries: readonly ChangelogEntry[], + lastSeen: string | null | undefined, +): ChangelogEntry[] { + if (entries.length === 0) return []; + if (!lastSeen || !isStrictSemver(lastSeen)) { + return [entries[0]]; + } + return entries.filter((entry) => compareSemver(entry.version, lastSeen) > 0); +} + +export function hasUnseen( + entries: readonly ChangelogEntry[], + lastSeen: string | null | undefined, +): boolean { + return unseenEntries(entries, lastSeen).length > 0; +} + +/** @internal Test-only helper to clear cached changelog promise */ +export function _resetChangelogCacheForTest(): void { + cachedChangelogPromise = null; +} diff --git a/src/app/lib/version.ts b/src/app/lib/version.ts index b8300dfa..8fb7969c 100644 --- a/src/app/lib/version.ts +++ b/src/app/lib/version.ts @@ -1,7 +1,7 @@ import { createSignal } from "solid-js"; import * as z from "zod/mini"; -export const APP_VERSION: string = __APP_VERSION__; +export let APP_VERSION: string = __APP_VERSION__; export const GIT_SHA: string = __GIT_SHA__; export const BUILD_TIME: string = __BUILD_TIME__; @@ -92,6 +92,11 @@ export function _setUpdateAvailableForTest(info: VersionInfo | null): void { setUpdateAvailable(info); } +/** @internal Test-only helper to override local build APP_VERSION */ +export function _setAppVersionForTest(version: string): void { + APP_VERSION = version; +} + /** @internal Test-only helper to override local build GIT_SHA */ export function _setGitShaForTest(sha: string): void { currentGitSha = sha; @@ -99,6 +104,7 @@ export function _setGitShaForTest(sha: string): void { /** @internal Test-only helper to reset version checker state */ export function _resetVersionStateForTest(): void { + APP_VERSION = __APP_VERSION__; setUpdateAvailable(null); currentGitSha = GIT_SHA; checkInFlight = null; diff --git a/src/shared/changelog-schema.ts b/src/shared/changelog-schema.ts new file mode 100644 index 00000000..ff6e63a4 --- /dev/null +++ b/src/shared/changelog-schema.ts @@ -0,0 +1,28 @@ +import * as z from "zod/mini"; + +export const ChangelogItemSchema = z.object({ + text: z.string().check(z.minLength(1), z.maxLength(300)), + pr: z.optional(z.number().check(z.int(), z.positive())), + sha: z.optional(z.string().check(z.regex(/^[0-9a-f]{7,40}$/))), +}); + +export type ChangelogItem = z.infer; + +export const ChangelogSectionSchema = z.object({ + title: z.string().check(z.minLength(1), z.maxLength(100)), + items: z.array(ChangelogItemSchema), +}); + +export type ChangelogSection = z.infer; + +export const ChangelogEntrySchema = z.object({ + version: z.string().check(z.regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/)), + date: z.string().check(z.regex(/^\d{4}-\d{2}-\d{2}$/)), + sections: z.array(ChangelogSectionSchema), +}); + +export type ChangelogEntry = z.infer; + +export const ChangelogSchema = z.array(ChangelogEntrySchema).check(z.maxLength(20)); + +export type ChangelogData = z.infer; diff --git a/src/shared/schemas.ts b/src/shared/schemas.ts index fe9cd9f8..9647508f 100644 --- a/src/shared/schemas.ts +++ b/src/shared/schemas.ts @@ -124,6 +124,7 @@ export const ConfigSchema = z.object({ customTabs: z._default(z.array(CustomTabSchema).check(z.maxLength(10)), []), mcpRelayEnabled: z._default(z.boolean(), false), mcpRelayPort: z._default(z.int().check(z.minimum(1024), z.maximum(65535)), 9876), + lastSeenVersion: z._default(z.nullable(z.string().check(z.maxLength(32))), null), // Explicit defaults (NOT .default({})) — inner field defaults don't apply with .default({}) per BUG-001 jira: z._default(JiraConfigSchema, { enabled: false, authMethod: "oauth", issueKeyDetection: true, expandIssueDetails: false, customFields: [], customScopes: [] }), dependencies: z._default(DependencyConfigSchema, { enabled: true, rebaseLabel: "rebase", excludedOrgs: [], excludedRepos: [] }), diff --git a/src/types/build-meta.d.ts b/src/types/build-meta.d.ts index ec149957..5912f2bb 100644 --- a/src/types/build-meta.d.ts +++ b/src/types/build-meta.d.ts @@ -2,3 +2,9 @@ declare const __APP_VERSION__: string; declare const __GIT_SHA__: string; declare const __BUILD_TIME__: string; + +declare module "virtual:changelog" { + import type { ChangelogEntry } from "../shared/changelog-schema"; + const entries: ChangelogEntry[]; + export default entries; +} diff --git a/tests/build/build-meta.test.ts b/tests/build/build-meta.test.ts index 58af5a27..32a091df 100644 --- a/tests/build/build-meta.test.ts +++ b/tests/build/build-meta.test.ts @@ -4,6 +4,7 @@ import { resolve } from "node:path"; const mockExecFileSync = vi.hoisted(() => vi.fn()); const mockReadFileSync = vi.hoisted(() => vi.fn()); +const mockExistsSync = vi.hoisted(() => vi.fn()); vi.mock("node:child_process", () => ({ execFileSync: (...args: unknown[]) => mockExecFileSync(...args), @@ -13,6 +14,10 @@ vi.mock("node:fs", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, + existsSync: (...args: Parameters) => + mockExistsSync.getMockImplementation() + ? mockExistsSync(...args) + : actual.existsSync(...args), readFileSync: (...args: Parameters) => mockReadFileSync.getMockImplementation() ? mockReadFileSync(...args) @@ -22,6 +27,7 @@ vi.mock("node:fs", async (importOriginal) => { import { buildMeta, + parseChangelog, resolveBuildMetadata, resolveGitSha, resolvePackageVersion, @@ -39,6 +45,7 @@ describe("buildMeta Vite plugin", () => { beforeEach(() => { mockExecFileSync.mockReset(); mockReadFileSync.mockReset(); + mockExistsSync.mockReset(); delete process.env.GITHUB_SHA; }); @@ -199,4 +206,206 @@ describe("buildMeta Vite plugin", () => { builtAt: "2026-04-14T12:34:56.789Z", }); }); + + describe("parseChangelog and virtual:changelog", () => { + it("parses linked ## headings, unlinked ## headings, legacy ### patch headings, bold-scope and plain bullets, BREAKING CHANGES, PR numbers, and hex SHAs", () => { + const md = [ + "# Changelog", + "", + "## [0.2.0](https://github.com/gordon-code/github-tracker/compare/github-tracker@0.1.1...github-tracker@0.2.0) (2026-11-10)", + "", + "### ⚠ BREAKING CHANGES", + "", + "* **api:** drop legacy v1 endpoint", + "", + "### Features", + "", + "* **dashboard:** add keyboard navigation ([#190](https://github.com/gordon-code/github-tracker/issues/190)) ([1a2b3c4](https://github.com/gordon-code/github-tracker/commit/1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b))", + "- plain bullet with unlinked PR (#191) ([ABCDEF1](https://github.com/gordon-code/github-tracker/commit/abcdef1))", + "", + "### [0.1.1](https://github.com/gordon-code/github-tracker/compare/github-tracker@0.1.0...github-tracker@0.1.1) (2026-11-06)", + "", + "### Bug Fixes", + "", + "* **release:** sync MCP version ([#183](https://github.com/gordon-code/github-tracker/issues/183)) ([97050e3](https://github.com/gordon-code/github-tracker/commit/97050e373da849c1863a08ce1b0c44fa12f17507))", + "", + "## 0.1.0 (2026-11-01)", + "", + "### Features", + "", + "* initial release ([deadbeef](https://github.com/gordon-code/github-tracker/commit/deadbeef))", + ].join("\n"); + + const entries = parseChangelog(md); + expect(entries).toEqual([ + { + version: "0.2.0", + date: "2026-11-10", + sections: [ + { + title: "⚠ BREAKING CHANGES", + items: [{ text: "api: drop legacy v1 endpoint" }], + }, + { + title: "Features", + items: [ + { + text: "dashboard: add keyboard navigation", + pr: 190, + sha: "1a2b3c4", + }, + { + text: "plain bullet with unlinked PR", + pr: 191, + sha: "abcdef1", + }, + ], + }, + ], + }, + { + version: "0.1.1", + date: "2026-11-06", + sections: [ + { + title: "Bug Fixes", + items: [ + { + text: "release: sync MCP version", + pr: 183, + sha: "97050e3", + }, + ], + }, + ], + }, + { + version: "0.1.0", + date: "2026-11-01", + sections: [ + { + title: "Features", + items: [ + { + text: "initial release", + sha: "deadbeef", + }, + ], + }, + ], + }, + ]); + }); + + it("strips markdown link syntax (discarding URLs) and preserves raw HTML/XSS strings only as plain text", () => { + const md = [ + "## 0.1.0 (2026-11-01)", + "", + "### Security", + "", + "* **xss:** sanitize [click here](javascript:alert(1)) and 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")); + expect(loadedReal).toMatch(/^export default \[.*\];$/); + + // 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/DashboardPage.test.tsx b/tests/components/DashboardPage.test.tsx index e630688e..cfd90b3e 100644 --- a/tests/components/DashboardPage.test.tsx +++ b/tests/components/DashboardPage.test.tsx @@ -306,10 +306,10 @@ describe("DashboardPage — tab switching", () => { }); describe("DashboardPage — footer", () => { - it("renders Source, Guide, Privacy, and the v0.1.0-test+abcdef1 release link in the 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-test+abcdef1" }); + const versionLink = screen.getByRole("link", { name: "v0.1.0+abcdef1" }); expect(versionLink.getAttribute("href")).toBe( "https://github.com/gordon-code/github-tracker/releases", ); diff --git a/tests/components/layout/Header.test.tsx b/tests/components/layout/Header.test.tsx index 019d7bab..7aa9a9fe 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 { _resetChangelogCacheForTest } from "../../../src/app/lib/changelog"; +import { render, waitFor } from "@solidjs/testing-library"; beforeEach(() => { + resetConfig(); + _resetChangelogCacheForTest(); mockNavigate.mockClear(); vi.mocked(authStore.clearAuth).mockClear(); vi.mocked(errorsModule.getUnreadCount).mockReturnValue(0); @@ -197,4 +201,31 @@ 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(() =>
); + + await new Promise((r) => setTimeout(r, 20)); + expect(screen.queryByTestId("whats-new-dot")).toBeNull(); + }); }); diff --git a/tests/components/settings/SettingsPage.test.tsx b/tests/components/settings/SettingsPage.test.tsx index 5ed9d239..162364a7 100644 --- a/tests/components/settings/SettingsPage.test.tsx +++ b/tests/components/settings/SettingsPage.test.tsx @@ -2105,7 +2105,7 @@ describe("SettingsPage — Data: About", () => { renderSettings(); screen.getByText("About"); - const versionLink = screen.getByRole("link", { name: "0.1.0-test+abcdef1" }); + const versionLink = screen.getByRole("link", { name: "0.1.0+abcdef1" }); expect(versionLink.getAttribute("href")).toBe( "https://github.com/gordon-code/github-tracker/releases", ); @@ -2124,10 +2124,23 @@ describe("SettingsPage — Data: About", () => { vi.mocked(urlModule.isSafeGitHubUrl).mockReturnValue(false); renderSettings(); - const versionEl = screen.getByText("0.1.0-test+abcdef1"); + 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/shared/WhatsNewDialog.test.tsx b/tests/components/shared/WhatsNewDialog.test.tsx new file mode 100644 index 00000000..fd49c65e --- /dev/null +++ b/tests/components/shared/WhatsNewDialog.test.tsx @@ -0,0 +1,180 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { render, screen, waitFor } from "@solidjs/testing-library"; +import WhatsNewDialog from "../../../src/app/components/shared/WhatsNewDialog"; +import { config, resetConfig } from "../../../src/app/stores/config"; +import { _resetChangelogCacheForTest } from "../../../src/app/lib/changelog"; +import { + APP_VERSION, + _resetVersionStateForTest, + _setAppVersionForTest, +} from "../../../src/app/lib/version"; +import type { ChangelogEntry } from "../../../src/shared/changelog-schema"; + +describe("WhatsNewDialog", () => { + beforeEach(() => { + resetConfig(); + _resetVersionStateForTest(); + _resetChangelogCacheForTest(); + }); + + afterEach(() => { + resetConfig(); + _resetVersionStateForTest(); + _resetChangelogCacheForTest(); + }); + + 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(); + _setAppVersionForTest("0.1.0-dev"); + render(() => ( + {}} entries={[]} /> + )); + expect(config.lastSeenVersion).toBeNull(); + }); + + 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("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..da7111d0 --- /dev/null +++ b/tests/lib/changelog.test.ts @@ -0,0 +1,91 @@ +import { describe, it, expect, beforeEach } from "vitest"; +import type { ChangelogEntry } from "../../src/shared/changelog-schema"; +import { + compareSemver, + hasUnseen, + isStrictSemver, + loadChangelog, + unseenEntries, + _resetChangelogCacheForTest, +} 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(() => { + _resetChangelogCacheForTest(); + }); + + 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("returns only the newest entry when lastSeen is null, undefined, or not strict x.y.z", () => { + expect(unseenEntries(SAMPLE_ENTRIES, null)).toEqual([SAMPLE_ENTRIES[0]]); + expect(unseenEntries(SAMPLE_ENTRIES, undefined)).toEqual([SAMPLE_ENTRIES[0]]); + expect(unseenEntries(SAMPLE_ENTRIES, "")).toEqual([SAMPLE_ENTRIES[0]]); + expect(unseenEntries(SAMPLE_ENTRIES, "0.1.1-test")).toEqual([SAMPLE_ENTRIES[0]]); + expect(unseenEntries(SAMPLE_ENTRIES, "v0.1.1")).toEqual([SAMPLE_ENTRIES[0]]); + expect(unseenEntries([], null)).toEqual([]); + }); + + it("returns all entries with semver > lastSeen and empty array when up to date", () => { + expect(unseenEntries(SAMPLE_ENTRIES, "0.1.1")).toEqual([ + SAMPLE_ENTRIES[0], + SAMPLE_ENTRIES[1], + ]); + expect(unseenEntries(SAMPLE_ENTRIES, "0.2.0")).toEqual([SAMPLE_ENTRIES[0]]); + expect(unseenEntries(SAMPLE_ENTRIES, "0.10.0")).toEqual([]); + expect(unseenEntries(SAMPLE_ENTRIES, "1.0.0")).toEqual([]); + }); + + it("computes hasUnseen boolean from unseenEntries", () => { + expect(hasUnseen(SAMPLE_ENTRIES, null)).toBe(true); + expect(hasUnseen(SAMPLE_ENTRIES, "0.2.0")).toBe(true); + expect(hasUnseen(SAMPLE_ENTRIES, "0.10.0")).toBe(false); + expect(hasUnseen([], null)).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); + }); +}); 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 index fccccd85..e7010570 100644 --- a/tests/lib/version.test.ts +++ b/tests/lib/version.test.ts @@ -37,14 +37,14 @@ describe("version metadata", () => { }); it("exposes build-time constants from Vite defines", () => { - expect(APP_VERSION).toBe("0.1.0-test"); + expect(APP_VERSION).toBe("0.1.0"); expect(GIT_SHA).toBe("abcdef123456"); expect(BUILD_TIME).toBe("2026-01-01T00:00:00.000Z"); }); it("formats displayVersion() as +<7-char GIT_SHA>", () => { expect(displayVersion()).toBe(`${APP_VERSION}+${GIT_SHA.slice(0, 7)}`); - expect(displayVersion()).toBe("0.1.0-test+abcdef1"); + expect(displayVersion()).toBe("0.1.0+abcdef1"); }); describe("VersionInfoSchema", () => { @@ -95,7 +95,7 @@ describe("version metadata", () => { it("leaves updateAvailable null when remote SHA matches local GIT_SHA", async () => { const fetchMock = vi.fn().mockResolvedValue( makeJsonResponse({ - version: "0.1.0-test", + version: "0.1.0", sha: GIT_SHA, builtAt: "2026-01-01T00:00:00.000Z", }), @@ -303,7 +303,7 @@ describe("version metadata", () => { vi.useFakeTimers(); const fetchMock = vi.fn().mockResolvedValue( makeJsonResponse({ - version: "0.1.0-test", + version: "0.1.0", sha: GIT_SHA, builtAt: "2026-01-01T00:00:00.000Z", }), @@ -320,7 +320,7 @@ describe("version metadata", () => { vi.useFakeTimers(); const fetchMock = vi.fn().mockResolvedValue( makeJsonResponse({ - version: "0.1.0-test", + version: "0.1.0", sha: GIT_SHA, builtAt: "2026-01-01T00:00:00.000Z", }), diff --git a/tests/stores/config.test.ts b/tests/stores/config.test.ts index ad41765d..a8774740 100644 --- a/tests/stores/config.test.ts +++ b/tests/stores/config.test.ts @@ -63,6 +63,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 +155,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", () => { 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 index c919df1f..73922a9b 100644 --- a/vite-plugins/build-meta.ts +++ b/vite-plugins/build-meta.ts @@ -1,9 +1,144 @@ import { execFileSync } from "node:child_process"; -import { readFileSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import { resolve } from "node:path"; import type { Plugin } from "vite"; +import * as z from "zod/mini"; +import { + ChangelogSchema, + type ChangelogEntry, + type ChangelogItem, + type ChangelogSection, +} from "../src/shared/changelog-schema"; const HEX_SHA_RE = /^[0-9a-f]{7,40}$/i; +const VIRTUAL_CHANGELOG_ID = "virtual:changelog"; +const RESOLVED_VIRTUAL_CHANGELOG_ID = "\0virtual:changelog"; +const MAX_CHANGELOG_ENTRIES = 20; +const MAX_ITEM_TEXT_LENGTH = 300; +const MAX_SECTION_TITLE_LENGTH = 100; + +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 = /(?:\(\[([0-9a-f]{7,40})\]\([^)]*\)\)|\[([0-9a-f]{7,40})\]\([^)]*\))/i; +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 { + let pr: number | undefined; + const prMatch = PR_REF_RE.exec(rawBullet); + if (prMatch) { + const rawPr = prMatch[1] ?? prMatch[2] ?? prMatch[3]; + if (rawPr) { + const parsedPr = Number.parseInt(rawPr, 10); + if (Number.isInteger(parsedPr) && parsedPr > 0) { + pr = parsedPr; + } + } + } + + let sha: string | undefined; + const shaMatch = COMMIT_LINK_RE.exec(rawBullet); + if (shaMatch) { + const rawSha = shaMatch[1] ?? shaMatch[2]; + if (rawSha && HEX_SHA_RE.test(rawSha)) { + sha = rawSha.toLowerCase(); + } + } + + let text = rawBullet + .replace(/\s*\(\[[0-9a-f]{7,40}\]\([^)]*\)\)/gi, "") + .replace(/\s+\[[0-9a-f]{7,40}\]\([^)]*\)\s*$/gi, "") + .replace(/\s*\(\[#\d+\]\([^)]*\)\)/g, "") + .replace(/\s*\(#\d+\)/g, ""); + + text = stripMarkdownLinks(text) + .replace(/\*\*([^*]+)\*\*/g, "$1") + .replace(/__([^_]+)__/g, "$1") + .replace(/\s+/g, " ") + .trim() + .slice(0, 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, 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, MAX_CHANGELOG_ENTRIES); + + return z.parse(ChangelogSchema, cleaned); +} export interface BuildMetadata { version: string; @@ -69,6 +204,27 @@ export function buildMeta(): Plugin[] { 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"); + if (typeof this.addWatchFile === "function") { + 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", diff --git a/vite.config.ts b/vite.config.ts index 72452f92..ba126a60 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -3,7 +3,7 @@ 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"; +import { buildMeta } from "./vite-plugins/build-meta"; export default defineConfig({ plugins: [ diff --git a/vitest.config.ts b/vitest.config.ts index 89e07f08..ae43d40b 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,14 +1,23 @@ +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; import { defineConfig } from "vitest/config"; import solid from "vite-plugin-solid"; import tailwindcss from "@tailwindcss/vite"; +const rootDir = dirname(fileURLToPath(import.meta.url)); + // 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()], + resolve: { + alias: { + "virtual:changelog": resolve(rootDir, "tests/stubs/virtual-changelog.ts"), + }, + }, define: { - __APP_VERSION__: JSON.stringify("0.1.0-test"), + __APP_VERSION__: JSON.stringify("0.1.0"), __GIT_SHA__: JSON.stringify("abcdef123456"), __BUILD_TIME__: JSON.stringify("2026-01-01T00:00:00.000Z"), }, diff --git a/vitest.workspace.ts b/vitest.workspace.ts index f9428a4a..a3856f62 100644 --- a/vitest.workspace.ts +++ b/vitest.workspace.ts @@ -1,8 +1,12 @@ +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; import { defineConfig, defineProject } from "vitest/config"; import { cloudflareTest } from "@cloudflare/vitest-plugin"; import solid from "vite-plugin-solid"; import tailwindcss from "@tailwindcss/vite"; +const rootDir = dirname(fileURLToPath(import.meta.url)); + export default defineConfig({ test: { projects: [ @@ -11,8 +15,13 @@ export default defineConfig({ // Browser/DOM tests (stores, services, UI) defineProject({ plugins: [solid(), tailwindcss()], + resolve: { + alias: { + "virtual:changelog": resolve(rootDir, "tests/stubs/virtual-changelog.ts"), + }, + }, define: { - __APP_VERSION__: JSON.stringify("0.1.0-test"), + __APP_VERSION__: JSON.stringify("0.1.0"), __GIT_SHA__: JSON.stringify("abcdef123456"), __BUILD_TIME__: JSON.stringify("2026-01-01T00:00:00.000Z"), }, From cee75a1c97197147c2339431f1ef9d40be17a326 Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Fri, 6 Nov 2026 13:47:17 -0500 Subject: [PATCH 04/11] fix(version): retry failed changelog loads and force view reset writes --- src/app/components/layout/Header.tsx | 7 +- src/app/components/shared/WhatsNewDialog.tsx | 8 ++- src/app/lib/changelog.ts | 5 +- src/app/stores/view.ts | 43 +++++++++---- .../components/shared/WhatsNewDialog.test.tsx | 18 +++++- tests/lib/changelog.test.ts | 37 ++++++++++- tests/stores/view.test.ts | 64 +++++++++++++++++++ 7 files changed, 163 insertions(+), 19 deletions(-) diff --git a/src/app/components/layout/Header.tsx b/src/app/components/layout/Header.tsx index c2e40137..a75f8315 100644 --- a/src/app/components/layout/Header.tsx +++ b/src/app/components/layout/Header.tsx @@ -17,9 +17,12 @@ export default function Header() { const [drawerOpen, setDrawerOpen] = createSignal(false); const [whatsNewOpen, setWhatsNewOpen] = createSignal(false); const [changelogEntries, setChangelogEntries] = createSignal([]); + let cancelled = false; + onCleanup(() => { + cancelled = true; + }); onMount(() => { - let cancelled = false; const load = () => { void (async () => { const entries = await loadChangelog(); @@ -51,7 +54,7 @@ export default function Header() { if (changelogEntries().length === 0) { void (async () => { const entries = await loadChangelog(); - setChangelogEntries(entries); + if (!cancelled) setChangelogEntries(entries); })(); } setWhatsNewOpen(true); diff --git a/src/app/components/shared/WhatsNewDialog.tsx b/src/app/components/shared/WhatsNewDialog.tsx index 6c314400..d62a2e50 100644 --- a/src/app/components/shared/WhatsNewDialog.tsx +++ b/src/app/components/shared/WhatsNewDialog.tsx @@ -1,4 +1,4 @@ -import { createEffect, createSignal, For, Show, untrack } from "solid-js"; +import { createEffect, createSignal, For, onCleanup, Show, untrack } from "solid-js"; import { Dialog } from "@kobalte/core/dialog"; import type { ChangelogEntry } from "../../../shared/changelog-schema"; import { isStrictSemver, loadChangelog } from "../../lib/changelog"; @@ -37,9 +37,13 @@ export default function WhatsNewDialog(props: WhatsNewDialogProps) { updateConfig({ lastSeenVersion: APP_VERSION }); } if (props.entries === undefined) { + let cancelled = false; + onCleanup(() => { + cancelled = true; + }); void (async () => { const data = await loadChangelog(); - setLoadedEntries(data); + if (!cancelled) setLoadedEntries(data); })(); } }); diff --git a/src/app/lib/changelog.ts b/src/app/lib/changelog.ts index 2e14026d..802e5e85 100644 --- a/src/app/lib/changelog.ts +++ b/src/app/lib/changelog.ts @@ -39,7 +39,10 @@ export function loadChangelog(): Promise { const parsed = z.safeParse(ChangelogSchema, mod.default); return parsed.success ? parsed.data : []; }) - .catch(() => []); + .catch(() => { + cachedChangelogPromise = null; + return []; + }); } return cachedChangelogPromise; } diff --git a/src/app/stores/view.ts b/src/app/stores/view.ts index 5def84ab..e208b49c 100644 --- a/src/app/stores/view.ts +++ b/src/app/stores/view.ts @@ -207,6 +207,8 @@ export type IgnoredItem = ViewState["ignoredItems"][number]; const REPO_STATE_TAB_IDS = ["issues", "pullRequests", "actions", "jiraAssigned"] as const; const VIEW_STATE_KEYS = new Set(Object.keys(ViewStateSchema.shape)); +let fullOverwritePending = false; +const forcedKeysPending = new Set(); /** * Top-level ViewState keys included in a settings export's `_viewPreferences` @@ -337,6 +339,7 @@ export function applyImportedViewState(raw: unknown): void { const validated = validateViewStateField(key, value); if (validated !== undefined) { patch[key] = validated; + forcedKeysPending.add(key); } } if (Object.keys(patch).length === 0) return; @@ -407,6 +410,8 @@ export const [viewState, setViewState] = createStore( ); export function resetViewState(): void { + fullOverwritePending = true; + forcedKeysPending.clear(); setViewState( produce((draft) => { // Delete dynamic custom tab keys that Object.assign wouldn't clear @@ -889,19 +894,31 @@ function readOnDiskState(): Record | undefined { } function commitSnapshot(snapshot: Record): void { - const onDisk = readOnDiskState(); - // Start from whatever is currently on disk (may include newer values another tab - // wrote); fall back to this tab's own snapshot if disk is unreadable/absent. - const merged: Record = { ...(onDisk ?? snapshot) }; - for (const key of Object.keys(snapshot)) { - // Always include a key this tab knows about but that's missing from the on-disk - // blob entirely (stale/corrupted/version-skewed data) — no legitimate flow ever - // produces a ViewState with a top-level key truly absent, so treat that as - // recoverable staleness rather than silently dropping this tab's known value - // (which Zod's .default() would otherwise backfill on the next load). - if (!(key in merged) || JSON.stringify(snapshot[key]) !== JSON.stringify(lastSyncedSnapshot[key])) { - merged[key] = snapshot[key]; + let merged: Record; + if (fullOverwritePending) { + fullOverwritePending = false; + forcedKeysPending.clear(); + merged = { ...snapshot }; + } else { + const onDisk = readOnDiskState(); + // Start from whatever is currently on disk (may include newer values another tab + // wrote); fall back to this tab's own snapshot if disk is unreadable/absent. + merged = { ...(onDisk ?? snapshot) }; + for (const key of Object.keys(snapshot)) { + // Always include a key this tab knows about but that's missing from the on-disk + // blob entirely (stale/corrupted/version-skewed data) — no legitimate flow ever + // produces a ViewState with a top-level key truly absent, so treat that as + // recoverable staleness rather than silently dropping this tab's known value + // (which Zod's .default() would otherwise backfill on the next load). + if ( + !(key in merged) || + forcedKeysPending.has(key) || + JSON.stringify(snapshot[key]) !== JSON.stringify(lastSyncedSnapshot[key]) + ) { + merged[key] = snapshot[key]; + } } + forcedKeysPending.clear(); } try { localStorage.setItem(VIEW_STORAGE_KEY, JSON.stringify(merged)); @@ -945,6 +962,8 @@ export function initViewPersistence(): void { } lastSyncedSnapshot = JSON.parse(JSON.stringify(untrack(() => viewState))); + fullOverwritePending = false; + forcedKeysPending.clear(); createEffect(() => { const json = JSON.stringify(viewState); // synchronous read → tracked by SolidJS diff --git a/tests/components/shared/WhatsNewDialog.test.tsx b/tests/components/shared/WhatsNewDialog.test.tsx index fd49c65e..84c823bf 100644 --- a/tests/components/shared/WhatsNewDialog.test.tsx +++ b/tests/components/shared/WhatsNewDialog.test.tsx @@ -4,7 +4,7 @@ import { describe, it, expect, beforeEach, afterEach } from "vitest"; import { render, screen, waitFor } from "@solidjs/testing-library"; import WhatsNewDialog from "../../../src/app/components/shared/WhatsNewDialog"; import { config, resetConfig } from "../../../src/app/stores/config"; -import { _resetChangelogCacheForTest } from "../../../src/app/lib/changelog"; +import { _resetChangelogCacheForTest, loadChangelog } from "../../../src/app/lib/changelog"; import { APP_VERSION, _resetVersionStateForTest, @@ -170,6 +170,22 @@ describe("WhatsNewDialog", () => { }); }); + it("does not throw or update state after disposal when unmounted while loadChangelog() is in flight", async () => { + _resetChangelogCacheForTest(); + const { unmount } = render(() => ( + {}} /> + )); + + // Unmount immediately while loadChangelog() is still pending + expect(() => unmount()).not.toThrow(); + + // Let the in-flight loadChangelog() promise settle and flush microtasks + await expect(loadChangelog()).resolves.toHaveLength(2); + await Promise.resolve(); + + expect(screen.queryByText("v0.1.0")).toBeNull(); + }); + it("contains zero occurrences of innerHTML in WhatsNewDialog.tsx source", () => { const source = readFileSync( resolve(process.cwd(), "src/app/components/shared/WhatsNewDialog.tsx"), diff --git a/tests/lib/changelog.test.ts b/tests/lib/changelog.test.ts index da7111d0..356010e8 100644 --- a/tests/lib/changelog.test.ts +++ b/tests/lib/changelog.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, beforeEach } from "vitest"; +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; import type { ChangelogEntry } from "../../src/shared/changelog-schema"; import { compareSemver, @@ -37,6 +37,11 @@ describe("lib/changelog", () => { _resetChangelogCacheForTest(); }); + afterEach(() => { + vi.doUnmock("virtual:changelog"); + _resetChangelogCacheForTest(); + }); + it("validates strict x.y.z semver strings", () => { expect(isStrictSemver("0.1.0")).toBe(true); expect(isStrictSemver("10.20.30")).toBe(true); @@ -88,4 +93,34 @@ describe("lib/changelog", () => { 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 _resetChangelogCacheForTest(), 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 _resetChangelogCacheForTest() + 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._resetChangelogCacheForTest(); + const recoveredAfterInvalid = await invalidMod.loadChangelog(); + expect(recoveredAfterInvalid).toHaveLength(2); + expect(recoveredAfterInvalid[0].version).toBe("0.1.0"); + }); }); diff --git a/tests/stores/view.test.ts b/tests/stores/view.test.ts index ed2d380d..c969487d 100644 --- a/tests/stores/view.test.ts +++ b/tests/stores/view.test.ts @@ -31,6 +31,8 @@ import { setJiraCustomOrder, applyImportedViewState, EXPORTED_VIEW_PREF_KEYS, + flushViewPersistence, + 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"; @@ -871,6 +873,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", () => { @@ -1676,4 +1709,35 @@ 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(); + } + }); }); From 7d0205da8f3db73f197387719c5f51dfbd5451a8 Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Fri, 6 Nov 2026 21:04:34 -0500 Subject: [PATCH 05/11] test(version): expand chunk-reload, header idle, and config flush tests --- docs/USER_GUIDE.md | 3 +- e2e/update.spec.ts | 10 +---- src/app/App.tsx | 2 +- tests/components/layout/Header.test.tsx | 37 ++++++++++++++++ tests/lib/chunk-reload.test.ts | 56 ++++++++++++++++++++++++- tests/stores/config.test.ts | 52 ++++++++++++++++++++++- 6 files changed, 148 insertions(+), 12 deletions(-) diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index 1f6ffad4..c4de14ff 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -62,6 +62,7 @@ GitHub Tracker is a dashboard that aggregates open issues, pull requests, and Gi - [Keep the Export File Safe](#keep-the-export-file-safe) - [Jira Credentials and Staleness](#jira-credentials-and-staleness) - [Same-Deployment Only](#same-deployment-only) +- [Updates & What's New](#updates--whats-new) - [Troubleshooting](#troubleshooting) --- @@ -845,7 +846,7 @@ GitHub Tracker checks `/version.json` in the background (30 seconds after load, - **Automatic Reload on Navigation:** If an update is waiting when you navigate between pages (for example, opening **Settings** or returning to the **Dashboard**), the app flushes any pending configuration or view-state changes to `localStorage` and performs a full page reload into the new build automatically. - **Stale Chunk Recovery:** If a lazy-loaded page chunk from a previous deployment is no longer available before a background check runs, the app automatically flushes pending state and reloads once to load the current bundle. - **What's New Dialog:** Click the **What's new** star icon in the dashboard header (or **What's new** in **Settings > Data > About**) to view recent release notes directly in the app. A small unread indicator dot appears on the header icon whenever a newer release has shipped since you last opened the dialog, and clears automatically once opened. -- **Version & Changelog:** You can view the running build version (`+`) and open the [Changelog](https://github.com/gordon-code/github-tracker/blob/main/CHANGELOG.md) or [GitHub Releases](https://github.com/gordon-code/github-tracker/releases) at any time from **Settings > Data > About** or the dashboard footer. +- **Version & Changelog:** You can view the running build version (`+`, linking to [GitHub Releases](https://github.com/gordon-code/github-tracker/releases)) in **Settings > Data > About** and in the dashboard footer, and open the [Changelog](https://github.com/gordon-code/github-tracker/blob/main/CHANGELOG.md) directly from **Settings > Data > About** (as well as from the **What's New** dialog and the update banner). --- diff --git a/e2e/update.spec.ts b/e2e/update.spec.ts index ff377168..58bcf5a8 100644 --- a/e2e/update.spec.ts +++ b/e2e/update.spec.ts @@ -1,14 +1,8 @@ -import { execFileSync } from "node:child_process"; import { test, expect } from "@playwright/test"; +import { resolveGitSha } from "../vite-plugins/build-meta"; import { setupAuth } from "./helpers"; -const rawSha = ( - process.env.GITHUB_SHA ?? - execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }) -) - .trim() - .toLowerCase(); -const currentSha = rawSha.slice(0, 12); +const currentSha = resolveGitSha(); const differentSha = currentSha === "111111111111" ? "222222222222" : "111111111111"; diff --git a/src/app/App.tsx b/src/app/App.tsx index 4d02f939..bf08000e 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -22,7 +22,7 @@ export function _resetAuthInitStartedForTests(): void { authInitGen++; } -function lazyWithReload(loader: Parameters[0]) { +export function lazyWithReload(loader: Parameters[0]) { return lazy(() => loader().catch((err) => { if (reloadOnceForStaleChunk()) { diff --git a/tests/components/layout/Header.test.tsx b/tests/components/layout/Header.test.tsx index 7aa9a9fe..5d2f7abe 100644 --- a/tests/components/layout/Header.test.tsx +++ b/tests/components/layout/Header.test.tsx @@ -228,4 +228,41 @@ describe("Header", () => { await new Promise((r) => setTimeout(r, 20)); expect(screen.queryByTestId("whats-new-dot")).toBeNull(); }); + + 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/lib/chunk-reload.test.ts b/tests/lib/chunk-reload.test.ts index e40c4682..29ef00ea 100644 --- a/tests/lib/chunk-reload.test.ts +++ b/tests/lib/chunk-reload.test.ts @@ -17,7 +17,9 @@ import { resetViewState, initViewPersistence, } from "../../src/app/stores/view"; -import { createRoot } from "solid-js"; +import { createRoot, ErrorBoundary, Suspense } from "solid-js"; +import { render, waitFor } from "@solidjs/testing-library"; +import { lazyWithReload } from "../../src/app/App"; describe("chunk-reload", () => { const originalLocation = window.location; @@ -134,4 +136,56 @@ describe("chunk-reload", () => { dispose(); }); + + 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); + }); }); diff --git a/tests/stores/config.test.ts b/tests/stores/config.test.ts index a8774740..c0ca609b 100644 --- a/tests/stores/config.test.ts +++ b/tests/stores/config.test.ts @@ -10,8 +10,9 @@ import { ConfigSchema, TrackedUserSchema, loadConfig, config, updateConfig, resetConfig, setMonitoredRepo, addCustomTab, updateCustomTab, removeCustomTab, reorderCustomTab, getCustomTab, isBuiltinTab, CustomTabSchema, updateJiraConfig, updateJiraCustomFields, updateJiraCustomScopes, - preParseConfigFixups, postParseConfigFixups, + preParseConfigFixups, postParseConfigFixups, initConfigPersistence, flushConfigPersistence, } from "../../src/app/stores/config"; +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"; @@ -1638,3 +1639,52 @@ 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("catches localStorage quota errors and pushes localStorage:config warning notification without throwing", () => { + 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(); + } + }); +}); From 1f253fdfcbfbd696e496f117c4b5f89e85e5572e Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Sat, 7 Nov 2026 11:29:33 -0500 Subject: [PATCH 06/11] fix(version): harden preload recovery, store flushes, and rollback state - Keep Suspense fallback active when a prevented vite:preloadError resolves a lazy route import to undefined - Guard pre-reload config and view flushes against overwriting other tabs' saved state when the current tab is clean, and move initConfigPersistence cleanup to the outer owner - Clear updateAvailable and dismiss the app-update notification when version.json reports the running build again, deduplicate shared build/changelog constants and repo links, and expand unit and E2E coverage --- docs/USER_GUIDE.md | 8 +- e2e/update.spec.ts | 38 +++++--- src/app/App.tsx | 30 ++++--- .../components/dashboard/DashboardPage.tsx | 6 +- src/app/components/layout/Header.tsx | 41 ++++----- src/app/components/settings/SettingsPage.tsx | 6 +- src/app/components/shared/ToastContainer.tsx | 4 +- src/app/components/shared/UpdateBanner.tsx | 16 ++-- src/app/components/shared/WhatsNewDialog.tsx | 89 +++++++++---------- src/app/lib/changelog.ts | 2 +- src/app/lib/chunk-reload.ts | 8 +- src/app/lib/flush-persistence.ts | 12 +++ src/app/lib/repo-links.ts | 3 + src/app/lib/version.ts | 61 ++++++------- src/app/stores/config.ts | 69 ++++++++++---- src/app/stores/view.ts | 13 ++- src/shared/build-meta.ts | 13 +++ src/shared/changelog-schema.ts | 23 +++-- tests/build/build-meta.test.ts | 8 ++ tests/components/App.test.tsx | 32 +++++++ tests/components/layout/Header.test.tsx | 28 +++++- .../components/shared/ToastContainer.test.tsx | 12 +-- tests/components/shared/UpdateBanner.test.tsx | 45 +++++++--- .../components/shared/WhatsNewDialog.test.tsx | 64 ++++++++----- tests/lib/changelog.test.ts | 12 +-- tests/lib/chunk-reload.test.ts | 40 +++++++++ tests/lib/version.test.ts | 72 +++++++++++++-- tests/stores/config.test.ts | 82 +++++++++++++++++ tests/stores/view.test.ts | 58 ++++++++++++ tests/stubs/build-meta-test-config.ts | 22 +++++ vite-plugins/build-meta.ts | 28 +++--- vitest.config.ts | 16 +--- vitest.workspace.ts | 16 +--- 33 files changed, 706 insertions(+), 271 deletions(-) create mode 100644 src/app/lib/flush-persistence.ts create mode 100644 src/app/lib/repo-links.ts create mode 100644 src/shared/build-meta.ts create mode 100644 tests/stubs/build-meta-test-config.ts diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index c4de14ff..06b7fe14 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -842,10 +842,10 @@ Encrypted credentials are sealed by this deployment's server and can only be imp GitHub Tracker checks `/version.json` in the background (30 seconds after load, when returning to a tab, and on each full poll cycle) to detect when a new build has been deployed. -- **Update Banner:** When a newer deployment is detected, a banner appears at the bottom of the screen (*"A new version is available."*) with a **Reload** button and a link to the **Changelog**, and an informational entry is added to the Notification Drawer. -- **Automatic Reload on Navigation:** If an update is waiting when you navigate between pages (for example, opening **Settings** or returning to the **Dashboard**), the app flushes any pending configuration or view-state changes to `localStorage` and performs a full page reload into the new build automatically. -- **Stale Chunk Recovery:** If a lazy-loaded page chunk from a previous deployment is no longer available before a background check runs, the app automatically flushes pending state and reloads once to load the current bundle. -- **What's New Dialog:** Click the **What's new** star icon in the dashboard header (or **What's new** in **Settings > Data > About**) to view recent release notes directly in the app. A small unread indicator dot appears on the header icon whenever a newer release has shipped since you last opened the dialog, and clears automatically once opened. +- **Update Banner:** When the deployed build differs from the one you are running, a banner appears at the bottom of the screen (*"A new version is available."*) with a **Reload** button and a link to the **Changelog**, and an informational entry is added to the Notification Drawer. If a later check reports the build you are running again (for example after a rollback), the banner and the notification go away. +- **Automatic Reload on Navigation:** If an update is waiting when you navigate between pages (for example, opening **Settings** or returning to the **Dashboard**), the app saves any pending configuration or view-state changes from this tab to `localStorage` and performs a full page reload into the new build automatically. A tab that has not changed its own settings leaves whatever another tab saved untouched. +- **Stale Chunk Recovery:** If a lazy-loaded page chunk from a previous deployment is no longer available before a background check runs, the app automatically saves pending state and reloads once to load the current bundle. +- **What's New Dialog:** Click the **What's new** star icon in the dashboard header (or **What's new** in **Settings > Data > About**) to view recent release notes directly in the app. A small unread indicator dot appears on the header icon whenever a newer release has shipped since you last opened the dialog, and clears automatically once opened. The icon's accessible label reads "What's new, unread release notes" while the dot is shown. - **Version & Changelog:** You can view the running build version (`+`, linking to [GitHub Releases](https://github.com/gordon-code/github-tracker/releases)) in **Settings > Data > About** and in the dashboard footer, and open the [Changelog](https://github.com/gordon-code/github-tracker/blob/main/CHANGELOG.md) directly from **Settings > Data > About** (as well as from the **What's New** dialog and the update banner). --- diff --git a/e2e/update.spec.ts b/e2e/update.spec.ts index 58bcf5a8..af1dceff 100644 --- a/e2e/update.spec.ts +++ b/e2e/update.spec.ts @@ -41,27 +41,39 @@ test("does not show update banner when version.json matches the running build SH page, }) => { await setupAuth(page); - let versionFetched = false; - await page.route("**/version.json", (route) => { - versionFetched = true; - return route.fulfill({ + let reportedSha = currentSha; + await page.route("**/version.json", (route) => + route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ version: "0.1.1", - sha: currentSha, + sha: reportedSha, builtAt: "2026-01-01T00:00:00.000Z", }), - }); - }); + }), + ); + const banner = page + .getByRole("status") + .filter({ hasText: "A new version is available." }); + + const firstResponse = page.waitForResponse("**/version.json"); await page.goto("/dashboard"); await expect(page.getByRole("tablist")).toBeVisible(); - await expect.poll(() => versionFetched).toBe(true); + await (await firstResponse).finished(); + // Two animation frames let the page parse the response and apply any state change. + await page.evaluate( + () => + new Promise((resolve) => { + requestAnimationFrame(() => requestAnimationFrame(() => resolve())); + }), + ); + await expect(banner).toHaveCount(0); - await expect( - page - .getByRole("status") - .filter({ hasText: "A new version is available." }), - ).toHaveCount(0); + // Control: the same check flags a different SHA, so the absence above reflects the + // SHA comparison and not a check that never ran. + reportedSha = differentSha; + await page.evaluate(() => document.dispatchEvent(new Event("visibilitychange"))); + await expect(banner).toBeVisible(); }); diff --git a/src/app/App.tsx b/src/app/App.tsx index bf08000e..66dea9d3 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -1,11 +1,12 @@ import { createSignal, createEffect, on, onMount, onCleanup, getOwner, runWithOwner, Show, ErrorBoundary, Suspense, lazy, type JSX } from "solid-js"; import { reportBoundaryError } from "./lib/sentry-facade"; import { reloadOnceForStaleChunk } from "./lib/chunk-reload"; +import { flushPersistedState } from "./lib/flush-persistence"; import { updateAvailable, reloadOncePerTarget, startVersionWatch } from "./lib/version"; import { Router, Route, Navigate, useNavigate, useLocation } from "@solidjs/router"; import { isAuthenticated, validateToken, AUTH_STORAGE_KEY } from "./stores/auth"; -import { config, initConfigPersistence, flushConfigPersistence, resolveTheme } from "./stores/config"; -import { initViewPersistence, flushViewPersistence, pruneStaleIgnoredItems } from "./stores/view"; +import { config, initConfigPersistence, resolveTheme } from "./stores/config"; +import { initViewPersistence, pruneStaleIgnoredItems } from "./stores/view"; import { evictStaleEntries, evictKeysWithPrefix } from "./stores/cache"; import UpdateBanner from "./components/shared/UpdateBanner"; import LoginPage from "./pages/LoginPage"; @@ -24,12 +25,22 @@ export function _resetAuthInitStartedForTests(): void { export function lazyWithReload(loader: Parameters[0]) { return lazy(() => - loader().catch((err) => { - if (reloadOnceForStaleChunk()) { - return new Promise(() => {}); - } - throw err; - }), + loader() + .then((mod) => { + // A cancelled `vite:preloadError` (see installChunkReloadHandler) makes Vite's + // preload helper resolve the import with `undefined` while the page reloads. + // Stay on the Suspense fallback instead of failing on a missing module. + if (mod === undefined) { + return new Promise(() => {}); + } + return mod; + }) + .catch((err) => { + if (reloadOnceForStaleChunk()) { + return new Promise(() => {}); + } + throw err; + }), ); } @@ -42,8 +53,7 @@ export function UpdateNavigator() { if (prev === undefined || path === prev) return; const info = updateAvailable(); if (info && reloadOncePerTarget(info.sha)) { - flushConfigPersistence(); - flushViewPersistence(); + flushPersistedState(); window.location.assign(path + location.search + location.hash); } }, diff --git a/src/app/components/dashboard/DashboardPage.tsx b/src/app/components/dashboard/DashboardPage.tsx index be95ed82..3d1ee9dd 100644 --- a/src/app/components/dashboard/DashboardPage.tsx +++ b/src/app/components/dashboard/DashboardPage.tsx @@ -51,12 +51,11 @@ import { isUserInvolved } from "../../lib/grouping"; import { KNOWN_CONCLUSIONS, KNOWN_EVENTS } from "../shared/filterTypes"; import { loadEmojiMap } from "../../lib/emoji"; import { mergeActiveFilters } from "../../lib/tabFilters"; +import { RELEASES_URL } from "../../lib/repo-links"; import { isSafeGitHubUrl } from "../../lib/url"; -import { displayVersion } from "../../lib/version"; +import { BUILD_TIME, displayVersion } from "../../lib/version"; import type { CustomTab } from "../../stores/config"; -const RELEASES_URL = "https://github.com/gordon-code/github-tracker/releases"; - const CustomTabModal = lazy(() => import("../shared/CustomTabModal")); // Hoisted to module scope — these are constant values (Zod schema defaults). @@ -2169,6 +2168,7 @@ export default function DashboardPage() { ([]); let cancelled = false; + let cancelScheduledLoad: (() => void) | undefined; onCleanup(() => { cancelled = true; + cancelScheduledLoad?.(); }); + function refreshChangelog() { + void (async () => { + const entries = await loadChangelog(); + if (!cancelled) setChangelogEntries(entries); + })(); + } + + // The changelog chunk is not needed to render the header, so load it when the browser is idle. onMount(() => { - const load = () => { - void (async () => { - const entries = await loadChangelog(); - if (!cancelled) setChangelogEntries(entries); - })(); - }; - if (typeof window !== "undefined" && typeof window.requestIdleCallback === "function") { - const idleId = window.requestIdleCallback(load); - onCleanup(() => { - cancelled = true; + if (typeof window.requestIdleCallback === "function") { + const idleId = window.requestIdleCallback(refreshChangelog); + cancelScheduledLoad = () => { if (typeof window.cancelIdleCallback === "function") { window.cancelIdleCallback(idleId); } - }); + }; } else { - const timerId = setTimeout(load, 0); - onCleanup(() => { - cancelled = true; - clearTimeout(timerId); - }); + const timerId = setTimeout(refreshChangelog, 0); + cancelScheduledLoad = () => clearTimeout(timerId); } }); @@ -51,12 +51,7 @@ export default function Header() { ); function handleWhatsNewClick() { - if (changelogEntries().length === 0) { - void (async () => { - const entries = await loadChangelog(); - if (!cancelled) setChangelogEntries(entries); - })(); - } + if (changelogEntries().length === 0) refreshChangelog(); setWhatsNewOpen(true); } @@ -163,7 +158,7 @@ export default function Header() { type="button" onClick={handleWhatsNewClick} class="btn btn-ghost btn-sm shrink-0 relative" - aria-label="What's new" + aria-label={showWhatsNewDot() ? "What's new, unread release notes" : "What's new"} aria-expanded={whatsNewOpen()} aria-haspopup="dialog" > diff --git a/src/app/components/settings/SettingsPage.tsx b/src/app/components/settings/SettingsPage.tsx index 9d751983..de473ca1 100644 --- a/src/app/components/settings/SettingsPage.tsx +++ b/src/app/components/settings/SettingsPage.tsx @@ -21,7 +21,8 @@ import { pushNotification, dismissNotificationBySource } from "../../lib/errors" import { buildOrgAccessUrl, buildJiraAuthorizeUrl } from "../../lib/oauth"; import { sealApiToken } from "../../lib/proxy"; import { isSafeGitHubUrl, openGitHubUrl } from "../../lib/url"; -import { displayVersion } from "../../lib/version"; +import { CHANGELOG_URL, RELEASES_URL } from "../../lib/repo-links"; +import { BUILD_TIME, displayVersion } from "../../lib/version"; import { relativeTime, formatScopeSummary } from "../../lib/format"; import { fetchOrgs } from "../../services/api"; import { getClient } from "../../services/github"; @@ -49,8 +50,6 @@ import type { RepoRef } from "../../services/api"; const VALID_JIRA_CLIENT_ID_RE = /^[A-Za-z0-9_-]+$/; const VALID_JIRA_SITE_URL_RE = /^https:\/\/[a-z0-9-]+\.atlassian\.net$/i; const VALID_JIRA_CLOUD_ID_RE = /^[a-zA-Z0-9-]+$/; -const RELEASES_URL = "https://github.com/gordon-code/github-tracker/releases"; -const CHANGELOG_URL = "https://github.com/gordon-code/github-tracker/blob/main/CHANGELOG.md"; interface NumberSelectOption { value: number; @@ -2136,6 +2135,7 @@ export default function SettingsPage() {
{(item) => { diff --git a/src/app/components/shared/UpdateBanner.tsx b/src/app/components/shared/UpdateBanner.tsx index c047c520..3ed38faa 100644 --- a/src/app/components/shared/UpdateBanner.tsx +++ b/src/app/components/shared/UpdateBanner.tsx @@ -1,11 +1,11 @@ import { createEffect, Show } from "solid-js"; import { updateAvailable } from "../../lib/version"; -import { pushNotification } from "../../lib/errors"; +import { dismissNotificationBySource, pushNotification } from "../../lib/errors"; +import { flushPersistedState } from "../../lib/flush-persistence"; +import { CHANGELOG_URL } from "../../lib/repo-links"; import { isSafeGitHubUrl } from "../../lib/url"; -import { flushConfigPersistence } from "../../stores/config"; -import { flushViewPersistence } from "../../stores/view"; -export const CHANGELOG_URL = "https://github.com/gordon-code/github-tracker/blob/main/CHANGELOG.md"; +const UPDATE_NOTIFICATION_SOURCE = "app-update"; export default function UpdateBanner() { let notified = false; @@ -15,16 +15,18 @@ export default function UpdateBanner() { if (info && !notified) { notified = true; pushNotification( - "app-update", + UPDATE_NOTIFICATION_SOURCE, "A new version of GitHub Tracker is available — reload to update.", "info", ); + } else if (!info && notified) { + notified = false; + dismissNotificationBySource(UPDATE_NOTIFICATION_SOURCE); } }); const handleReload = () => { - flushConfigPersistence(); - flushViewPersistence(); + flushPersistedState(); window.location.reload(); }; diff --git a/src/app/components/shared/WhatsNewDialog.tsx b/src/app/components/shared/WhatsNewDialog.tsx index d62a2e50..27fd145c 100644 --- a/src/app/components/shared/WhatsNewDialog.tsx +++ b/src/app/components/shared/WhatsNewDialog.tsx @@ -1,28 +1,31 @@ import { createEffect, createSignal, For, onCleanup, Show, untrack } from "solid-js"; import { Dialog } from "@kobalte/core/dialog"; -import type { ChangelogEntry } from "../../../shared/changelog-schema"; +import { + CHANGELOG_MAX_ITEM_TEXT_LENGTH, + COMMIT_SHA_RE, + type ChangelogEntry, +} from "../../../shared/changelog-schema"; import { isStrictSemver, loadChangelog } from "../../lib/changelog"; +import { CHANGELOG_URL, REPO_URL } from "../../lib/repo-links"; import { isSafeGitHubUrl } from "../../lib/url"; -import { APP_VERSION } from "../../lib/version"; +import { getAppVersion } from "../../lib/version"; import { config, updateConfig } from "../../stores/config"; -const REPO_BASE_URL = "https://github.com/gordon-code/github-tracker"; -const CHANGELOG_URL = `${REPO_BASE_URL}/blob/main/CHANGELOG.md`; -const HEX_SHA_RE = /^[0-9a-f]{7,40}$/; - -function buildPrUrl(pr: number | undefined): string | undefined { +// Entries arrive schema-validated, but the `entries` prop is public, so every link +// derived from entry data is re-checked here before it reaches an href. +function buildPrLink(pr: number | undefined): { href: string; label: string } | undefined { if (typeof pr !== "number" || !Number.isInteger(pr) || pr <= 0) return undefined; - const url = `${REPO_BASE_URL}/pull/${pr}`; - return isSafeGitHubUrl(url) ? url : undefined; + const href = `${REPO_URL}/pull/${pr}`; + return isSafeGitHubUrl(href) ? { href, label: `#${pr}` } : undefined; } -function buildCommitUrl(sha: string | undefined): string | undefined { - if (typeof sha !== "string" || !HEX_SHA_RE.test(sha)) return undefined; - const url = `${REPO_BASE_URL}/commit/${sha}`; - return isSafeGitHubUrl(url) ? url : undefined; +function buildCommitLink(sha: string | undefined): { href: string; label: string } | undefined { + if (typeof sha !== "string" || !COMMIT_SHA_RE.test(sha)) return undefined; + const href = `${REPO_URL}/commit/${sha}`; + return isSafeGitHubUrl(href) ? { href, label: `(${sha.slice(0, 7)})` } : undefined; } -export interface WhatsNewDialogProps { +interface WhatsNewDialogProps { open: boolean; onOpenChange: (open: boolean) => void; entries?: readonly ChangelogEntry[]; @@ -33,8 +36,9 @@ export default function WhatsNewDialog(props: WhatsNewDialogProps) { createEffect(() => { if (!props.open) return; - if (isStrictSemver(APP_VERSION) && untrack(() => config.lastSeenVersion) !== APP_VERSION) { - updateConfig({ lastSeenVersion: APP_VERSION }); + const appVersion = getAppVersion(); + if (isStrictSemver(appVersion) && untrack(() => config.lastSeenVersion) !== appVersion) { + updateConfig({ lastSeenVersion: appVersion }); } if (props.entries === undefined) { let cancelled = false; @@ -49,7 +53,6 @@ export default function WhatsNewDialog(props: WhatsNewDialogProps) { }); const entries = () => props.entries ?? loadedEntries(); - const fullChangelogHref = () => (isSafeGitHubUrl(CHANGELOG_URL) ? CHANGELOG_URL : undefined); return ( @@ -109,37 +112,37 @@ export default function WhatsNewDialog(props: WhatsNewDialogProps) {
{/* Footer */} - - {(href) => ( - - )} - + diff --git a/src/app/lib/changelog.ts b/src/app/lib/changelog.ts index 802e5e85..546a36b0 100644 --- a/src/app/lib/changelog.ts +++ b/src/app/lib/changelog.ts @@ -66,6 +66,6 @@ export function hasUnseen( } /** @internal Test-only helper to clear cached changelog promise */ -export function _resetChangelogCacheForTest(): void { +export function _resetChangelogCacheForTests(): void { cachedChangelogPromise = null; } diff --git a/src/app/lib/chunk-reload.ts b/src/app/lib/chunk-reload.ts index 53023db5..3d8ce2bf 100644 --- a/src/app/lib/chunk-reload.ts +++ b/src/app/lib/chunk-reload.ts @@ -1,5 +1,4 @@ -import { flushConfigPersistence } from "../stores/config"; -import { flushViewPersistence } from "../stores/view"; +import { flushPersistedState } from "./flush-persistence"; export const CHUNK_RELOAD_KEY = "github-tracker:chunk-reload"; export const CHUNK_RELOAD_MAX_AGE = 10_000; @@ -10,8 +9,7 @@ export function reloadOnceForStaleChunk(): boolean { const last = sessionStorage.getItem(CHUNK_RELOAD_KEY); if (!last || now - Number(last) > CHUNK_RELOAD_MAX_AGE) { sessionStorage.setItem(CHUNK_RELOAD_KEY, String(now)); - flushConfigPersistence(); - flushViewPersistence(); + flushPersistedState(); window.location.reload(); return true; } @@ -21,7 +19,7 @@ export function reloadOnceForStaleChunk(): boolean { return false; } -export function handleVitePreloadError(event: Event): void { +function handleVitePreloadError(event: Event): void { if (reloadOnceForStaleChunk()) { event.preventDefault(); } diff --git a/src/app/lib/flush-persistence.ts b/src/app/lib/flush-persistence.ts new file mode 100644 index 00000000..e519e149 --- /dev/null +++ b/src/app/lib/flush-persistence.ts @@ -0,0 +1,12 @@ +import { flushConfigPersistence } from "../stores/config"; +import { flushViewPersistence } from "../stores/view"; + +/** + * Synchronously commits any debounced config/view-state writes. Call immediately + * before unloading the page (reload or full navigation), where the debounce + * timers would otherwise be discarded. + */ +export function flushPersistedState(): void { + flushConfigPersistence(); + flushViewPersistence(); +} diff --git a/src/app/lib/repo-links.ts b/src/app/lib/repo-links.ts new file mode 100644 index 00000000..7189d608 --- /dev/null +++ b/src/app/lib/repo-links.ts @@ -0,0 +1,3 @@ +export const REPO_URL = "https://github.com/gordon-code/github-tracker"; +export const RELEASES_URL = `${REPO_URL}/releases`; +export const CHANGELOG_URL = `${REPO_URL}/blob/main/CHANGELOG.md`; diff --git a/src/app/lib/version.ts b/src/app/lib/version.ts index 8fb7969c..7ed2d764 100644 --- a/src/app/lib/version.ts +++ b/src/app/lib/version.ts @@ -1,29 +1,30 @@ import { createSignal } from "solid-js"; -import * as z from "zod/mini"; +import { BUILD_SHA_LENGTH, VersionInfoSchema, type VersionInfo } from "../../shared/build-meta"; -export let APP_VERSION: string = __APP_VERSION__; +export { VersionInfoSchema, type VersionInfo }; + +export const APP_VERSION: string = __APP_VERSION__; export const GIT_SHA: string = __GIT_SHA__; export const BUILD_TIME: string = __BUILD_TIME__; -export function displayVersion(): string { - return `${APP_VERSION}+${GIT_SHA.slice(0, 7)}`; -} +let currentAppVersion: string = APP_VERSION; +let currentGitSha: string = GIT_SHA; -export const VersionInfoSchema = z.object({ - version: z.string().check(z.maxLength(32)), - sha: z.string().check(z.regex(/^[0-9a-f]{7,40}$|^dev$/)), - builtAt: z.string().check(z.maxLength(40)), -}); +/** The running build's version (equals `APP_VERSION`; tests can override it). */ +export function getAppVersion(): string { + return currentAppVersion; +} -export type VersionInfo = z.infer; +export function displayVersion(): string { + return `${currentAppVersion}+${GIT_SHA.slice(0, 7)}`; +} -export const UPDATE_RELOADED_SHA_KEY = "github-tracker:update-reloaded-sha"; +const UPDATE_RELOADED_SHA_KEY = "github-tracker:update-reloaded-sha"; export const VERSION_WATCH_INITIAL_DELAY_MS = 30_000; const [updateAvailable, setUpdateAvailable] = createSignal(null); export { updateAvailable }; -let currentGitSha: string = GIT_SHA; let checkInFlight: Promise | null = null; export function checkForUpdate(): Promise { @@ -40,13 +41,13 @@ export function checkForUpdate(): Promise { const raw: unknown = await res.json(); const parsed = VersionInfoSchema.safeParse(raw); if (!parsed.success) return; - if ( - currentGitSha !== "dev" && - parsed.data.sha !== "dev" && - parsed.data.sha.slice(0, 12) !== currentGitSha.toLowerCase().slice(0, 12) - ) { - setUpdateAvailable(parsed.data); - } + if (currentGitSha === "dev" || parsed.data.sha === "dev") return; + const sameBuild = + parsed.data.sha.slice(0, BUILD_SHA_LENGTH) === + currentGitSha.toLowerCase().slice(0, BUILD_SHA_LENGTH); + // The deployed build is authoritative: it clears a previously flagged update + // when the server reports the running build again (e.g. after a rollback). + setUpdateAvailable(sameBuild ? null : parsed.data); } catch { // Best-effort — network errors or non-JSON bodies are ignored silently. } finally { @@ -57,7 +58,7 @@ export function checkForUpdate(): Promise { } export function reloadOncePerTarget(targetSha: string): boolean { - const normalized = targetSha.slice(0, 12); + const normalized = targetSha.slice(0, BUILD_SHA_LENGTH); if (!normalized || normalized === "dev") return false; try { if (sessionStorage.getItem(UPDATE_RELOADED_SHA_KEY) === normalized) { @@ -88,25 +89,25 @@ export function startVersionWatch(): () => void { } /** @internal Test-only helper to set updateAvailable signal directly */ -export function _setUpdateAvailableForTest(info: VersionInfo | null): void { +export function _setUpdateAvailableForTests(info: VersionInfo | null): void { setUpdateAvailable(info); } -/** @internal Test-only helper to override local build APP_VERSION */ -export function _setAppVersionForTest(version: string): void { - APP_VERSION = version; +/** @internal Test-only helper to override the running build's version */ +export function _setAppVersionForTests(version: string): void { + currentAppVersion = version; } -/** @internal Test-only helper to override local build GIT_SHA */ -export function _setGitShaForTest(sha: string): void { +/** @internal Test-only helper to override the running build's git SHA */ +export function _setGitShaForTests(sha: string): void { currentGitSha = sha; } /** @internal Test-only helper to reset version checker state */ -export function _resetVersionStateForTest(): void { - APP_VERSION = __APP_VERSION__; - setUpdateAvailable(null); +export function _resetVersionStateForTests(): void { + currentAppVersion = APP_VERSION; currentGitSha = GIT_SHA; + setUpdateAvailable(null); checkInFlight = null; try { sessionStorage.removeItem(UPDATE_RELOADED_SHA_KEY); diff --git a/src/app/stores/config.ts b/src/app/stores/config.ts index a8de310c..81c7fafd 100644 --- a/src/app/stores/config.ts +++ b/src/app/stores/config.ts @@ -1,5 +1,5 @@ import { createStore, produce } from "solid-js/store"; -import { createEffect, onCleanup, untrack } from "solid-js"; +import { createEffect, createSignal, onCleanup, untrack } from "solid-js"; import { pushNotification } from "../lib/errors"; import { viewState, updateViewState } from "./view"; import { ConfigSchema, type RepoRefSchema, THEME_OPTIONS, BUILTIN_TAB_IDS, CustomTabSchema } from "../../shared/schemas"; @@ -90,7 +90,18 @@ export function loadConfig(): Config { } } -export const [config, setConfig] = createStore(loadConfig()); +const [config, _setConfig] = createStore(loadConfig()); +let configDirty = false; +const [persistTrigger, setPersistTrigger] = createSignal(0); + +export { config }; + +export const setConfig: typeof _setConfig = (...args: unknown[]) => { + const result = (_setConfig as (...a: unknown[]) => unknown)(...args); + configDirty = true; + setPersistTrigger((n) => n + 1); + return result; +}; export function updateConfig(partial: Partial): void { const validated = z.partial(ConfigSchema).safeParse(partial); @@ -230,40 +241,64 @@ export function reorderCustomTab(id: string, direction: "up" | "down"): void { let debounceTimer: ReturnType | undefined; let pendingJson: string | undefined; +// The config this tab last loaded from, or wrote to, localStorage. Config is not synced +// between tabs, so writing this tab's whole config when it has no changes of its own +// would overwrite a newer config another tab saved in the meantime. +let lastPersistedJson = JSON.stringify(config); + +function writeConfigJson(json: string): boolean { + try { + localStorage.setItem(CONFIG_STORAGE_KEY, json); + lastPersistedJson = json; + configDirty = false; + return true; + } catch { + return false; + } +} +/** + * Synchronously commits a debounced config change before the page unloads. A no-op + * when this tab has not changed its config since it loaded or last wrote it. + */ export function flushConfigPersistence(): void { clearTimeout(debounceTimer); debounceTimer = undefined; pendingJson = undefined; - try { - const json = JSON.stringify(untrack(() => config)); - localStorage.setItem(CONFIG_STORAGE_KEY, json); - } catch { + const json = JSON.stringify(untrack(() => config)); + if (!configDirty && json === lastPersistedJson) return; + if (!writeConfigJson(json)) { pushNotification("localStorage:config", "Config write failed — storage may be full", "warning"); } } export function initConfigPersistence(): void { + lastPersistedJson = JSON.stringify(untrack(() => config)); + configDirty = false; + createEffect(() => { + persistTrigger(); const snapshot = JSON.parse(JSON.stringify(config)) as Config; const json = JSON.stringify(snapshot); pendingJson = json; clearTimeout(debounceTimer); debounceTimer = setTimeout(() => { pendingJson = undefined; - try { - localStorage.setItem(CONFIG_STORAGE_KEY, json); - } catch { + if (!writeConfigJson(json)) { pushNotification("localStorage:config", "Config write failed — storage may be full", "warning"); } }, 200); - onCleanup(() => { - clearTimeout(debounceTimer); - debounceTimer = undefined; - if (pendingJson !== undefined) { - try { localStorage.setItem(CONFIG_STORAGE_KEY, pendingJson); } catch { /* best-effort */ } - pendingJson = undefined; - } - }); + }); + + // Registered on the outer owner rather than inside createEffect so effect + // re-runs on intermediate config mutations do not synchronously flush stale + // pendingJson or prematurely clear configDirty. + onCleanup(() => { + clearTimeout(debounceTimer); + debounceTimer = undefined; + if (pendingJson !== undefined) { + writeConfigJson(pendingJson); + pendingJson = undefined; + } }); } diff --git a/src/app/stores/view.ts b/src/app/stores/view.ts index e208b49c..2afa0591 100644 --- a/src/app/stores/view.ts +++ b/src/app/stores/view.ts @@ -1,6 +1,6 @@ import * as z from "zod/mini"; import { createStore, produce } from "solid-js/store"; -import { createEffect, onCleanup, untrack } from "solid-js"; +import { createEffect, createSignal, onCleanup, untrack } from "solid-js"; import { pushNotification } from "../lib/errors"; export const VIEW_STORAGE_KEY = "github-tracker:view"; @@ -209,6 +209,7 @@ const REPO_STATE_TAB_IDS = ["issues", "pullRequests", "actions", "jiraAssigned"] const VIEW_STATE_KEYS = new Set(Object.keys(ViewStateSchema.shape)); let fullOverwritePending = false; const forcedKeysPending = new Set(); +const [persistTrigger, setPersistTrigger] = createSignal(0); /** * Top-level ViewState keys included in a settings export's `_viewPreferences` @@ -348,6 +349,7 @@ export function applyImportedViewState(raw: unknown): void { Object.assign(draft, patch); }) ); + setPersistTrigger((n) => n + 1); } catch { // Silent no-op, matching this function's documented silent-skip semantics. } @@ -457,6 +459,7 @@ export function resetViewState(): void { }); }) ); + setPersistTrigger((n) => n + 1); } // KNOWN LIMITATION: ViewStateSchema.pick() only prevents inflation of TOP-LEVEL fields @@ -933,6 +936,13 @@ export function flushViewPersistence(): void { debounceTimer = undefined; pendingSnapshot = undefined; const snapshot = JSON.parse(JSON.stringify(untrack(() => viewState))) as Record; + if ( + !fullOverwritePending && + forcedKeysPending.size === 0 && + JSON.stringify(snapshot) === JSON.stringify(lastSyncedSnapshot) + ) { + return; + } commitSnapshot(snapshot); } @@ -966,6 +976,7 @@ export function initViewPersistence(): void { forcedKeysPending.clear(); createEffect(() => { + persistTrigger(); const json = JSON.stringify(viewState); // synchronous read → tracked by SolidJS const snapshot = JSON.parse(json) as Record; pendingSnapshot = snapshot; diff --git a/src/shared/build-meta.ts b/src/shared/build-meta.ts new file mode 100644 index 00000000..7cc68992 --- /dev/null +++ b/src/shared/build-meta.ts @@ -0,0 +1,13 @@ +import * as z from "zod/mini"; + +/** Number of leading git SHA characters carried in builds and `version.json`. */ +export const BUILD_SHA_LENGTH = 12; + +/** Shape of `version.json`, emitted at build time and fetched to detect new deployments. */ +export const VersionInfoSchema = z.object({ + version: z.string().check(z.maxLength(32)), + sha: z.string().check(z.regex(/^[0-9a-f]{7,40}$|^dev$/)), + builtAt: z.string().check(z.maxLength(40)), +}); + +export type VersionInfo = z.infer; diff --git a/src/shared/changelog-schema.ts b/src/shared/changelog-schema.ts index ff6e63a4..6ddb922c 100644 --- a/src/shared/changelog-schema.ts +++ b/src/shared/changelog-schema.ts @@ -1,21 +1,28 @@ import * as z from "zod/mini"; -export const ChangelogItemSchema = z.object({ - text: z.string().check(z.minLength(1), z.maxLength(300)), +export const CHANGELOG_MAX_ENTRIES = 20; +export const CHANGELOG_MAX_ITEM_TEXT_LENGTH = 300; +export const CHANGELOG_MAX_SECTION_TITLE_LENGTH = 100; + +/** Lowercase hex commit SHA, abbreviated (7) through full (40). */ +export const COMMIT_SHA_RE = /^[0-9a-f]{7,40}$/; + +const ChangelogItemSchema = z.object({ + text: z.string().check(z.minLength(1), z.maxLength(CHANGELOG_MAX_ITEM_TEXT_LENGTH)), pr: z.optional(z.number().check(z.int(), z.positive())), - sha: z.optional(z.string().check(z.regex(/^[0-9a-f]{7,40}$/))), + sha: z.optional(z.string().check(z.regex(COMMIT_SHA_RE))), }); export type ChangelogItem = z.infer; -export const ChangelogSectionSchema = z.object({ - title: z.string().check(z.minLength(1), z.maxLength(100)), +const ChangelogSectionSchema = z.object({ + title: z.string().check(z.minLength(1), z.maxLength(CHANGELOG_MAX_SECTION_TITLE_LENGTH)), items: z.array(ChangelogItemSchema), }); export type ChangelogSection = z.infer; -export const ChangelogEntrySchema = z.object({ +const ChangelogEntrySchema = z.object({ version: z.string().check(z.regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/)), date: z.string().check(z.regex(/^\d{4}-\d{2}-\d{2}$/)), sections: z.array(ChangelogSectionSchema), @@ -23,6 +30,4 @@ export const ChangelogEntrySchema = z.object({ export type ChangelogEntry = z.infer; -export const ChangelogSchema = z.array(ChangelogEntrySchema).check(z.maxLength(20)); - -export type ChangelogData = z.infer; +export const ChangelogSchema = z.array(ChangelogEntrySchema).check(z.maxLength(CHANGELOG_MAX_ENTRIES)); diff --git a/tests/build/build-meta.test.ts b/tests/build/build-meta.test.ts index 32a091df..6965c9ba 100644 --- a/tests/build/build-meta.test.ts +++ b/tests/build/build-meta.test.ts @@ -400,7 +400,15 @@ describe("buildMeta Vite plugin", () => { 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); 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/layout/Header.test.tsx b/tests/components/layout/Header.test.tsx index 5d2f7abe..73a3765c 100644 --- a/tests/components/layout/Header.test.tsx +++ b/tests/components/layout/Header.test.tsx @@ -54,12 +54,12 @@ 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 { config, resetConfig, updateConfig } from "../../../src/app/stores/config"; -import { _resetChangelogCacheForTest } from "../../../src/app/lib/changelog"; +import { _resetChangelogCacheForTests, loadChangelog } from "../../../src/app/lib/changelog"; import { render, waitFor } from "@solidjs/testing-library"; beforeEach(() => { resetConfig(); - _resetChangelogCacheForTest(); + _resetChangelogCacheForTests(); mockNavigate.mockClear(); vi.mocked(authStore.clearAuth).mockClear(); vi.mocked(errorsModule.getUnreadCount).mockReturnValue(0); @@ -225,8 +225,30 @@ describe("Header", () => { updateConfig({ lastSeenVersion: "0.1.0" }); render(() =>
); - await new Promise((r) => setTimeout(r, 20)); + // 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 () => { diff --git a/tests/components/shared/ToastContainer.test.tsx b/tests/components/shared/ToastContainer.test.tsx index 755428b5..fe013fad 100644 --- a/tests/components/shared/ToastContainer.test.tsx +++ b/tests/components/shared/ToastContainer.test.tsx @@ -14,8 +14,8 @@ import ToastContainer, { TOAST_REPEAT_COOLDOWN_MS, } from "../../../src/app/components/shared/ToastContainer"; import { - _setUpdateAvailableForTest, - _resetVersionStateForTest, + _setUpdateAvailableForTests, + _resetVersionStateForTests, } from "../../../src/app/lib/version"; // Mirrors the private TOASTED_MESSAGES_KEY constant in ToastContainer.tsx — @@ -41,14 +41,14 @@ beforeEach(() => { clearNotifications(); clearMutedSources(); resetToastState(); - _resetVersionStateForTest(); + _resetVersionStateForTests(); vi.useFakeTimers(); // Ensure matchMedia returns non-reduced-motion vi.spyOn(window, "matchMedia").mockReturnValue({ matches: false } as MediaQueryList); }); afterEach(() => { - _resetVersionStateForTest(); + _resetVersionStateForTests(); vi.useRealTimers(); vi.restoreAllMocks(); }); @@ -546,7 +546,7 @@ describe("ToastContainer", () => { expect(wrapper.className).toContain("bottom-4"); expect(wrapper.className).not.toContain("bottom-20"); - _setUpdateAvailableForTest({ + _setUpdateAvailableForTests({ version: "0.1.2", sha: "fedcba987654", builtAt: "2026-01-02T00:00:00.000Z", @@ -554,7 +554,7 @@ describe("ToastContainer", () => { expect(wrapper.className).toContain("bottom-20"); expect(wrapper.className).not.toContain("bottom-4"); - _setUpdateAvailableForTest(null); + _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 index 9f9805fb..ee213f46 100644 --- a/tests/components/shared/UpdateBanner.test.tsx +++ b/tests/components/shared/UpdateBanner.test.tsx @@ -2,11 +2,11 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { render, screen, fireEvent } from "@solidjs/testing-library"; import { MemoryRouter, Route, useNavigate, createMemoryHistory } from "@solidjs/router"; import { createRoot } from "solid-js"; -import UpdateBanner, { CHANGELOG_URL } from "../../../src/app/components/shared/UpdateBanner"; +import UpdateBanner from "../../../src/app/components/shared/UpdateBanner"; import { UpdateNavigator } from "../../../src/app/App"; import { - _setUpdateAvailableForTest, - _resetVersionStateForTest, + _setUpdateAvailableForTests, + _resetVersionStateForTests, } from "../../../src/app/lib/version"; import { getNotifications, @@ -34,7 +34,7 @@ describe("UpdateBanner & UpdateNavigator", () => { vi.useFakeTimers(); sessionStorage.clear(); localStorage.clear(); - _resetVersionStateForTest(); + _resetVersionStateForTests(); resetNotificationState(); resetConfig(); resetViewState(); @@ -56,7 +56,7 @@ describe("UpdateBanner & UpdateNavigator", () => { }); afterEach(() => { - _resetVersionStateForTest(); + _resetVersionStateForTests(); resetNotificationState(); Object.defineProperty(window, "location", { configurable: true, @@ -76,7 +76,7 @@ describe("UpdateBanner & UpdateNavigator", () => { it("renders banner with Reload button and exact Changelog link when updateAvailable is set, and pushes app-update notification once", () => { render(() => ); - _setUpdateAvailableForTest({ + _setUpdateAvailableForTests({ version: "0.1.2", sha: "fedcba987654", builtAt: "2026-01-02T00:00:00.000Z", @@ -86,7 +86,9 @@ describe("UpdateBanner & UpdateNavigator", () => { expect(banner.textContent).toContain("A new version is available."); const changelogLink = screen.getByRole("link", { name: "Changelog" }); - expect(changelogLink.getAttribute("href")).toBe(CHANGELOG_URL); + 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"); @@ -98,7 +100,7 @@ describe("UpdateBanner & UpdateNavigator", () => { ); // Updating signal again must not duplicate or re-push the notification - _setUpdateAvailableForTest({ + _setUpdateAvailableForTests({ version: "0.1.3", sha: "111122223333", builtAt: "2026-01-03T00:00:00.000Z", @@ -106,6 +108,27 @@ describe("UpdateBanner & UpdateNavigator", () => { expect(getNotifications().filter((n) => n.source === "app-update")).toHaveLength(1); }); + 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(); + expect(getNotifications().filter((n) => n.source === "app-update")).toHaveLength(1); + }); + it("flushes pending config and viewState persistence before calling window.location.reload()", () => { let disposePersistence!: () => void; createRoot((d) => { @@ -114,7 +137,7 @@ describe("UpdateBanner & UpdateNavigator", () => { initViewPersistence(); }); - _setUpdateAvailableForTest({ + _setUpdateAvailableForTests({ version: "0.1.2", sha: "fedcba987654", builtAt: "2026-01-02T00:00:00.000Z", @@ -233,7 +256,7 @@ describe("UpdateBanner & UpdateNavigator", () => { )); - _setUpdateAvailableForTest({ + _setUpdateAvailableForTests({ version: "0.1.2", sha: "fedcba987654", builtAt: "2026-01-02T00:00:00.000Z", @@ -285,7 +308,7 @@ describe("UpdateBanner & UpdateNavigator", () => { )); - _setUpdateAvailableForTest({ + _setUpdateAvailableForTests({ version: "0.1.2", sha: "fedcba987654", builtAt: "2026-01-02T00:00:00.000Z", diff --git a/tests/components/shared/WhatsNewDialog.test.tsx b/tests/components/shared/WhatsNewDialog.test.tsx index 84c823bf..e553ec7d 100644 --- a/tests/components/shared/WhatsNewDialog.test.tsx +++ b/tests/components/shared/WhatsNewDialog.test.tsx @@ -1,28 +1,29 @@ import { readFileSync } from "node:fs"; import { resolve } from "node:path"; -import { describe, it, expect, beforeEach, afterEach } from "vitest"; +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 } from "../../../src/app/stores/config"; -import { _resetChangelogCacheForTest, loadChangelog } from "../../../src/app/lib/changelog"; +import * as changelogModule from "../../../src/app/lib/changelog"; +import { _resetChangelogCacheForTests } from "../../../src/app/lib/changelog"; import { APP_VERSION, - _resetVersionStateForTest, - _setAppVersionForTest, + _resetVersionStateForTests, + _setAppVersionForTests, } from "../../../src/app/lib/version"; import type { ChangelogEntry } from "../../../src/shared/changelog-schema"; describe("WhatsNewDialog", () => { beforeEach(() => { resetConfig(); - _resetVersionStateForTest(); - _resetChangelogCacheForTest(); + _resetVersionStateForTests(); + _resetChangelogCacheForTests(); }); afterEach(() => { resetConfig(); - _resetVersionStateForTest(); - _resetChangelogCacheForTest(); + _resetVersionStateForTests(); + _resetChangelogCacheForTests(); }); it("renders entries with version, date, section headings, items, PR link, commit SHA link, and full changelog link", () => { @@ -141,7 +142,7 @@ describe("WhatsNewDialog", () => { // Reset and test non-strict APP_VERSION resetConfig(); - _setAppVersionForTest("0.1.0-dev"); + _setAppVersionForTests("0.1.0-dev"); render(() => ( {}} entries={[]} /> )); @@ -170,20 +171,41 @@ describe("WhatsNewDialog", () => { }); }); - it("does not throw or update state after disposal when unmounted while loadChangelog() is in flight", async () => { - _resetChangelogCacheForTest(); - const { unmount } = render(() => ( - {}} /> - )); - - // Unmount immediately while loadChangelog() is still pending - expect(() => unmount()).not.toThrow(); + 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(); + } + }); - // Let the in-flight loadChangelog() promise settle and flush microtasks - await expect(loadChangelog()).resolves.toHaveLength(2); - await Promise.resolve(); + it("keeps the footer Close button and full-changelog link available", () => { + render(() => {}} entries={[]} />); - expect(screen.queryByText("v0.1.0")).toBeNull(); + // 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", () => { diff --git a/tests/lib/changelog.test.ts b/tests/lib/changelog.test.ts index 356010e8..5e578e32 100644 --- a/tests/lib/changelog.test.ts +++ b/tests/lib/changelog.test.ts @@ -6,7 +6,7 @@ import { isStrictSemver, loadChangelog, unseenEntries, - _resetChangelogCacheForTest, + _resetChangelogCacheForTests, } from "../../src/app/lib/changelog"; const SAMPLE_ENTRIES: ChangelogEntry[] = [ @@ -34,12 +34,12 @@ const SAMPLE_ENTRIES: ChangelogEntry[] = [ describe("lib/changelog", () => { beforeEach(() => { - _resetChangelogCacheForTest(); + _resetChangelogCacheForTests(); }); afterEach(() => { vi.doUnmock("virtual:changelog"); - _resetChangelogCacheForTest(); + _resetChangelogCacheForTests(); }); it("validates strict x.y.z semver strings", () => { @@ -103,13 +103,13 @@ describe("lib/changelog", () => { const rejectedMod = await import("../../src/app/lib/changelog"); await expect(rejectedMod.loadChangelog()).resolves.toEqual([]); - // Without even calling _resetChangelogCacheForTest(), unmocking allows the next load to succeed + // 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 _resetChangelogCacheForTest() + // 2. Invalid schema payload: loadChangelog() returns [] and recovers across _resetChangelogCacheForTests() vi.resetModules(); vi.doMock("virtual:changelog", () => ({ default: { invalid: "not-an-array" }, @@ -118,7 +118,7 @@ describe("lib/changelog", () => { await expect(invalidMod.loadChangelog()).resolves.toEqual([]); vi.doUnmock("virtual:changelog"); - invalidMod._resetChangelogCacheForTest(); + 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 index 29ef00ea..626c65f7 100644 --- a/tests/lib/chunk-reload.test.ts +++ b/tests/lib/chunk-reload.test.ts @@ -1,3 +1,5 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { CHUNK_RELOAD_KEY, @@ -137,6 +139,36 @@ describe("chunk-reload", () => { 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(); @@ -188,4 +220,12 @@ describe("chunk-reload", () => { }); expect(reloadMock).toHaveBeenCalledTimes(1); }); + + 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); + }); }); diff --git a/tests/lib/version.test.ts b/tests/lib/version.test.ts index e7010570..b42ac65b 100644 --- a/tests/lib/version.test.ts +++ b/tests/lib/version.test.ts @@ -4,14 +4,16 @@ import { GIT_SHA, BUILD_TIME, displayVersion, + getAppVersion, VersionInfoSchema, updateAvailable, checkForUpdate, reloadOncePerTarget, startVersionWatch, VERSION_WATCH_INITIAL_DELAY_MS, - _setGitShaForTest, - _resetVersionStateForTest, + _setAppVersionForTests, + _setGitShaForTests, + _resetVersionStateForTests, } from "../../src/app/lib/version"; function makeJsonResponse( @@ -28,11 +30,11 @@ function makeJsonResponse( describe("version metadata", () => { beforeEach(() => { - _resetVersionStateForTest(); + _resetVersionStateForTests(); }); afterEach(() => { - _resetVersionStateForTest(); + _resetVersionStateForTests(); vi.useRealTimers(); }); @@ -47,6 +49,15 @@ describe("version metadata", () => { 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); + }); + describe("VersionInfoSchema", () => { it("accepts valid version metadata with hex SHA or 'dev'", () => { const validHex = VersionInfoSchema.safeParse({ @@ -124,6 +135,53 @@ describe("version metadata", () => { 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", @@ -164,7 +222,7 @@ describe("version metadata", () => { }); it("compares 12-char SHA prefixes case-insensitively", async () => { - _setGitShaForTest("ABCDEF1234567890ABCDEF1234567890ABCDEF12"); + _setGitShaForTests("ABCDEF1234567890ABCDEF1234567890ABCDEF12"); vi.stubGlobal( "fetch", vi.fn().mockResolvedValue( @@ -211,7 +269,7 @@ describe("version metadata", () => { }); it("never flags an update when local GIT_SHA or remote SHA is 'dev'", async () => { - _setGitShaForTest("dev"); + _setGitShaForTests("dev"); vi.stubGlobal( "fetch", vi.fn().mockResolvedValue( @@ -225,7 +283,7 @@ describe("version metadata", () => { await checkForUpdate(); expect(updateAvailable()).toBeNull(); - _setGitShaForTest(GIT_SHA); + _setGitShaForTests(GIT_SHA); vi.stubGlobal( "fetch", vi.fn().mockResolvedValue( diff --git a/tests/stores/config.test.ts b/tests/stores/config.test.ts index c0ca609b..8247d7f8 100644 --- a/tests/stores/config.test.ts +++ b/tests/stores/config.test.ts @@ -1675,7 +1675,89 @@ describe("flushConfigPersistence", () => { } }); + 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 resulting JSON matches lastPersistedJson", () => { + // 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" }); + + // Even though JSON.stringify(config) matches the previous lastPersistedJson, + // setConfig marked the store dirty so flushConfigPersistence must write it. + flushConfigPersistence(); + expect(localStorageMock.getItem(STORAGE_KEY)).not.toBeNull(); + expect(JSON.parse(localStorageMock.getItem(STORAGE_KEY) ?? "{}").authMethod).toBe("pat"); + }); + + it("does not synchronously flush stale pendingJson 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 pendingJson 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"); }); diff --git a/tests/stores/view.test.ts b/tests/stores/view.test.ts index c969487d..2905b3d3 100644 --- a/tests/stores/view.test.ts +++ b/tests/stores/view.test.ts @@ -1740,4 +1740,62 @@ describe("applyImportedViewState", () => { 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..10b6d5b6 --- /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"), + __BUILD_TIME__: JSON.stringify("2026-01-01T00:00:00.000Z"), + }, +}; diff --git a/vite-plugins/build-meta.ts b/vite-plugins/build-meta.ts index 73922a9b..6782e7e4 100644 --- a/vite-plugins/build-meta.ts +++ b/vite-plugins/build-meta.ts @@ -3,19 +3,21 @@ import { existsSync, readFileSync } from "node:fs"; import { resolve } from "node:path"; import type { Plugin } from "vite"; import * as z from "zod/mini"; +import { BUILD_SHA_LENGTH, type VersionInfo } from "../src/shared/build-meta"; 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"; +// Case-insensitive on purpose: GITHUB_SHA and `git rev-parse` output are normalized to lowercase below. const HEX_SHA_RE = /^[0-9a-f]{7,40}$/i; const VIRTUAL_CHANGELOG_ID = "virtual:changelog"; const RESOLVED_VIRTUAL_CHANGELOG_ID = "\0virtual:changelog"; -const MAX_CHANGELOG_ENTRIES = 20; -const MAX_ITEM_TEXT_LENGTH = 300; -const MAX_SECTION_TITLE_LENGTH = 100; 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*$/; @@ -68,7 +70,7 @@ function parseBulletLine(rawBullet: string): ChangelogItem | null { .replace(/__([^_]+)__/g, "$1") .replace(/\s+/g, " ") .trim() - .slice(0, MAX_ITEM_TEXT_LENGTH) + .slice(0, CHANGELOG_MAX_ITEM_TEXT_LENGTH) .trim(); if (text.length === 0) { @@ -106,7 +108,7 @@ export function parseChangelog(markdown: string): ChangelogEntry[] { const title = stripMarkdownLinks(sectionMatch[1]) .replace(/\s+/g, " ") .trim() - .slice(0, MAX_SECTION_TITLE_LENGTH) + .slice(0, CHANGELOG_MAX_SECTION_TITLE_LENGTH) .trim(); if (title.length > 0) { const existing = currentEntry.sections.find((s) => s.title === title); @@ -135,17 +137,11 @@ export function parseChangelog(markdown: string): ChangelogEntry[] { for (const entry of entries) { entry.sections = entry.sections.filter((s) => s.items.length > 0); } - const cleaned = entries.slice(0, MAX_CHANGELOG_ENTRIES); + const cleaned = entries.slice(0, CHANGELOG_MAX_ENTRIES); return z.parse(ChangelogSchema, cleaned); } -export interface BuildMetadata { - version: string; - sha: string; - builtAt: string; -} - export function resolveGitSha(): string { const envSha = process.env.GITHUB_SHA?.trim(); let rawSha: string; @@ -164,7 +160,7 @@ export function resolveGitSha(): string { if (!HEX_SHA_RE.test(rawSha)) { return "dev"; } - return rawSha.toLowerCase().slice(0, 12); + return rawSha.toLowerCase().slice(0, BUILD_SHA_LENGTH); } export function resolvePackageVersion(): string { @@ -175,7 +171,7 @@ export function resolvePackageVersion(): string { : "0.0.0"; } -export function resolveBuildMetadata(): BuildMetadata { +export function resolveBuildMetadata(): VersionInfo { return { version: resolvePackageVersion(), sha: resolveGitSha(), @@ -215,9 +211,7 @@ export function buildMeta(): Plugin[] { return null; } const changelogPath = resolve(process.cwd(), "CHANGELOG.md"); - if (typeof this.addWatchFile === "function") { - this.addWatchFile(changelogPath); - } + this.addWatchFile(changelogPath); if (!existsSync(changelogPath)) { return "export default [];"; } diff --git a/vitest.config.ts b/vitest.config.ts index ae43d40b..184bdbc5 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,26 +1,14 @@ -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; import { defineConfig } from "vitest/config"; import solid from "vite-plugin-solid"; import tailwindcss from "@tailwindcss/vite"; - -const rootDir = dirname(fileURLToPath(import.meta.url)); +import { buildMetaTestConfig } from "./tests/stubs/build-meta-test-config"; // 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()], - resolve: { - alias: { - "virtual:changelog": resolve(rootDir, "tests/stubs/virtual-changelog.ts"), - }, - }, - define: { - __APP_VERSION__: JSON.stringify("0.1.0"), - __GIT_SHA__: JSON.stringify("abcdef123456"), - __BUILD_TIME__: JSON.stringify("2026-01-01T00:00:00.000Z"), - }, + ...buildMetaTestConfig, test: { environment: "happy-dom", globals: true, diff --git a/vitest.workspace.ts b/vitest.workspace.ts index a3856f62..ff0b8a49 100644 --- a/vitest.workspace.ts +++ b/vitest.workspace.ts @@ -1,11 +1,8 @@ -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; import { defineConfig, defineProject } from "vitest/config"; import { cloudflareTest } from "@cloudflare/vitest-plugin"; import solid from "vite-plugin-solid"; import tailwindcss from "@tailwindcss/vite"; - -const rootDir = dirname(fileURLToPath(import.meta.url)); +import { buildMetaTestConfig } from "./tests/stubs/build-meta-test-config"; export default defineConfig({ test: { @@ -15,16 +12,7 @@ export default defineConfig({ // Browser/DOM tests (stores, services, UI) defineProject({ plugins: [solid(), tailwindcss()], - resolve: { - alias: { - "virtual:changelog": resolve(rootDir, "tests/stubs/virtual-changelog.ts"), - }, - }, - define: { - __APP_VERSION__: JSON.stringify("0.1.0"), - __GIT_SHA__: JSON.stringify("abcdef123456"), - __BUILD_TIME__: JSON.stringify("2026-01-01T00:00:00.000Z"), - }, + ...buildMetaTestConfig, test: { name: "browser", environment: "happy-dom", From 69de26787e7ffe9c7fa9213a8b6f04d3f7b98a7c Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Sat, 7 Nov 2026 16:20:43 -0500 Subject: [PATCH 07/11] fix(version): sync settings across tabs and lock out-of-date tabs Persist config and view state through a shared per-key factory: each tab writes only the keys it changed on top of the validated stored blob, and adopts other tabs' changes live (storage events, boot reconcile). Resets, imports and failed writes keep their full-overwrite and forced-key state. Fingerprint the persisted schemas at build time (JSON Schema plus the .refine limits in PERSISTED_LIMITS) and ship it in version.json. A tab whose fingerprint differs from the deployed build stops saving, shows a banner and disables Settings; onboarding, login import and token sign-in refuse until it reloads. Also: - pause persistence after another tab changes the token until the account is confirmed, and discard unsaved keys on that change - reload on a failed chunk load only once a newer deploy is known - run tagged E2E specs on Firefox and WebKit in a separate CI job - verify the live version.json after deploy and probe it in the WAF test - drop BUILD_TIME from the bundle, move lazyWithReload and UpdateNavigator into their own modules, and fold unseenEntries into hasUnseen - reset poll seen-item state when selected or upstream repos change - strip htmlUrl and jiraStatus from imported tracked items --- .github/actions/verify/action.yml | 3 +- .github/workflows/ci.yml | 13 + .github/workflows/deploy.yml | 22 + .oxlintrc.json | 2 +- CONTRIBUTING.md | 5 +- DEPLOY.md | 3 +- docs/USER_GUIDE.md | 12 +- e2e/settings.spec.ts | 4 +- e2e/update.spec.ts | 84 ++- package.json | 1 + playwright.config.ts | 11 + scripts/waf-smoke-test.sh | 1 + src/app/App.tsx | 49 +- .../components/dashboard/DashboardPage.tsx | 14 +- .../onboarding/OnboardingWizard.tsx | 15 +- .../components/settings/CustomTabsSection.tsx | 5 +- src/app/components/settings/SettingsPage.tsx | 22 +- src/app/components/settings/ThemePicker.tsx | 11 +- src/app/components/shared/UpdateBanner.tsx | 13 +- src/app/components/shared/UpdateNavigator.tsx | 31 ++ src/app/components/shared/WhatsNewDialog.tsx | 11 +- src/app/lib/changelog.ts | 20 +- src/app/lib/chunk-reload.ts | 45 +- src/app/lib/field-persistence.ts | 225 ++++++++ src/app/lib/persisted-fields.ts | 94 ++++ src/app/lib/repo-links.ts | 1 + src/app/lib/settings-transfer.ts | 3 +- src/app/lib/version.ts | 63 ++- src/app/pages/LoginPage.tsx | 11 + src/app/services/poll.ts | 25 +- src/app/stores/auth.ts | 39 +- src/app/stores/config.ts | 172 +++--- src/app/stores/view.ts | 491 +++++------------- src/shared/build-meta.ts | 18 +- src/shared/changelog-schema.ts | 4 +- src/shared/schemas.ts | 8 +- src/shared/view-schema.ts | 209 ++++++++ src/types/build-meta.d.ts | 2 +- tests/build/build-meta.test.ts | 112 +++- tests/components/LoginPage.test.tsx | 44 ++ .../onboarding/OnboardingWizard.test.tsx | 40 +- .../components/settings/SettingsPage.test.tsx | 46 ++ .../components/settings/ThemePicker.test.tsx | 46 +- tests/components/shared/UpdateBanner.test.tsx | 193 +------ .../shared/UpdateNavigator.test.tsx | 214 ++++++++ .../components/shared/WhatsNewDialog.test.tsx | 25 +- tests/lib/changelog.test.ts | 32 +- tests/lib/chunk-reload.test.ts | 150 +++++- tests/lib/field-persistence.test.ts | 415 +++++++++++++++ tests/lib/persisted-fields.test.ts | 72 +++ tests/lib/version.test.ts | 129 ++++- tests/services/poll-repo-scope.test.ts | 82 +++ tests/services/poll.test.ts | 2 + tests/stores/auth.test.ts | 191 +++++++ tests/stores/config.test.ts | 461 +++++++++++++++- tests/stores/view-jira-order.test.ts | 12 +- tests/stores/view.test.ts | 336 +++++++++++- tests/stubs/build-meta-test-config.ts | 2 +- vite-plugins/build-meta.ts | 87 +++- vite.config.ts | 2 +- vitest.config.ts | 2 +- vitest.smoke.config.ts | 2 +- vitest.workspace.ts | 2 +- 63 files changed, 3611 insertions(+), 850 deletions(-) create mode 100644 src/app/components/shared/UpdateNavigator.tsx create mode 100644 src/app/lib/field-persistence.ts create mode 100644 src/app/lib/persisted-fields.ts create mode 100644 src/shared/view-schema.ts create mode 100644 tests/components/shared/UpdateNavigator.test.tsx create mode 100644 tests/lib/field-persistence.test.ts create mode 100644 tests/lib/persisted-fields.test.ts create mode 100644 tests/services/poll-repo-scope.test.ts diff --git a/.github/actions/verify/action.yml b/.github/actions/verify/action.yml index bb1531ca..dc8e526d 100644 --- a/.github/actions/verify/action.yml +++ b/.github/actions/verify/action.yml @@ -36,7 +36,8 @@ 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. + # 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. - name: Run E2E tests shell: bash run: pnpm test:e2e diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4d031dc4..5b189f7d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,3 +12,16 @@ 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. + 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..06d7e83e 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -50,3 +50,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: ${{ github.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..c3c26fac 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -37,6 +37,7 @@ 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: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 +53,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 +77,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..ce8d2df3 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 `