Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"test": "bun scripts/test.ts",
"test:changed": "bun scripts/test.ts --changed=dev",
"typecheck": "bun x tsc --noEmit",
"typecheck:gui:if-changed": "bun scripts/typecheck-gui-if-changed.ts",
"audit:high": "bun audit --audit-level=high && cd gui && bun audit --audit-level=high",
"privacy:scan": "bun scripts/privacy-scan.ts",
"favicons": "bun scripts/brand-favicons.ts",
Expand All @@ -69,7 +70,7 @@
"prepublishOnly": "bun run audit:high && bun run typecheck && bun run build:gui",
"release": "bun scripts/release.ts",
"release:watch": "bun scripts/release.ts watch",
"prepush": "bun run typecheck && bun run lint:gui:if-changed && bun run test && bun run privacy:scan && bun run doctor:gui:if-changed",
"prepush": "bun run typecheck && bun run typecheck:gui:if-changed && bun run lint:gui:if-changed && bun run test && bun run privacy:scan && bun run doctor:gui:if-changed",
"lint:gui": "cd gui && bun run lint",
"lint:gui:if-changed": "bun scripts/lint-gui-if-changed.ts",
"doctor:gui": "cd gui && bun run doctor",
Expand Down
1 change: 1 addition & 0 deletions scripts/test-layout/layout.json
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@
"chutes-provider.test.ts": "providers",
"ci-bun-crash-classifier.test.ts": "ci-workflows",
"ci-crash-disposition.test.ts": "ci-workflows",
"ci-gui-typecheck-gate.test.ts": "ci-workflows",
"ci-privacy-gate.test.ts": "ci-workflows",
"ci-review-lanes.test.ts": "ci-workflows",
"ci-scope-reduction.test.ts": "ci-workflows",
Expand Down
106 changes: 106 additions & 0 deletions scripts/typecheck-gui-if-changed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/**
* Run the GUI TypeScript build when this push includes gui/ changes.
* Used by "bun run prepush".
*
* Mirrors "scripts/lint-gui-if-changed.ts" so local push validation stays in
* one shape: root "typecheck" cannot see gui/ (no project references), so the
* gui compile check must run separately or a gui compile error ships silently
* to a fork pull request where no CI lane would catch it (#6471).
* "tsc -b" is local and deterministic, so a failure always fails the push —
* there is no soft-skip path.
*
* The base is the merge base with the integration branch (upstream/dev, then origin/dev, then
* dev, the order "test:changed" uses), not "@{u}": "prepush" is a package script, not a git hook,
* so it never sees the push destination, and a tracking branch can already hold a GUI change
* the destination lacks. Everything the branch adds over dev is a superset of any push range.
* Paths are read NUL-delimited so a quoted non-ASCII name still matches "gui/", and with rename
* detection off so a file moved out of gui/ still reports its gui/ source path. When no base
* resolves or the diff itself fails, the check runs rather than reading the failure as "no
* gui/ changes".
*
* Test hooks: TYPECHECK_DRY_RUN=1 prints the run/skip decision without
* spawning; TYPECHECK_FILES (newline-separated) overrides git-derived changed
* files; TYPECHECK_CMD overrides the spawned command (a JSON array of argv, or a
* space-separated string). The default command runs via process.execPath so the
* gate uses the same bun that launched it instead of trusting PATH.
*/
import { spawnSync } from "node:child_process";
import { join, resolve } from "node:path";

/** True when any changed path is the gui directory or inside it (slash-guarded). */
function guiPathsChanged(files: string[]): boolean {
return files.some(f => f === "gui" || f.startsWith("gui/"));
}

if (import.meta.main) {
const repoRoot = resolve(import.meta.dirname, "..");
const guiDir = join(repoRoot, "gui");

const hasRef = (ref: string): boolean => {
try {
const probe = spawnSync("git", ["rev-parse", "--verify", ref], {
cwd: repoRoot,
stdio: "ignore",
});
return probe.status === 0;
} catch {
return false;
}
};

/** Changed paths for the range, or null when git could not produce them. */
const diffNames = (range: string): string[] | null => {
try {
const diff = spawnSync("git", ["diff", "--name-only", "-z", "--no-renames", range], {
cwd: repoRoot,
encoding: "utf8",
});
if (diff.status !== 0) return null;
return (diff.stdout ?? "").split("\0").filter(Boolean);
} catch {
return null;
}
};

// null: no usable base, or the diff failed. Either way the check runs.
let files: string[] | null;
if (process.env.TYPECHECK_FILES !== undefined) {
files = process.env.TYPECHECK_FILES.split(/\r?\n/).map(f => f.trim()).filter(Boolean);
} else {
const base = ["upstream/dev", "origin/dev", "dev"].find(hasRef);
files = base ? diffNames(`${base}...HEAD`) : null;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

const shouldRun = files === null || guiPathsChanged(files);

if (process.env.TYPECHECK_DRY_RUN === "1") {
console.log(shouldRun ? "typecheck:run" : "typecheck:skip");
process.exit(0);
}

if (!shouldRun) {
console.log("typecheck:gui: skip (no gui/ changes in push range)");
process.exit(0);
}

console.log("typecheck:gui: gui/ changed — running tsc -b (trigger=gui-changed, scope=gui project)");
const override = process.env.TYPECHECK_CMD;
const [cmd, ...args]: string[] = override
? (override.trimStart().startsWith("[") ? JSON.parse(override) as string[] : override.split(" "))
: [process.execPath, "x", "tsc", "-b"];

const result = spawnSync(cmd!, args, {
cwd: guiDir,
encoding: "utf8",
stdio: "inherit",
});

// The compiler is local and deterministic: a compile error fails the push,
// and a failed spawn is a real error, not an infrastructure soft-skip.
if (result.error) {
console.error("typecheck:gui: could not run tsc -b: " + result.error.message);
process.exit(1);
}

process.exit(result.status === null ? 1 : result.status);
}
177 changes: 177 additions & 0 deletions tests/ci-workflows/ci-gui-typecheck-gate.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import { afterEach, describe, expect, test } from "bun:test";
import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { repoPath } from "../helpers/repo-root";

/**
* Local push validation ("bun run prepush") typechecks the root project only:
* tsconfig.json has no project references, so "bun x tsc --noEmit" never parses
* gui/. A gui compile error therefore ships silently and first surfaces in CI's
* gates "GUI build" step — which a fork pull request never runs (no repository
* CI on forks), so it reached ready-for-review as #6471 before any maintainer
* build. lint/doctor already gate local pushes with the same if-changed shape,
* so the gui type gate reuses it and the tests below pin the checked-in files
* rather than copies of them.
*/
const rootPkg = readFileSync(repoPath("package.json"), "utf8");
const prepush = rootPkg.match(/"prepush": "([^"]+)"/)![1]!;
const typecheckGuiIfChangedScript = fileURLToPath(new URL("../../scripts/typecheck-gui-if-changed.ts", import.meta.url));

describe("gui typecheck if-changed gate", () => {
test("root exposes the gui typecheck gate script", () => {
expect(rootPkg).toContain('"typecheck:gui:if-changed": "bun scripts/typecheck-gui-if-changed.ts"');
});

test("prepush runs the gui typecheck gate after the root typecheck", () => {
expect(prepush).toContain("bun run typecheck:gui:if-changed");
expect(prepush.indexOf("bun run typecheck")).toBeLessThan(prepush.indexOf("bun run typecheck:gui:if-changed"));
});

test("the if-changed gate runs on gui/ changes, skips otherwise, and fails the push on a compile error", () => {
const dryRun = (files: string): string => {
const probe = Bun.spawnSync([process.execPath, typecheckGuiIfChangedScript], {
env: { ...process.env, TYPECHECK_DRY_RUN: "1", TYPECHECK_FILES: files },
});
return probe.stdout.toString().trim();
};
expect(dryRun("gui/src/App.tsx\nscripts/x.ts")).toBe("typecheck:run");
expect(dryRun("scripts/x.ts\nREADME.md")).toBe("typecheck:skip");

// A Bun stub stands in for the compiler so the failure path is deterministic on every
// platform (native Windows has no `false`). A distinctive code proves the compiler's exit
// status propagates unchanged rather than the gate always returning 1.
const stubCompiler = JSON.stringify([process.execPath, "-e", "process.exit(23)"]);
const failing = Bun.spawnSync([process.execPath, typecheckGuiIfChangedScript], {
env: {
...process.env,
TYPECHECK_FILES: "gui/src/App.tsx",
TYPECHECK_CMD: stubCompiler,
},
});
expect(failing.exitCode).toBe(23);

// A compiler that cannot be spawned is a real failure, not a skip.
const missing = Bun.spawnSync([process.execPath, typecheckGuiIfChangedScript], {
env: {
...process.env,
TYPECHECK_FILES: "gui/src/App.tsx",
TYPECHECK_CMD: JSON.stringify(["ocx-gui-typecheck-missing-compiler"]),
},
});
expect(missing.exitCode).toBe(1);

const skipping = Bun.spawnSync([process.execPath, typecheckGuiIfChangedScript], {
env: {
...process.env,
TYPECHECK_FILES: "scripts/x.ts\nREADME.md",
TYPECHECK_CMD: stubCompiler,
},
});
expect(skipping.exitCode).toBe(0);
});

describe("base selection against a real repository", () => {
// The script finds its repository from its own location, so each fixture is a fresh git repo
// holding a copy of the checked-in script. Only the run/skip decision is observed.
const fixtures: string[] = [];
afterEach(() => { for (const dir of fixtures.splice(0)) rmSync(dir, { recursive: true, force: true }); });

const gitEnv = (): Record<string, string> => {
const env: Record<string, string> = {};
for (const [key, value] of Object.entries(process.env)) {
if (value !== undefined && !key.startsWith("GIT_")) env[key] = value;
}
return { ...env, GIT_AUTHOR_NAME: "fixture", GIT_AUTHOR_EMAIL: "fixture@example.test",
GIT_COMMITTER_NAME: "fixture", GIT_COMMITTER_EMAIL: "fixture@example.test", GIT_CONFIG_NOSYSTEM: "1" };
};
const repo = (): { dir: string; git: (...args: string[]) => void; commit: (path: string) => void; decide: () => string } => {
const dir = mkdtempSync(join(tmpdir(), "ocx-gui-typecheck-"));
fixtures.push(dir);
const git = (...args: string[]): void => {
const run = Bun.spawnSync(["git", ...args], { cwd: dir, env: gitEnv() });
if (run.exitCode !== 0) throw new Error(`git ${args.join(" ")}: ${run.stderr.toString()}`);
};
const commit = (path: string): void => {
mkdirSync(join(dir, dirname(path)), { recursive: true });
writeFileSync(join(dir, path), `${path}\n`);
git("add", "--", path);
git("commit", "-q", "-m", path);
};
git("init", "-q", "-b", "dev");
// git's default; pinned so a global core.quotePath=false cannot hide the quoting case.
git("config", "core.quotePath", "true");
mkdirSync(join(dir, "scripts"));
copyFileSync(typecheckGuiIfChangedScript, join(dir, "scripts", "typecheck-gui-if-changed.ts"));
commit("README.md");
const decide = (): string => {
const env = { ...gitEnv(), TYPECHECK_DRY_RUN: "1" };
delete env.TYPECHECK_FILES;
const probe = Bun.spawnSync([process.execPath, join(dir, "scripts", "typecheck-gui-if-changed.ts")], { cwd: dir, env });
return probe.stdout.toString().trim();
};
return { dir, git, commit, decide };
};

test("a branch that touches only non-gui files skips, and one gui commit runs", () => {
const fixture = repo();
fixture.git("checkout", "-q", "-b", "feature");
fixture.commit("scripts/other.ts");
expect(fixture.decide()).toBe("typecheck:skip");
fixture.commit("gui/src/App.tsx");
expect(fixture.decide()).toBe("typecheck:run");
});

test("moving a file out of gui/ still counts as a gui change", () => {
// git's rename detection would report only the destination (config/...), hiding that gui/ lost a file.
const fixture = repo();
fixture.commit("gui/tsconfig.node.json");
fixture.git("checkout", "-q", "-b", "feature");
mkdirSync(join(fixture.dir, "config"));
fixture.git("mv", "gui/tsconfig.node.json", "config/tsconfig.node.json");
fixture.git("commit", "-q", "-m", "move");
expect(fixture.decide()).toBe("typecheck:run");
});

test("a non-ASCII gui path still counts as a gui change", () => {
// Without -z, git quotes this name ("gui/src/\303\274ber.tsx") and the gui/ prefix check misses it.
const fixture = repo();
fixture.git("checkout", "-q", "-b", "feature");
fixture.git("branch", "-q", "--set-upstream-to=dev");
fixture.commit("gui/src/über.tsx");
expect(fixture.decide()).toBe("typecheck:run");
});

test("a gui change already on the tracking branch still runs", () => {
// The tracking branch holds the gui commit; comparing against @{u} would see nothing to check.
const fixture = repo();
fixture.git("checkout", "-q", "-b", "feature");
fixture.commit("gui/src/App.tsx");
fixture.git("branch", "-q", "tracked");
fixture.git("branch", "-q", "--set-upstream-to=tracked");
expect(fixture.decide()).toBe("typecheck:run");
});

test("a diff that git cannot compute runs the check instead of skipping", () => {
// dev and HEAD share no history, so "dev...HEAD" has no merge base and git diff fails.
const fixture = repo();
fixture.git("checkout", "-q", "--orphan", "unrelated");
fixture.git("rm", "-rq", "--cached", "README.md");
fixture.commit("scripts/other.ts");
fixture.git("branch", "-q", "--set-upstream-to=dev");
expect(fixture.decide()).toBe("typecheck:run");
});
});

test("ci gates keeps the GUI build step under the gui path filter", () => {
const workflow = Bun.YAML.parse(readFileSync(repoPath(".github", "workflows", "ci.yml"), "utf8")) as {
jobs: Record<string, { steps?: Array<{ name?: string; if?: string; run?: string }> }>;
};
const gatesSteps = workflow.jobs.gates?.steps ?? [];
const guiBuild = gatesSteps.find(step => step.name === "GUI build");
expect(guiBuild).toBeDefined();
expect(guiBuild!.if).toBe("needs.changes.outputs.gui == 'true'");
expect((guiBuild!.run ?? "").split(/\r?\n/).map(line => line.trim()).filter(Boolean)).toEqual(["cd gui", "bun run build"]);
});
});
4 changes: 2 additions & 2 deletions tests/ci-workflows/ci-workflows.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5290,8 +5290,8 @@ describe("GitHub Actions hardening", () => {
expect(rootPkg).toContain('"doctor:gui:if-changed": "bun scripts/doctor-gui-if-changed.ts"');
expect(rootPkg).toContain('"lint:gui": "cd gui && bun run lint"');
expect(rootPkg).toContain('"lint:gui:if-changed": "bun scripts/lint-gui-if-changed.ts"');
// Gating steps include lint and React Doctor only on gui/ pushes.
expect(rootPkg).toContain("bun run typecheck && bun run lint:gui:if-changed && bun run test");
// Gating steps include the gui typecheck, lint, and React Doctor only on gui/ pushes.
expect(rootPkg).toContain("bun run typecheck && bun run typecheck:gui:if-changed && bun run lint:gui:if-changed && bun run test");
expect(rootPkg).toContain("bun run privacy:scan && bun run doctor:gui:if-changed");
});
});
Expand Down
2 changes: 1 addition & 1 deletion tests/fixtures/test-layout-expected.json
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@
"bridge-raw-reasoning-hidden.test.ts": "adapters", "bridge-reasoning-replay-batch.test.ts": "adapters",
"bridge-stall.test.ts": "adapters", "bridge-terminal-singleness.test.ts": "adapters",
"bridge.test.ts": "adapters", "buffered-response-shape-guards.test.ts": "adapters",
"build-desktop-icon-set.test.ts": "ci-workflows", "build-release-changelog.test.ts": "ci-workflows",
"build-desktop-icon-set.test.ts": "ci-workflows", "build-release-changelog.test.ts": "ci-workflows", "ci-gui-typecheck-gate.test.ts": "ci-workflows",
"bump-dev-version.test.ts": "ci-workflows", "bun-runtime.test.ts": "ci-workflows",
"bun-stream-caps.test.ts": "lib", "cache-diagnostic.test.ts": "usage",
"cancel-body-on-abort.test.ts": "server", "catalog-auto-refresh-scheduler.test.ts": "codex-integration",
Expand Down
Loading