Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🔨 chore: warn on new component tests (#17523)

YuTengjing54abb8ed668f
diff --git a/.agents/scripts/check/advisories.ts b/.agents/scripts/check/advisories.ts
new file mode 100644
index 00000000000..da250d67d92
--- /dev/null
+++ b/.agents/scripts/check/advisories.ts
@@ -0,0 +1,65 @@
+import { run } from './exec';
+import { getConfig, mountDir } from './paths';
+import { resolveMount } from './routing';
+import type { RepoMount } from './types';
+
+interface BaseFileStatus {
+ baseRef: string;
+ exists: boolean;
+}
+
+type InspectBaseFile = (file: string) => Promise<BaseFileStatus | undefined>;
+
+const NEW_COMPONENT_TEST_PATTERN = /\.test\.tsx$/;
+const TESTING_SKILL_REFERENCE =
+ '.agents/skills/testing/SKILL.md (Core Principles: "No new component tests")';
+
+const createBaseFileInspector = (): InspectBaseFile => {
+ const mergeBases = new Map<RepoMount, Promise<string | undefined>>();
+
+ return async (file) => {
+ const { mount, subPath } = resolveMount(getConfig().repos, file);
+ if (!mount.baseRef) return;
+
+ let mergeBase = mergeBases.get(mount);
+ if (!mergeBase) {
+ // This advisory is best-effort: an unavailable local base skips it instead of failing checks.
+ mergeBase = run('git', ['merge-base', 'HEAD', mount.baseRef], mountDir(mount)).then(
+ (result) => (result.code === 0 ? result.stdout.trim() || undefined : undefined),
+ );
+ mergeBases.set(mount, mergeBase);
+ }
+
+ const baseCommit = await mergeBase;
+ // Unlike a missing file at a valid base, an unresolved base cannot prove the file is new.
+ if (!baseCommit) return;
+
+ const result = await run(
+ 'git',
+ ['cat-file', '-e', `${baseCommit}:${subPath}`],
+ mountDir(mount),
+ );
+
+ return {
+ baseRef: mount.baseRef,
+ exists: result.code === 0,
+ };
+ };
+};
+
+export const findNewComponentTestAdvisories = async (
+ files: string[],
+ inspectBaseFile: InspectBaseFile = createBaseFileInspector(),
+): Promise<string[]> => {
+ const candidates = [...new Set(files.filter((file) => NEW_COMPONENT_TEST_PATTERN.test(file)))];
+ const statuses = await Promise.all(candidates.map((file) => inspectBaseFile(file)));
+
+ return candidates.flatMap((file, index) => {
+ const status = statuses[index];
+ if (!status || status.exists) return [];
+
+ return [
+ `${file}: new .test.tsx file relative to ${status.baseRef}. New React component tests are not allowed; extract complex logic into a hook and test it in .test.ts instead (${TESTING_SKILL_REFERENCE}).`,
+ ];
+ });
+};
diff --git a/.agents/scripts/check/check.test.ts b/.agents/scripts/check/check.test.ts
index 553fa874d3e..6016de96482 100644
--- a/.agents/scripts/check/check.test.ts
+++ b/.agents/scripts/check/check.test.ts
@@ -4,6 +4,7 @@ import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
+import { findNewComponentTestAdvisories } from './advisories';
import { diffStat, renderDiffsForStdout } from './autofix';
import { hostRootFromGitdir } from './delegate';
import { lobehubPipelines } from './pipelines';
@@ -132,6 +133,31 @@ describe('relatedTestCandidates', () => {
});
});
+describe('findNewComponentTestAdvisories', () => {
+ it('warns only for new .test.tsx files', async () => {
+ const advisories = await findNewComponentTestAdvisories(
+ ['src/New.test.tsx', 'src/Existing.test.tsx', 'src/useFeature.test.ts'],
+ async (file) => ({
+ baseRef: 'origin/canary',
+ exists: file.includes('Existing'),
+ }),
+ );
+
+ expect(advisories).toEqual([
+ expect.stringContaining('src/New.test.tsx: new .test.tsx file relative to origin/canary'),
+ ]);
+ expect(advisories[0]).toContain(
+ '.agents/skills/testing/SKILL.md (Core Principles: "No new component tests")',
+ );
+ });
+
+ it('skips the warning when the configured base cannot be inspected', async () => {
+ await expect(
+ findNewComponentTestAdvisories(['src/New.test.tsx'], async () => undefined),
+ ).resolves.toEqual([]);
+ });
+});
+
describe('findVitestConfigDir', () => {
const configs = new Set([
'vitest.config.mts',
diff --git a/.agents/scripts/check/cli.ts b/.agents/scripts/check/cli.ts
index ac8f0bf90e0..ed4647293f4 100644
--- a/.agents/scripts/check/cli.ts
+++ b/.agents/scripts/check/cli.ts
@@ -28,7 +28,10 @@ const main = async () => {
return;
}
- await runCli({ repos: [{ dir: '', pipelines: lobehubPipelines }], rootDir });
+ await runCli({
+ repos: [{ baseRef: 'origin/canary', dir: '', pipelines: lobehubPipelines }],
+ rootDir,
+ });
};
main().catch((error) => {
diff --git a/.agents/scripts/check/index.ts b/.agents/scripts/check/index.ts
index 526092c04d9..c7b7401a588 100644
--- a/.agents/scripts/check/index.ts
+++ b/.agents/scripts/check/index.ts
@@ -19,6 +19,7 @@
* mounting this repo provides its own entry that adds its root pipelines and
* mounts this repo's via `pipelines.ts`.
*/
+import { findNewComponentTestAdvisories } from './advisories';
import { collectAutofixDiffs, snapshot, writeFullDiff } from './autofix';
import { collectFromGit, normalizeArgs } from './collect';
import { run } from './exec';
@@ -126,6 +127,8 @@ export const runCli = async (config: CheckConfig) => {
tests = await runTestGroups(testFiles);
}
+ const advisories = await findNewComponentTestAdvisories([...new Set([...files, ...testFiles])]);
+
/* ---- Type check ---- */
let typeOutput: string | null = null;
if (runType) {
@@ -135,6 +138,7 @@ export const runCli = async (config: CheckConfig) => {
const fullDiffPath = diffs.length > 0 ? await writeFullDiff(diffs) : null;
const { failed } = printReport({
+ advisories,
diffs,
fatal,
fileCount: files.length,
diff --git a/.agents/scripts/check/report.ts b/.agents/scripts/check/report.ts
index 25f966176ea..923c76426a8 100644
--- a/.agents/scripts/check/report.ts
+++ b/.agents/scripts/check/report.ts
@@ -2,6 +2,7 @@ import { renderDiffsForStdout } from './autofix';
import type { FileDiff, LintProblem, TestOutcome } from './types';
export interface ReportInput {
+ advisories: string[];
diffs: FileDiff[];
fatal: string[];
fileCount: number;
@@ -21,6 +22,7 @@ export interface ReportInput {
/** Print the compact report; the summary line mentions only checks that ran. */
export const printReport = (input: ReportInput): { failed: boolean } => {
const {
+ advisories,
diffs,
fatal,
fileCount,
@@ -65,6 +67,7 @@ export const printReport = (input: ReportInput): { failed: boolean } => {
);
}
if (typeOutput !== null) parts.push(typeOutput ? 'types failed' : 'types clean');
+ if (advisories.length > 0) parts.push(`${advisories.length} advisories`);
if (skipped > 0) parts.push(`${skipped} skipped (no linter)`);
console.log(`${failed ? '✗' : '✓'} ${parts.join(' · ')}`);
@@ -78,6 +81,11 @@ export const printReport = (input: ReportInput): { failed: boolean } => {
}
for (const message of fatal) console.log(`\nlint fatal:\n${message}`);
+ if (advisories.length > 0) {
+ console.log('\nadvisories:');
+ for (const advisory of advisories) console.log(`âš  ${advisory}`);
+ }
+
if (tests && tests.failedOutput.length > 0)
console.log(`\ntests:\n${tests.failedOutput.join('\n\n')}`);
if (tests && tests.noMatch.length > 0)
diff --git a/.agents/scripts/check/types.ts b/.agents/scripts/check/types.ts
index 60c1ace9692..bbac5e69f65 100644
--- a/.agents/scripts/check/types.ts
+++ b/.agents/scripts/check/types.ts
@@ -7,6 +7,8 @@ export interface PipelineEntry {
/** A repository participating in the check: the host root or a vendored sub-repo. */
export interface RepoMount {
+ /** Base ref used to decide whether a selected file is newly added in this PR. */
+ baseRef?: string;
/** Root-relative directory of the repo; '' means the host repo itself. */
dir: string;
pipelines: PipelineEntry[];