-
Notifications
You must be signed in to change notification settings - Fork 0
feat: ai for ci diff action #42
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Large diffs are not rendered by default.
Large diffs are not rendered by default.
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,96 @@ | ||||||
| import * as fs from 'fs'; | ||||||
| import { generateText, type LanguageModel } from 'ai'; | ||||||
| import { createAnthropic } from '@ai-sdk/anthropic'; | ||||||
| import { createDeepSeek } from '@ai-sdk/deepseek'; | ||||||
| import { createGoogleGenerativeAI } from '@ai-sdk/google'; | ||||||
| import { createOpenAI } from '@ai-sdk/openai'; | ||||||
| import { buildPrompt } from './prompt'; | ||||||
|
|
||||||
| export interface AIAnalysisResult { | ||||||
| analysis: string; | ||||||
| provider: string; | ||||||
| model: string; | ||||||
| } | ||||||
|
|
||||||
| type Provider = 'anthropic' | 'openai' | 'google' | 'deepseek' | 'qwen'; | ||||||
|
|
||||||
| function detectProvider(model: string): Provider { | ||||||
| const m = model.toLowerCase(); | ||||||
| if (m.startsWith('claude')) return 'anthropic'; | ||||||
| if (m.startsWith('gemini')) return 'google'; | ||||||
| if (m.startsWith('deepseek')) return 'deepseek'; | ||||||
| if (m.startsWith('qwen')) return 'qwen'; | ||||||
| return 'openai'; | ||||||
| } | ||||||
|
|
||||||
| function createModel(provider: Provider, model: string, token: string): LanguageModel { | ||||||
| switch (provider) { | ||||||
| case 'anthropic': { | ||||||
| const anthropic = createAnthropic({ apiKey: token }); | ||||||
| return anthropic(model); | ||||||
| } | ||||||
| case 'google': { | ||||||
| const google = createGoogleGenerativeAI({ apiKey: token }); | ||||||
| return google(model); | ||||||
| } | ||||||
| case 'deepseek': { | ||||||
| const deepseek = createDeepSeek({ apiKey: token }); | ||||||
| return deepseek(model); | ||||||
| } | ||||||
| case 'qwen': { | ||||||
| const qwen = createOpenAI({ | ||||||
| apiKey: token, | ||||||
| baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1', | ||||||
| }); | ||||||
| return qwen(model); | ||||||
| } | ||||||
| default: { | ||||||
| const openai = createOpenAI({ apiKey: token }); | ||||||
| return openai(model); | ||||||
| } | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| /** | ||||||
| * Run AI degradation analysis on a bundle-diff JSON file. | ||||||
| * | ||||||
| * @param diffJsonPath Path to the JSON file produced by `rsdoctor bundle-diff --json` | ||||||
| * @param token AI API key (Anthropic or OpenAI) | ||||||
| * @param model Model name — auto-detects provider from prefix (default: claude-3-5-haiku-latest) | ||||||
| */ | ||||||
| export async function analyzeWithAI( | ||||||
| diffJsonPath: string, | ||||||
| token: string, | ||||||
| model = 'claude-3-5-haiku-latest', | ||||||
| ): Promise<AIAnalysisResult | null> { | ||||||
| if (!token) { | ||||||
| console.log('ℹ️ No AI token provided, skipping AI analysis'); | ||||||
| return null; | ||||||
| } | ||||||
|
|
||||||
| if (!fs.existsSync(diffJsonPath)) { | ||||||
| console.log(`⚠️ Bundle diff JSON not found at ${diffJsonPath}, skipping AI analysis`); | ||||||
| return null; | ||||||
| } | ||||||
|
|
||||||
| try { | ||||||
| const diffData: unknown = JSON.parse(fs.readFileSync(diffJsonPath, 'utf8')); | ||||||
|
||||||
| const diffData: unknown = JSON.parse(fs.readFileSync(diffJsonPath, 'utf8')); | |
| const diffData: unknown = JSON.parse(await fs.promises.readFile(diffJsonPath, 'utf8')); |
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -3,6 +3,7 @@ import { uploadArtifact, hashPath } from './upload'; | |||||||||||||||||||||||||||||
| import { downloadArtifactByCommitHash } from './download'; | ||||||||||||||||||||||||||||||
| import { GitHubService } from './github'; | ||||||||||||||||||||||||||||||
| import { loadSizeData, generateSizeReport, parseRsdoctorData, generateBundleAnalysisReport, BundleAnalysis, generateProjectMarkdown, formatBytes, calculateDiff } from './report'; | ||||||||||||||||||||||||||||||
| import { analyzeWithAI, AIAnalysisResult } from './ai-analysis'; | ||||||||||||||||||||||||||||||
| import path from 'path'; | ||||||||||||||||||||||||||||||
| import * as fs from 'fs'; | ||||||||||||||||||||||||||||||
| import { execFile } from 'child_process'; | ||||||||||||||||||||||||||||||
|
|
@@ -99,6 +100,7 @@ interface ProjectReport { | |||||||||||||||||||||||||||||
| diffHtmlArtifactId?: number; | ||||||||||||||||||||||||||||||
| baselineUsedFallback?: boolean; | ||||||||||||||||||||||||||||||
| baselineLatestCommitHash?: string; | ||||||||||||||||||||||||||||||
| aiAnalysis?: AIAnalysisResult | null; | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| export function extractProjectName(filePath: string): string { | ||||||||||||||||||||||||||||||
|
|
@@ -152,6 +154,8 @@ async function processSingleFile( | |||||||||||||||||||||||||||||
| targetCommitHash: string | null, | ||||||||||||||||||||||||||||||
| baselineUsedFallback?: boolean, | ||||||||||||||||||||||||||||||
| baselineLatestCommitHash?: string, | ||||||||||||||||||||||||||||||
| aiToken?: string, | ||||||||||||||||||||||||||||||
| aiModel?: string, | ||||||||||||||||||||||||||||||
| ): Promise<ProjectReport> { | ||||||||||||||||||||||||||||||
| const fileName = path.basename(fullPath); | ||||||||||||||||||||||||||||||
| const relativePath = path.relative(process.cwd(), fullPath); | ||||||||||||||||||||||||||||||
|
|
@@ -273,11 +277,49 @@ async function processSingleFile( | |||||||||||||||||||||||||||||
| console.warn(`⚠️ Failed to upload diff html for ${projectName}: ${e}`); | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| // Generate JSON diff for AI analysis (requires @rsdoctor/cli >= 1.5.6-canary.0) | ||||||||||||||||||||||||||||||
| if (aiToken) { | ||||||||||||||||||||||||||||||
| try { | ||||||||||||||||||||||||||||||
| const diffJsonPath = path.join(tempOutDir, `rsdoctor-diff-${projectName}.json`); | ||||||||||||||||||||||||||||||
| const defaultDiffJsonPath = path.join(tempOutDir, 'rsdoctor-diff.json'); | ||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||
| try { | ||||||||||||||||||||||||||||||
| const cliEntry = require.resolve('@rsdoctor/cli', { paths: [process.cwd()] }); | ||||||||||||||||||||||||||||||
| const binCliEntry = path.join(path.dirname(path.dirname(cliEntry)), 'bin', 'rsdoctor'); | ||||||||||||||||||||||||||||||
| runRsdoctorViaNode(binCliEntry, [ | ||||||||||||||||||||||||||||||
| 'bundle-diff', | ||||||||||||||||||||||||||||||
| '--json', | ||||||||||||||||||||||||||||||
| `--baseline=${baselineJsonPath}`, | ||||||||||||||||||||||||||||||
| `--current=${fullPath}`, | ||||||||||||||||||||||||||||||
| ]); | ||||||||||||||||||||||||||||||
| } catch (e) { | ||||||||||||||||||||||||||||||
| console.log(`⚠️ rsdoctor CLI (json) not found in node_modules: ${e}`); | ||||||||||||||||||||||||||||||
| try { | ||||||||||||||||||||||||||||||
| const shellCmd = `npx @rsdoctor/cli bundle-diff --json --baseline="${baselineJsonPath}" --current="${fullPath}"`; | ||||||||||||||||||||||||||||||
| console.log(`🛠️ Running rsdoctor --json via npx: ${shellCmd}`); | ||||||||||||||||||||||||||||||
| await execFileAsync('sh', ['-c', shellCmd], { cwd: tempOutDir }); | ||||||||||||||||||||||||||||||
|
Comment on lines
+299
to
+301
|
||||||||||||||||||||||||||||||
| const shellCmd = `npx @rsdoctor/cli bundle-diff --json --baseline="${baselineJsonPath}" --current="${fullPath}"`; | |
| console.log(`🛠️ Running rsdoctor --json via npx: ${shellCmd}`); | |
| await execFileAsync('sh', ['-c', shellCmd], { cwd: tempOutDir }); | |
| const npxArgs = [ | |
| '@rsdoctor/cli', | |
| 'bundle-diff', | |
| '--json', | |
| '--baseline', | |
| baselineJsonPath, | |
| '--current', | |
| fullPath, | |
| ]; | |
| console.log(`🛠️ Running rsdoctor --json via npx with args: ${JSON.stringify(npxArgs)}`); | |
| await execFileAsync('npx', npxArgs, { cwd: tempOutDir }); |
Copilot
AI
Mar 24, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The action introduces ai_model as an input, but the token is only configurable via process.env.AI_TOKEN (not an action input) and isn’t documented in action.yml in this diff. Consider adding an ai_token input (and calling core.setSecret on it) or explicitly documenting the required env var in action.yml so users can discover/configure it reliably.
Copilot
AI
Mar 24, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
AI output is injected directly into the PR comment body as GitHub-flavored Markdown. This can unintentionally trigger @mentions, issue/PR links, or other noisy formatting. Consider neutralizing mentions (e.g., replacing @ with @\\u200b), or constraining the rendering (e.g., wrapping the AI response in a blockquote or details section that discourages mention expansion) before posting.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| const MAX_CHARS = 50000; | ||
|
|
||
| export function buildPrompt(diffData: unknown): string { | ||
| // Truncate large diff data to avoid token limits (~50k chars) | ||
| let diffStr = JSON.stringify(diffData, null, 2); | ||
| if (diffStr.length > MAX_CHARS) { | ||
| diffStr = diffStr.substring(0, MAX_CHARS) + '\n... (truncated due to size)'; | ||
| } | ||
|
|
||
| return `You are a senior frontend performance engineer. Analyze the Rsdoctor bundle-diff JSON below (baseline → current) and produce a concise GitHub PR comment in Markdown. | ||
|
|
||
| ## Output format | ||
|
|
||
| ### 📊 Size Changes | ||
|
|
||
| | Asset / Chunk | Baseline | Current | Δ Size | Δ % | Initial? | | ||
| |---|---|---|---|---|---| | ||
|
|
||
| (Only list entries with **>5 % or >10 KB** increase. If none, write "No significant regressions detected 🎉".) | ||
|
|
||
| ### 🔍 Root Cause Analysis | ||
| - Bullet points: which modules / dependencies drove each regression. | ||
|
|
||
| ### ⚠️ Risk Assessment | ||
| Overall severity: **Low / Medium / High** | ||
| - One-sentence justification focusing on initial-chunk impact and total size delta. | ||
|
|
||
| ### 💡 Optimization Suggestions | ||
| - Numbered, actionable steps (e.g. code-split, tree-shake, replace heavy deps). | ||
|
|
||
| ## Priority rules | ||
| 1. Initial / entry chunks > async chunks > static assets. | ||
| 2. Newly added large modules or duplicate dependencies deserve explicit callout. | ||
| 3. If total bundle size *decreased*, highlight the wins instead. | ||
|
|
||
| ## Constraints | ||
| - Be concise — aim for <400 words. | ||
| - Use exact numbers from the data; do not fabricate figures. | ||
| - If the diff data is empty or shows no meaningful change, state that clearly and skip the table. | ||
|
|
||
| Bundle diff data: | ||
| \`\`\`json | ||
| ${diffStr} | ||
| \`\`\``; | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Other inputs in this file specify
type: string, butai_modeldoes not. For consistency (and clearer metadata for tooling), addtype: stringto the newai_modelinput.