diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3b13dd6b..56ccccc3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,18 +12,63 @@ on: concurrency: group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} permissions: contents: read jobs: + static: + name: Static Analysis & Build + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Checkout repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 + + - name: Setup Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 + with: + node-version: 22 + cache: "npm" + + - name: Install dependencies + run: npm ci + + - name: Check build coverage + run: npm run check:builds + + - name: Build packages + run: npm run build:packages + + - name: Validate package exports + run: | + npm run check:exports + for dir in packages/*/; do + echo "publint $dir" + (cd "$dir" && npx --no-install publint) || exit 1 + done + + - name: Static Analysis (Typecheck) + run: npm run typecheck && npm run typecheck:all + + - name: Static Analysis (Lint) + run: npm run lint + + - name: Build (client bundle) + run: npx vite build + + - name: Build (worker bundle, dry run) + run: cd apps/worker && npx wrangler deploy --dry-run --outdir=.wrangler/dry + verify: name: Verify Stability + needs: static runs-on: ubuntu-latest + timeout-minutes: 20 services: postgres: - image: postgres:16 + image: postgres:16-alpine env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres @@ -31,7 +76,7 @@ jobs: ports: - 5432:5432 options: >- - --health-cmd pg_isready + --health-cmd "pg_isready -U postgres -d codra_test" --health-interval 10s --health-timeout 5s --health-retries 5 @@ -69,25 +114,8 @@ jobs: - name: Install dependencies run: npm ci - - name: Check build coverage - run: npm run check:builds - - - name: Build packages - run: npm run build:packages - - - name: Validate package exports - run: | - npm run check:exports - for dir in packages/*/; do - echo "publint $dir" - (cd "$dir" && npx --no-install publint) || exit 1 - done - - - name: Static Analysis (Typecheck) - run: npm run typecheck && npm run typecheck:all - - - name: Static Analysis (Lint) - run: npm run lint + - name: Build packages, client, and Node server + run: npm run build:node - name: Automated Tests run: npm test @@ -95,27 +123,36 @@ jobs: - name: Automated Tests (packages) run: npm run test:all - - name: Build (client bundle) - run: npx vite build - - - name: Build (worker bundle, dry run) - run: cd apps/worker && npx wrangler deploy --dry-run --outdir=.wrangler/dry + - name: Cache Playwright browsers + id: playwright-cache + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ~/.cache/ms-playwright + key: ${{ runner.os }}-playwright-${{ hashFiles('package-lock.json') }} + restore-keys: | + ${{ runner.os }}-playwright- - - name: Install Playwright browsers - run: npx playwright install chromium --with-deps + - name: Install Playwright Chromium + run: | + if [ "${{ steps.playwright-cache.outputs.cache-hit }}" != "true" ]; then + npx playwright install chromium --with-deps + else + npx playwright install-deps chromium + fi - name: Prepare E2E environment run: | cp .env.e2e.example .env.e2e - node -e "import('postgres').then(async ({default: p}) => { const sql = p('postgresql://postgres:postgres@127.0.0.1:5432/postgres'); await sql\`CREATE DATABASE codra_e2e\`.catch(() => {}); await sql.end(); })" + node -e "import('postgres').then(async ({default: p}) => { const sql = p('postgresql://postgres:postgres@127.0.0.1:5432/postgres'); try { await sql\`CREATE DATABASE codra_e2e\`; } catch (err) { if (err?.code !== '42P04') throw err; } finally { await sql.end(); } })" DATABASE_URL=postgresql://postgres:postgres@127.0.0.1:5432/codra_e2e npm run migrate - name: Run Playwright E2E tests - run: npm run test:e2e + id: e2e + run: npx playwright test - name: Upload Playwright report uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1 - if: failure() + if: failure() && steps.e2e.outcome == 'failure' with: name: playwright-report path: playwright-report/ diff --git a/apps/dashboard/src/components/features/job-detail/comment-card.tsx b/apps/dashboard/src/components/features/job-detail/comment-card.tsx index edaeb8f8..a9e0ef6f 100644 --- a/apps/dashboard/src/components/features/job-detail/comment-card.tsx +++ b/apps/dashboard/src/components/features/job-detail/comment-card.tsx @@ -1,5 +1,10 @@ import { CopyButton, FileDiff } from "@codraoss/ui"; -import { memo, useState, type ComponentPropsWithoutRef } from "react"; +import { + isValidElement, + memo, + useState, + type ComponentPropsWithoutRef, +} from "react"; import ReactMarkdown from "react-markdown"; import remarkGfm from "remark-gfm"; import { FileText, ThumbsDown, ThumbsUp } from "lucide-react"; @@ -26,6 +31,18 @@ const DISPOSITION_LABEL: Record = { }; export const markdownComponents = { + pre({ + children, + ...props + }: ComponentPropsWithoutRef<"pre">) { + if ( + isValidElement<{ className?: string }>(children) && + /language-(?:diff|patch)(?::|\b)/.test(children.props?.className ?? "") + ) { + return <>{children}; + } + return
{children}
; + }, code({ className, children, diff --git a/apps/node/Dockerfile b/apps/node/Dockerfile index 2b2b0fa4..80bb79f3 100644 --- a/apps/node/Dockerfile +++ b/apps/node/Dockerfile @@ -74,6 +74,6 @@ COPY --from=builder /app/packages/db/scripts ./packages/db/scripts EXPOSE 3000 -HEALTHCHECK --interval=30s --timeout=3s CMD ["/nodejs/bin/node", "-e", "fetch('http://127.0.0.1:3000/health').then((response) => process.exit(response.ok ? 0 : 1)).catch(() => process.exit(1))"] +HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 CMD ["/nodejs/bin/node", "-e", "fetch('http://127.0.0.1:3000/health/ready').then((response) => process.exit(response.ok ? 0 : 1)).catch(() => process.exit(1))"] CMD ["apps/node/dist/index.js"] diff --git a/packages/api/src/routes/webhook.ts b/packages/api/src/routes/webhook.ts index 3085d712..0b899f09 100644 --- a/packages/api/src/routes/webhook.ts +++ b/packages/api/src/routes/webhook.ts @@ -110,6 +110,27 @@ async function handleFeedbackEvent( } } +function isPlainRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function extractRepoIdentity(payload: Record): { + owner: string | null; + repo: string | null; +} { + const repoObj = isPlainRecord(payload.repository) ? payload.repository : null; + if (!repoObj) return { owner: null, repo: null }; + const owner = isPlainRecord(repoObj.owner) + ? typeof repoObj.owner.login === "string" + ? repoObj.owner.login + : null + : typeof repoObj.owner === "string" + ? repoObj.owner + : null; + const repo = typeof repoObj.name === "string" ? repoObj.name : null; + return { owner, repo }; +} + export async function handleGitHubWebhook(c: Context) { const eventName = c.req.header("x-github-event"); const deliveryId = c.req.header("x-github-delivery"); @@ -128,18 +149,24 @@ export async function handleGitHubWebhook(c: Context) { return jsonError("Invalid webhook signature.", 401); } - let payload: GitHubWebhookPayload; + let parsedBody: unknown; try { - payload = JSON.parse(rawBody) as GitHubWebhookPayload; + parsedBody = JSON.parse(rawBody); } catch { return jsonError("Invalid webhook JSON payload.", 400); } + if (!isPlainRecord(parsedBody)) { + return jsonError("Invalid webhook JSON payload.", 400); + } + const payload = parsedBody as GitHubWebhookPayload & Record; + // Feedback deliveries carry the whole PR object plus diff hunks per comment; skip storing the payload (row is still written, so dedup still works). const isFeedbackEvent = isFeedbackGitHubWebhookEvent(eventName); const normalized = c.env.deps.webhook.normalizePayload(eventName, payload); const canonicalEventName = normalized?.eventName ?? eventName; + const { owner, repo } = extractRepoIdentity(payload); const delivery = await c.env.deps.repositories.webhookDeliveries.recordWebhookDelivery( @@ -147,12 +174,9 @@ export async function handleGitHubWebhook(c: Context) { { deliveryId, eventName: canonicalEventName, - owner: - "repository" in payload - ? (payload as any).repository.owner.login - : null, - repo: "repository" in payload ? (payload as any).repository.name : null, - payload: isFeedbackEvent ? null : payload, + owner, + repo, + payload: isFeedbackEvent ? null : (normalized?.payload ?? payload), }, ); @@ -160,8 +184,13 @@ export async function handleGitHubWebhook(c: Context) { return c.json({ ok: true, duplicate: true }, 202); } - const installationId = String((payload as any).installation?.id ?? ""); - if (!installationId || !("repository" in payload) || !payload.repository) { + const installationObj = isPlainRecord(payload.installation) + ? payload.installation + : null; + const installationId = String( + installationObj?.id ?? payload.installationId ?? "", + ); + if (!installationId || !owner || !repo) { return c.json({ ok: true, ignored: true }, 202); } @@ -186,8 +215,8 @@ export async function handleGitHubWebhook(c: Context) { const repoConfig = await c.env.deps.config.loadRepoConfig({ installationId, - owner: (payload as any).repository.owner.login, - repo: (payload as any).repository.name, + owner, + repo, }); if (repoConfig.enabled === false) { @@ -204,26 +233,28 @@ export async function handleGitHubWebhook(c: Context) { config: repoConfig.parsedJson, }); - if (extracted?.commitSha && extracted.baseSha) { - const jobsRepo = c.env.deps.repositories.jobs; - const existingJob = await jobsRepo.findExistingJobForHead(c.env as any, { - owner: extracted.owner, - repo: extracted.repo, - prNumber: extracted.prNumber, - commitSha: extracted.commitSha, - trigger: extracted.trigger, - }); - - if (existingJob) { - return c.json( - { - ok: true, - duplicate: true, - message: existingJob.status === "queued" ? "queued" : "duplicate", - job: existingJob, - }, - 202, - ); + if (extracted) { + if (extracted.commitSha && extracted.baseSha) { + const jobsRepo = c.env.deps.repositories.jobs; + const existingJob = await jobsRepo.findExistingJobForHead(c.env as any, { + owner: extracted.owner, + repo: extracted.repo, + prNumber: extracted.prNumber, + commitSha: extracted.commitSha, + trigger: extracted.trigger, + }); + + if (existingJob) { + return c.json( + { + ok: true, + duplicate: true, + message: existingJob.status === "queued" ? "queued" : "duplicate", + job: existingJob, + }, + 202, + ); + } } const throttled = await c.env.deps.checkQuota?.({ @@ -239,40 +270,61 @@ export async function handleGitHubWebhook(c: Context) { return c.json({ ok: true, ignored: true, reason: "quota_exceeded" }, 202); } - const job = await jobsRepo.insertJob(c.env as any, { - installationId: extracted.installationId, - owner: extracted.owner, - repo: extracted.repo, - prNumber: extracted.prNumber, - prTitle: extracted.prTitle, - prAuthor: extracted.prAuthor, - commitSha: extracted.commitSha, - baseSha: extracted.baseSha, - trigger: extracted.trigger, - headRef: extracted.headRef, - baseRef: extracted.baseRef, - configSnapshot: repoConfig.parsedJson, - }); + if (extracted.commitSha && extracted.baseSha) { + const jobsRepo = c.env.deps.repositories.jobs; + const job = await jobsRepo.insertJob(c.env as any, { + installationId: extracted.installationId, + owner: extracted.owner, + repo: extracted.repo, + prNumber: extracted.prNumber, + prTitle: extracted.prTitle, + prAuthor: extracted.prAuthor, + commitSha: extracted.commitSha, + baseSha: extracted.baseSha, + trigger: extracted.trigger, + headRef: extracted.headRef, + baseRef: extracted.baseRef, + configSnapshot: repoConfig.parsedJson, + }); + + await jobsRepo.supersedeOlderJobs(c.env as any, { + installationId: extracted.installationId, + owner: extracted.owner, + repo: extracted.repo, + prNumber: extracted.prNumber, + newJobId: job.id, + }); - await jobsRepo.supersedeOlderJobs(c.env as any, { - installationId: extracted.installationId, - owner: extracted.owner, - repo: extracted.repo, - prNumber: extracted.prNumber, - newJobId: job.id, - }); + await c.env.deps.platform.enqueueReviewJob({ + jobId: job.id, + deliveryId, + phase: "prepare", + requestId: c.get("requestId"), + }); + return c.json({ ok: true, message: "queued", job }, 202); + } + + // Mention triggers resolve PR head/base SHAs inside the worker. await c.env.deps.platform.enqueueReviewJob({ - jobId: job.id, deliveryId, - phase: "prepare", + eventName: canonicalEventName, requestId: c.get("requestId"), - }); + } as any); - return c.json({ ok: true, message: "queued", job }, 202); + return c.json({ ok: true, message: "queued" }, 202); + } + + // Only enqueue non-review events that still need worker-side cleanup (e.g., removing review labels on PR close). + const needsCloseLabelCleanup = + normalized.eventName === "change_request" && + normalized.payload?.action === "closed" && + repoConfig.parsedJson.review.labels !== false; + + if (!needsCloseLabelCleanup) { + return c.json({ ok: true, ignored: true }, 202); } - // Events without a concrete job (e.g. PR close cleanup, mention lookups) still get handled by the worker. await c.env.deps.platform.enqueueReviewJob({ deliveryId, eventName: canonicalEventName, diff --git a/packages/core/src/ports/index.ts b/packages/core/src/ports/index.ts index efa50c72..4d5ed212 100644 --- a/packages/core/src/ports/index.ts +++ b/packages/core/src/ports/index.ts @@ -23,6 +23,7 @@ export type { RepoConfigLoader, ReviewSettingsReader, WebhookDeliveryReader, + WebhookRuntime, } from "./settings"; export type { GitProviderFactory, diff --git a/packages/core/src/ports/runtime.ts b/packages/core/src/ports/runtime.ts index 761328d6..d938ab7c 100644 --- a/packages/core/src/ports/runtime.ts +++ b/packages/core/src/ports/runtime.ts @@ -10,7 +10,7 @@ import type { ModelConfigReader, RepoConfigLoader, ReviewSettingsReader, - WebhookDeliveryReader, + WebhookRuntime, } from "./settings"; import type { TelemetrySink } from "./telemetry"; @@ -22,7 +22,7 @@ export interface ReviewRuntime { jobs: JobStore; fileReviews: FileReviewStore; settings: ReviewSettingsReader; - webhooks: WebhookDeliveryReader; + webhooks: WebhookRuntime; learning: LearningStore; modelConfigs: ModelConfigReader; repoConfig: RepoConfigLoader; diff --git a/packages/core/src/ports/settings.ts b/packages/core/src/ports/settings.ts index 78e3988d..e7753a4d 100644 --- a/packages/core/src/ports/settings.ts +++ b/packages/core/src/ports/settings.ts @@ -30,7 +30,10 @@ export interface WebhookDeliveryReader { event_name: string; payload: unknown; } | null>; - normalizePayload?( +} + +export interface WebhookRuntime extends WebhookDeliveryReader { + normalizePayload( eventName: string, payload: unknown, ): { eventName: WebhookEventName; payload: WebhookPayload } | null; diff --git a/packages/core/src/review/diff-cache.ts b/packages/core/src/review/diff-cache.ts index c96a388f..ddcf0e04 100644 --- a/packages/core/src/review/diff-cache.ts +++ b/packages/core/src/review/diff-cache.ts @@ -21,15 +21,25 @@ export function incrementalDiffCacheKey( return `diff:${jobId}:${previousCommitSha}..${newHeadSha}`; } +const COMMIT_SHA_RE = /^[0-9a-f]{4,40}$/i; + async function getOrFetchCachedDiff( env: Pick, cacheKey: string, fetchDiff: () => Promise, + cacheReadFailureMessage: string, cacheFailureMessage: string, ): Promise { - const cached = await env.kv.get(cacheKey); - if (cached != null) { - return cached; + try { + const cached = await env.kv.get(cacheKey); + if (cached != null) { + return cached; + } + } catch (error) { + logger.warn( + cacheReadFailureMessage, + error instanceof Error ? error : new Error(String(error)), + ); } const rawDiff = await fetchDiff(); @@ -57,6 +67,7 @@ export async function getDiffFiles( env, diffCacheKey(job.id), () => github.getPullRequestDiff(job.owner, job.repo, job.prNumber), + `Failed to read cached PR diff for job ${job.id}; fetching from GitHub`, `Failed to cache PR diff for job ${job.id}; it will be re-fetched on the next phase`, ); @@ -86,20 +97,23 @@ export async function getIncrementalDiffFiles( newHeadSha: string, maxFiles: number = reviewMaxFilesRange.default, ): Promise<{ files: FileDiff[]; skipped: number }> { - if (!previousCommitSha?.trim() || !newHeadSha?.trim()) { + const prevSha = previousCommitSha?.trim() ?? ""; + const headSha = newHeadSha?.trim() ?? ""; + if (!prevSha || !headSha) { throw new Error("Incremental diff requires non-empty commit SHAs"); } + if (!COMMIT_SHA_RE.test(prevSha) || !COMMIT_SHA_RE.test(headSha)) { + throw new Error("Incremental diff requires valid hex commit SHAs"); + } + if (prevSha.toLowerCase() === headSha.toLowerCase()) { + return { files: [], skipped: 0 }; + } const rawDiff = await getOrFetchCachedDiff( env, - incrementalDiffCacheKey(job.id, previousCommitSha, newHeadSha), - () => - github.getCompareDiff( - job.owner, - job.repo, - previousCommitSha, - newHeadSha, - ), + incrementalDiffCacheKey(job.id, prevSha, headSha), + () => github.getCompareDiff(job.owner, job.repo, prevSha, headSha), + `Failed to read cached incremental diff for job ${job.id}; fetching from GitHub`, `Failed to cache incremental diff for job ${job.id}; it will be re-fetched on the next phase`, ); @@ -126,6 +140,7 @@ export async function getOrFetchRawDiffForCompletedJob( diffCacheKey(job.id), () => github.getCompareDiff(job.owner, job.repo, job.baseSha, job.commitSha), + `Failed to read cached reconstructed diff for job ${job.id}; fetching from GitHub`, `Failed to cache reconstructed diff for job ${job.id}`, ); } diff --git a/packages/core/src/review/request.ts b/packages/core/src/review/request.ts index 4c10f1cf..6c2544d1 100644 --- a/packages/core/src/review/request.ts +++ b/packages/core/src/review/request.ts @@ -4,7 +4,41 @@ import type { CommentWebhookPayload, ChangeRequestWebhookPayload, } from "@codraoss/schema/webhook"; -import type { RepoConfig } from "@codraoss/schema"; +import { DEFAULT_MENTION_TRIGGER, type RepoConfig } from "@codraoss/schema"; + +function stripQuotedAndCode(body: string): string { + return body + .replace(/```[\s\S]*?```/g, " ") + .replace(/~~~[\s\S]*?~~~/g, " ") + .replace(/`[^`\n]+`/g, " ") + .replace(/^[ \t]*>.*$/gm, " "); +} + +function escapeRegExp(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +function hasMentionTrigger(body: string, trigger: string): boolean { + const trimmed = trigger.trim(); + if (!trimmed) return false; + const pattern = new RegExp( + `(?:^|(? + hasMentionTrigger(sanitizedBody, trigger), + ); if (!matchesTrigger) { return null; diff --git a/packages/core/src/review/resolve-job.ts b/packages/core/src/review/resolve-job.ts index 7718d8f6..b7770563 100644 --- a/packages/core/src/review/resolve-job.ts +++ b/packages/core/src/review/resolve-job.ts @@ -1,7 +1,6 @@ import type { ReviewJobMessage } from "@codraoss/schema"; import type { ChangeRequestWebhookPayload, - WebhookEventName, WebhookPayload, } from "@codraoss/schema/webhook"; import { logger } from "../logger"; @@ -9,102 +8,8 @@ import type { ReviewRuntime } from "../ports"; import type { PersistedReviewJob } from "./phase-control"; import { extractReviewRequest } from "./request"; -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null; -} - -function normalizeRawGitHubEvent( - eventName: string, - payload: unknown, -): { eventName: WebhookEventName; payload: WebhookPayload } | null { - if (!isRecord(payload)) { - return null; - } - const raw = payload as any; - - if (eventName === "pull_request" || eventName === "change_request") { - if ("changeRequest" in payload) { - return { eventName: "change_request", payload: raw as WebhookPayload }; - } - if (raw.pull_request) { - return { - eventName: "change_request", - payload: { - action: raw.action, - installationId: String( - raw.installation?.id ?? raw.installationId ?? "", - ), - repository: { - owner: - typeof raw.repository?.owner === "string" - ? raw.repository.owner - : (raw.repository?.owner?.login ?? ""), - name: raw.repository?.name ?? "", - }, - changeRequest: { - number: raw.pull_request.number, - title: raw.pull_request.title, - author: raw.pull_request.user?.login ?? "", - head: { - sha: raw.pull_request.head?.sha ?? "", - ref: raw.pull_request.head?.ref ?? "", - }, - base: { - sha: raw.pull_request.base?.sha ?? "", - ref: raw.pull_request.base?.ref ?? "", - }, - draft: Boolean(raw.pull_request.draft), - body: raw.pull_request.body ?? null, - }, - }, - }; - } - if (raw.repository) { - return { - eventName: "change_request", - payload: raw as WebhookPayload, - }; - } - } - - if (eventName === "issue_comment" || eventName === "comment") { - if (isRecord(payload.issue) && "isChangeRequest" in payload.issue) { - return { eventName: "comment", payload: raw as WebhookPayload }; - } - if (raw.comment && isRecord(payload.issue)) { - return { - eventName: "comment", - payload: { - action: raw.action, - installationId: String( - raw.installation?.id ?? raw.installationId ?? "", - ), - repository: { - owner: - typeof raw.repository?.owner === "string" - ? raw.repository.owner - : (raw.repository?.owner?.login ?? ""), - name: raw.repository?.name ?? "", - }, - issue: { - number: raw.issue.number, - isChangeRequest: !!raw.issue.pull_request, - }, - comment: { - body: raw.comment.body ?? "", - }, - }, - }; - } - if (raw.repository) { - return { - eventName: "comment", - payload: raw as WebhookPayload, - }; - } - } - - return null; +function isPlainRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); } export async function resolveQueuedJob( @@ -139,46 +44,30 @@ export async function resolveQueuedJob( } const rawEventName = delivery.event_name || eventName; - const rawPayload = delivery.payload; - - const normalized = env.webhooks.normalizePayload - ? env.webhooks.normalizePayload(rawEventName, rawPayload) - : null; - - if (normalized) { - eventName = normalized.eventName; - payload = normalized.payload; - } else { - const fallback = normalizeRawGitHubEvent(rawEventName, rawPayload); - if (fallback) { - eventName = fallback.eventName; - payload = fallback.payload; - } else { - eventName = rawEventName; - payload = rawPayload as WebhookPayload; - } + const normalized = env.webhooks.normalizePayload( + rawEventName, + delivery.payload, + ); + if (!normalized) { + logger.info( + `Queue message ignored: unsupported or malformed webhook event ${rawEventName}`, + ); + return null; } - } else { - const normalized = env.webhooks.normalizePayload - ? env.webhooks.normalizePayload(eventName, payload) - : null; - if (normalized) { - eventName = normalized.eventName; - payload = normalized.payload; - } else { - const fallback = normalizeRawGitHubEvent(eventName, payload); - if (fallback) { - eventName = fallback.eventName; - payload = fallback.payload; - } + eventName = normalized.eventName; + payload = normalized.payload; + } else { + const normalized = env.webhooks.normalizePayload(eventName, payload); + if (!normalized) { + logger.info( + `Queue message ignored: unsupported or malformed webhook event ${eventName}`, + ); + return null; } - } - if (eventName === "issue_comment") { - eventName = "comment"; - } else if (eventName === "pull_request") { - eventName = "change_request"; + eventName = normalized.eventName; + payload = normalized.payload; } if (eventName !== "change_request" && eventName !== "comment") { @@ -189,7 +78,11 @@ export async function resolveQueuedJob( } const installationId = String(payload?.installationId ?? ""); - if (!installationId || !isRecord(payload) || !("repository" in payload) || !payload.repository) { + if ( + !installationId || + !isPlainRecord(payload) || + !isPlainRecord(payload.repository) + ) { logger.info( "Queue message ignored: missing installation or repository info", ); diff --git a/packages/core/test/in-memory-mocks.ts b/packages/core/test/in-memory-mocks.ts index 5a7ea061..709b3f65 100644 --- a/packages/core/test/in-memory-mocks.ts +++ b/packages/core/test/in-memory-mocks.ts @@ -1,4 +1,5 @@ import type { ParsedReviewComment } from "@codraoss/schema"; +import type { WebhookEventName, WebhookPayload } from "@codraoss/schema/webhook"; import type { PersistedReviewJob, ReviewFormatter, @@ -178,3 +179,89 @@ export function createMockFormatter(): ReviewFormatter { `### Codra Review\nReviewed ${commitSha.slice(0, 7)}: ${postedFindings} posted`, }; } + +function isPlainRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +// Test-only normalizer so core unit tests can seed raw GitHub-shaped fixtures without importing provider-github. +export function defaultTestNormalizePayload( + eventName: string, + payload: unknown, +): { eventName: WebhookEventName; payload: WebhookPayload } | null { + if (!isPlainRecord(payload)) return null; + const raw = payload as any; + + if (eventName === "pull_request" || eventName === "change_request") { + if (isPlainRecord(payload.changeRequest) && isPlainRecord(payload.repository)) { + return { eventName: "change_request", payload: raw as WebhookPayload }; + } + if (isPlainRecord(raw.pull_request) && isPlainRecord(raw.repository)) { + return { + eventName: "change_request", + payload: { + action: raw.action, + installationId: String(raw.installation?.id ?? raw.installationId ?? ""), + repository: { + owner: + typeof raw.repository?.owner === "string" + ? raw.repository.owner + : (raw.repository?.owner?.login ?? ""), + name: raw.repository?.name ?? "", + }, + changeRequest: { + number: raw.pull_request.number, + title: raw.pull_request.title, + author: raw.pull_request.user?.login ?? "", + head: { + sha: raw.pull_request.head?.sha ?? "", + ref: raw.pull_request.head?.ref ?? "", + }, + base: { + sha: raw.pull_request.base?.sha ?? "", + ref: raw.pull_request.base?.ref ?? "", + }, + draft: Boolean(raw.pull_request.draft), + body: raw.pull_request.body ?? null, + }, + }, + }; + } + } + + if (eventName === "issue_comment" || eventName === "comment") { + if ( + isPlainRecord(payload.issue) && + "isChangeRequest" in payload.issue && + isPlainRecord(payload.comment) && + isPlainRecord(payload.repository) + ) { + return { eventName: "comment", payload: raw as WebhookPayload }; + } + if (isPlainRecord(raw.comment) && isPlainRecord(raw.issue) && isPlainRecord(raw.repository)) { + return { + eventName: "comment", + payload: { + action: raw.action, + installationId: String(raw.installation?.id ?? raw.installationId ?? ""), + repository: { + owner: + typeof raw.repository?.owner === "string" + ? raw.repository.owner + : (raw.repository?.owner?.login ?? ""), + name: raw.repository?.name ?? "", + }, + issue: { + number: raw.issue.number, + isChangeRequest: !!raw.issue.pull_request, + }, + comment: { + body: typeof raw.comment.body === "string" ? raw.comment.body : "", + }, + }, + }; + } + } + + return null; +} diff --git a/packages/core/test/in-memory.ts b/packages/core/test/in-memory.ts index dc8794a4..97056a38 100644 --- a/packages/core/test/in-memory.ts +++ b/packages/core/test/in-memory.ts @@ -16,6 +16,7 @@ import { createMockFormatter, createMockGitHub, createMockModel, + defaultTestNormalizePayload, TokenTrackerStub, } from "./in-memory-mocks"; @@ -347,9 +348,7 @@ export function createInMemoryRuntime( webhooks: { getWebhookDelivery: async (deliveryId: string) => seed.deliveries?.get(deliveryId) ?? null, - ...(seed.normalizePayload - ? { normalizePayload: seed.normalizePayload } - : {}), + normalizePayload: seed.normalizePayload ?? defaultTestNormalizePayload, }, learning: { getRepositoryIdForJob: async () => 1, diff --git a/packages/core/test/request.spec.ts b/packages/core/test/request.spec.ts new file mode 100644 index 00000000..90f093dd --- /dev/null +++ b/packages/core/test/request.spec.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from "vitest"; +import { defaultRepoConfig } from "@codraoss/schema"; +import { extractReviewRequest } from "../src/review/request"; + +describe("extractReviewRequest mention hardening", () => { + const baseCommentPayload = { + action: "created" as const, + installationId: "123", + repository: { owner: "acme", name: "widgets" }, + issue: { number: 7, isChangeRequest: true }, + }; + + it("ignores bot comments and self-mentions to prevent trigger loops", () => { + expect( + extractReviewRequest({ + eventName: "comment", + payload: { + ...baseCommentPayload, + comment: { body: "@codra review", author: "some-bot[bot]", isBot: true }, + }, + botUsername: "codra-app", + config: defaultRepoConfig, + }), + ).toBeNull(); + + expect( + extractReviewRequest({ + eventName: "comment", + payload: { + ...baseCommentPayload, + comment: { body: "@codra review", author: "codra-app" }, + }, + botUsername: "codra-app", + config: defaultRepoConfig, + }), + ).toBeNull(); + }); + + it("matches case-insensitively with token boundaries and ignores code blocks, quotes, emails, and bare mentions", () => { + const cases: Array<{ body: string; expected: boolean }> = [ + { body: "@Codra Review please", expected: true }, + { body: "Please run @CODRA-APP", expected: true }, + { body: "Hey @my-codra-bot review", expected: true }, + { body: "Thanks @my-codra-bot!", expected: false }, + { body: "Ping @codra-bot review", expected: false }, + { body: "Contact user@codra.dev", expected: false }, + { body: "```\n@codra review\n```", expected: false }, + { body: "Run `@codra review` to trigger", expected: false }, + { body: "> @codra review\nLooks fine", expected: false }, + ]; + + for (const testCase of cases) { + const req = extractReviewRequest({ + eventName: "comment", + payload: { + ...baseCommentPayload, + comment: { body: testCase.body, author: "human-dev", isBot: false }, + }, + botUsername: "my-codra-bot", + config: defaultRepoConfig, + }); + expect(Boolean(req), `body=${JSON.stringify(testCase.body)}`).toBe(testCase.expected); + } + }); + + it("respects custom mention_trigger without falling back to @codra review", () => { + const customConfig = { + ...defaultRepoConfig, + review: { ...defaultRepoConfig.review, mention_trigger: "!please-review" }, + }; + + expect( + extractReviewRequest({ + eventName: "comment", + payload: { + ...baseCommentPayload, + comment: { body: "@codra review", author: "human-dev", isBot: false }, + }, + botUsername: "codra-app", + config: customConfig, + }), + ).toBeNull(); + + expect( + extractReviewRequest({ + eventName: "comment", + payload: { + ...baseCommentPayload, + comment: { body: "!please-review", author: "human-dev", isBot: false }, + }, + botUsername: "codra-app", + config: customConfig, + })?.trigger, + ).toBe("mention"); + }); +}); diff --git a/packages/core/test/resolve-job.spec.ts b/packages/core/test/resolve-job.spec.ts index 4ba9d0b1..9b7c9e3d 100644 --- a/packages/core/test/resolve-job.spec.ts +++ b/packages/core/test/resolve-job.spec.ts @@ -391,10 +391,10 @@ describe("resolveQueuedJob", () => { const deliveries = new Map([ ["d-null-issue", { delivery_id: "d-null-issue", event_name: "issue_comment", payload: { issue: null } }], ["d-prim", { delivery_id: "d-prim", event_name: "issue_comment", payload: "bad-payload" }], + ["d-partial-repo", { delivery_id: "d-partial-repo", event_name: "issue_comment", payload: { repository: { owner: "acme", name: "widgets" } } }], ]); const { runtime } = createInMemoryRuntime({ noDefaultJob: true, deliveries }); - runtime.webhooks.normalizePayload = undefined; await expect( resolveQueuedJob(runtime, { deliveryId: "d-null-issue", eventName: "issue_comment" }), @@ -402,5 +402,8 @@ describe("resolveQueuedJob", () => { await expect( resolveQueuedJob(runtime, { deliveryId: "d-prim", eventName: "issue_comment" }), ).resolves.toBeNull(); + await expect( + resolveQueuedJob(runtime, { deliveryId: "d-partial-repo", eventName: "issue_comment" }), + ).resolves.toBeNull(); }); }); diff --git a/packages/models/src/providers/openai.ts b/packages/models/src/providers/openai.ts index 6cb468a0..a595feb1 100644 --- a/packages/models/src/providers/openai.ts +++ b/packages/models/src/providers/openai.ts @@ -13,10 +13,12 @@ import { profileSampling } from "./profile-sampling"; const OPENAI_TIMEOUT_MS = MODEL_TIMEOUT_MAX_MS; const OPENAI_DEFAULT_OUTPUT_TOKENS = 4096; +const OPENAI_REASONING_DEFAULT_OUTPUT_TOKENS = 8192; const OPENAI_MAX_OUTPUT_TOKENS = 16_384; export interface OpenAIResponse { choices?: Array<{ + finish_reason?: string | null; message?: { content?: string | Array<{ text?: string; type?: string }>; reasoning_content?: string; @@ -31,13 +33,27 @@ export interface OpenAIResponse { }; } +function normalizeOpenAiModelId(model: string): string { + let normalized = model.trim().toLowerCase(); + if (normalized.startsWith("ft:")) { + normalized = normalized.slice(3).split(":")[0] ?? normalized; + } + const slashIdx = normalized.lastIndexOf("/"); + if (slashIdx !== -1) { + normalized = normalized.slice(slashIdx + 1); + } + return normalized; +} + export function isOpenAIReasoningModel(model: string): boolean { - const lower = model.toLowerCase(); - return ( - /^o\d/.test(lower) || - lower.includes("-reasoning") || - lower.startsWith("gpt-6") - ); + const base = normalizeOpenAiModelId(model); + if (/^o[1-9](?:$|[-.])/.test(base)) { + return true; + } + if (/^gpt-[56](?:$|[-.])/.test(base) && !base.includes("-chat")) { + return true; + } + return false; } export type OpenAIReasoningEffort = "low" | "medium" | "high"; @@ -121,10 +137,6 @@ function extractOpenAiText(data: OpenAIResponse) { .trim(); if (text) return text; } - const reasoningContent = choice?.message?.reasoning_content; - if (typeof reasoningContent === "string" && reasoningContent.trim()) { - return reasoningContent.trim(); - } const outputText = data?.output_text; if (typeof outputText === "string") return outputText.trim(); return ""; @@ -147,10 +159,14 @@ export async function reviewWithOpenAI( ): Promise { logger.info(`Calling OpenAI-format model: ${model}`); const timeoutMs = config.timeoutMs ?? OPENAI_TIMEOUT_MS; + const baseModel = normalizeOpenAiModelId(model); + const isReasoning = isOpenAIReasoningModel(model); const outputCeiling = resolveOutputTokenCeiling( input.outputBudgetTokens, OPENAI_MAX_OUTPUT_TOKENS, - OPENAI_DEFAULT_OUTPUT_TOKENS, + isReasoning + ? OPENAI_REASONING_DEFAULT_OUTPUT_TOKENS + : OPENAI_DEFAULT_OUTPUT_TOKENS, ); assertPublicBaseUrl(config.baseUrl, config.providerName); @@ -175,28 +191,33 @@ export async function reviewWithOpenAI( ? Math.max(outputCeiling, 2048) : outputCeiling; - const isReasoning = isOpenAIReasoningModel(model); - // o1-mini and o1-preview reject `reasoning_effort` with HTTP 400 on OpenAI's API. - const supportsReasoningEffort = - isReasoning && - !lowerModel.startsWith("o1-mini") && - !lowerModel.startsWith("o1-preview"); + // Legacy o1-mini and o1-preview reject `developer`/`system` roles, `reasoning_effort`, and `response_format`. + const isLegacyO1 = + baseModel === "o1-mini" || + baseModel.startsWith("o1-mini-") || + baseModel === "o1-preview" || + baseModel.startsWith("o1-preview-"); + const supportsReasoningEffort = isReasoning && !isLegacyO1; const reasoningEffort = supportsReasoningEffort ? reasoningEffortFor(sampling?.thinkingBudget) : undefined; + const messages = isLegacyO1 + ? [{ role: "user", content: `${prompts.system}\n\n${prompts.user}` }] + : [ + { role: isReasoning ? "developer" : "system", content: prompts.system }, + { role: "user", content: prompts.user }, + ]; + const bodyPayload: Record = { model, - messages: [ - { role: isReasoning ? "developer" : "system", content: prompts.system }, - { role: "user", content: prompts.user }, - ], + messages, ...(isReasoning ? { max_completion_tokens: effectiveCeiling } : { temperature, max_tokens: effectiveCeiling }), ...(sampling?.topP !== undefined && !isReasoning ? { top_p: sampling.topP } : {}), ...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}), - response_format: { type: "json_object" }, + ...(!isLegacyO1 ? { response_format: { type: "json_object" } } : {}), }; if (isZai) { @@ -260,6 +281,21 @@ export async function reviewWithOpenAI( const data = (await response.json()) as OpenAIResponse; const rawText = extractOpenAiText(data); if (!rawText) { + const choice = data?.choices?.[0]; + const finishReason = choice?.finish_reason; + const hasReasoningOnly = + typeof choice?.message?.reasoning_content === "string" && + choice.message.reasoning_content.trim().length > 0; + if (hasReasoningOnly) { + throw new Error( + `OpenAI provider returned a reasoning-only response${finishReason ? ` (finish_reason=${finishReason})` : ""}.`, + ); + } + if (finishReason) { + throw new Error( + `OpenAI provider returned an empty response (finish_reason=${finishReason}).`, + ); + } throw new Error("OpenAI provider returned an empty response."); } @@ -283,5 +319,6 @@ export async function reviewWithOpenAI( throw lastError ?? new Error("OpenAI request failed after retries."); } +/** @deprecated Use {@link reviewWithOpenAI} instead. */ export const callOpenAi = reviewWithOpenAI; diff --git a/packages/models/test/providers/openai.test.ts b/packages/models/test/providers/openai.test.ts index 50cdba25..0636385d 100644 --- a/packages/models/test/providers/openai.test.ts +++ b/packages/models/test/providers/openai.test.ts @@ -50,7 +50,7 @@ describe("OpenAI provider adapter", () => { }; describe("isOpenAIReasoningModel", () => { - it("returns true for reasoning models", () => { + it("returns true for OpenAI reasoning models including gpt-5, gateway prefixes, and fine-tunes", () => { const reasoningModels = [ "o1", "o1-mini", @@ -58,14 +58,17 @@ describe("OpenAI provider adapter", () => { "o3", "o3-mini", "o4-mini", + "gpt-5", + "gpt-5-mini", + "gpt-5.1", "gpt-6", "gpt-6-preview", - "custom-reasoning", - "deepseek-reasoning", + "openai/o3-mini", + "azure/gpt-5", + "ft:o4-mini:org:name:abc", "O1", "O3-MINI", "GPT-6-TURBO", - "CUSTOM-MODEL-REASONING", ]; for (const model of reasoningModels) { @@ -76,16 +79,19 @@ describe("OpenAI provider adapter", () => { } }); - it("returns false for standard / non-reasoning models", () => { + it("returns false for standard, chat, and non-OpenAI reasoning models", () => { const nonReasoningModels = [ "gpt-4o", "gpt-4o-mini", - "gpt-5", + "gpt-5-chat-latest", "gpt-4-turbo", "gpt-3.5-turbo", "chatgpt-4o-latest", "claude-3-5-sonnet", "gemini-2.5-flash", + "custom-reasoning", + "deepseek-reasoning", + "CUSTOM-MODEL-REASONING", ]; for (const model of nonReasoningModels) { @@ -203,31 +209,67 @@ describe("OpenAI provider adapter", () => { expect(body.response_format).toEqual({ type: "json_object" }); }); - it("works with reviewWithOpenAI function directly", async () => { - const fetchSpy = vi - .spyOn(globalThis, "fetch") - .mockResolvedValueOnce(mockOpenAiResponse()); + it("constructs legacy user-only payload without response_format for o1-mini and o1-preview", async () => { + for (const model of ["o1-mini", "o1-preview", "openai/o1-mini"]) { + const fetchSpy = vi + .spyOn(globalThis, "fetch") + .mockResolvedValueOnce(mockOpenAiResponse()); - await reviewWithOpenAI( - { - apiKey: "test-api-key", - baseUrl: "https://api.openai.com/v1", - providerName: "OpenAI", - }, - "o1-mini", - input, + await reviewWithOpenAI( + { + apiKey: "test-api-key", + baseUrl: "https://api.openai.com/v1", + providerName: "OpenAI", + }, + model, + input, + ); + + const body = getRequestBody(fetchSpy); + expect(body.model).toBe(model); + expect(body.max_completion_tokens).toBeDefined(); + expect(body.temperature).toBeUndefined(); + expect(body.max_tokens).toBeUndefined(); + expect(body.response_format).toBeUndefined(); + expect(body.reasoning_effort).toBeUndefined(); + const messages = body.messages as Array<{ role: string; content: string }>; + expect(messages).toHaveLength(1); + expect(messages[0].role).toBe("user"); + expect(messages[0].content).toContain("You are a code reviewer."); + expect(messages[0].content).toContain("Review this pull request diff."); + vi.restoreAllMocks(); + } + }); + + it("rejects reasoning-only and truncated length responses instead of returning reasoning prose", async () => { + vi.spyOn(globalThis, "fetch").mockResolvedValueOnce( + new Response( + JSON.stringify({ + choices: [ + { + finish_reason: "length", + message: { + content: "", + reasoning_content: "Let me think step by step...", + }, + }, + ], + }), + { status: 200, headers: { "content-type": "application/json" } }, + ), ); - const body = getRequestBody(fetchSpy); - expect(body.model).toBe("o1-mini"); - expect(body.max_completion_tokens).toBeDefined(); - expect(body.temperature).toBeUndefined(); - expect(body.max_tokens).toBeUndefined(); - const messages = body.messages as Array<{ role: string; content: string }>; - expect(messages[0].role).toBe("developer"); - expect(messages[0].content).toContain("You are a code reviewer."); - expect(messages[1].role).toBe("user"); - expect(messages[1].content).toContain("Review this pull request diff."); + await expect( + reviewWithOpenAI( + { + apiKey: "test-api-key", + baseUrl: "https://api.openai.com/v1", + providerName: "OpenAI", + }, + "o3-mini", + input, + ), + ).rejects.toThrow(/reasoning-only response.*finish_reason=length/i); }); }); @@ -326,5 +368,46 @@ describe("OpenAI provider adapter", () => { expect(await requestBodyFor("o1-mini", 20000)).not.toHaveProperty("reasoning_effort"); expect(await requestBodyFor("o1-preview", "high")).not.toHaveProperty("reasoning_effort"); }); + + it("strips mocked topP on reasoning models while sending it on standard models", async () => { + const makeProfile = (model: string) => + ModelProfileSchema.parse({ + id: model, + provider: "openai", + displayName: model, + sampling: { temperature: 0.5, topP: 0.85 }, + prompts: {}, + schema: {}, + limits: {}, + verification: {}, + }); + + vi.spyOn(ModelRegistryService.getInstance(), "findProfile").mockReturnValue( + makeProfile("o3-mini"), + ); + let fetchSpy = vi + .spyOn(globalThis, "fetch") + .mockResolvedValueOnce(mockOpenAiResponse()); + await reviewWithOpenAI( + { apiKey: "k", baseUrl: "https://api.openai.com/v1", providerName: "OpenAI" }, + "o3-mini", + input, + ); + expect(getRequestBody(fetchSpy).top_p).toBeUndefined(); + vi.restoreAllMocks(); + + vi.spyOn(ModelRegistryService.getInstance(), "findProfile").mockReturnValue( + makeProfile("gpt-4o"), + ); + fetchSpy = vi + .spyOn(globalThis, "fetch") + .mockResolvedValueOnce(mockOpenAiResponse()); + await reviewWithOpenAI( + { apiKey: "k", baseUrl: "https://api.openai.com/v1", providerName: "OpenAI" }, + "gpt-4o", + input, + ); + expect(getRequestBody(fetchSpy).top_p).toBe(0.85); + }); }); }); diff --git a/packages/provider-github/src/client.ts b/packages/provider-github/src/client.ts index a82adb3c..af4883ed 100644 --- a/packages/provider-github/src/client.ts +++ b/packages/provider-github/src/client.ts @@ -285,29 +285,33 @@ export class GitHubClient { detailsUrl?: string; }, ) { - return withRetry(`createCheckRun ${owner}/${repo}`, async () => { - const response = await this.requestAndCheck( - `${repoApiPath(owner, repo)}/check-runs`, - { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: JSON.stringify({ - name: "Codra", - head_sha: input.headSha, - status: "in_progress", - details_url: input.detailsUrl, - output: { - title: input.title, - summary: input.summary, + return withRetry( + `createCheckRun ${owner}/${repo}`, + async () => { + const response = await this.requestAndCheck( + `${repoApiPath(owner, repo)}/check-runs`, + { + method: "POST", + headers: { + "content-type": "application/json", }, - }), - }, - ); + body: JSON.stringify({ + name: "Codra", + head_sha: input.headSha, + status: "in_progress", + details_url: input.detailsUrl, + output: { + title: input.title, + summary: input.summary, + }, + }), + }, + ); - return (await response.json()) as { id: number }; - }); + return (await response.json()) as { id: number }; + }, + { retryServerErrors: false }, + ); } async updateCheckRun( diff --git a/packages/provider-github/src/http.ts b/packages/provider-github/src/http.ts index 51b81815..48d649b8 100644 --- a/packages/provider-github/src/http.ts +++ b/packages/provider-github/src/http.ts @@ -1,15 +1,52 @@ import { logger } from "@codraoss/core/logger"; +const ALLOWED_ERROR_HEADERS = [ + "retry-after", + "x-ratelimit-reset", + "x-ratelimit-remaining", + "x-ratelimit-limit", + "x-github-request-id", +] as const; + +const DEFAULT_MAX_RETRY_DELAY_MS = 60_000; + +function sanitizeGitHubHeaders( + headers?: Headers | Record, +): Record | undefined { + if (!headers) return undefined; + const out: Record = {}; + if (typeof (headers as Headers).get === "function") { + for (const key of ALLOWED_ERROR_HEADERS) { + const value = (headers as Headers).get(key); + if (typeof value === "string" && value.length > 0) { + out[key] = value; + } + } + } else { + const allowed = new Set(ALLOWED_ERROR_HEADERS); + for (const [key, value] of Object.entries(headers)) { + const lower = key.toLowerCase(); + if (allowed.has(lower) && typeof value === "string" && value.length > 0) { + out[lower] = value; + } + } + } + return Object.keys(out).length > 0 ? out : undefined; +} + export class GitHubError extends Error { + public readonly headers?: Record; + constructor( public readonly status: number, public readonly body: string, public readonly path: string, message: string, - public readonly headers?: Headers, + headers?: Headers | Record, ) { super(message); this.name = "GitHubError"; + this.headers = sanitizeGitHubHeaders(headers); } } @@ -45,77 +82,151 @@ export function isDiffTooLargeError(error: unknown): boolean { } function getHeader( - headers: Headers | Record | undefined, + headers: Record | undefined, name: string, -): string | null | undefined { +): string | undefined { if (!headers) return undefined; - if (typeof (headers as Headers).get === "function") { - return (headers as Headers).get(name) ?? undefined; + return headers[name.toLowerCase()]; +} + +function parseRetryAfterMs(raw: string | undefined): number | null { + if (!raw) return null; + const trimmed = raw.trim(); + if (/^\d+$/.test(trimmed)) { + return Number(trimmed) * 1000; } - const lower = name.toLowerCase(); - for (const [key, value] of Object.entries(headers)) { - if (key.toLowerCase() === lower && typeof value === "string") { - return value; - } + const timestamp = Date.parse(trimmed); + if (!Number.isNaN(timestamp)) { + return Math.max(0, timestamp - Date.now()); } - return undefined; + return null; +} + +function parseRateLimitResetMs(raw: string | undefined): number | null { + if (!raw) return null; + const trimmed = raw.trim(); + if (!/^\d+$/.test(trimmed)) return null; + return Math.max(0, Number(trimmed) * 1000 - Date.now()) + 1000; } +function sleepWithSignal(ms: number, signal?: AbortSignal): Promise { + if (signal?.aborted) { + return Promise.reject(signal.reason ?? new DOMException("Aborted", "AbortError")); + } + return new Promise((resolve, reject) => { + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason ?? new DOMException("Aborted", "AbortError")); + }; + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} + +export type RetryOptions = { + maxRetries?: number; + maxDelayMs?: number; + signal?: AbortSignal; + retryServerErrors?: boolean; +}; + export async function withRetry( operation: string, fn: () => Promise, - maxRetries = 2, + maxRetriesOrOptions: number | RetryOptions = 2, ): Promise { + const opts: RetryOptions = + typeof maxRetriesOrOptions === "number" + ? { maxRetries: maxRetriesOrOptions } + : maxRetriesOrOptions; + const maxRetries = opts.maxRetries ?? 2; + const maxDelayMs = opts.maxDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS; + const retryServerErrors = opts.retryServerErrors ?? true; + const signal = opts.signal; + let attempt = 0; while (true) { + if (signal?.aborted) { + throw signal.reason ?? new DOMException("Aborted", "AbortError"); + } try { return await fn(); } catch (error: any) { attempt++; + const lowerBody = + error instanceof GitHubError ? error.body?.toLowerCase() ?? "" : ""; + const retryAfterHeader = + error instanceof GitHubError + ? getHeader(error.headers, "retry-after") + : undefined; + const remainingHeader = + error instanceof GitHubError + ? getHeader(error.headers, "x-ratelimit-remaining") + : undefined; + const resetHeader = + error instanceof GitHubError + ? getHeader(error.headers, "x-ratelimit-reset") + : undefined; + const isSecondaryRateLimit = error instanceof GitHubError && error.status === 403 && - error.body?.toLowerCase().includes("secondary rate limit"); + (lowerBody.includes("secondary rate limit") || + lowerBody.includes("abuse detection")); const isPrimaryRateLimit = error instanceof GitHubError && error.status === 403 && - (error.body?.toLowerCase().includes("rate limit exceeded") || - error.body?.toLowerCase().includes("api rate limit")); + (lowerBody.includes("rate limit exceeded") || + lowerBody.includes("api rate limit") || + remainingHeader === "0"); - const isRetryable = + const isRateLimit = isSecondaryRateLimit || isPrimaryRateLimit || (error instanceof GitHubError && - (error.status === 429 || error.status >= 500)) || - error.name === "TimeoutError" || - (typeof error.message === "string" && error.message.includes("timeout")); + error.status === 403 && + retryAfterHeader !== undefined) || + (error instanceof GitHubError && error.status === 429); + + const isServerOrTimeoutError = + (error instanceof GitHubError && error.status >= 500) || + error?.name === "TimeoutError" || + (typeof error?.message === "string" && error.message.includes("timeout")); + + const isRetryable = + isRateLimit || (retryServerErrors && isServerOrTimeoutError); if (!isRetryable || attempt > maxRetries) { throw error; } - const rateLimitReset = - error instanceof GitHubError - ? getHeader(error.headers, "x-ratelimit-reset") - : undefined; - const retryAfter = - error instanceof GitHubError - ? getHeader(error.headers, "retry-after") - : undefined; - - const resetSeconds = rateLimitReset ? parseInt(rateLimitReset, 10) : NaN; - const retrySeconds = retryAfter ? parseInt(retryAfter, 10) : NaN; + const retryAfterMs = parseRetryAfterMs(retryAfterHeader); + const resetMs = + retryAfterMs === null && (isPrimaryRateLimit || remainingHeader === "0") + ? parseRateLimitResetMs(resetHeader) + : null; let delay: number; - if (!Number.isNaN(resetSeconds)) { - delay = Math.max(0, resetSeconds * 1000 - Date.now()) + 1000; - } else if (!Number.isNaN(retrySeconds)) { - delay = Math.max(0, retrySeconds * 1000); - } else if (isSecondaryRateLimit) { - delay = Math.pow(2, attempt) * 30000; + if (retryAfterMs !== null) { + if (retryAfterMs > maxDelayMs) { + throw error; + } + delay = retryAfterMs; + } else if (resetMs !== null) { + if (resetMs > maxDelayMs) { + throw error; + } + delay = resetMs; } else { - delay = Math.pow(2, attempt) * 1000; + const base = isSecondaryRateLimit + ? Math.pow(2, attempt) * 30_000 + : Math.pow(2, attempt) * 1_000; + const jitterFactor = 0.9 + Math.random() * 0.2; + delay = Math.min(maxDelayMs, Math.round(base * jitterFactor)); } logger.warn( @@ -125,7 +236,7 @@ export async function withRetry( error: error.message, }, ); - await new Promise((resolve) => setTimeout(resolve, delay)); + await sleepWithSignal(delay, signal); } } } diff --git a/packages/provider-github/src/review-post.ts b/packages/provider-github/src/review-post.ts index cfa9a97b..6fae9017 100644 --- a/packages/provider-github/src/review-post.ts +++ b/packages/provider-github/src/review-post.ts @@ -67,7 +67,9 @@ export async function postReview( comments: ReviewComment[]; }, ) { - return withRetry(`createReview ${owner}/${repo}#${pullNumber}`, async () => { + return withRetry( + `createReview ${owner}/${repo}#${pullNumber}`, + async () => { // Address by `line` + `side`, or legacy `position`. const mapped = input.comments.map((comment, index) => { if (typeof comment.line === "number" && comment.line > 0) { @@ -188,7 +190,9 @@ export async function postReview( const review = (await response.json()) as { id: number }; return { id: review.id, postedIndices }; - }); + }, + { retryServerErrors: false }, + ); } // Used by finalize to avoid double-posting when an earlier invocation died. diff --git a/packages/provider-github/src/webhook.ts b/packages/provider-github/src/webhook.ts index 46d50d83..c371818d 100644 --- a/packages/provider-github/src/webhook.ts +++ b/packages/provider-github/src/webhook.ts @@ -8,7 +8,7 @@ import type { } from "@codraoss/schema/github"; function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null; + return typeof value === "object" && value !== null && !Array.isArray(value); } export function normalizeGitHubWebhook( @@ -20,11 +20,11 @@ export function normalizeGitHubWebhook( } if (eventName === "pull_request" || eventName === "change_request") { - if ("changeRequest" in payload) { + if (isRecord(payload.changeRequest) && isRecord(payload.repository)) { return { eventName: "change_request", payload: payload as unknown as WebhookPayload }; } const prPayload = payload as unknown as PullRequestWebhookPayload; - if (prPayload.pull_request) { + if (isRecord(prPayload.pull_request) && isRecord(prPayload.repository)) { return { eventName: "change_request", payload: { @@ -60,11 +60,25 @@ export function normalizeGitHubWebhook( } if (eventName === "issue_comment" || eventName === "comment") { - if (isRecord(payload.issue) && "isChangeRequest" in payload.issue) { + if ( + isRecord(payload.issue) && + "isChangeRequest" in payload.issue && + isRecord(payload.comment) && + isRecord(payload.repository) + ) { return { eventName: "comment", payload: payload as unknown as WebhookPayload }; } const icPayload = payload as unknown as IssueCommentWebhookPayload; - if (icPayload.comment && icPayload.issue) { + if (isRecord(icPayload.comment) && isRecord(icPayload.issue) && isRecord(icPayload.repository)) { + const commentUser = isRecord(icPayload.comment.user) + ? icPayload.comment.user + : null; + const author = + typeof commentUser?.login === "string" ? commentUser.login : undefined; + const isBot = + commentUser?.type === "Bot" || + (author ? author.toLowerCase().endsWith("[bot]") : false); + return { eventName: "comment", payload: { @@ -84,7 +98,9 @@ export function normalizeGitHubWebhook( isChangeRequest: !!icPayload.issue.pull_request, }, comment: { - body: icPayload.comment.body ?? "", + body: typeof icPayload.comment.body === "string" ? icPayload.comment.body : "", + ...(author !== undefined ? { author } : {}), + ...(commentUser !== null ? { isBot } : {}), }, }, }; diff --git a/packages/provider-github/test/http.test.ts b/packages/provider-github/test/http.test.ts index 8fac264f..30cda52e 100644 --- a/packages/provider-github/test/http.test.ts +++ b/packages/provider-github/test/http.test.ts @@ -3,10 +3,12 @@ import { GitHubError, assertResponseOk, withRetry } from "../src/http"; import { logger } from "@codraoss/core/logger"; describe("GitHubError", () => { - it("carries headers when provided", () => { + it("extracts allowlisted serializable headers and drops sensitive ones", () => { const headers = new Headers({ "x-ratelimit-reset": "1700000000", "retry-after": "60", + "set-cookie": "session=secret", + "x-oauth-scopes": "repo", }); const error = new GitHubError( 403, @@ -20,9 +22,14 @@ describe("GitHubError", () => { expect(error.body).toBe("API rate limit exceeded"); expect(error.path).toBe("/repos/owner/repo"); expect(error.message).toBe("Request failed"); - expect(error.headers).toBe(headers); - expect(error.headers?.get("x-ratelimit-reset")).toBe("1700000000"); - expect(error.headers?.get("retry-after")).toBe("60"); + expect(error.headers).toEqual({ + "x-ratelimit-reset": "1700000000", + "retry-after": "60", + }); + expect(JSON.parse(JSON.stringify(error.headers))).toEqual({ + "x-ratelimit-reset": "1700000000", + "retry-after": "60", + }); }); it("handles omitted headers gracefully", () => { @@ -37,10 +44,11 @@ describe("assertResponseOk", () => { await expect(assertResponseOk(response, "/test", "Test")).resolves.toBeUndefined(); }); - it("throws GitHubError carrying response headers on error", async () => { + it("throws GitHubError carrying allowlisted response headers on error", async () => { const headers = new Headers({ "x-ratelimit-reset": "1700005000", "retry-after": "30", + "set-cookie": "secret=1", }); const response = new Response("API rate limit exceeded for user ID 12345", { status: 403, @@ -59,9 +67,10 @@ describe("assertResponseOk", () => { expect(gitHubError.status).toBe(403); expect(gitHubError.body).toContain("API rate limit exceeded"); expect(gitHubError.path).toBe("/repos/owner/repo/pulls"); - expect(gitHubError.headers).toBeDefined(); - expect(gitHubError.headers?.get("x-ratelimit-reset")).toBe("1700005000"); - expect(gitHubError.headers?.get("retry-after")).toBe("30"); + expect(gitHubError.headers).toEqual({ + "x-ratelimit-reset": "1700005000", + "retry-after": "30", + }); }); }); @@ -230,7 +239,8 @@ describe("withRetry", () => { expect(fn).toHaveBeenCalledTimes(2); }); - it("falls back to secondary rate limit backoff when no headers present", async () => { + it("falls back to secondary rate limit backoff with jitter when no headers present", async () => { + vi.spyOn(Math, "random").mockReturnValue(0.5); // jitterFactor = 1.0 const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout"); const warnSpy = vi.spyOn(logger, "warn"); @@ -251,8 +261,7 @@ describe("withRetry", () => { const promise = withRetry("testSecondaryBackoff", fn, 2); const expectedDelay = Math.pow(2, 1) * 30000; // 60,000 ms - await Promise.resolve(); - await Promise.resolve(); + await vi.waitFor(() => expect(setTimeoutSpy).toHaveBeenCalled()); expect(warnSpy).toHaveBeenCalledWith( expect.stringContaining(`in ${expectedDelay}ms`), @@ -267,7 +276,8 @@ describe("withRetry", () => { expect(fn).toHaveBeenCalledTimes(2); }); - it("falls back to exponential backoff for other errors without headers", async () => { + it("falls back to exponential backoff with jitter for other errors without headers", async () => { + vi.spyOn(Math, "random").mockReturnValue(0.5); // jitterFactor = 1.0 const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout"); const warnSpy = vi.spyOn(logger, "warn"); @@ -288,8 +298,7 @@ describe("withRetry", () => { const promise = withRetry("test500Backoff", fn, 2); const expectedDelay = Math.pow(2, 1) * 1000; // 2000 ms - await Promise.resolve(); - await Promise.resolve(); + await vi.waitFor(() => expect(setTimeoutSpy).toHaveBeenCalled()); expect(warnSpy).toHaveBeenCalledWith( expect.stringContaining(`in ${expectedDelay}ms`), @@ -317,4 +326,109 @@ describe("withRetry", () => { await expect(withRetry("testForbidden", fn, 2)).rejects.toThrow("Forbidden"); expect(fn).toHaveBeenCalledTimes(1); }); + + it("prioritizes retry-after over x-ratelimit-reset and ignores x-ratelimit-reset on 5xx errors", async () => { + const fixedNow = 1_000_000_000_000; + vi.setSystemTime(fixedNow); + vi.spyOn(Math, "random").mockReturnValue(0.5); + const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout"); + + const farReset = String(Math.floor(fixedNow / 1000) + 3600); + let callCount = 0; + const fn = vi.fn(async () => { + callCount++; + if (callCount === 1) { + throw new GitHubError( + 403, + "secondary rate limit", + "/repos/o/r", + "Secondary", + new Headers({ "retry-after": "10", "x-ratelimit-reset": farReset }), + ); + } + if (callCount === 2) { + throw new GitHubError( + 502, + "Bad Gateway", + "/repos/o/r", + "502", + new Headers({ "x-ratelimit-reset": farReset, "x-ratelimit-remaining": "4999" }), + ); + } + return "ok"; + }); + + const promise = withRetry("testPrecedence", fn, 2); + await vi.waitFor(() => expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), 10_000)); + await vi.advanceTimersByTimeAsync(10_000); + + // 502 attempt 2 must use exponential backoff (4000ms), NOT x-ratelimit-reset (3600s) + await vi.waitFor(() => expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), 4_000)); + await vi.advanceTimersByTimeAsync(4_000); + + await expect(promise).resolves.toBe("ok"); + }); + + it("detects 403 rate limits from x-ratelimit-remaining: 0 even when body is , and parses HTTP-date retry-after", async () => { + const fixedNow = 1_700_000_000_000; + vi.setSystemTime(fixedNow); + const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout"); + const httpDate = new Date(fixedNow + 12_000).toUTCString(); + + let calls = 0; + const fn = vi.fn(async () => { + calls++; + if (calls === 1) { + throw new GitHubError( + 403, + "", + "/repos/o/r", + "403", + new Headers({ "x-ratelimit-remaining": "0", "retry-after": httpDate }), + ); + } + return "ok"; + }); + + const promise = withRetry("testHttpDate", fn, 2); + await Promise.resolve(); + await Promise.resolve(); + expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), 12_000); + await vi.advanceTimersByTimeAsync(12_000); + await expect(promise).resolves.toBe("ok"); + }); + + it("fails fast when retry-after or x-ratelimit-reset exceeds maxDelayMs", async () => { + const fn = vi.fn(async () => { + throw new GitHubError( + 429, + "Too Many Requests", + "/repos/o/r", + "Long retry", + new Headers({ "retry-after": "3600" }), + ); + }); + + await expect(withRetry("testCap", fn, 2)).rejects.toThrow("Long retry"); + expect(fn).toHaveBeenCalledTimes(1); + }); + + it("skips 5xx/timeout retries when retryServerErrors is false and supports AbortSignal", async () => { + const fn502 = vi.fn(async () => { + throw new GitHubError(502, "Bad Gateway", "/repos/o/r", "Bad Gateway"); + }); + await expect( + withRetry("testNoPost502", fn502, { retryServerErrors: false }), + ).rejects.toThrow("Bad Gateway"); + expect(fn502).toHaveBeenCalledTimes(1); + + const controller = new AbortController(); + const fnAbort = vi.fn(async () => { + throw new GitHubError(429, "Too Many Requests", "/r", "429", new Headers({ "retry-after": "30" })); + }); + const abortedPromise = withRetry("testAbort", fnAbort, { signal: controller.signal }); + await vi.waitFor(() => expect(fnAbort).toHaveBeenCalledTimes(1)); + controller.abort(new Error("cancelled")); + await expect(abortedPromise).rejects.toThrow("cancelled"); + }); }); diff --git a/packages/provider-github/test/webhook.spec.ts b/packages/provider-github/test/webhook.spec.ts index 351175ba..0f9ad137 100644 --- a/packages/provider-github/test/webhook.spec.ts +++ b/packages/provider-github/test/webhook.spec.ts @@ -122,13 +122,47 @@ describe("normalizeGitHubWebhook", () => { it("returns null without throwing when payload or nested issue is null or primitive", () => { expect(normalizeGitHubWebhook("issue_comment", null)).toBeNull(); + expect(normalizeGitHubWebhook("issue_comment", ["array"])).toBeNull(); expect(normalizeGitHubWebhook("issue_comment", "primitive")).toBeNull(); expect(normalizeGitHubWebhook("issue_comment", 42)).toBeNull(); expect(normalizeGitHubWebhook("issue_comment", { issue: null })).toBeNull(); expect(normalizeGitHubWebhook("issue_comment", { issue: "not-an-object" })).toBeNull(); expect(normalizeGitHubWebhook("comment", { issue: null })).toBeNull(); + expect(normalizeGitHubWebhook("change_request", { changeRequest: null, repository: { owner: "o", name: "r" } })).toBeNull(); expect(normalizeGitHubWebhook("pull_request", null)).toBeNull(); expect(normalizeGitHubWebhook("pull_request", "primitive")).toBeNull(); expect(normalizeGitHubWebhook("change_request", 123)).toBeNull(); }); + + it("extracts comment author and bot flag when comment.user is present and is idempotent", () => { + const rawPayload = { + action: "created", + installation: { id: 98765 }, + repository: { + owner: { login: "codraoss" }, + name: "codra", + }, + issue: { + number: 101, + pull_request: { url: "https://api.github.com/repos/codraoss/codra/pulls/101" }, + }, + comment: { + body: "@codra review", + user: { login: "codra-app[bot]", type: "Bot" }, + }, + }; + + const first = normalizeGitHubWebhook("issue_comment", rawPayload); + expect(first).toEqual({ + eventName: "comment", + payload: { + action: "created", + installationId: "98765", + repository: { owner: "codraoss", name: "codra" }, + issue: { number: 101, isChangeRequest: true }, + comment: { body: "@codra review", author: "codra-app[bot]", isBot: true }, + }, + }); + expect(normalizeGitHubWebhook(first!.eventName, first!.payload)).toEqual(first); + }); }); diff --git a/packages/schema/src/github.ts b/packages/schema/src/github.ts index 408f844a..7a87f996 100644 --- a/packages/schema/src/github.ts +++ b/packages/schema/src/github.ts @@ -73,6 +73,10 @@ export type IssueCommentWebhookPayload = { }; comment: { body: string; + user?: { + login?: string | null; + type?: string | null; + } | null; }; }; diff --git a/packages/schema/src/schema-model-registry.ts b/packages/schema/src/schema-model-registry.ts index 42d22065..0e78dde8 100644 --- a/packages/schema/src/schema-model-registry.ts +++ b/packages/schema/src/schema-model-registry.ts @@ -4,6 +4,7 @@ export const ModelSamplingConfigSchema = z.object({ temperature: z.number().min(0).max(2).default(0.7), topP: z.number().min(0).max(1).optional(), topK: z.number().int().min(1).optional(), + // String effort levels ("low" | "medium" | "high") map to OpenAI `reasoning_effort` and fall back to codraDefault on Gemini. thinkingBudget: z .union([ z.enum(["off", "auto", "low", "medium", "high"]), diff --git a/packages/schema/src/schema.ts b/packages/schema/src/schema.ts index 1695d2dc..03151c2c 100644 --- a/packages/schema/src/schema.ts +++ b/packages/schema/src/schema.ts @@ -36,6 +36,7 @@ import { defaultRepoConfig, } from "./schema-repo-config"; import { + DEFAULT_MENTION_TRIGGER, KIMI_K2_5_MODEL, KIMI_K2_6_MODEL, DEPRECATED_MODEL_ALIASES, @@ -82,6 +83,7 @@ export { defaultRepoConfig, }; export { + DEFAULT_MENTION_TRIGGER, KIMI_K2_5_MODEL, KIMI_K2_6_MODEL, DEPRECATED_MODEL_ALIASES, diff --git a/packages/schema/src/webhook.ts b/packages/schema/src/webhook.ts index 1c8905f7..893a98fa 100644 --- a/packages/schema/src/webhook.ts +++ b/packages/schema/src/webhook.ts @@ -20,7 +20,7 @@ export type CommentWebhookPayload = { installationId: string; repository: { owner: string; name: string }; issue: { number: number; isChangeRequest: boolean }; - comment: { body: string }; + comment: { body: string; author?: string; isBot?: boolean }; }; export type WebhookPayload = diff --git a/packages/ui/package.json b/packages/ui/package.json index bfd2f20a..ed763c0c 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -30,7 +30,8 @@ "./markdown-plugins": "./src/lib/markdown-plugins.ts", "./motion": "./src/components/motion/index.ts", "./hooks": "./src/hooks/index.ts", - "./styles": "./src/styles/tokens.css" + "./styles": "./src/styles/tokens.css", + "./styles/file-diff.css": "./src/styles/file-diff.css" }, "files": [ "dist", @@ -91,7 +92,8 @@ "types": "./dist/hooks/index.d.ts", "import": "./dist/hooks/index.js" }, - "./styles": "./dist/styles/tokens.css" + "./styles": "./dist/styles/tokens.css", + "./styles/file-diff.css": "./dist/styles/file-diff.css" } }, "scripts": { diff --git a/packages/ui/src/components/file-diff.tsx b/packages/ui/src/components/file-diff.tsx index 753a38e9..846fbfbb 100644 --- a/packages/ui/src/components/file-diff.tsx +++ b/packages/ui/src/components/file-diff.tsx @@ -1,6 +1,6 @@ import { memo, useMemo, type CSSProperties } from "react"; import { CopyButton } from "./copy-button"; -import { highlightLine, langForPath } from "../lib/highlight"; +import { highlightLine, langForPath, type Lang } from "../lib/highlight"; import { cn } from "../lib/utils"; import { normalizeRows, @@ -22,6 +22,59 @@ export interface FileDiffProps { maxHeight?: number | string; } +const DiffRow = memo(function DiffRow({ + row, + lang, +}: { + row: FileDiffRow; + lang: Lang; +}) { + if (row.type === "hunk") { + return ( +
+ + + + {row.text} +
+ ); + } + + return ( +
+ {row.old ?? ""} + {row.cur ?? ""} + + {row.type === "add" ? ( + <> + + Added line: + + ) : row.type === "del" ? ( + <> + + Removed line: + + ) : null} + + + {lang ? ( + highlightLine(row.text, lang) + ) : ( + tokenize(row.text).map((tok, j) => ( + + {tok.v} + + )) + )} + +
+ ); +}); + export const FileDiff = memo(function FileDiff({ file, rows: initialRows, @@ -36,26 +89,43 @@ export const FileDiff = memo(function FileDiff({ [initialRows, diff], ); - const displayFile = file || detectedFile || "src/auth.ts"; - const lang = useMemo(() => langForPath(displayFile), [displayFile]); + const displayFile = file || detectedFile || ""; + const lang = useMemo( + () => (displayFile ? langForPath(displayFile) : undefined), + [displayFile], + ); const added = useMemo(() => rows.filter((r) => r.type === "add").length, [rows]); const removed = useMemo(() => rows.filter((r) => r.type === "del").length, [rows]); + const gutterStyle = useMemo(() => { + let maxLine = 0; + for (const r of rows) { + if (r.old != null && r.old > maxLine) maxLine = r.old; + if (r.cur != null && r.cur > maxLine) maxLine = r.cur; + } + const digits = maxLine > 0 ? String(maxLine).length : 0; + if (digits < 4) return undefined; + return { "--aicss-ln-w": `${digits + 2}ch` } as CSSProperties; + }, [rows]); + const fullText = useMemo(() => { - if (diff) return diff; + if (diff !== undefined) return diff; return rows .map((r) => { + if (r.type === "hunk") return r.text; const prefix = r.type === "add" ? "+" : r.type === "del" ? "-" : " "; return `${prefix}${r.text}`; }) .join("\n"); }, [diff, rows]); + const mergedStyle = gutterStyle ? { ...gutterStyle, ...style } : style; + return ( -
+
- + - {displayFile} + {displayFile || "Diff"} +{added} @@ -87,45 +157,15 @@ export const FileDiff = memo(function FileDiff({
- {rows.map((r, i) => { - if (r.type === "hunk") { - return ( -
- - - - {r.text} -
- ); - } - - return ( -
- {r.old ?? ""} - {r.cur ?? ""} - - {r.type === "add" ? "+" : r.type === "del" ? "-" : ""} - - - {lang ? ( - highlightLine(r.text, lang) - ) : ( - tokenize(r.text).map((tok, j) => ( - - {tok.v} - - )) - )} - -
- ); - })} + {rows.map((r, i) => ( + + ))}
diff --git a/packages/ui/src/lib/file-diff-parser.ts b/packages/ui/src/lib/file-diff-parser.ts index 3ec5d021..603684c0 100644 --- a/packages/ui/src/lib/file-diff-parser.ts +++ b/packages/ui/src/lib/file-diff-parser.ts @@ -1,3 +1,7 @@ +import { isDigitChar, tokenize } from "./file-diff-tokenizer"; + +export { tokenize }; + export interface FileDiffRow { old?: number | null; cur?: number | null; @@ -14,156 +18,59 @@ export type DiffRowInput = text: string; }; -export const DEFAULT_ROWS: FileDiffRow[] = [ - { old: 12, cur: 12, type: "ctx", text: "export function getToken() {" }, - { old: 13, cur: null, type: "del", text: " return localStorage.token;" }, - { old: null, cur: 13, type: "add", text: ' const t = cookies.get("session");' }, - { old: null, cur: 14, type: "add", text: ' if (!t) throw new Error("no session");' }, - { old: null, cur: 15, type: "add", text: " return t;" }, - { old: 14, cur: 16, type: "ctx", text: "}" }, -]; - -const KEYWORDS = new Set([ - "export", "function", "return", "const", "let", "var", "if", "else", "throw", "new", - "import", "from", "async", "await", "class", "extends", "typeof", "void", "true", - "false", "null", "undefined", "for", "while", "switch", "case", "break", "continue", - "try", "catch", "finally", "this", "super", "static", "type", "interface", "enum", "as", "of", "in", -]); - -function isWhitespaceChar(ch: string): boolean { - return ch === " " || ch === "\t" || ch === "\r" || ch === "\n" || /\s/.test(ch); -} - -function isDigitChar(ch: string): boolean { - return ch >= "0" && ch <= "9"; -} - -function isWordChar(ch: string): boolean { - return ( - (ch >= "a" && ch <= "z") || - (ch >= "A" && ch <= "Z") || - (ch >= "0" && ch <= "9") || - ch === "_" - ); -} - -function isIdentStart(ch: string): boolean { - return ( - (ch >= "a" && ch <= "z") || - (ch >= "A" && ch <= "Z") || - ch === "_" || - ch === "$" - ); -} - -/** - * Linear-time fallback tokenizer for diff lines without a known language highlighter. - */ -export function tokenize(line: string): Array<{ t: string; v: string }> { - const raw: Array<{ kind: string; v: string }> = []; - let i = 0; - const len = line.length; - - while (i < len) { - const ch = line[i]; - - if (isWhitespaceChar(ch)) { - const start = i; - i++; - while (i < len && isWhitespaceChar(line[i])) i++; - raw.push({ kind: "ws", v: line.slice(start, i) }); - continue; - } - - if (ch === "/" && i + 1 < len) { - if (line[i + 1] === "/") { - raw.push({ kind: "cm", v: line.slice(i) }); - break; - } - if (line[i + 1] === "*") { - const closeIdx = line.indexOf("*/", i + 2); - if (closeIdx !== -1) { - raw.push({ kind: "cm", v: line.slice(i, closeIdx + 2) }); - i = closeIdx + 2; - } else { - raw.push({ kind: "cm", v: line.slice(i) }); - break; - } - continue; - } - } - - if (ch === '"' || ch === "'") { - const start = i; - let j = i + 1; - let closed = false; - while (j < len) { - if (line[j] === "\\") { - j += 2; - continue; - } - if (line[j] === ch) { - j++; - closed = true; - break; - } - j++; - } - raw.push({ kind: "str", v: line.slice(start, closed ? j : len) }); - i = closed ? j : len; - continue; - } +const HUNK_RE = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/; - if (isDigitChar(ch) && (i === 0 || !isWordChar(line[i - 1]))) { - let j = i + 1; - while (j < len && isDigitChar(line[j])) j++; - if (j + 1 < len && line[j] === "." && isDigitChar(line[j + 1])) { - j += 2; - while (j < len && isDigitChar(line[j])) j++; - } - if (j === len || !isWordChar(line[j])) { - raw.push({ kind: "num", v: line.slice(i, j) }); - i = j; - continue; - } - } +function parseGitDiffHeaderPath(line: string): string | undefined { + const rest = line.slice("diff --git ".length).trim(); + if (!rest) return undefined; - if (isIdentStart(ch) && (ch === "$" || i === 0 || !isWordChar(line[i - 1]))) { - let j = i + 1; - while (j < len && (isWordChar(line[j]) || line[j] === "$")) j++; - raw.push({ kind: "id", v: line.slice(i, j) }); - i = j; - continue; + // Handle quoted paths like "a/foo bar.ts" "b/foo bar.ts" + if (rest.startsWith('"')) { + const secondQuoteStart = rest.indexOf(' "b/', 1); + if (secondQuoteStart !== -1) { + const rawB = rest.slice(secondQuoteStart + 2).replace(/^"|"$/g, ""); + return rawB.startsWith("b/") ? rawB.slice(2) : rawB; } - - raw.push({ kind: "txt", v: ch }); - i++; } - const out: Array<{ t: string; v: string }> = []; - for (let k = 0; k < raw.length; k++) { - const cur = raw[k]; - if (cur.kind === "ws") { - out.push({ t: "txt", v: cur.v }); - continue; + if (rest.startsWith("a/")) { + const n = (rest.length - 5) / 2; + if ( + Number.isInteger(n) && + n > 0 && + rest[2 + n] === " " && + rest.startsWith("b/", 3 + n) + ) { + const a = rest.slice(2, 2 + n); + if (a === rest.slice(5 + n)) return a; } - if (cur.kind !== "id") { - out.push({ t: cur.kind, v: cur.v }); - continue; - } - if (KEYWORDS.has(cur.v)) { - out.push({ t: "kw", v: cur.v }); - continue; - } - let j = k + 1; - while (j < raw.length && raw[j].kind === "ws") j++; - const next = raw[j]; - out.push({ t: next && next.v.startsWith("(") ? "fn" : "txt", v: cur.v }); } - return out; + + const bStart = rest.indexOf(" b/", rest.startsWith("a/") ? 2 : 0); + const bPath = + bStart === -1 + ? rest.slice(rest.lastIndexOf(" ") + 1) + : rest.slice(bStart + 3); + return bPath.startsWith("b/") ? bPath.slice(2) : bPath; } -const HUNK_RE = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/; +function isGitExtendedHeader(line: string): boolean { + return ( + line.startsWith("index ") || + line.startsWith("old mode ") || + line.startsWith("new mode ") || + line.startsWith("deleted file mode ") || + line.startsWith("new file mode ") || + line.startsWith("copy from ") || + line.startsWith("copy to ") || + line.startsWith("rename from ") || + line.startsWith("rename to ") || + line.startsWith("similarity index ") || + line.startsWith("dissimilarity index ") || + line.startsWith("Binary files ") || + line.startsWith("GIT binary patch") + ); +} function parseSnippetLine( line: string, @@ -195,7 +102,7 @@ function parseSnippetLine( text: line.slice(i + 1), }; } - if (i >= 2 && line[i - 2] === " " && line[i - 1] === " ") { + if (i >= 2 && i < len && line[i - 2] === " " && line[i - 1] === " ") { return { lineNum: null, prefix: " ", @@ -211,6 +118,7 @@ function parsePaddedLine(line: string) { if (prefix !== "+" && prefix !== "-" && prefix !== " ") return null; const oldNo = line.slice(0, 4).trim(); const newNo = line.slice(5, 9).trim(); + if (!oldNo && !newNo) return null; if (oldNo && !/^\d+$/.test(oldNo)) return null; if (newNo && !/^\d+$/.test(newNo)) return null; return { prefix, oldNo, newNo, content: line.slice(11) }; @@ -224,74 +132,100 @@ export function parseDiffText(rawDiff: string): { file?: string; rows: FileDiffR let detectedFile: string | undefined; let oldNo = 0; let curNo = 0; + let inUnifiedHunk = false; + let snippetDelta = 0; - for (const line of rawDiff.split("\n")) { - if (line.startsWith("diff --git")) { - const parts = line.split(" "); - if (parts[3]) { - detectedFile = parts[3].replace(/^b\//, ""); - } + const normalizedDiff = rawDiff.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); + + for (const line of normalizedDiff.split("\n")) { + if (line.startsWith("diff --git ")) { + inUnifiedHunk = false; + const parsed = parseGitDiffHeaderPath(line); + if (parsed) detectedFile = parsed; continue; } if (line.startsWith("+++ ")) { - const match = line.slice(4).trim().replace(/^b\//, ""); + inUnifiedHunk = false; + const match = line.slice(4).trim().replace(/^"|"$/g, "").replace(/^b\//, ""); if (match && match !== "/dev/null") detectedFile = match; continue; } if (line.startsWith("--- ")) { - const match = line.slice(4).trim().replace(/^a\//, ""); + inUnifiedHunk = false; + const match = line.slice(4).trim().replace(/^"|"$/g, "").replace(/^a\//, ""); if (match && match !== "/dev/null" && !detectedFile) detectedFile = match; continue; } + if (!inUnifiedHunk && isGitExtendedHeader(line)) { + if (line.startsWith("rename to ")) { + const renamed = line.slice(10).trim().replace(/^b\//, ""); + if (renamed) detectedFile = renamed; + } + continue; + } + const hunk = HUNK_RE.exec(line); if (hunk) { + inUnifiedHunk = true; oldNo = Number(hunk[1]); curNo = Number(hunk[2]); rows.push({ old: null, cur: null, type: "hunk", text: line }); continue; } - if (line.startsWith("\\") || line.startsWith("[NOTE")) continue; - - const padded = parsePaddedLine(line); - if (padded) { - if (padded.prefix === "+") { - rows.push({ - old: null, - cur: padded.newNo ? Number(padded.newNo) : null, - type: "add", - text: padded.content, - }); - } else if (padded.prefix === "-") { - rows.push({ - old: padded.oldNo ? Number(padded.oldNo) : null, - cur: null, - type: "del", - text: padded.content, - }); - } else { - rows.push({ - old: padded.oldNo ? Number(padded.oldNo) : null, - cur: padded.newNo ? Number(padded.newNo) : null, - type: "ctx", - text: padded.content, - }); - } + if (line.startsWith("[NOTE")) continue; + if (line.startsWith("\\ No newline")) { + rows.push({ old: null, cur: null, type: "hunk", text: line }); continue; } + if (line.startsWith("\\")) continue; + + if (!inUnifiedHunk) { + if (line.trim().length === 0) continue; - const snippet = parseSnippetLine(line); - if (snippet) { - const { lineNum, prefix, text } = snippet; - if (prefix === "+") { - rows.push({ old: null, cur: lineNum, type: "add", text }); - } else if (prefix === "-") { - rows.push({ old: lineNum, cur: null, type: "del", text }); - } else { - rows.push({ old: lineNum, cur: lineNum, type: "ctx", text }); + const padded = parsePaddedLine(line); + if (padded) { + if (padded.prefix === "+") { + rows.push({ + old: null, + cur: padded.newNo ? Number(padded.newNo) : null, + type: "add", + text: padded.content, + }); + } else if (padded.prefix === "-") { + rows.push({ + old: padded.oldNo ? Number(padded.oldNo) : null, + cur: null, + type: "del", + text: padded.content, + }); + } else { + rows.push({ + old: padded.oldNo ? Number(padded.oldNo) : null, + cur: padded.newNo ? Number(padded.newNo) : null, + type: "ctx", + text: padded.content, + }); + } + continue; + } + + const snippet = parseSnippetLine(line); + if (snippet) { + const { lineNum, prefix, text } = snippet; + if (prefix === "+") { + snippetDelta += 1; + rows.push({ old: null, cur: lineNum, type: "add", text }); + } else if (prefix === "-") { + snippetDelta -= 1; + rows.push({ old: lineNum, cur: null, type: "del", text }); + } else { + const oldLine = lineNum !== null ? lineNum - snippetDelta : null; + rows.push({ old: oldLine, cur: lineNum, type: "ctx", text }); + } + continue; } - continue; } const prefix = line[0]; @@ -339,12 +273,12 @@ export function normalizeRows( rows?: DiffRowInput[], diff?: string, ): { file?: string; normalized: FileDiffRow[] } { - if (diff) { + if (diff !== undefined) { const parsed = parseDiffText(diff); return { file: parsed.file, normalized: parsed.rows }; } if (!rows || rows.length === 0) { - return { normalized: DEFAULT_ROWS }; + return { normalized: [] }; } return { normalized: rows.map((r) => { diff --git a/packages/ui/src/lib/file-diff-tokenizer.ts b/packages/ui/src/lib/file-diff-tokenizer.ts new file mode 100644 index 00000000..f3e30c7d --- /dev/null +++ b/packages/ui/src/lib/file-diff-tokenizer.ts @@ -0,0 +1,151 @@ +const KEYWORDS = new Set([ + "export", "function", "return", "const", "let", "var", "if", "else", "throw", "new", + "import", "from", "async", "await", "class", "extends", "typeof", "void", "true", + "false", "null", "undefined", "for", "while", "switch", "case", "break", "continue", + "try", "catch", "finally", "this", "super", "static", "type", "interface", "enum", "as", "of", "in", +]); + +function isWhitespaceChar(ch: string): boolean { + return ch === " " || ch === "\t" || ch === "\r" || ch === "\n" || /\s/.test(ch); +} + +export function isDigitChar(ch: string): boolean { + return ch >= "0" && ch <= "9"; +} + +function isWordChar(ch: string): boolean { + return ( + (ch >= "a" && ch <= "z") || + (ch >= "A" && ch <= "Z") || + (ch >= "0" && ch <= "9") || + ch === "_" + ); +} + +function isIdentStart(ch: string): boolean { + return ( + (ch >= "a" && ch <= "z") || + (ch >= "A" && ch <= "Z") || + ch === "_" || + ch === "$" + ); +} + +/** + * Linear-time fallback tokenizer for diff lines without a known language highlighter. + */ +export function tokenize(line: string): Array<{ t: string; v: string }> { + if (line.length > 1000) { + return [{ t: "txt", v: line }]; + } + + const raw: Array<{ kind: string; v: string }> = []; + let i = 0; + const len = line.length; + + while (i < len) { + const ch = line[i]; + + if (isWhitespaceChar(ch)) { + const start = i; + i++; + while (i < len && isWhitespaceChar(line[i])) i++; + raw.push({ kind: "ws", v: line.slice(start, i) }); + continue; + } + + if (ch === "/" && i + 1 < len) { + if (line[i + 1] === "/") { + raw.push({ kind: "cm", v: line.slice(i) }); + break; + } + if (line[i + 1] === "*") { + const closeIdx = line.indexOf("*/", i + 2); + if (closeIdx !== -1) { + raw.push({ kind: "cm", v: line.slice(i, closeIdx + 2) }); + i = closeIdx + 2; + } else { + raw.push({ kind: "cm", v: line.slice(i) }); + break; + } + continue; + } + } + + if (ch === '"' || ch === "'") { + const start = i; + let j = i + 1; + let closed = false; + while (j < len) { + if (line[j] === "\\") { + j += 2; + continue; + } + if (line[j] === ch) { + j++; + closed = true; + break; + } + j++; + } + raw.push({ kind: "str", v: line.slice(start, closed ? j : len) }); + i = closed ? j : len; + continue; + } + + if (isDigitChar(ch) && (i === 0 || !isWordChar(line[i - 1]))) { + let j = i + 1; + while (j < len && isDigitChar(line[j])) j++; + if (j + 1 < len && line[j] === "." && isDigitChar(line[j + 1])) { + j += 2; + while (j < len && isDigitChar(line[j])) j++; + } + if (j === len || !isWordChar(line[j])) { + raw.push({ kind: "num", v: line.slice(i, j) }); + i = j; + continue; + } + } + + if (isIdentStart(ch) && (ch === "$" || i === 0 || !isWordChar(line[i - 1]))) { + let j = i + 1; + while (j < len && (isWordChar(line[j]) || line[j] === "$")) j++; + raw.push({ kind: "id", v: line.slice(i, j) }); + i = j; + continue; + } + + raw.push({ kind: "txt", v: ch }); + i++; + } + + const out: Array<{ t: string; v: string }> = []; + const pushToken = (t: string, v: string) => { + if (t === "txt" && out.length > 0 && out[out.length - 1].t === "txt") { + out[out.length - 1].v += v; + } else { + out.push({ t, v }); + } + }; + + for (let k = 0; k < raw.length; k++) { + const cur = raw[k]; + if (cur.kind === "ws") { + pushToken("txt", cur.v); + continue; + } + if (cur.kind !== "id") { + pushToken(cur.kind, cur.v); + continue; + } + if (KEYWORDS.has(cur.v)) { + pushToken("kw", cur.v); + continue; + } + let j = k + 1; + while (j < raw.length && raw[j].kind === "ws") j++; + const next = raw[j]; + pushToken(next && next.v.startsWith("(") ? "fn" : "txt", cur.v); + } + return out; +} diff --git a/packages/ui/src/styles/file-diff.css b/packages/ui/src/styles/file-diff.css index 3f2a0c7f..dc701fb2 100644 --- a/packages/ui/src/styles/file-diff.css +++ b/packages/ui/src/styles/file-diff.css @@ -4,6 +4,7 @@ /* Base Styles (Light Theme) */ .aicss-diff { + --aicss-ln-w: 44px; border-radius: 12px; background: #ffffff; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05), 0 2px 4px rgba(0, 0, 0, 0.02), 0 0 0 0.5px rgba(0, 0, 0, 0.08); @@ -15,6 +16,18 @@ line-height: 20px; } +.aicss-sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border-width: 0; +} + .aicss-diff-head { display: flex; align-items: center; @@ -37,7 +50,7 @@ display: block; width: 15px; height: 15px; - color: var(--ui-subtle, #a1a1a1); + color: var(--ui-subtle, #57606a); flex: none; } @@ -63,11 +76,11 @@ } .aicss-diff-stat .aicss-diff-add { - color: #15a06a; + color: #116329; } .aicss-diff-stat .aicss-diff-del { - color: #dc2626; + color: #b91c1c; } .aicss-diff-actions { @@ -88,19 +101,24 @@ scrollbar-width: thin; } +.aicss-diff-body:focus-visible { + outline: 2px solid var(--ring, #2563eb); + outline-offset: -2px; +} + .aicss-diff-lines { position: relative; width: max-content; min-width: 100%; } -/* full-height gutter divider at the line-number edge (32px + 32px = 64px) */ +/* full-height gutter divider at the line-number edge */ .aicss-diff-lines::before { content: ""; position: absolute; top: 0; bottom: 0; - left: 64px; + left: calc(var(--aicss-ln-w, 44px) * 2); width: 0.5px; background: #e6e8eb; z-index: 1; @@ -110,14 +128,14 @@ .aicss-diff-row { position: relative; display: grid; - grid-template-columns: 32px 32px 18px 1fr; + grid-template-columns: var(--aicss-ln-w, 44px) var(--aicss-ln-w, 44px) 18px 1fr; align-items: stretch; } .aicss-diff-row .aicss-diff-ln, .aicss-diff-row .aicss-diff-sign { user-select: none; - color: #a1a1a1; + color: #57606a; font-size: 11px; } @@ -153,11 +171,11 @@ } .aicss-diff-row.add::before { - background: #15a06a; + background: #1a7f37; } .aicss-diff-row.del::before { - background: repeating-linear-gradient(45deg, #dc2626 0, #dc2626 1.5px, transparent 1.5px, transparent 3px); + background: repeating-linear-gradient(45deg, #cf222e 0, #cf222e 1.5px, transparent 1.5px, transparent 3px); } .aicss-diff-row.add { @@ -166,7 +184,7 @@ .aicss-diff-row.add .aicss-diff-sign, .aicss-diff-row.add .aicss-diff-ln.new { - color: #15a06a; + color: #116329; } .aicss-diff-row.del { @@ -175,16 +193,16 @@ .aicss-diff-row.del .aicss-diff-sign, .aicss-diff-row.del .aicss-diff-ln.old { - color: #dc2626; + color: #b91c1c; } .aicss-diff-row.hunk { background: #f6f8fa; - color: #6e7781; + color: #57606a; } .aicss-diff-row.hunk code { - color: #6e7781; + color: #57606a; } /* Syntax tokens in Light Mode */ @@ -192,12 +210,11 @@ .aicss-diff-row code .str { color: #0a3069; } .aicss-diff-row code .fn { color: #8250df; } .aicss-diff-row code .num { color: #0550ae; } -.aicss-diff-row code .cm { color: #6e7781; } +.aicss-diff-row code .cm { color: #57606a; } /* ========================================================================== - Explicit Light Mode Theme (Overrides any ambient OS dark mode) + Explicit Light Mode Theme (Nested inside dark containers) ========================================================================== */ -:root:not(.dark) .aicss-diff, [data-theme="light"] .aicss-diff, [data-mode="light"] .aicss-diff { background: #ffffff; @@ -205,125 +222,102 @@ border-color: rgba(0, 0, 0, 0.08); } -:root:not(.dark) .aicss-diff-head, [data-theme="light"] .aicss-diff-head, [data-mode="light"] .aicss-diff-head { border-bottom-color: #e6e8eb; } -:root:not(.dark) .aicss-diff-file, [data-theme="light"] .aicss-diff-file, [data-mode="light"] .aicss-diff-file { color: #1a1a1a; } -:root:not(.dark) .aicss-diff-stat .aicss-diff-add, [data-theme="light"] .aicss-diff-stat .aicss-diff-add, [data-mode="light"] .aicss-diff-stat .aicss-diff-add { - color: #15a06a; + color: #116329; } -:root:not(.dark) .aicss-diff-stat .aicss-diff-del, [data-theme="light"] .aicss-diff-stat .aicss-diff-del, [data-mode="light"] .aicss-diff-stat .aicss-diff-del { - color: #dc2626; + color: #b91c1c; } -:root:not(.dark) .aicss-diff-lines::before, [data-theme="light"] .aicss-diff-lines::before, [data-mode="light"] .aicss-diff-lines::before { background: #e6e8eb; } -:root:not(.dark) .aicss-diff-row .aicss-diff-ln, [data-theme="light"] .aicss-diff-row .aicss-diff-ln, -:root:not(.dark) .aicss-diff-row .aicss-diff-sign, [data-theme="light"] .aicss-diff-row .aicss-diff-sign, [data-mode="light"] .aicss-diff-row .aicss-diff-ln, [data-mode="light"] .aicss-diff-row .aicss-diff-sign { - color: #a1a1a1; + color: #57606a; } -:root:not(.dark) .aicss-diff-row code, [data-theme="light"] .aicss-diff-row code, [data-mode="light"] .aicss-diff-row code { color: #1a1a1a; } -:root:not(.dark) .aicss-diff-row.add, [data-theme="light"] .aicss-diff-row.add, [data-mode="light"] .aicss-diff-row.add { background: rgba(26, 127, 55, 0.09); } -:root:not(.dark) .aicss-diff-row.add::before, [data-theme="light"] .aicss-diff-row.add::before, [data-mode="light"] .aicss-diff-row.add::before { - background: #15a06a; + background: #1a7f37; } -:root:not(.dark) .aicss-diff-row.add .aicss-diff-sign, -:root:not(.dark) .aicss-diff-row.add .aicss-diff-ln.new, [data-theme="light"] .aicss-diff-row.add .aicss-diff-sign, [data-theme="light"] .aicss-diff-row.add .aicss-diff-ln.new, [data-mode="light"] .aicss-diff-row.add .aicss-diff-sign, [data-mode="light"] .aicss-diff-row.add .aicss-diff-ln.new { - color: #15a06a; + color: #116329; } -:root:not(.dark) .aicss-diff-row.del, [data-theme="light"] .aicss-diff-row.del, [data-mode="light"] .aicss-diff-row.del { background: rgba(207, 34, 46, 0.09); } -:root:not(.dark) .aicss-diff-row.del::before, [data-theme="light"] .aicss-diff-row.del::before, [data-mode="light"] .aicss-diff-row.del::before { - background: repeating-linear-gradient(45deg, #dc2626 0, #dc2626 1.5px, transparent 1.5px, transparent 3px); + background: repeating-linear-gradient(45deg, #cf222e 0, #cf222e 1.5px, transparent 1.5px, transparent 3px); } -:root:not(.dark) .aicss-diff-row.del .aicss-diff-sign, -:root:not(.dark) .aicss-diff-row.del .aicss-diff-ln.old, [data-theme="light"] .aicss-diff-row.del .aicss-diff-sign, [data-theme="light"] .aicss-diff-row.del .aicss-diff-ln.old, [data-mode="light"] .aicss-diff-row.del .aicss-diff-sign, [data-mode="light"] .aicss-diff-row.del .aicss-diff-ln.old { - color: #dc2626; + color: #b91c1c; } -:root:not(.dark) .aicss-diff-row.hunk, [data-theme="light"] .aicss-diff-row.hunk, [data-mode="light"] .aicss-diff-row.hunk { background: #f6f8fa; - color: #6e7781; + color: #57606a; } -:root:not(.dark) .aicss-diff-row.hunk code, [data-theme="light"] .aicss-diff-row.hunk code, [data-mode="light"] .aicss-diff-row.hunk code { - color: #6e7781; + color: #57606a; } -:root:not(.dark) .aicss-diff-row code .kw, [data-theme="light"] .aicss-diff-row code .kw, [data-mode="light"] .aicss-diff-row code .kw { color: #cf222e; } -:root:not(.dark) .aicss-diff-row code .str, [data-theme="light"] .aicss-diff-row code .str, [data-mode="light"] .aicss-diff-row code .str { color: #0a3069; } -:root:not(.dark) .aicss-diff-row code .fn, [data-theme="light"] .aicss-diff-row code .fn, [data-mode="light"] .aicss-diff-row code .fn { color: #8250df; } -:root:not(.dark) .aicss-diff-row code .num, [data-theme="light"] .aicss-diff-row code .num, [data-mode="light"] .aicss-diff-row code .num { color: #0550ae; } -:root:not(.dark) .aicss-diff-row code .cm, [data-theme="light"] .aicss-diff-row code .cm, -[data-mode="light"] .aicss-diff-row code .cm { color: #6e7781; } +[data-mode="light"] .aicss-diff-row code .cm { color: #57606a; } /* ========================================================================== Dark Mode Theme (Active strictly under .dark, [data-theme="dark"], or [data-mode="dark"]) diff --git a/packages/ui/src/styles/tokens.css b/packages/ui/src/styles/tokens.css index d0f4c5d0..f179f404 100644 --- a/packages/ui/src/styles/tokens.css +++ b/packages/ui/src/styles/tokens.css @@ -1,6 +1,7 @@ /* * @codraoss/ui design tokens: the tokens and classes this package's components reference, without which they render unstyled. A Tailwind v4 partial, not an entry, so import it from the app's stylesheet AFTER `@import "tailwindcss"` for the @theme/@utility directives to be processed. */ +@import "./file-diff.css"; /* dark: utilities follow .dark class, not OS prefers-color-scheme. */ @custom-variant dark (&:where(.dark, .dark *)); @@ -352,5 +353,3 @@ --sh-entity: oklch(76% 0.1 260); --sh-property: oklch(78% 0.1 200); } - -@import "./file-diff.css"; diff --git a/public/diff-preview.html b/public/diff-preview.html deleted file mode 100644 index 40731688..00000000 --- a/public/diff-preview.html +++ /dev/null @@ -1,502 +0,0 @@ - - - - - - Codra ยท AICSS File Diff Component Preview - - - - -
-
-
-
-

Codra ยท AICSS File Diff Component

- Branch: feature/aicss-file-diff -
-

Implementation of https://www.aicss.dev/components/file-diff for codeblocks & diff viewers

-
- -
- - -
-
1. Canonical File Diff Card (AICSS Spec)
-
-
- - - src/auth.ts - - - +3 - -1 - - - - -
-
-
-
- 12 - 12 - - export function getToken() { -
-
- 13 - - - - return localStorage.token; -
-
- - 13 - + - const t = cookies.get("session"); -
-
- - 14 - + - if (!t) throw new Error("no session"); -
-
- - 15 - + - return t; -
-
- 14 - 16 - - } -
-
-
-
-
- - -
-
2. Review Finding Diff Context (ContextSnippet Component)
-
-
- - - packages/core/src/model-output/evidence.ts - - - +2 - -2 - - - - -
-
-
-
- - - - @@ -42,4 +42,4 @@ export function verifyFinding(item: Finding) { -
-
- 42 - - - - if (!item.verified) { -
-
- 43 - - - - return null; -
-
- - 42 - + - if (!item.verified && !item.grounded) { -
-
- - 43 - + - return { status: "unverified", score: 0 }; -
-
- 44 - 44 - - } -
-
-
-
-
-
- - - - diff --git a/test/api/webhook-handling.spec.ts b/test/api/webhook-handling.spec.ts index cbfdf25c..48de66c3 100644 --- a/test/api/webhook-handling.spec.ts +++ b/test/api/webhook-handling.spec.ts @@ -226,12 +226,84 @@ describe("Webhook Handling Suite", () => { const json = (await response.json()) as any; expect(response.status).toBe(202); - expect(json.message).toBe("queued"); + expect(json.ignored).toBe(true); const queue = env.REVIEW_QUEUE as any; - expect(queue.sent).toHaveLength(1); - expect(queue.sent[0].payload).toBeUndefined(); - expect(queue.sent[0].eventName).toBe("change_request"); + expect(queue.sent).toHaveLength(0); + }); + + it("rejects signed non-object JSON payloads (null, array, primitive) with 400", async () => { + for (const raw of ["null", "[1, 2]", '"hello"']) { + const signature = await signPayload(env.GITHUB_APP_WEBHOOK_SECRET, raw); + const response = await app.request( + "http://codra.test/webhook", + { + method: "POST", + headers: { + "x-github-event": "pull_request", + "x-github-delivery": uniqueName("non-obj"), + "x-hub-signature-256": signature, + "content-type": "application/json", + }, + body: raw, + }, + env, + ); + expect(response.status).toBe(400); + } + }); + + it("enforces quota on mention-triggered issue_comment webhooks", async () => { + const throttledEnv = createTestEnv( + {}, + { + async checkQuota() { + return { allowed: false, reason: "plan limit" }; + }, + }, + ); + const commentPayload = { + action: "created", + installation: { id: 12345 }, + repository: { + name: uniqueName("repo-comment-quota"), + owner: { login: "test-owner" }, + }, + issue: { + number: 1, + pull_request: { url: "https://api.github.com/repos/test-owner/test-repo/pulls/1" }, + }, + comment: { + id: 124, + body: "@codra review", + user: { login: "human-dev", type: "User" }, + }, + }; + const body = JSON.stringify(commentPayload); + const signature = await signPayload(throttledEnv.GITHUB_APP_WEBHOOK_SECRET, body); + + const response = await app.request( + "http://codra.test/webhook", + { + method: "POST", + headers: { + "x-github-event": "issue_comment", + "x-github-delivery": uniqueName("comment-quota"), + "x-hub-signature-256": signature, + "content-type": "application/json", + }, + body, + }, + throttledEnv, + ); + + expect(response.status).toBe(202); + expect(await response.json()).toEqual({ + ok: true, + ignored: true, + reason: "quota_exceeded", + }); + expect((throttledEnv.REVIEW_QUEUE as any).sent).toHaveLength(0); }); it("enqueues mention trigger from issue_comment with canonical comment eventName", async () => { diff --git a/test/file-diff-component.spec.tsx b/test/file-diff-component.spec.tsx index c7230e49..3f804668 100644 --- a/test/file-diff-component.spec.tsx +++ b/test/file-diff-component.spec.tsx @@ -3,26 +3,26 @@ */ import { describe, expect, it } from "vitest"; import { render } from "@testing-library/react"; +import ReactMarkdown from "react-markdown"; +import remarkGfm from "remark-gfm"; import { FileDiff } from "@codraoss/ui"; import { parseDiffText, tokenize } from "@codraoss/ui/file-diff"; +import { markdownComponents } from "../apps/dashboard/src/components/features/job-detail/comment-card"; describe("AICSS FileDiff Component", () => { - it("renders default file and rows with correct statistics", () => { + it("renders empty state safely without leaking demo auth code or filename", () => { const { container } = render(); - expect(container.querySelector(".aicss-diff-file")?.textContent).toBe("src/auth.ts"); - expect(container.querySelector(".aicss-diff-add")?.textContent).toBe("+3"); - expect(container.querySelector(".aicss-diff-del")?.textContent).toBe("-1"); - - const addRows = container.querySelectorAll(".aicss-diff-row.add"); - const delRows = container.querySelectorAll(".aicss-diff-row.del"); - const ctxRows = container.querySelectorAll(".aicss-diff-row.ctx"); + expect(container.querySelector(".aicss-diff-file")?.textContent).toBe("Diff"); + expect(container.querySelector(".aicss-diff-add")?.textContent).toBe("+0"); + expect(container.querySelector(".aicss-diff-del")?.textContent).toBe("-0"); + expect(container.querySelectorAll(".aicss-diff-row").length).toBe(0); - expect(addRows.length).toBe(3); - expect(delRows.length).toBe(1); - expect(ctxRows.length).toBe(2); + const emptyDiff = render(); + expect(emptyDiff.container.querySelectorAll(".aicss-diff-row").length).toBe(0); + expect(emptyDiff.container.textContent).not.toContain("localStorage.token"); }); - it("renders custom rows with old and cur line numbers", () => { + it("renders custom rows with old and cur line numbers and a11y attributes", () => { const rows = [ { old: 1, cur: 1, type: "ctx" as const, text: "const a = 1;" }, { old: 2, cur: null, type: "del" as const, text: "const b = 2;" }, @@ -34,6 +34,10 @@ describe("AICSS FileDiff Component", () => { expect(container.querySelector(".aicss-diff-add")?.textContent).toBe("+1"); expect(container.querySelector(".aicss-diff-del")?.textContent).toBe("-1"); + const body = container.querySelector(".aicss-diff-body"); + expect(body?.getAttribute("role")).toBe("region"); + expect(body?.getAttribute("tabindex")).toBe("0"); + const lns = container.querySelectorAll(".aicss-diff-ln"); // Each row has old and new line numbers expect(lns[0].textContent).toBe("1"); // row 1 old @@ -44,28 +48,58 @@ describe("AICSS FileDiff Component", () => { expect(lns[5].textContent).toBe("2"); // row 3 new }); - it("parses raw unified diff string automatically", () => { - const rawDiff = `diff --git a/lib/math.ts b/lib/math.ts ---- a/lib/math.ts -+++ b/lib/math.ts -@@ -10,3 +10,4 @@ - function add(x, y) { -- return x - y; -+ // Fix addition -+ return x + y; - }`; + it("parses raw unified diff string automatically including indented context lines", () => { + const rawDiff = [ + "diff --git a/lib/my math.ts b/lib/my math.ts", + "index 1234567..89abcdef 100644", + "--- a/lib/my math.ts", + "+++ b/lib/my math.ts", + "@@ -10,4 +10,5 @@", + " function add(x, y) {", + " - listItem", + "- return x - y;", + "+ // Fix addition", + "+ return x + y;", + " }", + "\\ No newline at end of file", + ].join("\r\n"); + const { file, rows } = parseDiffText(rawDiff); - expect(file).toBe("lib/math.ts"); - expect(rows.length).toBe(6); // 1 hunk + 1 ctx + 1 del + 2 add + 1 ctx + expect(file).toBe("lib/my math.ts"); + // 1 hunk + 1 indented ctx + 1 indented ctx starting with '-' + 1 del + 2 add + 1 ctx + 1 no-newline + expect(rows).toEqual([ + { old: null, cur: null, type: "hunk", text: "@@ -10,4 +10,5 @@" }, + { old: 10, cur: 10, type: "ctx", text: " function add(x, y) {" }, + { old: 11, cur: 11, type: "ctx", text: " - listItem" }, + { old: 12, cur: null, type: "del", text: " return x - y;" }, + { old: null, cur: 12, type: "add", text: " // Fix addition" }, + { old: null, cur: 13, type: "add", text: " return x + y;" }, + { old: 13, cur: 14, type: "ctx", text: " }" }, + { old: null, cur: null, type: "hunk", text: "\\ No newline at end of file" }, + ]); const { container } = render(); - expect(container.querySelector(".aicss-diff-file")?.textContent).toBe("lib/math.ts"); + expect(container.querySelector(".aicss-diff-file")?.textContent).toBe("lib/my math.ts"); expect(container.querySelector(".aicss-diff-add")?.textContent).toBe("+2"); expect(container.querySelector(".aicss-diff-del")?.textContent).toBe("-1"); expect(container.querySelector(".aicss-diff-actions button")).toBeTruthy(); }); - it("parses snippet lines (%4d [+- ]content) from finding contextSnippet", () => { + it("ignores git extended headers and binary file notices", () => { + const rawDiff = [ + "diff --git a/old name.ts b/new name.ts", + "similarity index 95%", + "rename from old name.ts", + "rename to new name.ts", + "Binary files a/img.png and b/img.png differ", + ].join("\n"); + + const { file, rows } = parseDiffText(rawDiff); + expect(file).toBe("new name.ts"); + expect(rows).toEqual([]); + }); + + it("parses snippet lines (%4d [+- ]content) with accurate old/cur context line numbers", () => { const snippet = ` 12 export function getToken() { 13 - return localStorage.token; 13 + const t = cookies.get("session"); @@ -73,10 +107,21 @@ describe("AICSS FileDiff Component", () => { 15 }`; const { rows } = parseDiffText(snippet); expect(rows.length).toBe(5); - expect(rows[1].type).toBe("del"); - expect(rows[1].old).toBe(13); - expect(rows[2].type).toBe("add"); - expect(rows[2].cur).toBe(13); + expect(rows[0]).toEqual({ old: 12, cur: 12, type: "ctx", text: " export function getToken() {" }); + expect(rows[1]).toEqual({ old: 13, cur: null, type: "del", text: " return localStorage.token;" }); + expect(rows[2]).toEqual({ old: null, cur: 13, type: "add", text: ' const t = cookies.get("session");' }); + expect(rows[4]).toEqual({ old: 14, cur: 15, type: "ctx", text: " }" }); + }); + + it("unwraps
 around fenced diff blocks in markdownComponents", () => {
+    const md = "```diff:src/app.ts\n@@ -1,1 +1,1 @@\n-old\n+new\n```";
+    const { container } = render(
+      
+        {md}
+      ,
+    );
+    expect(container.querySelector(".aicss-diff")).toBeTruthy();
+    expect(container.querySelector("pre .aicss-diff")).toBeNull();
   });
 
   it("tokenizes language keywords, strings, numbers, function calls, and comments", () => {
@@ -87,21 +132,20 @@ describe("AICSS FileDiff Component", () => {
     expect(kinds).toContain("num");
     expect(kinds).toContain("str");
     expect(kinds).toContain("cm");
+    expect(tokenize("x".repeat(1200))).toEqual([{ t: "txt", v: "x".repeat(1200) }]);
   });
 
-  it("handles pathological inputs in linear time without regex backtracking", () => {
+  it("handles pathological inputs in linear time without regex backtracking or false padded matches", () => {
     const commentSpam = "/*" + "a/*".repeat(10_000);
     const doubleQuoteSpam = '"' + '\\"'.repeat(10_000);
     const singleQuoteSpam = "'" + "\\'".repeat(10_000);
     const paddedWhitespaceSpam = "  " + "   ".repeat(10_000);
     const snippetWhitespaceSpam = "    \t" + "   ".repeat(10_000);
 
-    const start = performance.now();
     expect(tokenize(commentSpam).length).toBe(1);
     expect(tokenize(doubleQuoteSpam).length).toBe(1);
     expect(tokenize(singleQuoteSpam).length).toBe(1);
-    expect(parseDiffText(paddedWhitespaceSpam).rows.length).toBe(1);
+    expect(parseDiffText(paddedWhitespaceSpam).rows.length).toBe(0);
     expect(parseDiffText(snippetWhitespaceSpam).rows.length).toBe(0);
-    expect(performance.now() - start).toBeLessThan(250);
   });
 });
diff --git a/test/review/diff-cache.spec.ts b/test/review/diff-cache.spec.ts
index dcd0956b..975325c3 100644
--- a/test/review/diff-cache.spec.ts
+++ b/test/review/diff-cache.spec.ts
@@ -227,7 +227,50 @@ describe("getIncrementalDiffFiles", () => {
     await expect(
       getIncrementalDiffFiles({ kv }, job, github, config, "aaa111", "  "),
     ).rejects.toThrow(/non-empty commit SHAs/i);
+    await expect(
+      getIncrementalDiffFiles({ kv }, job, github, config, "aaa111..bbb222", "ccc333"),
+    ).rejects.toThrow(/valid hex commit SHAs/i);
+    expect(github.getCompareDiff).not.toHaveBeenCalled();
+    expect(kv.get).not.toHaveBeenCalled();
+  });
+
+  it("short-circuits identical commit SHAs without calling getCompareDiff or KV", async () => {
+    const kv = makeKv();
+    const github = {
+      getCompareDiff: vi.fn(async () => ""),
+    };
+
+    const result = await getIncrementalDiffFiles(
+      { kv },
+      job,
+      github,
+      config,
+      "aaa111",
+      "AAA111",
+    );
+
+    expect(result).toEqual({ files: [], skipped: 0 });
     expect(github.getCompareDiff).not.toHaveBeenCalled();
     expect(kv.get).not.toHaveBeenCalled();
   });
+
+  it("falls back to getCompareDiff when KV read throws", async () => {
+    const kv = makeKv();
+    kv.get.mockRejectedValueOnce(new Error("kv read timeout"));
+    const github = {
+      getCompareDiff: vi.fn(async () => fileDiff("src/fallback.ts")),
+    };
+
+    const result = await getIncrementalDiffFiles(
+      { kv },
+      job,
+      github,
+      config,
+      "aaa111",
+      "bbb222",
+    );
+
+    expect(github.getCompareDiff).toHaveBeenCalledTimes(1);
+    expect(result.files.map((file) => file.path)).toEqual(["src/fallback.ts"]);
+  });
 });
diff --git a/vitest.config.ts b/vitest.config.ts
index fc6415fd..e0e3652f 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -34,8 +34,6 @@ const testInclude =
         "test/**/*.spec.tsx",
         "test/**/*.test.ts",
         "test/**/*.test.tsx",
-        "packages/models/test/providers/openai.test.ts",
-        "packages/provider-github/test/**/*.test.ts",
       ];
 
 const testExclude =
@@ -47,11 +45,11 @@ export default defineConfig({
   plugins: [react()],
   resolve: {
     alias: {
-      "@server": resolve(__dirname, "./apps/worker/src"),
-      "@client": resolve(__dirname, "./apps/dashboard/src"),
-      "@": resolve(__dirname, "./apps/dashboard/src"),
+      "@server": resolve(import.meta.dirname, "./apps/worker/src"),
+      "@client": resolve(import.meta.dirname, "./apps/dashboard/src"),
+      "@": resolve(import.meta.dirname, "./apps/dashboard/src"),
       "cloudflare:workers": resolve(
-        __dirname,
+        import.meta.dirname,
         "./test/mocks/cloudflare-workers.ts",
       ),
     },
@@ -62,7 +60,7 @@ export default defineConfig({
     include: testInclude,
     exclude: testExclude,
     passWithNoTests: true,
-    setupFiles: [resolve(__dirname, "./test/setup.ts")],
+    setupFiles: [resolve(import.meta.dirname, "./test/setup.ts")],
     // The suite is dominated by round trips to a remote Postgres, so wall clock is latency-bound,
     // not CPU-bound: running files concurrently overlaps the waiting. Safe because DB-backed suites
     // isolate by unique row names (see `uniqueName`) and nothing truncates a shared table.