diff --git a/.env.example b/.env.example index e99e05d..494b19a 100644 --- a/.env.example +++ b/.env.example @@ -1,22 +1,11 @@ -# Copy to .env. Add real values only to the ignored .env file. +# Optional: local mode works without an env file or service accounts. +COMIC_CODE_MODE=local +NEXT_PUBLIC_APP_URL=http://127.0.0.1:3000 +WXT_PUBLIC_API_BASE_URL=http://127.0.0.1:3000 -NEXT_PUBLIC_APP_URL=http://localhost:3000 -WXT_PUBLIC_API_BASE_URL=http://localhost:3000 +# Optional server-side GitHub token for a higher public API request limit. +# Never use a NEXT_PUBLIC_ or WXT_PUBLIC_ prefix for this token. +GITHUB_TOKEN= -TRIGGER_SECRET_KEY= -TRIGGER_PROJECT_REF= - -GITHUB_APP_ID= -GITHUB_CLIENT_ID= -GITHUB_CLIENT_SECRET= -GITHUB_PRIVATE_KEY_BASE64= -GITHUB_WEBHOOK_SECRET= -GITHUB_APP_SLUG= - -NEXT_PUBLIC_SUPABASE_URL= -SUPABASE_SECRET_KEY= - -SHARE_TOKEN_PEPPER= -SAFETY_IDENTIFIER_SECRET= -SESSION_ENCRYPTION_SECRET= -CRON_SECRET= +# Optional absolute directory on a persistent local disk. +# COMIC_CODE_DATA_DIR=/absolute/path/to/comic-data diff --git a/.env.hosted.example b/.env.hosted.example new file mode 100644 index 0000000..6626d40 --- /dev/null +++ b/.env.hosted.example @@ -0,0 +1,27 @@ +COMIC_CODE_MODE=hosted + +# Copy to .env. Add real values only to the ignored .env file. + +NEXT_PUBLIC_APP_URL=http://localhost:3000 +WXT_PUBLIC_API_BASE_URL=http://localhost:3000 + +TRIGGER_SECRET_KEY= +TRIGGER_PROJECT_REF= + +GITHUB_APP_ID= +GITHUB_CLIENT_ID= +GITHUB_CLIENT_SECRET= +GITHUB_PRIVATE_KEY_BASE64= +GITHUB_WEBHOOK_SECRET= +# Hosted extension OAuth recipients. Comma-separated IDs from chrome://extensions. +# Empty permits web login only. Local mode never needs OAuth or this setting. +ALLOWED_EXTENSION_IDS= +GITHUB_APP_SLUG= + +NEXT_PUBLIC_SUPABASE_URL= +SUPABASE_SECRET_KEY= + +SHARE_TOKEN_PEPPER= +SAFETY_IDENTIFIER_SECRET= +SESSION_ENCRYPTION_SECRET= +CRON_SECRET= diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..39e7833 --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,42 @@ +name: CI + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + verify: + name: Tests, builds, and dependency audit + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + WXT_PUBLIC_API_BASE_URL: https://comic-code-ci.example + steps: + - name: Check out source + uses: actions/checkout@v4 + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: 24 + - name: Set up pnpm + uses: pnpm/action-setup@v4 + with: + version: 11.11.0 + - name: Install locked dependencies + run: pnpm install --frozen-lockfile + - name: Run tests, lint, formatting, production builds and typechecks + run: pnpm check + - name: Package Chrome extension + run: pnpm extension:zip + - name: Audit runtime and development dependencies + run: pnpm audit diff --git a/.gitignore b/.gitignore index 58d1cd2..bcc67fe 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ # Local secrets .env .env.local +.env.production .env.*.local *.pem @@ -24,3 +25,9 @@ test-results/ .DS_Store coverage/ .vercel + +# Single-user local comics (never commit generated content) +.comic-code/ +# Built browser preview mirrors the extension output; regenerated by the build. +apps/web/public/extension-preview/ +.impeccable/review/ diff --git a/.node-version b/.node-version new file mode 100644 index 0000000..a45fd52 --- /dev/null +++ b/.node-version @@ -0,0 +1 @@ +24 diff --git a/.prettierignore b/.prettierignore index 29dae7e..e52fe45 100644 --- a/.prettierignore +++ b/.prettierignore @@ -9,3 +9,5 @@ pnpm-lock.yaml apps/web/next-env.d.ts .env.example supabase/migrations/*.sql + +apps/web/public/extension-preview diff --git a/README.md b/README.md index 4af484d..1d7f94c 100644 --- a/README.md +++ b/README.md @@ -1,207 +1,173 @@ # Comic Code -Comic Code reads selected source files from a GitHub pull request and turns how the code works into a grounded four-panel comic. It includes a Chrome side-panel extension, a hosted Next.js demo, private Supabase storage, durable Trigger.dev jobs, and optional user-funded Cloudflare AI generation. +Turn a public GitHub repository into a four- or twelve-panel comic with evidence links. +The default local mode runs on your computer: no login, database account, +background-worker account, AI key, or hosting subscription is required. -Built for the OpenAI Build Week hackathon in the **Work & Productivity** category. +## Start -## What works - -- Public and private GitHub pull requests. -- Native Chrome 114+ side panel with an injected **Explain PR** button. -- GitHub App OAuth with state + PKCE and encrypted seven-hour sessions. -- Read-only repository access; private repositories require a GitHub App installation. -- Safe public-repository fallback without requiring an installation. -- File selection with a maximum of 20 files and 3,000 changed lines. -- Sensitive-file exclusion, secret masking, and high-entropy token detection. -- Full selected-file reading at the PR head, with diff locations used only to prioritize bounded source sampling. -- API-free structural scan that detects languages, control flow, validation, async work, data access, UI state, security checks, and tests. -- Optional Cloudflare BYOK pipeline: Llama analyzes and verifies transient code context, then FLUX creates four distinct panels using the user's own Workers AI allocation; creator credits are never used as a hidden fallback. -- Bundled visual-template fallback when artwork credentials or quota are unavailable. -- Private PNG storage, short-lived downloads, seven-day revocable share links, and deletion. -- Daily retention cleanup and a 25-generation-per-user safety limit. -- Desktop, mobile, and narrow side-panel layouts using the supplied indigo visual direction. - -## Repository layout - -```text -apps/web Next.js App Router site, API, OAuth, Trigger.dev task -apps/extension WXT Manifest V3 Chrome extension -packages/comic Analysis prompts, validation, artwork, PNG composition -packages/contracts Shared Zod contracts -packages/database Supabase repository and private storage operations -packages/github GitHub App client, source filtering, masking, evidence mapping -supabase CLI config and timestamped database migration -``` - -## Security model - -Raw source, reconstructed patches, and prompts containing source exist only in authenticated function or worker memory. They are never written to PostgreSQL, Storage, Trigger.dev payloads or outputs, audit metadata, analytics, or application logs. - -Cloudflare BYOK Account IDs and API tokens are accepted only by the authenticated code-analysis/artwork route over HTTPS. They remain in webpage tab memory or Chrome extension local storage, are never placed in Trigger.dev payloads, and are never persisted by Comic Code servers, databases, logs, or audit records. Masked selected code context is sent transiently to Cloudflare for Llama analysis and claim verification; FLUX then generates four images. The user's Cloudflare account pays for both text and image inference. - -The worker receives only an explanation UUID. It fetches selected files at the PR head, masks secrets, creates an API-free preview, and persists only sanitized claims, captions, evidence locators/hashes, and generated artwork. If a user supplies Cloudflare credentials, the authenticated web route refetches the same bounded source and sends it transiently to that user's Workers AI account. - -See [SECURITY.md](./SECURITY.md) and [PR_EXPLAINER_IMPLEMENTATION_PLAN.md](./PR_EXPLAINER_IMPLEMENTATION_PLAN.md) for the threat model and acceptance criteria. - -## Prerequisites - -- Node.js 20.12+ -- pnpm 11.11.0 -- Chrome 114+ -- Optional Cloudflare account for user-funded semantic analysis and FLUX artwork -- GitHub App -- Supabase project -- Trigger.dev project -- Vercel project for the hosted demo - -## Environment setup - -The repository-level `.env` is ignored by Git. Copy the example and add real values locally: +Install Node.js 24+ and pnpm 11.11.0, then run from this repository: ```bash -cp .env.example .env +pnpm install --frozen-lockfile +pnpm dev ``` -| Variable | Used by | Notes | -| --------------------------- | --------------- | ------------------------------------------------------------------ | -| `NEXT_PUBLIC_APP_URL` | Web | `http://localhost:3000` locally; production HTTPS origin on Vercel | -| `WXT_PUBLIC_API_BASE_URL` | Extension build | Same origin as the hosted web app | -| `TRIGGER_SECRET_KEY` | Web | Trigger.dev DEV key locally, production key on Vercel | -| `TRIGGER_PROJECT_REF` | Trigger config | `proj_...` from the Trigger.dev dashboard | -| `GITHUB_APP_ID` | Web + worker | Numeric GitHub App ID | -| `GITHUB_CLIENT_ID` | Web | GitHub App OAuth client ID | -| `GITHUB_CLIENT_SECRET` | Web | GitHub App OAuth client secret | -| `GITHUB_PRIVATE_KEY_BASE64` | Web + worker | Entire GitHub App PEM encoded as one base64 line | -| `GITHUB_WEBHOOK_SECRET` | Web | At least 32 random characters | -| `GITHUB_APP_SLUG` | Web | Slug used by the install URL | -| `NEXT_PUBLIC_SUPABASE_URL` | Web + worker | Project URL; no browser database access is used | -| `SUPABASE_SECRET_KEY` | Web + worker | Server-side secret/service key only | -| `SHARE_TOKEN_PEPPER` | Web | 32+ random bytes; changing it invalidates shares | -| `SAFETY_IDENTIFIER_SECRET` | Web + worker | 32+ random bytes | -| `SESSION_ENCRYPTION_SECRET` | Web | 32+ random bytes; changing it signs everyone out | -| `CRON_SECRET` | Web | 32+ random bytes; Vercel sends it to cron routes | - -Generate independent local secrets with `openssl rand -hex 32`. Do not reuse one value for multiple variables. Encode the GitHub PEM without line breaks, for example: +Open **http://127.0.0.1:3000**, paste a GitHub repository URL, inspect it, and +choose **Generate fixed comic**. Download the PNG or reopen it from **Saved +comics** after a restart. Leave the API key empty for the free flow. + +## Preview without using API quota + +Choose **Explore a sample** or **Try the sample** to inspect the bundled example +story and evidence without contacting GitHub or image providers. The sample is labeled +illustrative; it does not pretend to be a fresh scan. You can download its PNG. Twelve panels are selected by default; choose four +for a quick overview. Existing saved comics keep their original length. + +To test image composition without an API key, open **Use your own images · no +API key**, choose **Load sample artwork**, then **Compose 12-panel PNG**. You +can also copy each panel prompt into an image tool manually and choose the +resulting PNG/JPEG/WebP files. Files stay in browser memory; download the result +before closing or changing the story. See [the manual artwork guide](docs/MANUAL_ARTWORK.md). + +Open **http://127.0.0.1:3000/extension** for the actual built side-panel interface +in a browser. Explain, Story, Evidence and compact-layout controls work with sample +data. Its browser-served preview blocks all `connect-src` requests with CSP. The +installed Chrome extension also has an **Explore sample** control. Live OAuth, +private repository access and provider quota behavior still need separate tests. +`pnpm dev` and `pnpm build` generate the extension preview automatically. +With the server running, `pnpm smoke:preview` checks preview assets, fonts, +framing policy and the sample PNG without consuming provider quota. + +The free result uses bounded structural analysis and bundled artwork. It +identifies patterns in sampled files; it does not provide AI semantic analysis +or prove that the repository is correct. A scan selects up to 40 files and +150,000 characters at the inspected commit. Branches containing slashes work. + +## What “free” means + +- Local generation, storage and PNG export make no paid API calls. +- GitHub access still needs internet. Anonymous REST access has a limit of + [60 requests per hour per IP](https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api). + A large scan can use most of that allowance. An optional server-side + `GITHUB_TOKEN` raises the limit; no token is needed to start. +- Optional OpenAI or Google Gemini image generation uses **your own API key**. + Four or twelve panel images use your selected provider's quota and billing. Free API + access is not guaranteed. Captions and evidence come from the saved storyboard + and are not rewritten by the image provider. A failed request preserves the + existing comic. See [image BYOK setup](docs/IMAGE_BYOK.md). +- Public hosting, private repository login and online share links need the + separate [hosted setup](docs/HOSTED_SETUP.md). Their free tiers are limited; + unlimited hosted AI generation is not promised. + +## Local data and limits + +Local mode accepts public repositories only, even if the optional token can read +private code. It is a single-user desktop server bound to loopback by `pnpm dev`. +Requests using public hostnames and cross-site mutations are rejected. Installed +Chrome extensions may access it through their declared localhost host permission. +Do not tunnel or reverse-proxy local mode to the internet or run several server +processes against the same data directory. + +Completed analysis, evidence locators and PNG bytes are saved atomically under +`apps/web/.comic-code/` when launched with the commands above. Raw source and +Image API keys are not persisted. The directory is ignored by Git; +new directories/files use owner-only permissions where the OS supports them. +Records expire after 30 days and are removed on the next read/list. There is a +100-record storage cap and a 25-generation daily safety limit over retained +records. Download comics you want to keep. Delete removes the local record and +its PNG; it cannot revoke a previously downloaded copy. + +To adjust local configuration, copy `.env.example` to `.env`. Set +`COMIC_CODE_DATA_DIR` to an absolute directory for a persistent disk location. +Keep secrets in the ignored `.env`; never put tokens in public-prefixed variables. +Use `COMIC_CODE_MODE=hosted` for the authenticated service-backed runtime. + +## Chrome extension + +Keep the local server running, then build: ```bash -base64 < path/to/github-app.private-key.pem | tr -d '\n' +pnpm extension:build +# Or create a distributable ZIP: +pnpm extension:zip ``` -Only these variables belong in Trigger.dev: `GITHUB_APP_ID`, `GITHUB_PRIVATE_KEY_BASE64`, `NEXT_PUBLIC_SUPABASE_URL`, `SUPABASE_SECRET_KEY`, and `SAFETY_IDENTIFIER_SECRET`. - -## GitHub App configuration - -Create a GitHub App with: - -- Homepage URL: `NEXT_PUBLIC_APP_URL` -- Callback URL: `NEXT_PUBLIC_APP_URL/api/v1/auth/github/callback` -- Webhook URL: `NEXT_PUBLIC_APP_URL/api/v1/github/webhooks` -- Webhook secret: `GITHUB_WEBHOOK_SECRET` -- Repository permissions: **Contents: Read-only**, **Pull requests: Read-only**, **Metadata: Read-only** -- No write permissions -- User authorization enabled -- Expiring user access tokens enabled - -Public PRs work without installing the app on that repository. Private PRs require the user to install the app on the selected repository and still revalidate the signed-in user’s access. - -## Supabase setup - -The migration was created with Supabase CLI 2.109.1 and enables RLS/forced RLS, explicit service-role grants, constraints, indexes, retention fields, and a private 10 MB PNG bucket. - -```bash -pnpm dlx supabase@2.109.1 login -pnpm dlx supabase@2.109.1 link --project-ref YOUR_PROJECT_REF -pnpm dlx supabase@2.109.1 db push -``` - -Do not paste the migration into the SQL editor manually. The application intentionally exposes no anon/authenticated table policies; all database access goes through authenticated server routes. - -## Trigger.dev setup - -From `apps/web`: +Load `apps/extension/.output/chrome-mv3` at `chrome://extensions` using +**Developer mode → Load unpacked**. Open a GitHub repository and select its +**Explain repository** button. The side panel detects the local server and +needs no OAuth login. Local mode supports generation and PNG download; online +sharing requires hosted mode. Image API keys stay in side-panel memory and are cleared when the panel +closes or you select **Clear API key**. Old saved Cloudflare credentials are +removed automatically when the updated extension initializes. + +For a hosted extension, set `WXT_PUBLIC_API_BASE_URL` to the final HTTPS origin +before building. The manifest grants access to that exact API origin. For hosted OAuth, also add +the extension ID from `chrome://extensions` to the server’s comma-separated +`ALLOWED_EXTENSION_IDS`. An empty list allows web login only. + +## Where to enter your API key (BYOK) + +- **Web:** select **API key / BYOK** in the top navigation. +- **Extension:** expand **API key / BYOK** below the header, from any tab. +- Choose **OpenAI** or **Google Gemini**, choose an image model available to your + account, and enter that provider's API key. Keys from other providers are not + interchangeable. Switching providers clears the entered key. +- Generate a comic or select **Generate 4 AI panels** or **Generate 12 AI panels** on a saved comic. One + provider request per panel creates an illustration; captions and evidence stay intact. +- Keys remain in current tab/panel memory. **Clear API key** removes the value. + There is no API call just for entering a key or changing a provider. +- Sample mode lets you inspect providers/models with key entry disabled. No + provider calls or credential storage occur in samples. + +Free bundled artwork works without a key. Image-provider keys do not raise +GitHub's independent request limit; configure an optional server-side +`GITHUB_TOKEN` separately in `.env`. Read the [setup and privacy details](docs/IMAGE_BYOK.md). + +## Project structure -```bash -pnpm exec trigger.dev login -pnpm exec trigger.dev dev +```text +apps/web/ Next.js UI, APIs, local runtime, optional hosted worker +apps/extension/ Chrome Manifest V3 side panel and GitHub page integration +packages/comic/ Grounded analysis, optional providers and PNG composition +packages/contracts/ Shared request and response validation +packages/ui/ Browser-only manual artwork studio and PNG export +packages/github/ GitHub access, file selection, source masking and evidence +packages/database/ Optional Supabase repository and private artifact storage +supabase/ Hosted database migrations +scripts/ Repeatable local extension packaging +docs/ Setup, deployment and debugging evidence +docs/archive/ Historical implementation and hackathon documents ``` -After the task appears in the dashboard, sync only the worker variables listed above. Deploy the task with: +## Check and build ```bash -pnpm exec trigger.dev deploy +pnpm check +pnpm audit +# With the local server running, check the real public GitHub flow: +pnpm smoke:local ``` -The task payload is `{ explanationId }`; it never includes source, patches, prompts, GitHub tokens, or captions. - -## Local development - -Install dependencies and run the web app: +`pnpm check` runs tests, lint, formatting, web/extension production builds and +TypeScript checks. The web production build uses webpack for compatibility with +restricted build environments. To run the built web app locally: ```bash -pnpm install -pnpm --filter @comic-code/web dev +pnpm --filter @comic-code/web start --hostname 127.0.0.1 ``` -In another terminal, run Trigger.dev as described above. For extension hot reload: - -```bash -pnpm --filter @comic-code/extension dev -``` - -Load the generated extension directory from `chrome://extensions` → **Developer mode** → **Load unpacked**. - -Chrome controls whether side panels appear on the left or right. Comic Code reads the selected side and adapts its border treatment; users move it under Chrome **Settings → Appearance → Side panel**. - -### User-funded artwork - -Before generating, choose the image mode. Leave both fields empty for the fixed API-free comic, or provide: - -- Cloudflare Account ID. -- API token with Workers AI Read and Workers AI Edit permissions. - -Web credentials live only in current tab memory. Extension credentials use `chrome.storage.local` until the user selects **Remove saved credentials** or uninstalls the extension. With a valid key, generation automatically creates the fixed preview first, then refetches and masks bounded source from the selected files, asks Cloudflare Llama for a grounded story plus independent claim verification, generates four distinct FLUX panels with separate prompts and seeds, composes a new PNG, then atomically replaces the preview. Failures leave the fixed comic unchanged. - -## Verification - -```bash -pnpm typecheck -pnpm lint -pnpm test -pnpm audit --prod -pnpm --filter @comic-code/web build -pnpm --filter @comic-code/extension build -pnpm --filter @comic-code/extension zip -``` - -Current local verification: - -- Production dependency audit: no known vulnerabilities. -- 23 unit/security/composition tests passing. -- TypeScript passing across all workspaces. -- ESLint passing with zero warnings. -- Next.js production build passing for every page and API route. -- WXT Chrome MV3 build and ZIP passing. -- Browser checks passing at 1280 px and 390 px with no runtime errors or horizontal overflow. - -Live integration tests require real service credentials and a test PR; they cannot be meaningfully mocked as proof of deployment readiness. - -## Deployment - -See [docs/DEPLOYMENT_CHECKLIST.md](./docs/DEPLOYMENT_CHECKLIST.md) for the exact order. In short: - -1. Push the Supabase migration. -2. Deploy the Trigger.dev task and worker environment. -3. Deploy `apps/web` on Vercel with the server environment. -4. Update the GitHub App URLs to the production origin. -5. Set `WXT_PUBLIC_API_BASE_URL` to the production origin and rebuild the extension. -6. If using a custom domain instead of `*.vercel.app`, add its exact origin to `host_permissions` before the final extension build. - -Release artifacts are generated at: - -- Unpacked extension: `apps/extension/.output/chrome-mv3` -- Chrome ZIP: `apps/extension/.output/comic-codeextension-0.1.0-chrome.zip` +GitHub Actions uses [`.github/workflows/ci.yaml`](.github/workflows/ci.yaml). +It checks PRs when opened, updated, reopened or marked ready for review, as well +as pushes to `main`. A manual trigger is available once the workflow is on the +default branch. Draft PRs run checks too. The job runs `pnpm check`, extension +packaging and the dependency audit for runtime and development tools; it needs no AI keys or hosted +service credentials. CI reports results on the PR and does not merge it. +See [the current functional audit](docs/FUNCTIONAL_AUDIT.md) for reproduced +failures, fixes, cleanup decisions and current verification. -## License +See [the debugging report](docs/DEBUGGING_REPORT.md) for reproduced defects, +fixes, test results and the limits of hosted verification. -[MIT](./LICENSE) +[Security model](SECURITY.md) · [Hosted deployment](docs/DEPLOYMENT_CHECKLIST.md) · [MIT license](LICENSE) diff --git a/SECURITY.md b/SECURITY.md index 4d37975..0adfb2f 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,8 +1,30 @@ -# Security policy +# Security + +## Local runtime + +The default runtime is a single-user desktop service. It accepts public GitHub +repositories only, with no OAuth session or remote database. Its proxy and API +handler reject non-loopback hosts and origins. Mutations require a same-port +loopback origin or a Chrome extension origin; bearer strings do not bypass this +check. This trusts locally installed browser extensions and local processes. +It is not an authentication boundary against another user on the same computer. +Use `pnpm dev` or `next start --hostname 127.0.0.1`; do not expose it through a +tunnel or reverse proxy. Vercel defaults to hosted mode and requires the hosted +credentials. The `/api/local` handler returns 404 in hosted mode. + +Local persistence contains sanitized analysis, evidence locators and PNG bytes, +never source or provider credentials. Writes replace complete records atomically +using owner-only file permissions. One server process per data directory is +supported, with one mutation at a time. Expired records are removed lazily on +read/list, including their PNG bytes. Local deletion removes the complete file. +Downloaded copies cannot be revoked. Online capability sharing is unavailable +in local mode. See the README for storage and generation limits. + +## Hosted runtime ## Scope -Comic Code handles private source code and treats pull-request titles, descriptions, paths, patches, and generated model output as untrusted. +Comic Code handles private source code and treats repository names, descriptions, README content, manifests, paths, source, and generated model output as untrusted. ## Implemented controls @@ -10,7 +32,7 @@ Comic Code handles private source code and treats pull-request titles, descripti - Authenticated/encrypted seven-hour session JWE; browser cookies are HttpOnly, SameSite Lax, and Secure in production. - Bearer sessions returned to the extension only in the `chromiumapp.org` URL fragment. - Read-only GitHub permissions and separate user-access plus installation-access checks for private repositories. -- Server verification of repository, PR number, selected paths, and captured head SHA. +- Server verification of repository access, requested ref, and captured immutable commit SHA. - Exclusion of `.env`, credentials, lockfiles, binary, generated, vendored, minified, and oversized reconstructed files. - Secret/token/email/connection-string masking plus high-entropy masking. - Prompt-injection boundaries, strict Zod structured output, no model tools, and opaque safety identifiers. @@ -20,27 +42,32 @@ Comic Code handles private source code and treats pull-request titles, descripti - Forced RLS and no anon/authenticated table grants. - Tombstone-first deletion, worker tombstone checks, artifact cleanup, Trigger.dev cancellation, and daily retention. - CSP, frame denial, HSTS, no-sniff, restrictive permissions policy, CSRF origin checks, webhook HMAC verification, quotas, and bounded request bodies. -- Cloudflare BYOK credentials accepted only on authenticated, same-origin analysis/artwork requests; strict Account ID/token bounds; provider errors reduced to safe codes; credentials excluded from persistence, Trigger.dev, analytics, and audit metadata. -- BYOK source context is secret-masked, bounded, and sent to Cloudflare only after an explicit user action; model output passes strict schema, grounding, leak, and safety validation. +- Image BYOK requests require the existing local-origin or hosted authentication/ownership/repository-access checks. Provider/model/key combinations are validated strictly; only fixed official OpenAI and Gemini endpoints are used, with redirects disabled. Keys are excluded from persistence, Trigger.dev, analytics and audit metadata. +- Image BYOK sends only sanitized illustration prompts from the saved storyboard, after an explicit generation action. No raw source or evidence bodies are sent. JSON responses, base64 data, raster signatures and decoded pixels are bounded; remote image URLs are never followed. Provider response/error bodies are never logged or returned to clients. - BYOK artwork uploaded under a new random object path and swapped only after successful composition; failed regeneration preserves prior comic. ## Data that is persisted -Repository/PR coordinates, captured SHAs, selected/excluded file paths, evidence line locators and hashes, sanitized claims/storyboard text, generated PNG paths, usage counts, progress, and low-cardinality audit metadata. +Repository coordinates, captured ref and commit SHA, scan summary, selected/excluded file paths, evidence line locators and hashes, sanitized claims/storyboard text, generated PNG paths, usage counts, progress, and low-cardinality audit metadata. Raw patches, source blobs, prompt bodies containing source, GitHub access tokens, OAuth codes, share tokens, and provider request bodies are not persisted. -Cloudflare Account IDs and API tokens are not persisted by Comic Code. Web values remain in tab memory. Extension values remain in `chrome.storage.local` on the user's device until removed. API tokens and masked selected code context cross the Comic Code server transiently over HTTPS for Cloudflare Llama and FLUX calls. Tokens must be dedicated and scoped only to Workers AI. +OpenAI and Gemini image keys remain in webpage tab or extension panel memory; +they are not saved in Chrome storage. They cross the Comic Code server +transiently and authenticate only with the selected provider. Hosted traffic +uses HTTPS; local traffic stays on loopback. The extension removes obsolete +saved Cloudflare credentials during initialization. Gemini Interactions calls +set `store: false`; provider-specific data policies still apply. ## Residual considerations -- Cloudflare receives the masked source context in BYOK mode under the user's Cloudflare account and applicable Cloudflare data-usage terms; Comic Code does not present that path as Zero Data Retention. +- The selected image provider receives illustration prompts under the user's account and applicable provider data policies. Image generation does not verify the storyboard's claims or guarantee text-free artwork. - A revoked share may retain an already minted signed asset URL for at most five minutes. - The encrypted extension session is still a bearer capability and expires after seven hours. Chrome extension storage must be treated as sensitive. - Public-repository fallback uses unauthenticated GitHub API capacity and may be rate limited. - Chrome, not the extension, controls left/right side-panel placement. -- A local extension credential can be read by Comic Code extension code and anyone controlling that Chrome profile. Users should create a dedicated least-privilege Workers AI token and revoke it if the device or extension becomes untrusted. -- A complete live review must test the deployed GitHub, Supabase, Trigger.dev, Cloudflare BYOK, and Vercel configuration with real credentials. +- Keys in tab/panel memory can be read by someone controlling that page or device. Use a dedicated provider key with suitable account limits and revoke it if compromised. +- A complete live review must test the deployed GitHub, Supabase, Trigger.dev, OpenAI/Gemini BYOK, and Vercel configuration with real credentials. ## Dependency status @@ -49,3 +76,12 @@ On 2026-07-20, `pnpm audit --prod` reported no known vulnerabilities after scope ## Reporting Do not include private source, secrets, tokens, or full request logs in a report. Revoke affected credentials first, then provide a minimal reproduction through the repository’s private security-reporting channel. + +## Manual artwork + +The shared browser artwork studio accepts PNG/JPEG/WebP files up to 8 MB each, +checks decoded images against a 40-megapixel limit, and composes four or twelve +panels on a local Canvas. It makes no upload or AI-provider requests. Object URLs +are revoked when artwork changes or the component closes. Manual artwork is not +added to persisted comics or shared artifacts. The extension browser preview +permits blob images while keeping API connections blocked. diff --git a/apps/extension/entrypoints/background.ts b/apps/extension/entrypoints/background.ts index 6b1667d..5c3c0b9 100644 --- a/apps/extension/entrypoints/background.ts +++ b/apps/extension/entrypoints/background.ts @@ -8,11 +8,6 @@ export default defineBackground(() => { comicCodeCoordinate: message.coordinate, }) - void chrome.sidePanel.setOptions({ - tabId: sender.tab.id, - path: 'sidepanel.html', - enabled: true, - }) void chrome.sidePanel.open({ tabId: sender.tab.id }) }) diff --git a/apps/extension/entrypoints/github.content.ts b/apps/extension/entrypoints/github.content.ts index f53aa5c..fcbf7c2 100644 --- a/apps/extension/entrypoints/github.content.ts +++ b/apps/extension/entrypoints/github.content.ts @@ -1,19 +1,7 @@ -const pullRequestPath = /^\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:\/|$)/ +import { parseGitHubRepositoryUrl } from '@comic-code/contracts/repository-url' function readCoordinate() { - const match = window.location.pathname.match(pullRequestPath) - if (!match) return null - - const pullRequestNumber = Number(match[3]) - if (!Number.isSafeInteger(pullRequestNumber) || pullRequestNumber < 1) { - return null - } - - return { - owner: match[1]!, - repository: match[2]!, - pullRequestNumber, - } + return parseGitHubRepositoryUrl(window.location.href) } function mountExplainButton() { @@ -26,14 +14,13 @@ function mountExplainButton() { existing?.remove() return } - if (existing) return const button = document.createElement('button') button.type = 'button' button.dataset.comicCodeTrigger = 'true' button.className = 'Button--primary Button--medium Button' - button.textContent = 'Explain PR' + button.textContent = 'Explain Repository' button.addEventListener('click', () => { void chrome.runtime.sendMessage({ type: 'comic-code:open-sidepanel', @@ -42,10 +29,9 @@ function mountExplainButton() { }) const target = - document.querySelector('.gh-header-actions') ?? - document.querySelector('[data-testid="pull-request-header"]') ?? + document.querySelector('[data-testid="repository-overview"]') ?? + document.querySelector('.file-navigation') ?? document.querySelector('main') - target?.prepend(button) } @@ -54,15 +40,22 @@ export default defineContentScript({ runAt: 'document_idle', main() { let currentHref = window.location.href - mountExplainButton() - - const observer = new MutationObserver(() => { + let scheduled = false + const refresh = () => { + scheduled = false if (window.location.href !== currentHref) { currentHref = window.location.href + document.querySelector('[data-comic-code-trigger]')?.remove() } mountExplainButton() + } + const observer = new MutationObserver(() => { + if (scheduled) return + scheduled = true + window.requestAnimationFrame(refresh) }) + refresh() observer.observe(document.documentElement, { childList: true, subtree: true, diff --git a/apps/extension/entrypoints/sidepanel/bootstrap.tsx b/apps/extension/entrypoints/sidepanel/bootstrap.tsx new file mode 100644 index 0000000..99d44c6 --- /dev/null +++ b/apps/extension/entrypoints/sidepanel/bootstrap.tsx @@ -0,0 +1,15 @@ +import React from 'react' +import { createRoot } from 'react-dom/client' +import { SidePanelShell } from './main' + +const root = document.getElementById('root') + +if (!root) { + throw new Error('Missing Comic Code side-panel root') +} + +createRoot(root).render( + + + , +) diff --git a/apps/extension/entrypoints/sidepanel/index.html b/apps/extension/entrypoints/sidepanel/index.html index 8f148a3..64d5e83 100644 --- a/apps/extension/entrypoints/sidepanel/index.html +++ b/apps/extension/entrypoints/sidepanel/index.html @@ -7,6 +7,6 @@
- + diff --git a/apps/extension/entrypoints/sidepanel/main.test.tsx b/apps/extension/entrypoints/sidepanel/main.test.tsx new file mode 100644 index 0000000..098c8e8 --- /dev/null +++ b/apps/extension/entrypoints/sidepanel/main.test.tsx @@ -0,0 +1,142 @@ +// @vitest-environment jsdom +import React, { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { getSampleExplanation } from '@comic-code/comic/sample' +import { SidePanelShell } from './main' + +let root: Root +let container: HTMLDivElement +let changeCoordinate: (changes: Record, area: string) => void +let finishGeneration: (response: Response) => void +let failGeneration: (error: Error) => void +function json(value: unknown) { + return new Response(JSON.stringify(value)) +} +const repository = (name: string) => ({ + owner: 'owner', + repository: name, + ref: 'main', + defaultBranch: 'main', + description: name, + commitSha: 'a'.repeat(40), + totalFiles: 1, + selectedFileCount: 1, + excludedFileCount: 0, + representativeFiles: ['src/main.ts'], + languages: ['TypeScript'], +}) +async function settle() { + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 10)) + }) +} +beforeEach(() => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + window.history.replaceState(null, '', '/') + vi.stubGlobal('chrome', { + tabs: { + query: vi + .fn() + .mockResolvedValue([{ url: 'https://github.com/owner/repo-a' }]), + }, + storage: { + local: { + get: vi.fn().mockResolvedValue({}), + set: vi.fn().mockResolvedValue(undefined), + remove: vi.fn().mockResolvedValue(undefined), + }, + onChanged: { + addListener: (listener: typeof changeCoordinate) => { + changeCoordinate = listener + }, + removeListener: vi.fn(), + }, + }, + sidePanel: {}, + }) + vi.stubGlobal( + 'fetch', + vi.fn((input: string, options?: RequestInit) => { + if (input.includes('/auth/me')) + return Promise.resolve(json({ mode: 'local' })) + if (input.includes('/github/repository')) + return Promise.resolve( + json({ + repository: repository( + decodeURIComponent(input).includes('repo-b') + ? 'repo-b' + : 'repo-a', + ), + }), + ) + if (options?.method === 'POST') + return new Promise((resolve, reject) => { + finishGeneration = resolve + failGeneration = reject + }) + return Promise.resolve(json({})) + }), + ) + container = document.createElement('div') + document.body.append(container) + root = createRoot(container) +}) +afterEach(async () => { + await act(async () => root.unmount()) + container.remove() + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +async function startThenSwitch() { + await act(async () => root.render()) + await settle() + const generate = [...container.querySelectorAll('button')].find( + (button) => button.textContent?.includes('Generate') && !button.disabled, + )! + expect(generate).toBeDefined() + await act(async () => generate.click()) + await settle() + await act(async () => + changeCoordinate( + { + comicCodeCoordinate: { + newValue: { owner: 'owner', repository: 'repo-b' }, + }, + }, + 'local', + ), + ) + await settle() + expect(container.textContent).toContain('repo-b') +} +describe('extension repository-switch race', () => { + it('does not show the previous repository result after switching repositories', async () => { + await startThenSwitch() + await act(async () => + finishGeneration( + json({ + explanation: { + ...getSampleExplanation(4), + id: 'old-comic', + repository: 'owner/repo-a', + progress: { + percent: 100, + message: 'OLD REPOSITORY COMIC', + updatedAt: new Date().toISOString(), + }, + }, + }), + ), + ) + await settle() + expect(container.textContent).not.toContain('OLD REPOSITORY COMIC') + }) + it('does not attach a previous repository failure to the new repository', async () => { + await startThenSwitch() + await act(async () => failGeneration(new Error('github_rate_limited'))) + await settle() + expect(container.textContent).not.toContain('GitHub request limit reached') + }) +}) diff --git a/apps/extension/entrypoints/sidepanel/main.tsx b/apps/extension/entrypoints/sidepanel/main.tsx index a0430e8..cf958a0 100644 --- a/apps/extension/entrypoints/sidepanel/main.tsx +++ b/apps/extension/entrypoints/sidepanel/main.tsx @@ -1,7 +1,19 @@ -import React, { useCallback, useEffect, useRef, useState } from 'react' -import { createRoot } from 'react-dom/client' +import { useCallback, useEffect, useRef, useState } from 'react' +import { + hasByokArtwork, + imageProviders, + type ImageProvider, +} from '@comic-code/contracts/image-providers' import type { ComicAnalysis } from '@comic-code/contracts' +import { + getSampleRepository, + getSampleExplanation, +} from '@comic-code/comic/sample' +import type { PanelCount } from '@comic-code/contracts/comic-layout' +import { ManualArtwork } from '@comic-code/ui' +import '@comic-code/ui/styles.css' +import { parseGitHubRepositoryUrl } from '@comic-code/contracts/repository-url' import { BrandGlyph } from './brand-glyph' import './style.css' @@ -9,29 +21,26 @@ import './style.css' type Coordinate = { owner: string repository: string - pullRequestNumber: number + ref?: string } -type PullRequestFile = { - path: string - status: string - additions: number - deletions: number - changes: number -} -type PullRequest = Coordinate & { - title: string +type Repository = Coordinate & { + description: string htmlUrl: string isPrivate: boolean - baseSha: string - headSha: string - files: PullRequestFile[] + defaultBranch: string + commitSha: string + totalFiles: number + selectedFileCount: number excludedFileCount: number - selectedChangedLines: number + representativeFiles: string[] + languages: string[] } type Explanation = { id: string repository: string - pullRequestNumber: number + ref: string + commitSha: string + scanSummary: Record status: string progress: { percent: number; message: string; updatedAt: string } analysis: ComicAnalysis | null @@ -43,48 +52,104 @@ type StoredState = { comicCodeCoordinate?: Coordinate comicCodeSession?: string comicCodeCompact?: boolean - comicCodeCloudflareAccountId?: string - comicCodeCloudflareApiToken?: string + comicCodeExplanationIds?: Record } type Tab = 'explain' | 'story' | 'evidence' -const apiBase = ( - import.meta.env.WXT_PUBLIC_API_BASE_URL || 'http://localhost:3000' -).replace(/\/$/, '') +const configuredApiBase = import.meta.env.WXT_PUBLIC_API_BASE_URL?.trim() + +if (!configuredApiBase && import.meta.env.PROD) { + throw new Error( + 'WXT_PUBLIC_API_BASE_URL is required for production extension builds', + ) +} + +const apiBase = (configuredApiBase || 'http://localhost:3000').replace( + /\/$/, + '', +) const terminalStatuses = new Set(['completed', 'failed', 'canceled', 'deleted']) +function coordinateKey(coordinate: Coordinate) { + return JSON.stringify([ + coordinate.owner.toLowerCase(), + coordinate.repository.toLowerCase(), + coordinate.ref ?? null, + ]) +} -function parsePullRequestUrl(value: string | undefined): Coordinate | null { - if (!value) return null - try { - const url = new URL(value) - const match = url.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:\/|$)/) - if (url.hostname !== 'github.com' || !match) return null - return { - owner: match[1]!, - repository: match[2]!, - pullRequestNumber: Number(match[3]), - } - } catch { - return null - } +async function persistExplanationId( + coordinate: Coordinate, + explanationId: string, +) { + const stored = (await chrome.storage.local.get( + 'comicCodeExplanationIds', + )) as Pick + await chrome.storage.local.set({ + comicCodeExplanationIds: { + ...stored.comicCodeExplanationIds, + [coordinateKey(coordinate)]: explanationId, + }, + }) +} + +async function removePersistedExplanationId(coordinate: Coordinate) { + const stored = (await chrome.storage.local.get( + 'comicCodeExplanationIds', + )) as Pick + const explanationIds = { ...stored.comicCodeExplanationIds } + delete explanationIds[coordinateKey(coordinate)] + await chrome.storage.local.set({ + comicCodeExplanationIds: explanationIds, + }) +} + +function parseRepositoryUrl(value: string | undefined): Coordinate | null { + return value ? parseGitHubRepositoryUrl(value) : null } function friendlyError(value: string) { if ( - value.startsWith('Cloudflare Workers AI ') || value.startsWith('Comic Code image runtime error:') || value.startsWith('Comic Code artwork error during ') ) { return value } const messages: Record = { - authentication_required: 'Connect GitHub to explain this pull request.', - pull_request_changed: 'This PR changed. Refresh it before generating.', - change_too_large: 'Select fewer files to stay below 3,000 changed lines.', + github_rate_limited: + 'GitHub request limit reached. Wait for it to reset, or configure an optional GITHUB_TOKEN for a higher limit.', + github_token_invalid: + 'The configured GITHUB_TOKEN is invalid or expired. Replace or remove it, then restart.', + repository_too_large: + 'GitHub returned an incomplete tree for this large repository. Try a smaller repository.', + local_public_only: + 'Local mode supports public repositories. Use hosted mode with GitHub sign-in for private code.', + local_busy: + 'Another comic operation is still running. Wait for it to finish, then retry.', + local_storage_full: + 'You have 100 saved comics. Delete an older comic before creating another.', + comic_not_found: 'This comic expired or was deleted. Generate it again.', + local_comic_corrupt: + 'This saved comic file is damaged. Other comics are still available. Inspect its repository to generate a replacement.', + artwork_conflict: + 'This comic changed in another tab. Reload it before replacing its artwork again.', + explanation_not_found: + 'This comic expired, was deleted, or is not available to your account.', + github_unavailable: + 'Comic Code could not reach GitHub after retrying. Try Inspect again when the connection recovers. Saved comics and samples still work.', + local_storage_unavailable: + 'Comic Code cannot write to its data directory. Check free disk space and permissions, or set COMIC_CODE_DATA_DIR to a writable folder and restart.', + local_request_failed: + 'Comic Code could not complete this local operation. Retry, or check the server log if it keeps failing.', + + authentication_required: 'Connect GitHub to explain this repository.', + repository_changed: + 'This repository branch moved. Inspect it again before generating.', daily_quota_reached: 'You reached the 25-comic daily safety limit.', - no_eligible_files: 'No safe text files are available to explain.', + invalid_repository_url: 'Open a full GitHub repository URL.', no_executable_code: - 'This PR changes documentation or unsupported files, not executable code.', + 'This repository has no safe, readable source files to explain.', + extension_not_allowed: + 'This extension is not approved by the hosted server. Configure ALLOWED_EXTENSION_IDS with its Chrome extension ID.', github_reconnect_required: 'Your GitHub login expired. Reconnect GitHub, then try again.', github_access_denied: @@ -94,17 +159,17 @@ function friendlyError(value: string) { github_app_installation_required: 'Install Comic Code on this private repository, then try again.', invalid_image_provider_credentials: - 'Enter a valid Cloudflare Account ID and Workers AI token.', + 'Choose an image provider, model and valid API key.', image_provider_auth_failed: - 'Cloudflare rejected these credentials. Check token permissions.', + 'The image provider rejected this key. Check the provider and key permissions.', image_provider_quota_reached: - 'Your Cloudflare Workers AI limit is exhausted.', + 'Your image provider quota or rate limit was reached. Check billing and credits.', image_provider_unavailable: - 'Cloudflare image generation is unavailable. Existing comic is safe.', - cloudflare_analysis_failed: - 'Cloudflare could not create a grounded code explanation. Check Workers AI and retry.', - explanation_not_ready: - 'Wait for the template comic to finish before generating AI artwork.', + 'The image provider is unavailable. Your existing comic is safe.', + image_provider_model_unavailable: + 'This image model is unavailable to your key. Choose another model or check account access.', + image_provider_rejected: + 'The image request was rejected. Check your key and model access, or try a different image model.', } return ( messages[value] ?? 'Comic Code could not complete that request. Try again.' @@ -125,21 +190,65 @@ async function requestApi( ...init?.headers, }, }) - const data = (await response.json()) as T & { + const responseText = await response.text() + const data = ( + responseText + ? (() => { + try { + return JSON.parse(responseText) as T + } catch { + return {} as T + } + })() + : ({} as T) + ) as T & { error?: string detail?: string } if (!response.ok) - throw new Error(data.detail ?? data.error ?? 'request_failed') - return data + throw new Error( + data.detail ?? data.error ?? `request_failed_${response.status}`, + ) + const result = data as T & { explanation?: Explanation } + if (result.explanation?.artifactUrl) { + result.explanation.artifactUrl = new URL( + result.explanation.artifactUrl, + apiBase, + ).href + } + return result } -function SidePanelShell() { - const [coordinate, setCoordinate] = useState(null) - const [session, setSession] = useState(null) - const [pullRequest, setPullRequest] = useState(null) - const [selectedFiles, setSelectedFiles] = useState([]) - const [explanation, setExplanation] = useState(null) +const previewDocument = + new URLSearchParams(window.location.search).get('preview') === '1' + +function bundledSampleFor(count: PanelCount) { + const sample = getSampleExplanation(count) + return { + ...sample, + artifactUrl: new URL( + sample.artifactUrl, + previewDocument ? window.location.origin : apiBase, + ).href, + } +} + +export function SidePanelShell() { + const [sampleMode, setSampleMode] = useState(previewDocument) + const [panelCount, setPanelCount] = useState(12) + const [coordinate, setCoordinate] = useState( + previewDocument ? getSampleRepository(12) : null, + ) + const [session, setSession] = useState( + previewDocument ? 'sample-preview' : null, + ) + const [localMode, setLocalMode] = useState(previewDocument) + const [repository, setRepository] = useState( + previewDocument ? getSampleRepository(12) : null, + ) + const [explanation, setExplanation] = useState( + previewDocument ? bundledSampleFor(12) : null, + ) const [activeTab, setActiveTab] = useState('explain') const [busy, setBusy] = useState(false) const [error, setError] = useState(null) @@ -148,36 +257,52 @@ function SidePanelShell() { const [panelSide, setPanelSide] = useState<'left' | 'right' | 'unknown'>( 'unknown', ) - const [cloudflareAccountId, setCloudflareAccountId] = useState('') - const [cloudflareApiToken, setCloudflareApiToken] = useState('') + const [imageProvider, setImageProvider] = useState('openai') + const [imageModel, setImageModel] = useState( + imageProviders.openai.models[0], + ) + const [imageApiKey, setImageApiKey] = useState('') const [artworkBusy, setArtworkBusy] = useState(false) const [aiGenerationRequested, setAiGenerationRequested] = useState(false) - const pendingCloudflare = useRef(false) - const cloudflareReady = - cloudflareAccountId.trim().length === 32 && - cloudflareApiToken.trim().length >= 20 + const pendingImage = useRef(false) + const viewVersion = useRef(0) + const imageReady = + imageApiKey.trim().length >= 20 && + imageApiKey.trim().length <= 2_048 && + !/\s/.test(imageApiKey.trim()) + + const activePanelCount = explanation?.analysis?.panels.length ?? panelCount useEffect(() => { + if (sampleMode) return let active = true const initialize = async () => { const stored = (await chrome.storage.local.get([ 'comicCodeCoordinate', 'comicCodeSession', 'comicCodeCompact', - 'comicCodeCloudflareAccountId', - 'comicCodeCloudflareApiToken', ])) as StoredState const [tab] = await chrome.tabs.query({ active: true, currentWindow: true, }) - const tabCoordinate = parsePullRequestUrl(tab?.url) + const tabCoordinate = parseRepositoryUrl(tab?.url) if (!active) return setCoordinate(tabCoordinate ?? stored.comicCodeCoordinate ?? null) - setSession(stored.comicCodeSession ?? null) + const runtime = await requestApi<{ mode?: string }>( + '/api/v1/auth/me', + '', + ).catch(() => null) + if (!active) return + const local = runtime?.mode === 'local' + setLocalMode(local) + setSession(local ? 'local-desktop' : (stored.comicCodeSession ?? null)) setCompact(stored.comicCodeCompact ?? false) - setCloudflareAccountId(stored.comicCodeCloudflareAccountId ?? '') - setCloudflareApiToken(stored.comicCodeCloudflareApiToken ?? '') + // Remove obsolete provider credentials instead of reusing them as new keys. + await chrome.storage.local.remove([ + 'comicCodeCloudflareAccountId', + 'comicCodeCloudflareApiToken', + ]) const sidePanel = chrome.sidePanel as typeof chrome.sidePanel & { getLayout?: () => Promise<{ side: 'left' | 'right' }> @@ -194,8 +319,14 @@ function SidePanelShell() { area: string, ) => { if (area === 'local' && changes.comicCodeCoordinate?.newValue) { + viewVersion.current += 1 + pendingImage.current = false + setBusy(false) + setArtworkBusy(false) + setError(null) + setNotice(null) setCoordinate(changes.comicCodeCoordinate.newValue as Coordinate) - setPullRequest(null) + setRepository(null) setExplanation(null) setAiGenerationRequested(false) setActiveTab('explain') @@ -206,23 +337,51 @@ function SidePanelShell() { active = false chrome.storage.onChanged.removeListener(storageListener) } - }, []) + }, [sampleMode]) useEffect(() => { - if (!coordinate || !session) return + if (sampleMode || !coordinate || !session) return let active = true const inspect = async () => { setBusy(true) setError(null) - const url = `https://github.com/${coordinate.owner}/${coordinate.repository}/pull/${coordinate.pullRequestNumber}` + const url = `https://github.com/${coordinate.owner}/${coordinate.repository}${coordinate.ref ? `/tree/${coordinate.ref.split('/').map(encodeURIComponent).join('/')}` : ''}` try { - const result = await requestApi<{ pullRequest: PullRequest }>( - `/api/v1/github/pull-request?url=${encodeURIComponent(url)}`, + const result = await requestApi<{ repository: Repository }>( + `/api/v1/github/repository?url=${encodeURIComponent(url)}`, session, ) if (active) { - setPullRequest(result.pullRequest) - setSelectedFiles(result.pullRequest.files.map((file) => file.path)) + setRepository(result.repository) + + const stored = (await chrome.storage.local.get( + 'comicCodeExplanationIds', + )) as Pick + const persistedId = + stored.comicCodeExplanationIds?.[coordinateKey(coordinate)] + if (persistedId) { + const recovered = await requestApi<{ explanation: Explanation }>( + `/api/v1/explanations/${persistedId}`, + session, + ).catch(() => null) + if ( + active && + recovered && + recovered.explanation.ref === result.repository.ref && + recovered.explanation.repository.toLowerCase() === + `${coordinate.owner}/${coordinate.repository}`.toLowerCase() + ) { + setExplanation(recovered.explanation) + if ( + recovered.explanation.analysis && + recovered.explanation.status !== 'failed' + ) { + setActiveTab('story') + } + } else if (recovered) { + await removePersistedExplanationId(coordinate) + } + } } } catch (caught) { if (active) { @@ -242,12 +401,14 @@ function SidePanelShell() { return () => { active = false } - }, [coordinate, session]) + }, [coordinate, session, sampleMode]) const explanationId = explanation?.id const explanationStatus = explanation?.status useEffect(() => { if ( + sampleMode || + !coordinate || !session || !explanationId || !explanationStatus || @@ -264,10 +425,11 @@ function SidePanelShell() { ) if (active) { setExplanation(result.explanation) + void persistExplanationId(coordinate, result.explanation.id) if ( result.explanation.analysis && - (!pendingCloudflare.current || - result.explanation.analysis.artworkProvider === 'cloudflare_byok') + (!pendingImage.current || + hasByokArtwork(result.explanation.analysis.artworkProvider)) ) { setActiveTab('story') } @@ -282,7 +444,38 @@ function SidePanelShell() { active = false window.clearInterval(interval) } - }, [explanationId, explanationStatus, session]) + }, [coordinate, explanationId, explanationStatus, session, sampleMode]) + + useEffect(() => { + if ( + sampleMode || + !session || + !explanationId || + explanationStatus !== 'completed' || + !explanation?.artifactUrl + ) { + return + } + let active = true + const refreshArtifact = async () => { + const result = await requestApi<{ explanation: Explanation }>( + `/api/v1/explanations/${explanationId}`, + session, + ).catch(() => null) + if (active && result) setExplanation(result.explanation) + } + const interval = window.setInterval(refreshArtifact, 4 * 60 * 1_000) + return () => { + active = false + window.clearInterval(interval) + } + }, [ + explanation?.artifactUrl, + explanationId, + explanationStatus, + session, + sampleMode, + ]) const connectGitHub = async () => { setError(null) @@ -310,37 +503,44 @@ function SidePanelShell() { } const generate = async () => { - if (!session || !pullRequest || selectedFiles.length === 0) return + if (sampleMode) { + setExplanation(bundledSampleFor(panelCount)) + setActiveTab('story') + setNotice('Illustrative sample · no API requests or credits used.') + return + } + if (!session || !repository) return + const version = viewVersion.current setBusy(true) setError(null) setNotice(null) - pendingCloudflare.current = cloudflareReady - setAiGenerationRequested(cloudflareReady) + pendingImage.current = imageReady + setAiGenerationRequested(imageReady) try { - if (cloudflareReady) { - await chrome.storage.local.set({ - comicCodeCloudflareAccountId: cloudflareAccountId.trim(), - comicCodeCloudflareApiToken: cloudflareApiToken.trim(), - }) - } const result = await requestApi<{ explanation: Explanation }>( '/api/v1/explanations', session, { method: 'POST', body: JSON.stringify({ - owner: pullRequest.owner, - repository: pullRequest.repository, - pullRequestNumber: pullRequest.pullRequestNumber, - headSha: pullRequest.headSha, - selectedFiles, + owner: repository.owner, + repository: repository.repository, + ref: repository.ref, + commitSha: repository.commitSha, forceRegenerate: Boolean(explanation), + panelCount, }), }, ) + if (coordinate) + void persistExplanationId(coordinate, result.explanation.id).catch( + () => undefined, + ) + if (version !== viewVersion.current) return setExplanation(result.explanation) } catch (caught) { - pendingCloudflare.current = false + if (version !== viewVersion.current) return + pendingImage.current = false setAiGenerationRequested(false) setError( friendlyError( @@ -348,32 +548,37 @@ function SidePanelShell() { ), ) } finally { - setBusy(false) + if (version === viewVersion.current) setBusy(false) } } const createShare = async () => { if (!session || !explanation) return - const result = await requestApi<{ share: { url: string } }>( - `/api/v1/explanations/${explanation.id}/shares`, - session, - { method: 'POST' }, - ) - await navigator.clipboard.writeText(result.share.url) - setNotice('Private 7-day link copied') + try { + const result = await requestApi<{ share: { url: string } }>( + `/api/v1/explanations/${explanation.id}/shares`, + session, + { method: 'POST' }, + ) + await navigator.clipboard.writeText(result.share.url) + setNotice('Private 7-day link copied') + } catch (caught) { + setError( + friendlyError( + caught instanceof Error ? caught.message : 'request_failed', + ), + ) + } } - const generateWithCloudflare = useCallback( + const generateWithImageProvider = useCallback( async (target: Explanation) => { - if (!session || !target.analysis) return + if (sampleMode || !session || !target.analysis) return + const version = viewVersion.current setAiGenerationRequested(true) setArtworkBusy(true) setError(null) setNotice(null) - await chrome.storage.local.set({ - comicCodeCloudflareAccountId: cloudflareAccountId.trim(), - comicCodeCloudflareApiToken: cloudflareApiToken.trim(), - }) try { const result = await requestApi<{ explanation: Explanation }>( `/api/v1/explanations/${target.id}/artwork`, @@ -381,76 +586,112 @@ function SidePanelShell() { { method: 'POST', body: JSON.stringify({ - provider: 'cloudflare', - accountId: cloudflareAccountId.trim(), - apiToken: cloudflareApiToken.trim(), + provider: imageProvider, + model: imageModel, + apiKey: imageApiKey.trim(), }), }, ) + if (coordinate) + void persistExplanationId(coordinate, result.explanation.id).catch( + () => undefined, + ) + if (version !== viewVersion.current) return setExplanation(result.explanation) setAiGenerationRequested(false) setActiveTab('story') setNotice( - 'Code analyzed and four panels generated with your Cloudflare credits', + `${target.analysis.panels.length} AI panels ready. Captions and evidence are unchanged.`, ) } catch (caught) { + if (version !== viewVersion.current) return const failed = await requestApi<{ explanation: Explanation }>( `/api/v1/explanations/${target.id}`, session, ).catch(() => null) - if (failed) setExplanation(failed.explanation) - setActiveTab('explain') + if (version !== viewVersion.current) return + if (failed) { + setExplanation(failed.explanation) + setActiveTab( + failed.explanation.status === 'completed' && + failed.explanation.analysis + ? 'story' + : 'explain', + ) + } else { + setActiveTab('explain') + } setError( friendlyError( caught instanceof Error ? caught.message : 'request_failed', ), ) } finally { - setArtworkBusy(false) + if (version === viewVersion.current) { + setAiGenerationRequested(false) + setArtworkBusy(false) + } } }, - [cloudflareAccountId, cloudflareApiToken, session], + [imageProvider, imageModel, imageApiKey, coordinate, session, sampleMode], ) useEffect(() => { if ( - !pendingCloudflare.current || + !pendingImage.current || artworkBusy || explanation?.status !== 'completed' || !explanation.analysis ) { return } - pendingCloudflare.current = false - void generateWithCloudflare(explanation) - }, [artworkBusy, explanation, generateWithCloudflare]) + pendingImage.current = false + void generateWithImageProvider(explanation) + }, [artworkBusy, explanation, generateWithImageProvider]) - const clearCloudflareCredentials = async () => { - pendingCloudflare.current = false + const clearImageCredentials = async () => { + pendingImage.current = false setAiGenerationRequested(false) - await chrome.storage.local.remove([ - 'comicCodeCloudflareAccountId', - 'comicCodeCloudflareApiToken', - ]) - setCloudflareAccountId('') - setCloudflareApiToken('') - setNotice('Cloudflare credentials removed from this device') + setImageApiKey('') + setNotice('API key cleared from this panel') } const toggleCompact = async () => { const next = !compact setCompact(next) - await chrome.storage.local.set({ comicCodeCompact: next }) + if (!sampleMode) await chrome.storage.local.set({ comicCodeCompact: next }) } const logout = async () => { + viewVersion.current += 1 + setBusy(false) + setArtworkBusy(false) await chrome.storage.local.remove('comicCodeSession') + pendingImage.current = false + setImageApiKey('') setSession(null) - setPullRequest(null) + setRepository(null) setExplanation(null) setAiGenerationRequested(false) } + const loadSample = () => { + viewVersion.current += 1 + setAiGenerationRequested(false) + setArtworkBusy(false) + pendingImage.current = false + setSampleMode(true) + setLocalMode(true) + setCoordinate(getSampleRepository(panelCount)) + setRepository(getSampleRepository(panelCount)) + setExplanation(bundledSampleFor(panelCount)) + setSession('sample-preview') + setActiveTab('explain') + setError(null) + setNotice(null) + setBusy(false) + } + return (
Comic Code - PRs, translated visually + Repositories, translated visually
+
+ {sampleMode ? ( + <> + Sample workspace + No API calls · no credits + {!previewDocument ? ( + + ) : null} + + ) : ( + <> + Just looking around? + + + )} +
+
+ + +
+
+ + API key / BYOK + + +

Bring your own image AI

+

+ Use OpenAI or Google Gemini to generate {activePanelCount}{' '} + illustrations with your own key. Captions and evidence stay unchanged. + No key uses free bundled artwork. +

+ {sampleMode ? ( +

+ Preview only. Choose a provider to see its models. Key entry is + disabled in sample mode. +

+ ) : null} + + + + + The key stays in this panel until it closes or you clear it. It passes + through Comic Code for generation and is never saved. Only + illustration prompts go to the selected provider. {activePanelCount}{' '} + images use your provider’s quota and billing. + + + Get a key from {imageProviders[imageProvider].label} + + {!sampleMode && + ['completed', 'failed'].includes(explanation?.status ?? '') && + explanation?.analysis ? ( + + ) : ( +

+ {sampleMode + ? 'Sample mode never uses or saves keys.' + : imageReady + ? 'Key entered. Generate a comic to use your image AI.' + : 'No key: free bundled artwork remains available.'} +

+ )} + +
{coordinate ? (
{coordinate.owner}/{coordinate.repository}
- Pull request #{coordinate.pullRequestNumber} - Live + Repository architecture + {sampleMode ? 'Sample' : 'Live'}
- {pullRequest ?

{pullRequest.title}

: null} + {repository?.description ?

{repository.description}

: null}
) : (
-

Open a GitHub pull request.

+

Open a GitHub repository.

- Comic Code appears beside the diff and keeps working as you browse. + Comic Code maps its important parts and explains them as one system.

)} @@ -505,6 +918,7 @@ function SidePanelShell() { - ) : ( -

- {cloudflareReady - ? 'Key ready. Full AI comic will run after source scan.' - : 'No key: fixed fallback remains available.'} -

- )} - - +
✦

- Reads selected files at the PR head, not only the diff. Up to - 20 files; secrets and generated files are excluded. + {sampleMode ? ( + 'Illustrative source files for previewing the interface. This sample is not a live GitHub scan.' + ) : ( + <> + Scans repository tree, then reads up to 40 representative + files at commit {repository.commitSha.slice(0, 7)}. + Secrets, binaries, dependencies, and generated files stay + excluded. + + )}

) : (
- Reading the pull request… + Mapping repository architecture…
)} @@ -703,8 +1036,8 @@ function SidePanelShell() { {explanation.status} {aiGenerationRequested && - explanation.analysis?.artworkProvider !== 'cloudflare_byok' - ? 'Analyzing code + generating 4 AI panels…' + !hasByokArtwork(explanation.analysis?.artworkProvider) + ? `Generating ${activePanelCount} AI panels…` : explanation.progress.message} @@ -737,28 +1070,38 @@ function SidePanelShell() { {explanation.analysis.generationMode === 'deterministic_fallback' ? (

- {explanation.analysis.artworkProvider === 'cloudflare_byok' + {hasByokArtwork(explanation.analysis.artworkProvider) ? 'API-free story · user-funded AI artwork.' - : 'API-free template mode.'} + : sampleMode + ? 'Illustrative sample.' + : 'API-free template mode.'} {' '} - Story explains selected source code without an OpenAI API call. - {explanation.analysis.artworkProvider === 'cloudflare_byok' - ? ' Images use your Cloudflare credits.' + {sampleMode + ? 'Bundled example panels and evidence. No repository was fetched or verified.' + : 'Story explains selected source code without an OpenAI API call.'} + {hasByokArtwork(explanation.analysis.artworkProvider) + ? ' Images use your selected provider key.' : ' Images use bundled templates.'}{' '} - Add your key in Explain for semantic analysis and unique images. + {!sampleMode + ? 'Add your key in API key / BYOK to generate unique images.' + : ''}

) : null} + {explanation.artifactUrl ? ( Generated four-panel pull request comic ) : null} {explanation.analysis.panels.map((panel) => (
- 0{panel.sequence} + {String(panel.sequence).padStart(2, '0')} {panel.purpose}

{panel.title}

@@ -777,13 +1120,16 @@ function SidePanelShell() { Download PNG ) : null} - + {!sampleMode ? ( + + ) : null} {notice ? (

{notice}

@@ -798,7 +1144,6 @@ function SidePanelShell() {
- Traceable claims

Evidence map

{explanation.analysis.evidence.length} @@ -810,7 +1155,7 @@ function SidePanelShell() { {evidence.newStart ? `Lines ${evidence.newStart}–${evidence.newEnd}` - : 'PR metadata'}{' '} + : 'Repository context'}{' '} · {evidence.id}
@@ -820,17 +1165,21 @@ function SidePanelShell() { ) : null}
- - {session ? ( - + )} + {session && !localMode ? ( + ) : null} @@ -838,15 +1187,3 @@ function SidePanelShell() {
) } - -const root = document.getElementById('root') - -if (!root) { - throw new Error('Missing Comic Code side-panel root') -} - -createRoot(root).render( - - - , -) diff --git a/apps/extension/entrypoints/sidepanel/style.css b/apps/extension/entrypoints/sidepanel/style.css index cd3064d..291b096 100644 --- a/apps/extension/entrypoints/sidepanel/style.css +++ b/apps/extension/entrypoints/sidepanel/style.css @@ -1,647 +1,623 @@ +@font-face { + font-family: 'Plus Jakarta Sans'; + font-style: normal; + font-weight: 400 800; + font-display: swap; + src: url('/fonts/plus-jakarta-sans.woff2') format('woff2'); +} :root { - color-scheme: dark; - --ink: #05050d; - --ink-2: #0b0b1b; - --paper: #f8f8ff; - --muted: #9c9db3; - --violet: #5c60ff; - --violet-soft: #888aff; - --amber: #ffb53e; - --line: rgba(255, 255, 255, 0.12); + color-scheme: light; + --ink: #162019; + --paper: #fff; + --muted: #68735f; + --line: #dde4d4; + --green: #365e36; font-family: - Inter, - ui-sans-serif, - system-ui, + 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; - background: var(--ink); - color: var(--paper); + color: var(--ink); + background: #f3f5ed; + font-synthesis: none; + -webkit-font-smoothing: antialiased; + text-rendering: optimizeLegibility; } - * { box-sizing: border-box; } html, body, #root { + margin: 0; min-width: 300px; min-height: 100%; - margin: 0; } body { - background: - radial-gradient( - circle at 85% 10%, - rgba(75, 79, 255, 0.23), - transparent 280px - ), - linear-gradient(180deg, #090915, #030308); + background: #f3f5ed; } button, -input { +input, +select { font: inherit; } button, a, -label { +label, +summary { -webkit-tap-highlight-color: transparent; } -button:focus-visible, -a:focus-visible, -input:focus-visible { - outline: 2px solid var(--amber); - outline-offset: 2px; +button { + cursor: pointer; +} +button:disabled { + opacity: 0.45; + cursor: not-allowed; +} +a { + color: var(--green); + text-underline-offset: 3px; +} +:focus-visible { + outline: 2px solid #4e7043; + outline-offset: 3px; +} +input { + caret-color: var(--green); } - input::placeholder { - color: #66677d; + color: #747e70; +} +::selection { + background: #d4e5b0; + color: #203623; } - .panel-shell { min-height: 100vh; padding-bottom: 58px; } .panel-header { - min-height: 66px; - padding: 12px 14px; display: flex; align-items: center; justify-content: space-between; - border-bottom: 1px solid var(--line); - background: rgba(4, 4, 11, 0.7); - backdrop-filter: blur(14px); + gap: 10px; + padding: 20px 19px 17px; + background: #f8faf3; + border-bottom: 1px solid #e0e6d9; } .panel-brand { display: flex; align-items: center; gap: 10px; - min-width: 0; } .panel-brand strong { + font-size: 17px; + font-weight: 800; + letter-spacing: -0.035em; display: block; - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; - font-size: 14px; - letter-spacing: -0.04em; } .panel-brand small { display: block; - margin-top: 2px; - color: var(--muted); - font-size: 10px; + font-size: 9px; + color: #6c7864; + margin-top: 3px; } .glyph, .empty-glyph { - width: 30px; - height: 30px; - display: grid; - place-items: center; - filter: drop-shadow(0 0 12px rgba(104, 107, 255, 0.6)); + display: inline-flex; + width: 28px; + height: 28px; + color: #283c2a; } .glyph svg, .empty-glyph svg { width: 100%; - fill: white; + fill: currentColor; } -.glyph .brand-cut, -.empty-glyph .brand-cut { - fill: var(--ink); +.brand-cut { + fill: #f8faf3; } .icon-button { - width: 32px; - height: 32px; - border: 1px solid var(--line); + border: 1px solid #dae1d1; border-radius: 9px; - background: rgba(255, 255, 255, 0.04); - color: #c9caff; - cursor: pointer; + width: 31px; + height: 31px; + padding: 7px; + color: #576b4f; + background: transparent; +} +.icon-button svg { + width: 100%; +} +.sample-switch { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 11px 19px; + background: #f4dfe7; + font-size: 10px; + color: #725263; + flex-wrap: wrap; +} +.sample-switch button { + border: 0; + background: transparent; + text-decoration: underline; + text-underline-offset: 3px; + color: #55404b; + font-size: 10px; + font-weight: 700; +} +.sample-switch small { + font-size: 9px; + color: #705b65; +} +.sample-indicator { + font-weight: 800; } - .pr-heading { - padding: 17px 15px 14px; + margin: 16px 14px 0; + padding: 20px; + border: 1px solid #fff; + border-radius: 18px; + background: + radial-gradient(100% 130% at 100% 100%, #f1f3b6, transparent), + linear-gradient(150deg, #e3edce, #e9efc4); } -.repo-label, -.eyebrow { - color: #8f92ff; - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; +.repo-label { + color: #557347; + font-family: ui-monospace, SFMono-Regular, monospace; font-size: 9px; - font-weight: 750; - letter-spacing: 0.12em; - text-transform: uppercase; + overflow-wrap: anywhere; } .pr-heading > div { - margin-top: 6px; display: flex; align-items: center; + justify-content: space-between; gap: 8px; + margin-top: 10px; } .pr-heading strong { - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; - font-size: 16px; + font-size: 21px; + line-height: 1.25; + font-weight: 800; + letter-spacing: -0.035em; } .pr-heading p { - margin: 8px 0 0; - color: #b9bacd; - font-size: 12px; - line-height: 1.45; + margin: 11px 0 0; + color: #5b6a4f; + font-size: 11px; + line-height: 1.7; } .live-dot { - border: 1px solid rgba(113, 214, 165, 0.25); + display: inline-flex; + align-items: center; + gap: 5px; + padding: 5px 8px; border-radius: 999px; - padding: 3px 6px; - color: #71d6a5; + background: #ffffffa8; + color: #48633c; font-size: 8px; - text-transform: uppercase; + font-weight: 700; + white-space: nowrap; } .live-dot::before { content: ''; - width: 5px; - height: 5px; - margin-right: 4px; - display: inline-block; + width: 4px; + height: 4px; + background: #76924d; border-radius: 50%; - background: #71d6a5; - box-shadow: 0 0 7px #71d6a5; } - .panel-tabs { - height: 43px; - padding: 0 9px; display: grid; grid-template-columns: repeat(3, 1fr); - border-block: 1px solid var(--line); + gap: 5px; + margin: 18px 18px 0; + padding: 5px; + background: #e7ebdf; + border-radius: 999px; } .panel-tabs button { - position: relative; border: 0; - background: transparent; - color: #898a9f; - cursor: pointer; + border-radius: 999px; + padding: 9px 7px; font-size: 11px; + color: #66745c; + background: transparent; text-transform: capitalize; } .panel-tabs button.active { - color: white; + background: #fff; + color: #28402b; + font-weight: 700; + box-shadow: 0 2px 6px #24341b08; } -.panel-tabs button.active::after { - position: absolute; - content: ''; - inset: auto 8px -1px; - height: 2px; - background: var(--violet); - box-shadow: 0 0 12px var(--violet); -} -.panel-tabs button:disabled { - opacity: 0.35; - cursor: not-allowed; -} - .panel-content, .connect-card { - padding: 16px 14px; + padding: 21px 19px; } -.connect-card h1, -.empty-state h1 { - margin: 13px 0 9px; - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; - font-size: 28px; - letter-spacing: -0.06em; - line-height: 1.02; +.section-title { + display: flex; + align-items: center; + justify-content: space-between; + gap: 14px; + margin-bottom: 14px; } -.connect-card p, -.empty-state p { - color: var(--muted); - font-size: 12px; - line-height: 1.55; +.eyebrow { + font-size: 9px; + color: #789064; + font-weight: 600; +} +.section-title h2 { + font-size: 15px; + line-height: 1.4; + font-weight: 800; + letter-spacing: -0.025em; + margin: 5px 0 0; +} +.section-title > span { + background: #e5ebda; + color: #657651; + padding: 5px 8px; + font-size: 9px; + border-radius: 999px; + white-space: nowrap; +} +.side-file-list { + padding: 8px 13px; + border-radius: 12px; + background: #fdfefa; + border: 1px solid #e0e7d7; + max-height: 220px; + overflow: auto; +} +.side-file { + padding: 10px 0; + border-bottom: 1px solid #edf0e6; + color: #586a4f; + font-size: 10px; +} +.side-file:last-child { + border: 0; +} +.side-file code { + font-family: ui-monospace, SFMono-Regular, monospace; + overflow-wrap: anywhere; } .primary-action, .secondary-action { - min-height: 44px; width: 100%; - border: 0; - border-radius: 10px; - padding: 0 13px; + min-height: 44px; display: flex; align-items: center; justify-content: center; - background: var(--violet); - color: white; - cursor: pointer; - font-size: 12px; - font-weight: 760; + border: 0; + border-radius: 999px; + padding: 12px 15px; + font-size: 11px; + font-weight: 700; text-decoration: none; - box-shadow: 0 10px 24px rgba(71, 75, 255, 0.22); + background: #345735; + color: white; +} +.primary-action:hover:not(:disabled) { + background: #496c3d; } .primary-action--amber { - margin-top: 13px; - background: var(--amber); - color: #1a1104; - box-shadow: 0 10px 24px rgba(255, 181, 62, 0.14); + margin-top: 18px; + background: #304d2d; + color: #fff; } .secondary-action { - border: 1px solid var(--line); - background: rgba(255, 255, 255, 0.05); - box-shadow: none; + background: #f7faf2; + color: #5b6c50; + border: 1px solid #d5dfcb; } -.primary-action:hover:not(:disabled), -.secondary-action:hover:not(:disabled) { - filter: brightness(1.08); +.story-actions { + display: flex; + flex-direction: column; + gap: 9px; + margin-top: 20px; } -.primary-action:disabled { - opacity: 0.45; - cursor: not-allowed; +.side-byok { + border: 1px solid #d9e2ce; + border-radius: 12px; + padding: 13px; + margin-top: 18px; + background: #eef3e5; } - -.section-title { - margin-bottom: 11px; +.side-byok summary { display: flex; - align-items: flex-end; justify-content: space-between; -} -.section-title h2 { - margin: 4px 0 0; - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; - font-size: 18px; - letter-spacing: -0.05em; -} -.section-title > span { - color: var(--amber); - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; + align-items: center; font-size: 11px; + color: #4f653f; + cursor: pointer; } -.side-file-list { - max-height: 300px; - overflow: auto; - border: 1px solid var(--line); - border-radius: 11px; - background: rgba(0, 0, 0, 0.22); +.side-byok h2 { + margin: 18px 0 8px; + font-size: 15px; + letter-spacing: -0.02em; } -.side-file { - min-height: 43px; - padding: 8px 10px; - display: grid; - grid-template-columns: auto minmax(0, 1fr) auto; - align-items: center; - gap: 8px; - border-bottom: 1px solid rgba(255, 255, 255, 0.055); - cursor: pointer; +.side-byok p, +.side-byok small { + font-size: 10px; + line-height: 1.8; + color: #637254; } -.side-file:hover { - background: rgba(83, 87, 255, 0.08); +.side-byok label { + display: grid; + gap: 7px; + font-size: 10px; + color: #5d6a53; + margin: 13px 0; } -.side-file input { - accent-color: var(--violet); +.side-byok input, +.side-byok select { + width: 100%; + min-width: 0; + height: 39px; + padding: 0 10px; + border: 1px solid #d3dec7; + border-radius: 8px; + background: #fff; + color: #26391f; + font-size: 11px; } -.side-file code { - overflow: hidden; - color: #d6d7f1; +.side-byok > a { + display: block; font-size: 10px; - text-overflow: ellipsis; - white-space: nowrap; + margin-block: 12px; } -.side-file small { - color: #d07c8c; - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; - font-size: 9px; +.side-byok > small { + display: block; } -.side-file small b { - color: #71d6a5; +.side-byok__clear { + width: 100%; + background: none; + border: 0; + padding: 12px 5px 2px; + color: #6f7a62; + font-size: 10px; +} +.side-byok__status { + margin-bottom: 0; } .privacy-note { - margin-top: 13px; - display: grid; - grid-template-columns: auto 1fr; + display: flex; gap: 9px; - color: #8e8fa4; + margin-top: 16px; + align-items: flex-start; + color: #7d8a6e; } -.privacy-note span { - color: var(--amber); +.privacy-note > span { + font-size: 18px; } .privacy-note p { margin: 0; - font-size: 10px; - line-height: 1.5; + color: #758069; + font-size: 9px; + line-height: 1.8; } - .side-progress { - margin-top: 14px; - border: 1px solid var(--line); - border-radius: 11px; - padding: 12px; - background: rgba(81, 85, 255, 0.06); + border-top: 1px solid var(--line); + margin-top: 25px; + padding-top: 18px; } .side-progress header { display: flex; - align-items: center; justify-content: space-between; - gap: 10px; + align-items: center; + gap: 12px; } -.side-progress header strong { +.side-progress strong { display: block; - margin-top: 4px; - color: #d3d4e8; + margin: 5px 0 12px; font-size: 11px; + line-height: 1.5; } -.side-progress header > b { - color: var(--amber); - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; +.side-progress b { + font-size: 15px; + color: #718946; + font-variant-numeric: tabular-nums; } -.side-progress > div { +.side-progress > div[role='progressbar'] { height: 3px; - margin-top: 10px; + border-radius: 3px; overflow: hidden; - border-radius: 99px; - background: rgba(255, 255, 255, 0.08); + background: #e0e6d6; } -.side-progress > div span { +.side-progress > div[role='progressbar'] > span { display: block; height: 100%; - border-radius: inherit; - background: linear-gradient(90deg, var(--violet), #9c8cff, var(--amber)); - transition: width 0.3s ease; -} - -.story-content > img { - width: 100%; - height: auto; - display: block; - margin-bottom: 10px; - border: 1px solid rgba(111, 115, 255, 0.4); - border-radius: 11px; + background: #91a761; } -.side-byok { - margin-bottom: 12px; - border: 1px solid rgba(111, 115, 255, 0.36); - border-radius: 11px; - padding: 13px; - background: - radial-gradient( - circle at 100% 0%, - rgba(84, 89, 255, 0.18), - transparent 52% - ), - rgba(3, 3, 12, 0.78); -} -.side-byok h2 { - margin: 6px 0; - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; - font-size: 16px; - letter-spacing: -0.04em; +.panel-notice { + padding: 14px; + border-radius: 12px; + margin: 14px 18px; + font-size: 10px; + line-height: 1.8; + background: #f6f0e3; + color: #746241; } -.side-byok > p, -.side-byok > small { - color: var(--muted); - font-size: 9px; - line-height: 1.5; +.panel-notice p { + margin: 0; } -.side-byok > p { - margin: 0 0 11px; +.panel-notice--error { + background: #fae4df; + color: #914a39; } -.side-byok > .side-byok__status { - margin: 2px 0 0; - color: #c8c9dd; +.panel-notice--error button { + border: 0; + background: transparent; + color: inherit; + text-decoration: underline; + padding: 7px 0; } -.side-byok label { - margin-top: 8px; - display: grid; - gap: 5px; - color: #c8c9dd; - font-size: 9px; +.panel-notice--success { + background: #e9f1dc; + color: #597342; } -.side-byok input { - width: 100%; - min-width: 0; - height: 37px; - border: 1px solid var(--line); - border-radius: 8px; - padding: 0 10px; - background: rgba(0, 0, 0, 0.42); - color: var(--paper); - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; - font-size: 9px; +.story-content .panel-notice { + margin: 0 0 18px; } -.side-byok > small { - margin-top: 9px; +.story-content > img { display: block; -} -.side-byok > a { - margin: 7px 0 11px; - display: inline-block; - color: #b8baff; - font-size: 9px; -} -.side-byok__clear { width: 100%; - margin-top: 6px; - border: 0; - padding: 6px; - background: transparent; - color: #9798ae; - cursor: pointer; - font-size: 9px; -} -.side-byok__clear:disabled { - cursor: not-allowed; - opacity: 0.45; + height: auto; + border: 1px solid #dce3d1; + border-radius: 10px; } .side-story { - min-height: 160px; - margin-bottom: 9px; - padding: 14px; - border: 1px solid var(--line); - border-radius: 11px; - background: - radial-gradient( - circle at 100% 100%, - rgba(70, 74, 255, 0.18), - transparent 58% - ), - rgba(255, 255, 255, 0.025); + padding: 18px 0; + border-bottom: 1px solid #dfe6d5; } .side-story header { display: flex; + align-items: center; justify-content: space-between; - color: var(--amber); - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; - font-size: 10px; + color: #5b6d43; + font-size: 9px; } -.side-story header small { - color: #898bff; - text-transform: uppercase; +.side-story header > span { + font-weight: 800; } .side-story h2 { - margin: 22px 0 7px; - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; - font-size: 17px; - letter-spacing: -0.04em; + margin: 12px 0 8px; + font-size: 16px; + letter-spacing: -0.025em; + font-weight: 800; } .side-story p { - margin: 0; - color: #c1c2d5; font-size: 11px; - line-height: 1.55; + line-height: 1.8; + color: #596a50; + margin: 0; } .side-story em { display: block; - margin-top: 10px; - color: #8f90a6; - font-size: 9px; - line-height: 1.45; -} -.story-actions { - display: grid; - gap: 8px; + font-size: 10px; + color: #5d6850; + line-height: 1.6; + margin-top: 8px; + font-style: normal; } - .side-evidence { - border: 1px solid var(--line); - border-radius: 11px; - overflow: hidden; + border-radius: 12px; + padding: 0 14px; + background: #e4edf0; } .side-evidence > div { - padding: 11px; - display: grid; - gap: 5px; - border-bottom: 1px solid rgba(255, 255, 255, 0.055); + padding: 15px 0; + border-bottom: 1px solid #d0dce0; +} +.side-evidence > div:last-child { + border: 0; } .side-evidence code { - overflow: hidden; - color: #d9daf5; + display: block; font-size: 10px; - text-overflow: ellipsis; - white-space: nowrap; + color: #45636d; + overflow-wrap: anywhere; } .side-evidence small { - color: #85869a; - font-size: 9px; + display: block; + font-size: 8px; + margin-top: 7px; + color: #48656d; } - .empty-state { - min-height: 68vh; - padding: 40px 25px; - display: grid; - place-items: center; - align-content: center; + padding: 56px 24px; text-align: center; } .empty-glyph { - width: 78px; - height: 78px; + width: 46px; + height: 46px; + color: #6e8848; +} +.connect-card h1, +.empty-state h1 { + font-size: 28px; + letter-spacing: -0.04em; + font-weight: 800; + line-height: 1.2; +} +.connect-card p, +.empty-state p { + color: #728061; + font-size: 12px; + line-height: 1.8; } .loading-state { - min-height: 200px; + padding: 24px 0; + color: #778569; + font-size: 11px; display: flex; + gap: 10px; align-items: center; - justify-content: center; - gap: 8px; - color: var(--muted); - font-size: 11px; } -.loading-state span { - width: 8px; - height: 8px; +.loading-state > span { + width: 7px; + height: 7px; border-radius: 50%; - background: var(--violet-soft); - box-shadow: 0 0 12px var(--violet); -} -.panel-notice { - margin: 12px 14px; - border-radius: 9px; - padding: 10px; - font-size: 10px; - line-height: 1.45; -} -.panel-notice--error { - border: 1px solid rgba(255, 127, 141, 0.3); - background: rgba(255, 127, 141, 0.08); - color: #ffb1ba; -} -.panel-notice--error p { - margin: 0; + background: #8fa366; } -.panel-notice--error button { - margin-top: 7px; - border: 0; - padding: 0; - background: transparent; - color: white; - cursor: pointer; - font-size: 10px; - font-weight: 760; - text-decoration: underline; -} -.panel-notice--success { - margin-inline: 0; - border: 1px solid rgba(113, 214, 165, 0.25); - background: rgba(113, 214, 165, 0.07); - color: #8ce3b7; -} -.panel-notice--fallback { - margin-inline: 0; - border: 1px solid rgba(255, 181, 62, 0.28); - background: rgba(255, 181, 62, 0.08); - color: #ffd28a; -} - .panel-footer { position: fixed; - inset: auto 0 0; - min-height: 43px; - padding: 7px 10px; + bottom: 0; + left: 0; + right: 0; display: flex; - align-items: center; justify-content: space-between; - gap: 8px; - border-top: 1px solid var(--line); - background: rgba(5, 5, 13, 0.92); - backdrop-filter: blur(14px); + gap: 10px; + padding: 13px 18px; + border-top: 1px solid #dfe6d6; + background: #f8faf3; + color: #62704e; + font-size: 9px; } .panel-footer button { - border: 0; - padding: 4px; - background: transparent; - color: #77788d; - cursor: pointer; font-size: 8px; - text-align: left; -} -.panel-footer button:last-child { - color: #a4a5bc; - white-space: nowrap; + background: none; + color: #6c7e60; + border: 0; + padding: 0; } - -.panel-shell--compact .pr-heading p, -.panel-shell--compact .privacy-note, -.panel-shell--compact .panel-brand small { - display: none; +.panel-shell--compact .side-file { + padding: 6px 0; } -.panel-shell--compact .side-file-list { - max-height: 210px; +.panel-shell--compact .pr-heading { + padding: 15px; } -.panel-shell[data-side='left'] .panel-header { - box-shadow: inset -2px 0 rgba(84, 88, 255, 0.18); +.panel-shell--compact .panel-content { + padding-block: 14px; } -.panel-shell[data-side='right'] .panel-header { - box-shadow: inset 2px 0 rgba(84, 88, 255, 0.18); +.panel-shell--compact .side-story { + padding-block: 12px; } - -@media (min-width: 520px) { - .side-file code, - .side-story p { - font-size: 12px; +@media (prefers-reduced-motion: no-preference) { + .pr-heading { + animation: panel-in 0.55s cubic-bezier(0.16, 1, 0.3, 1) both; } - .panel-content, - .connect-card { - padding-inline: 19px; + @keyframes panel-in { + from { + opacity: 0; + translate: 0 8px; + } + to { + opacity: 1; + translate: 0 0; + } } } - @media (prefers-reduced-motion: reduce) { *, *::before, *::after { - transition-duration: 0.01ms !important; - animation-duration: 0.01ms !important; + animation: none !important; + transition: none !important; } } diff --git a/apps/extension/package.json b/apps/extension/package.json index 7710b11..aed2ff8 100644 --- a/apps/extension/package.json +++ b/apps/extension/package.json @@ -7,12 +7,14 @@ "dev": "wxt", "icons": "node ../../packages/comic/scripts/generate-extension-icons.mjs", "lint": "wxt prepare && tsc --noEmit", - "test": "vitest run --passWithNoTests", + "test": "wxt prepare && vitest run --passWithNoTests", "typecheck": "wxt prepare && tsc --noEmit", "zip": "wxt zip" }, "dependencies": { + "@comic-code/comic": "workspace:*", "@comic-code/contracts": "workspace:*", + "@comic-code/ui": "workspace:*", "react": "19.2.7", "react-dom": "19.2.7" }, @@ -21,8 +23,10 @@ "@types/react": "19.2.17", "@types/react-dom": "19.2.3", "@wxt-dev/module-react": "1.2.2", + "jsdom": "27.4.0", "typescript": "5.9.3", - "vitest": "4.1.10", + "vite": "8.1.6", + "vitest": "4.1.12", "wxt": "0.20.27" } } diff --git a/apps/extension/public/fonts/OFL.txt b/apps/extension/public/fonts/OFL.txt new file mode 100644 index 0000000..cd44467 --- /dev/null +++ b/apps/extension/public/fonts/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The Plus Jakarta Sans Project Authors (https://github.com/tokotype/PlusJakartaSans) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/apps/extension/public/fonts/plus-jakarta-sans.woff2 b/apps/extension/public/fonts/plus-jakarta-sans.woff2 new file mode 100644 index 0000000..5ec77ed Binary files /dev/null and b/apps/extension/public/fonts/plus-jakarta-sans.woff2 differ diff --git a/apps/extension/public/icon/128.png b/apps/extension/public/icon/128.png index d65114d..23c1146 100644 Binary files a/apps/extension/public/icon/128.png and b/apps/extension/public/icon/128.png differ diff --git a/apps/extension/public/icon/16.png b/apps/extension/public/icon/16.png index 8d10b38..7316501 100644 Binary files a/apps/extension/public/icon/16.png and b/apps/extension/public/icon/16.png differ diff --git a/apps/extension/public/icon/32.png b/apps/extension/public/icon/32.png index 5c0cbc9..1f845e5 100644 Binary files a/apps/extension/public/icon/32.png and b/apps/extension/public/icon/32.png differ diff --git a/apps/extension/public/icon/48.png b/apps/extension/public/icon/48.png index 575c4d2..1bf464c 100644 Binary files a/apps/extension/public/icon/48.png and b/apps/extension/public/icon/48.png differ diff --git a/apps/extension/wxt.config.ts b/apps/extension/wxt.config.ts index 043829e..e6735c6 100644 --- a/apps/extension/wxt.config.ts +++ b/apps/extension/wxt.config.ts @@ -1,33 +1,65 @@ +import path from 'node:path' + +import { loadEnv } from 'vite' import { defineConfig } from 'wxt' +const repositoryRoot = path.resolve(import.meta.dirname, '../..') +const isReleaseCommand = + process.argv.includes('build') || process.argv.includes('zip') + +function apiBaseForMode(mode: string) { + const configured = loadEnv( + mode, + repositoryRoot, + 'WXT_', + ).WXT_PUBLIC_API_BASE_URL?.trim() + if (!configured && mode === 'production' && isReleaseCommand) { + throw new Error( + 'WXT_PUBLIC_API_BASE_URL is required for production extension builds', + ) + } + return configured || 'http://localhost:3000' +} + export default defineConfig({ modules: ['@wxt-dev/module-react'], - vite: () => ({ envDir: '../..' }), - manifest: { - name: 'Comic Code', - description: - 'Explain selected source code in GitHub pull requests as grounded four-panel comics.', - minimum_chrome_version: '114', - permissions: ['clipboardWrite', 'identity', 'sidePanel', 'storage', 'tabs'], - host_permissions: [ - 'https://github.com/*', - 'http://localhost:3000/*', - 'https://*.vercel.app/*', - ], - action: { - default_title: 'Open Comic Code', - default_icon: { + vite: ({ mode }) => { + apiBaseForMode(mode) + return { + envDir: repositoryRoot, + build: { modulePreload: { polyfill: false } }, + } + }, + manifest: ({ mode }) => { + const apiOrigin = new URL(apiBaseForMode(mode)).origin + return { + name: 'Comic Code', + description: + 'Explain how an entire GitHub repository works as a grounded four- or twelve-panel comic.', + minimum_chrome_version: '114', + permissions: [ + 'clipboardWrite', + 'identity', + 'sidePanel', + 'storage', + 'tabs', + ], + host_permissions: ['https://github.com/*', `${apiOrigin}/*`], + action: { + default_title: 'Open Comic Code', + default_icon: { + 16: 'icon/16.png', + 32: 'icon/32.png', + 48: 'icon/48.png', + 128: 'icon/128.png', + }, + }, + icons: { 16: 'icon/16.png', 32: 'icon/32.png', 48: 'icon/48.png', 128: 'icon/128.png', }, - }, - icons: { - 16: 'icon/16.png', - 32: 'icon/32.png', - 48: 'icon/48.png', - 128: 'icon/128.png', - }, + } }, }) diff --git a/apps/web/.impeccable/design.json b/apps/web/.impeccable/design.json new file mode 100644 index 0000000..f6001a6 --- /dev/null +++ b/apps/web/.impeccable/design.json @@ -0,0 +1,412 @@ +{ + "schemaVersion": 2, + "generatedAt": "2026-10-28T09:55:10.516114+00:00", + "title": "Design System: Comic Code", + "extensions": { + "colorMeta": { + "canvas": { + "role": "neutral", + "displayName": "Canvas", + "tonalRamp": [ + "oklch(15% 0.0000 0.00)", + "oklch(26% 0.0000 0.00)", + "oklch(38% 0.0000 0.00)", + "oklch(49% 0.0000 0.00)", + "oklch(61% 0.0000 0.00)", + "oklch(72% 0.0000 0.00)", + "oklch(84% 0.0000 0.00)", + "oklch(95% 0.0000 0.00)" + ] + }, + "text": { + "role": "neutral", + "displayName": "Text", + "tonalRamp": [ + "oklch(15% 0.0000 0.00)", + "oklch(26% 0.0000 0.00)", + "oklch(38% 0.0000 0.00)", + "oklch(49% 0.0000 0.00)", + "oklch(61% 0.0000 0.00)", + "oklch(72% 0.0000 0.00)", + "oklch(84% 0.0000 0.00)", + "oklch(95% 0.0000 0.00)" + ] + }, + "muted": { + "role": "neutral", + "displayName": "Muted", + "tonalRamp": [ + "oklch(15% 0.0169 148.54)", + "oklch(26% 0.0169 148.54)", + "oklch(38% 0.0169 148.54)", + "oklch(49% 0.0169 148.54)", + "oklch(61% 0.0169 148.54)", + "oklch(72% 0.0169 148.54)", + "oklch(84% 0.0169 148.54)", + "oklch(95% 0.0169 148.54)" + ] + }, + "green": { + "role": "primary", + "displayName": "Green", + "tonalRamp": [ + "oklch(15% 0.0829 145.91)", + "oklch(26% 0.0829 145.91)", + "oklch(38% 0.0829 145.91)", + "oklch(49% 0.0829 145.91)", + "oklch(61% 0.0829 145.91)", + "oklch(72% 0.0829 145.91)", + "oklch(84% 0.0829 145.91)", + "oklch(95% 0.0829 145.91)" + ] + }, + "lime": { + "role": "primary", + "displayName": "Lime", + "tonalRamp": [ + "oklch(15% 0.0515 114.50)", + "oklch(26% 0.0515 114.50)", + "oklch(38% 0.0515 114.50)", + "oklch(49% 0.0515 114.50)", + "oklch(61% 0.0515 114.50)", + "oklch(72% 0.0515 114.50)", + "oklch(84% 0.0515 114.50)", + "oklch(95% 0.0515 114.50)" + ] + }, + "line": { + "role": "neutral", + "displayName": "Line", + "tonalRamp": [ + "oklch(15% 0.0141 124.57)", + "oklch(26% 0.0141 124.57)", + "oklch(38% 0.0141 124.57)", + "oklch(49% 0.0141 124.57)", + "oklch(61% 0.0141 124.57)", + "oklch(72% 0.0141 124.57)", + "oklch(84% 0.0141 124.57)", + "oklch(95% 0.0141 124.57)" + ] + }, + "white": { + "role": "neutral", + "displayName": "White", + "tonalRamp": [ + "oklch(15% 0.0000 0.00)", + "oklch(26% 0.0000 0.00)", + "oklch(38% 0.0000 0.00)", + "oklch(49% 0.0000 0.00)", + "oklch(61% 0.0000 0.00)", + "oklch(72% 0.0000 0.00)", + "oklch(84% 0.0000 0.00)", + "oklch(95% 0.0000 0.00)" + ] + }, + "action": { + "role": "primary", + "displayName": "Action", + "tonalRamp": [ + "oklch(15% 0.0582 149.05)", + "oklch(26% 0.0582 149.05)", + "oklch(38% 0.0582 149.05)", + "oklch(49% 0.0582 149.05)", + "oklch(61% 0.0582 149.05)", + "oklch(72% 0.0582 149.05)", + "oklch(84% 0.0582 149.05)", + "oklch(95% 0.0582 149.05)" + ] + }, + "action-hover": { + "role": "primary", + "displayName": "Action Hover", + "tonalRamp": [ + "oklch(15% 0.0836 137.66)", + "oklch(26% 0.0836 137.66)", + "oklch(38% 0.0836 137.66)", + "oklch(49% 0.0836 137.66)", + "oklch(61% 0.0836 137.66)", + "oklch(72% 0.0836 137.66)", + "oklch(84% 0.0836 137.66)", + "oklch(95% 0.0836 137.66)" + ] + }, + "pale-action": { + "role": "primary", + "displayName": "Pale Action", + "tonalRamp": [ + "oklch(15% 0.0540 113.10)", + "oklch(26% 0.0540 113.10)", + "oklch(38% 0.0540 113.10)", + "oklch(49% 0.0540 113.10)", + "oklch(61% 0.0540 113.10)", + "oklch(72% 0.0540 113.10)", + "oklch(84% 0.0540 113.10)", + "oklch(95% 0.0540 113.10)" + ] + }, + "pale-action-ink": { + "role": "primary", + "displayName": "Pale Action Ink", + "tonalRamp": [ + "oklch(15% 0.0520 139.69)", + "oklch(26% 0.0520 139.69)", + "oklch(38% 0.0520 139.69)", + "oklch(49% 0.0520 139.69)", + "oklch(61% 0.0520 139.69)", + "oklch(72% 0.0520 139.69)", + "oklch(84% 0.0520 139.69)", + "oklch(95% 0.0520 139.69)" + ] + }, + "pink": { + "role": "secondary", + "displayName": "Pink", + "tonalRamp": [ + "oklch(15% 0.0410 346.27)", + "oklch(26% 0.0410 346.27)", + "oklch(38% 0.0410 346.27)", + "oklch(49% 0.0410 346.27)", + "oklch(61% 0.0410 346.27)", + "oklch(72% 0.0410 346.27)", + "oklch(84% 0.0410 346.27)", + "oklch(95% 0.0410 346.27)" + ] + }, + "cool-blue": { + "role": "secondary", + "displayName": "Cool Blue", + "tonalRamp": [ + "oklch(15% 0.0187 232.54)", + "oklch(26% 0.0187 232.54)", + "oklch(38% 0.0187 232.54)", + "oklch(49% 0.0187 232.54)", + "oklch(61% 0.0187 232.54)", + "oklch(72% 0.0187 232.54)", + "oklch(84% 0.0187 232.54)", + "oklch(95% 0.0187 232.54)" + ] + }, + "peach": { + "role": "tertiary", + "displayName": "Peach", + "tonalRamp": [ + "oklch(15% 0.0148 70.89)", + "oklch(26% 0.0148 70.89)", + "oklch(38% 0.0148 70.89)", + "oklch(49% 0.0148 70.89)", + "oklch(61% 0.0148 70.89)", + "oklch(72% 0.0148 70.89)", + "oklch(84% 0.0148 70.89)", + "oklch(95% 0.0148 70.89)" + ] + }, + "extension-canvas": { + "role": "neutral", + "displayName": "Extension Canvas", + "tonalRamp": [ + "oklch(15% 0.0108 118.02)", + "oklch(26% 0.0108 118.02)", + "oklch(38% 0.0108 118.02)", + "oklch(49% 0.0108 118.02)", + "oklch(61% 0.0108 118.02)", + "oklch(72% 0.0108 118.02)", + "oklch(84% 0.0108 118.02)", + "oklch(95% 0.0108 118.02)" + ] + }, + "extension-ink": { + "role": "neutral", + "displayName": "Extension Ink", + "tonalRamp": [ + "oklch(15% 0.0197 154.13)", + "oklch(26% 0.0197 154.13)", + "oklch(38% 0.0197 154.13)", + "oklch(49% 0.0197 154.13)", + "oklch(61% 0.0197 154.13)", + "oklch(72% 0.0197 154.13)", + "oklch(84% 0.0197 154.13)", + "oklch(95% 0.0197 154.13)" + ] + }, + "extension-action": { + "role": "primary", + "displayName": "Extension Action", + "tonalRamp": [ + "oklch(15% 0.0688 144.86)", + "oklch(26% 0.0688 144.86)", + "oklch(38% 0.0688 144.86)", + "oklch(49% 0.0688 144.86)", + "oklch(61% 0.0688 144.86)", + "oklch(72% 0.0688 144.86)", + "oklch(84% 0.0688 144.86)", + "oklch(95% 0.0688 144.86)" + ] + }, + "evidence-blue": { + "role": "secondary", + "displayName": "Evidence Blue", + "tonalRamp": [ + "oklch(15% 0.0105 219.59)", + "oklch(26% 0.0105 219.59)", + "oklch(38% 0.0105 219.59)", + "oklch(49% 0.0105 219.59)", + "oklch(61% 0.0105 219.59)", + "oklch(72% 0.0105 219.59)", + "oklch(84% 0.0105 219.59)", + "oklch(95% 0.0105 219.59)" + ] + } + }, + "typographyMeta": { + "display": { + "displayName": "Mosaic heading", + "purpose": "Central transformation heading; responsive override at 700px." + }, + "code": { + "displayName": "Source paths", + "purpose": "Repository paths and evidence references." + } + }, + "shadows": [ + { + "name": "mosaic-ambient", + "value": "0 2px 16px rgba(24, 30, 45, 0.045)", + "purpose": "Soft depth around pastel panels." + }, + { + "name": "splayed-window", + "value": "0 12px 28px #404a2c29", + "purpose": "Overlapping illustrative app windows." + }, + { + "name": "sample-toast", + "value": "0 6px 12px #7a566a16, 0 11px 0 -3px #e5d6d6", + "purpose": "Notification with a small offset backing layer." + }, + { + "name": "preview-device", + "value": "0 18px 48px #263a2010", + "purpose": "Built extension preview frame." + } + ], + "motion": [ + { + "name": "control-transition", + "value": "background 0.18s, color 0.18s, box-shadow 0.18s", + "purpose": "Web control state changes." + }, + { + "name": "mosaic-settle", + "value": "0.8s cubic-bezier(0.16, 1, 0.3, 1)", + "purpose": "Opacity, 12px translation, .988 scale and inset clipping; staggered .04\u2013.28s. Only without reduced-motion preference." + }, + { + "name": "extension-entry", + "value": "0.55s cubic-bezier(0.16, 1, 0.3, 1)", + "purpose": "Repository card opacity and 8px translation. Only without reduced-motion preference." + } + ], + "breakpoints": [ + { + "name": "two-column", + "value": "1050px" + }, + { + "name": "single-column", + "value": "700px" + } + ] + }, + "components": [ + { + "name": "Primary action", + "kind": "button", + "description": "Green workspace action.", + "html": "", + "css": ".ds-primary{font-family:\"Plus Jakarta Sans\",-apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;min-height:42px;display:inline-flex;align-items:center;justify-content:center;border-radius:999px;padding:11px 20px;font-size:12px;font-weight:700;text-decoration:none;cursor:pointer;transition:background .18s,color .18s,box-shadow .18s;border:1px solid transparent;background:#2c4c32;color:white}.ds-primary:hover:not(:disabled){background:#476a3a;color:white}.ds-primary:focus-visible{outline:2px solid var(--green,#315e35);outline-offset:4px}.ds-primary:disabled{opacity:.5;cursor:not-allowed}", + "refersTo": "button-primary" + }, + { + "name": "Pale action", + "kind": "button", + "description": "Chartreuse web generation and sample replay action.", + "html": "", + "css": ".ds-pale{font-family:\"Plus Jakarta Sans\",-apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;min-height:42px;display:inline-flex;align-items:center;justify-content:center;border-radius:999px;padding:11px 20px;font-size:12px;font-weight:700;text-decoration:none;cursor:pointer;transition:background .18s,color .18s,box-shadow .18s;border:1px solid transparent;background:#e8edc4;color:#24391f}.ds-pale:hover:not(:disabled){background:#476a3a;color:white}.ds-pale:focus-visible{outline:2px solid var(--green,#315e35);outline-offset:4px}.ds-pale:disabled{opacity:.5;cursor:not-allowed}", + "refersTo": "button-pale" + }, + { + "name": "Secondary action", + "kind": "button", + "description": "White bordered workspace or return action.", + "html": "", + "css": ".ds-secondary{font-family:\"Plus Jakarta Sans\",-apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;min-height:42px;display:inline-flex;align-items:center;justify-content:center;border-radius:999px;padding:11px 20px;font-size:12px;font-weight:700;text-decoration:none;cursor:pointer;transition:background .18s,color .18s,box-shadow .18s;border:1px solid #d5dfd0;background:var(--white,#fff);color:#2f4335;white-space:nowrap}.ds-secondary:hover:not(:disabled){background:#edf3e8}.ds-secondary:focus-visible{outline:2px solid var(--green,#315e35);outline-offset:4px}.ds-secondary:disabled{opacity:.5;cursor:not-allowed}", + "refersTo": "button-secondary" + }, + { + "name": "Credential field", + "kind": "input", + "description": "Labeled field inside optional artwork controls.", + "html": "", + "css": ".ds-field{font-family:\"Plus Jakarta Sans\",-apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;display:grid;gap:7px;font-size:11px;color:#4b5a48}.ds-field input{font:inherit;width:100%;height:43px;padding:0 12px;border:1px solid #d7dfcf;border-radius:9px;background:var(--white,#fff);color:var(--text,#141414);font-size:12px;caret-color:var(--green,#315e35)}.ds-field input::placeholder{color:#68716c;opacity:1}.ds-field input:focus-visible{outline:2px solid var(--green,#315e35);outline-offset:4px}" + }, + { + "name": "Extension sections", + "kind": "nav", + "description": "Three sections with a white selected segment.", + "html": "", + "css": ".ds-tabs{font-family:\"Plus Jakarta Sans\",-apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;display:grid;grid-template-columns:repeat(3,1fr);gap:5px;padding:5px;background:#e7ebdf;border-radius:999px}.ds-tabs button{font:inherit;border:0;border-radius:999px;padding:9px 7px;font-size:11px;color:#66745c;background:transparent;cursor:pointer}.ds-tabs button[aria-pressed=\"true\"]{background:#fff;color:#28402b;font-weight:700;box-shadow:0 2px 6px #24341b08}.ds-tabs button:focus-visible{outline:2px solid #4e7043;outline-offset:3px}.ds-tabs button:disabled{opacity:.45;cursor:not-allowed}" + }, + { + "name": "State chip", + "kind": "chip", + "description": "Sample or privacy state carried by text.", + "html": "Illustrative sample", + "css": ".ds-chip{font-family:\"Plus Jakarta Sans\",-apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;display:inline-block;padding:7px 12px;border-radius:999px;background:#eff3e8;color:#4e6243;white-space:nowrap;font-size:10px;font-weight:700}" + }, + { + "name": "Workspace container", + "kind": "card", + "description": "White working surface below the mosaic.", + "html": "

A little context goes a long way.

Inspect a repository above, or explore the sample.

", + "css": ".ds-workspace{font-family:\"Plus Jakarta Sans\",-apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;background:var(--white,#fff);color:var(--text,#141414);border:1px solid #e2e4dd;border-radius:22px;padding:30px}.ds-workspace h2{font-size:24px;letter-spacing:-.03em;margin:0 0 9px;font-weight:800}.ds-workspace p{font-size:13px;color:var(--muted,#586159);margin:0;max-width:70ch;line-height:1.7}", + "refersTo": "workspace" + }, + { + "name": "Extension evidence", + "kind": "custom", + "description": "Cool-blue evidence inset with wrapping source paths.", + "html": "
src/book-form.tsxLines 12\u201324 \u00b7 sample-form
src/library.tsLines 8\u201317 \u00b7 sample-storage
", + "css": ".ds-evidence{font-family:\"Plus Jakarta Sans\",-apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;border-radius:12px;padding:0 14px;background:#e4edf0}.ds-evidence>div{padding:15px 0;border-bottom:1px solid #d0dce0}.ds-evidence>div:last-child{border:0}.ds-evidence code{display:block;font-family:ui-monospace,SFMono-Regular,monospace;font-size:10px;color:#45636d;overflow-wrap:anywhere}.ds-evidence small{display:block;font-size:8px;margin-top:7px;color:#48656d}" + } + ], + "narrative": { + "northStar": "Source becomes a clear visual story.", + "overview": "The user-pinned world is a light SaaS mosaic: a gray canvas, pastel panels,\nrounded white chrome, near-black type and restrained green actions. Unequal\npanels and splayed source/comic windows give the introduction its character;\nthe working interface uses quieter white and pale-green surfaces.\n\nThis vocabulary covers the web workspace and Chrome side panel. The extension\ncompresses it into a single column with a chartreuse repository card, pink\nsample strip and cool-blue evidence list. Its preview embeds the actual built\nextension rather than a separate mock interface.", + "keyCharacteristics": [ + "Five unequal introductory panels, followed by a functional white workspace.", + "Plus Jakarta Sans, heavy compact headings and small calm supporting text.", + "Soft tonal depth, rounded containers and pill controls.", + "Inline SVG geometry, explicit illustrative-sample labels and visible evidence." + ], + "rules": [ + { + "name": "The Light Surface Rule", + "body": "Keep this light canvas and pastel vocabulary; do not restore the replaced violet glow or giant dark hero.", + "section": "colors" + } + ], + "dos": [ + "**Do** retain Plus Jakarta Sans and the light gray/pastel surface hierarchy.", + "**Do** preserve readable supporting text, keyboard outlines and explicit selection states.", + "**Do** label bundled sample source, panels and evidence as illustrative.", + "**Do** adapt the shared vocabulary to the extension's narrow single column.", + "**Do** keep provenance with shipping raster assets; bundled PNG icons have procedural source." + ], + "donts": [ + "**Don't** introduce violet glows, a giant dark hero or replacement typography.", + "**Don't** present decorative process bars as measured performance or savings.", + "**Don't** imply the bundled sample is a live repository scan or paid generation.", + "**Don't** replace the actual extension preview with a disconnected mockup." + ] + } +} diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md new file mode 100644 index 0000000..643577d --- /dev/null +++ b/apps/web/AGENTS.md @@ -0,0 +1,9 @@ + + +# This is NOT the Next.js you know + +This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices. + +This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean. + + diff --git a/apps/web/CLAUDE.md b/apps/web/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/apps/web/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/apps/web/DESIGN-BRIEF.md b/apps/web/DESIGN-BRIEF.md new file mode 100644 index 0000000..9359dde --- /dev/null +++ b/apps/web/DESIGN-BRIEF.md @@ -0,0 +1,20 @@ +# Pinned redesign direction + +Scope: web home/workspace and Chrome extension. Mode: Operate with a product +mosaic introduction. The user-supplied reference pins the direction; execute in +code with inline SVG geometry and the existing React stack, adapting the sample +landing page's generic copy to Comic Code's real capabilities. + +First viewport: a compact brand header over five unequal panels. Pink sample +notification upper left, cool-blue repository/evidence module below it, large +chartreuse comic transformation in the center, warm peach process module right, +and the functional URL inspection bar across the lower two columns. The sample +CTA and extension-preview link must be discoverable without credentials. + +Signature: two splayed app windows show source becoming four comic panels. +The actual result area and browser extension inherit the light surfaces and +clear type. No violet glows, giant dark hero, invented charts or savings claims. + +Success: real controls preserved, a clearly labeled sample works without API +calls, desktop and mobile are readable, the extension preview uses the actual +extension bundle, checks pass, and the changes have a descriptive local commit. diff --git a/apps/web/DESIGN.md b/apps/web/DESIGN.md new file mode 100644 index 0000000..b2c8db1 --- /dev/null +++ b/apps/web/DESIGN.md @@ -0,0 +1,217 @@ +--- +name: Comic Code +description: A light pastel mosaic that makes source and its visual explanation feel connected. +colors: + canvas: '#f0f0f0' + text: '#141414' + muted: '#586159' + green: '#315e35' + lime: '#e9efc8' + line: '#dce0d6' + white: '#fff' + action: '#2c4c32' + action-hover: '#476a3a' + pale-action: '#e8edc4' + pale-action-ink: '#24391f' + pink: '#f9d9e9' + cool-blue: '#cedce4' + peach: '#f7efe6' + extension-canvas: '#f3f5ed' + extension-ink: '#162019' + extension-action: '#345735' + evidence-blue: '#e4edf0' +typography: + display: + fontFamily: 'Plus Jakarta Sans, -apple-system, BlinkMacSystemFont, Segoe UI, sans-serif' + fontSize: 'clamp(25px, 2.55vw, 36px)' + fontWeight: 800 + lineHeight: 1.32 + letterSpacing: '-0.035em' + title: + fontFamily: 'Plus Jakarta Sans, -apple-system, BlinkMacSystemFont, Segoe UI, sans-serif' + fontSize: '24px' + fontWeight: 800 + letterSpacing: '-0.03em' + body: + fontFamily: 'Plus Jakarta Sans, -apple-system, BlinkMacSystemFont, Segoe UI, sans-serif' + fontSize: '13px' + lineHeight: 1.7 + label: + fontFamily: 'Plus Jakarta Sans, -apple-system, BlinkMacSystemFont, Segoe UI, sans-serif' + fontSize: '12px' + fontWeight: 700 + code: + fontFamily: 'ui-monospace, SFMono-Regular, monospace' +rounded: + field: '9px' + inset: '12px' + preview: '14px' + panel: '22px' + pill: '999px' +spacing: + small: '10px' + medium: '18px' + large: '24px' + workspace: '30px' +components: + button-primary: + backgroundColor: '{colors.action}' + textColor: '{colors.white}' + rounded: '{rounded.pill}' + padding: '11px 20px' + button-primary-hover: + backgroundColor: '{colors.action-hover}' + textColor: '{colors.white}' + button-pale: + backgroundColor: '{colors.pale-action}' + textColor: '{colors.pale-action-ink}' + rounded: '{rounded.pill}' + padding: '11px 20px' + button-secondary: + backgroundColor: '{colors.white}' + rounded: '{rounded.pill}' + padding: '11px 20px' + workspace: + backgroundColor: '{colors.white}' + rounded: '{rounded.panel}' + padding: '{spacing.workspace}' +--- + +# Design System: Comic Code + +## Overview + +**Creative North Star: "Source becomes a clear visual story."** + +The user-pinned world is a light SaaS mosaic: a gray canvas, pastel panels, +rounded white chrome, near-black type and restrained green actions. Unequal +panels and splayed source/comic windows give the introduction its character; +the working interface uses quieter white and pale-green surfaces. + +This vocabulary covers the web workspace and Chrome side panel. The extension +compresses it into a single column with a chartreuse repository card, pink +sample strip and cool-blue evidence list. Its preview embeds the actual built +extension rather than a separate mock interface. + +**Key Characteristics:** + +- Five unequal introductory panels, followed by a functional white workspace. +- Plus Jakarta Sans, heavy compact headings and small calm supporting text. +- Soft tonal depth, rounded containers and pill controls. +- Inline SVG geometry, explicit illustrative-sample labels and visible evidence. + +## Colors + +The palette puts dark readable type on light pastel surfaces. Frontmatter +records reusable colors; multi-stop surface gradients remain in the source CSS. + +### Primary + +- **Chartreuse / Lime:** the central transformation surface, sample disclosures + and pale action variant. +- **Deep Green:** primary actions, focus outlines and selected emphasis. + +### Secondary + +- **Blush Pink:** sample notification panel and the extension sample strip. +- **Cool Blue:** source/tools module, inspection band and extension evidence. + +### Tertiary + +- **Warm Peach:** the process module and warm notice backgrounds. + +### Neutral + +- **Canvas / White:** surrounding page and functional containers. +- **Text / Muted:** primary copy and supporting explanations. +- **Line:** quiet dividers and restrained container boundaries. + +**The Light Surface Rule.** Keep this light canvas and pastel vocabulary; do not +restore the replaced violet glow or giant dark hero. + +## Typography + +Plus Jakarta Sans is bundled locally as a variable WOFF2 (weights 400–800), with +its OFL license. The same family serves display, body and controls. Source paths +use the system monospace stack and wrap instead of forcing horizontal overflow. + +The central heading uses the display role; workspace titles use the title role. +The extension reduces its repository heading to 21px and section headings to +15px, while preserving weight 800 and tight tracking. Web supporting copy is +typically 12–13px; the denser extension uses 9–11px metadata and 11px story copy. +The extension-preview page uses a larger heading, scaling to 56px on desktop. + +## Layout + +Web containers cap at 1374px with 32px outer gutters. The introduction is a +three-column, three-row grid with proportions 339:627:388 and 149:343:156; +its inspection bar spans the lower two columns. Gaps are approximately 10px. +The workspace follows with 36px separation and 30px internal padding. + +At 1050px the mosaic becomes two columns and story text becomes two columns. +At 700px it becomes one column in this order: transformation, inspection, +sample notification, source/tools, process. Gutters become 14px, the workspace +uses 22px by 18px padding, fields and story panels stack, and evidence rows wrap. +The preview page changes from copy beside a 410px device to a stacked layout. + +The extension is a single column with a 300px minimum width, roughly 19px content +insets, scrolling file/evidence content and a fixed footer. Compact mode reduces +vertical padding. Keep this narrow form rather than copying the web mosaic. + +## Elevation & Depth + +Pastel gradients and white edges supply most depth. Mosaic containers have a +faint ambient shadow; the splayed windows receive stronger soft shadows, while +the sample toast has a small offset layer beneath it. Functional workspace +sections mostly use borders and tonal insets. The sidecar records exact shadows. + +Mosaic panels settle in with staggered opacity, translation, scale and clipping; +the extension repository card enters with opacity and a short translation. +Both surfaces disable animation and transitions for reduced-motion users. + +## Shapes + +Large web panels and the workspace use the panel radius. Fields and inset +surfaces use smaller rounded corners; buttons, state chips and section controls +use pills. The extension repository card uses 18px corners. White borders frame +the illustrative windows, which are rotated in opposing directions. These +decorative compositions are hidden from assistive technology. + +## Components + +- **Buttons:** green primary, pale chartreuse generation/replay variant on the + web, white bordered secondary and quiet text actions. Web buttons have a 42px + minimum height; extension actions fill the width with a 44px minimum. Hover + changes fill; disabled actions reduce opacity. Focus remains visibly outlined. +- **Inputs:** the introduction uses a white pill containing a repository field + and Inspect button. Its entire form gains a focus outline. Credential fields + are labeled white rectangles; keep their keyboard focus treatment. +- **Navigation:** a compact brand header with text links on the web. Explain, + Story and Evidence use a pill section switch in the extension, with a white + active segment and `aria-pressed` reflecting selection. +- **Chips:** soft pills convey sample, privacy, confidence and counts. Their + wording carries the state; color is supplementary. +- **Containers:** use white for the working area and tonal insets for notices, + optional artwork controls, files and evidence. Evidence paths remain monospace. +- **Story:** the comic image is followed by four numbered text panels and an + evidence disclosure on the web. The extension stacks image, four sections and + actions, with Evidence available as its own section. +- **Signature illustration:** two splayed app windows show source turning into + a four-panel comic. It is procedural SVG/CSS geometry, not external imagery. + +## Do's and Don'ts + +### Do: + +- **Do** retain Plus Jakarta Sans and the light gray/pastel surface hierarchy. +- **Do** preserve readable supporting text, keyboard outlines and explicit selection states. +- **Do** label bundled sample source, panels and evidence as illustrative. +- **Do** adapt the shared vocabulary to the extension's narrow single column. +- **Do** keep provenance with shipping raster assets; bundled PNG icons have procedural source. + +### Don't: + +- **Don't** introduce violet glows, a giant dark hero or replacement typography. +- **Don't** present decorative process bars as measured performance or savings. +- **Don't** imply the bundled sample is a live repository scan or paid generation. +- **Don't** replace the actual extension preview with a disconnected mockup. diff --git a/apps/web/PRODUCT.md b/apps/web/PRODUCT.md new file mode 100644 index 0000000..e312f2c --- /dev/null +++ b/apps/web/PRODUCT.md @@ -0,0 +1,40 @@ +# Comic Code + + + +## Platform + +web + +## Product Purpose + +Explain a GitHub repository as four evidence-linked comic panels. Preserve the +web workspace, Chrome side panel, source inspection, generation, evidence, +download and deletion workflows already implemented. + +## Operating Context + +The user evaluates their own project in a local web preview and Chrome extension. +GitHub and image-provider quotas make repeated live inspection difficult. A clearly +labeled bundled sample must allow visual review without either API. + +## Capabilities and Constraints + +Local mode supports public repositories and free structural analysis/template +artwork. OpenAI/Gemini image generation is optional and uses the user's own key and allocation; captions and evidence remain unchanged. +Hosted private access and sharing require configured services. Sample content +must never imply a fresh scan, live verification or successful paid generation. + +## Brand Commitments + +Keep the Comic Code name and components. The user explicitly replaces the violet +appearance with the supplied light SaaS mosaic reference: neutral canvas, +chartreuse, pink, cool blue and peach surfaces, dark text, rounded white chrome, +and Plus Jakarta Sans. Adapt the composition to actual product controls and a +narrow extension. The reference asks for no external images and SVG geometry. + +## Evidence on Hand + +The repository contains the working components, tests and a prior debugging +report. The user supplied a detailed written design reference on 28 October 2026. +There are no customer testimonials, performance statistics or savings claims. diff --git a/apps/web/eslint.config.mjs b/apps/web/eslint.config.mjs index af8d662..2c009c5 100644 --- a/apps/web/eslint.config.mjs +++ b/apps/web/eslint.config.mjs @@ -5,5 +5,10 @@ import nextTypescript from 'eslint-config-next/typescript' export default defineConfig([ ...nextVitals, ...nextTypescript, - globalIgnores(['.next/**', 'next-env.d.ts']), + globalIgnores([ + '.next/**', + '.trigger/**', + 'next-env.d.ts', + 'public/extension-preview/**', + ]), ]) diff --git a/apps/web/next-env.d.ts b/apps/web/next-env.d.ts index 9edff1c..ce4e94a 100644 --- a/apps/web/next-env.d.ts +++ b/apps/web/next-env.d.ts @@ -1,6 +1,7 @@ /// /// import "./.next/types/routes.d.ts"; +import "./.next/types/root-params.d.ts"; // NOTE: This file should not be edited // see https://nextjs.org/docs/app/api-reference/config/typescript for more information. diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index 6f3f296..d0b9406 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -32,15 +32,16 @@ const nextConfig: NextConfig = { outputFileTracingRoot: path.join(import.meta.dirname, '../..'), outputFileTracingIncludes: { '/*': [ - '../../node_modules/.pnpm/sharp@0.35.3*/node_modules/sharp/**/*', - '../../node_modules/.pnpm/@img+sharp-linux-x64@0.35.3/node_modules/@img/sharp-linux-x64/**/*', - '../../node_modules/.pnpm/@img+sharp-libvips-linux-x64@1.3.2/node_modules/@img/sharp-libvips-linux-x64/**/*', + '../../node_modules/.pnpm/sharp@0.35.5*/node_modules/sharp/**/*', + '../../node_modules/.pnpm/@img+sharp-linux-x64@0.35.5/node_modules/@img/sharp-linux-x64/**/*', + '../../node_modules/.pnpm/@img+sharp-libvips-linux-x64@1.3.4/node_modules/@img/sharp-libvips-linux-x64/**/*', ], }, poweredByHeader: false, reactStrictMode: true, transpilePackages: [ '@comic-code/comic', + '@comic-code/ui', '@comic-code/contracts', '@comic-code/database', '@comic-code/github', @@ -51,6 +52,17 @@ const nextConfig: NextConfig = { source: '/:path*', headers: securityHeaders, }, + { + source: '/extension-preview/:path*', + headers: [ + { key: 'X-Frame-Options', value: 'SAMEORIGIN' }, + { + key: 'Content-Security-Policy', + value: + "default-src 'self'; base-uri 'none'; connect-src 'none'; font-src 'self'; frame-ancestors 'self'; img-src 'self' blob:; object-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'", + }, + ], + }, { source: '/share/:path*', headers: [ diff --git a/apps/web/package.json b/apps/web/package.json index 3faac49..8e4ba72 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -3,7 +3,7 @@ "version": "0.1.0", "private": true, "scripts": { - "build": "next build", + "build": "node ../../scripts/extension.mjs build && next build --webpack", "dev": "next dev --turbopack", "lint": "eslint . --max-warnings=0", "start": "next start", @@ -15,29 +15,31 @@ "@comic-code/contracts": "workspace:*", "@comic-code/database": "workspace:*", "@comic-code/github": "workspace:*", - "@trigger.dev/sdk": "4.5.4", + "@comic-code/ui": "workspace:*", + "@trigger.dev/sdk": "4.8.1", "jose": "6.2.3", - "next": "16.2.10", + "next": "16.4.3", "react": "19.2.7", "react-dom": "19.2.7", - "sharp": "0.35.3", - "zod": "4.4.3" + "sharp": "0.35.5", + "zod": "4.6.7" }, "optionalDependencies": { - "@img/sharp-libvips-linux-x64": "1.3.2", - "@img/sharp-linux-x64": "0.35.3" + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-linux-x64": "0.35.5" }, "devDependencies": { "@tailwindcss/postcss": "4.3.3", + "@trigger.dev/build": "4.8.1", "@types/node": "24.10.1", "@types/react": "19.2.17", "@types/react-dom": "19.2.3", - "@trigger.dev/build": "4.5.4", "eslint": "9.39.2", - "eslint-config-next": "16.2.10", - "trigger.dev": "4.5.4", + "eslint-config-next": "16.4.3", + "jsdom": "27.4.0", "tailwindcss": "4.3.3", + "trigger.dev": "4.8.1", "typescript": "5.9.3", - "vitest": "4.1.10" + "vitest": "4.1.12" } } diff --git a/apps/web/public/fonts/OFL.txt b/apps/web/public/fonts/OFL.txt new file mode 100644 index 0000000..cd44467 --- /dev/null +++ b/apps/web/public/fonts/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The Plus Jakarta Sans Project Authors (https://github.com/tokotype/PlusJakartaSans) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/apps/web/public/fonts/plus-jakarta-sans.woff2 b/apps/web/public/fonts/plus-jakarta-sans.woff2 new file mode 100644 index 0000000..5ec77ed Binary files /dev/null and b/apps/web/public/fonts/plus-jakarta-sans.woff2 differ diff --git a/apps/web/src/app/api/local/[...path]/route.ts b/apps/web/src/app/api/local/[...path]/route.ts new file mode 100644 index 0000000..ddd50d1 --- /dev/null +++ b/apps/web/src/app/api/local/[...path]/route.ts @@ -0,0 +1,8 @@ +import { handleLocalApi } from '@/lib/local-api' + +export const runtime = 'nodejs' +export const dynamic = 'force-dynamic' +export const maxDuration = 300 +export const GET = handleLocalApi +export const POST = handleLocalApi +export const DELETE = handleLocalApi diff --git a/apps/web/src/app/api/v1/auth/github/callback/route.ts b/apps/web/src/app/api/v1/auth/github/callback/route.ts index 4b373bf..e1afcb1 100644 --- a/apps/web/src/app/api/v1/auth/github/callback/route.ts +++ b/apps/web/src/app/api/v1/auth/github/callback/route.ts @@ -9,7 +9,7 @@ import { sessionCookieOptions, } from '@/lib/auth/session' import { getServerEnv } from '@/lib/env' -import { jsonNoStore } from '@/lib/http' +import { jsonNoStore, safeExtensionRedirect, safeReturnTo } from '@/lib/http' export async function GET(request: Request) { const requestUrl = new URL(request.url) @@ -23,6 +23,15 @@ export async function GET(request: Request) { return jsonNoStore({ error: 'invalid_oauth_callback' }, { status: 400 }) } + const extensionRedirect = flow.extensionRedirect + ? safeExtensionRedirect( + flow.extensionRedirect, + getServerEnv().ALLOWED_EXTENSION_IDS, + ) + : undefined + if (flow.extensionRedirect && !extensionRedirect) + return jsonNoStore({ error: 'extension_not_allowed' }, { status: 403 }) + try { const token = await exchangeGitHubCode(code, flow.verifier) const user = await fetchGitHubUser(token.access_token) @@ -34,15 +43,18 @@ export async function GET(request: Request) { accessToken: token.access_token, }) - if (flow.extensionRedirect) { - const redirect = new URL(flow.extensionRedirect) + if (extensionRedirect) { + const redirect = new URL(extensionRedirect) redirect.hash = `session=${encodeURIComponent(sessionToken)}` return Response.redirect(redirect) } cookieStore.set(sessionCookieName, sessionToken, sessionCookieOptions()) return Response.redirect( - new URL(flow.returnTo ?? '/', getServerEnv().NEXT_PUBLIC_APP_URL), + new URL( + safeReturnTo(flow.returnTo ?? null), + getServerEnv().NEXT_PUBLIC_APP_URL, + ), ) } catch { return jsonNoStore( diff --git a/apps/web/src/app/api/v1/auth/github/start/route.test.ts b/apps/web/src/app/api/v1/auth/github/start/route.test.ts new file mode 100644 index 0000000..0675b9f --- /dev/null +++ b/apps/web/src/app/api/v1/auth/github/start/route.test.ts @@ -0,0 +1,121 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +const mocks = vi.hoisted(() => ({ + cookies: vi.fn(), + seal: vi.fn(), + read: vi.fn(), + exchange: vi.fn(), + user: vi.fn(), + session: vi.fn(), +})) +const approved = 'a'.repeat(32) +const unapproved = 'b'.repeat(32) +vi.mock('next/headers', () => ({ cookies: mocks.cookies })) +vi.mock('@/lib/env', () => ({ + getServerEnv: () => ({ + NEXT_PUBLIC_APP_URL: 'https://example.com', + ALLOWED_EXTENSION_IDS: ['a'.repeat(32)], + }), +})) +vi.mock('@/lib/auth/github', () => ({ + githubAuthorizationUrl: () => + new URL('https://github.com/login/oauth/authorize'), + exchangeGitHubCode: mocks.exchange, + fetchGitHubUser: mocks.user, +})) +vi.mock('@/lib/auth/session', () => ({ + createOAuthValues: () => ({ + state: 'state', + verifier: 'verifier', + challenge: 'challenge', + }), + oauthCookieName: 'oauth', + sessionCookieName: 'session', + sealOAuthFlow: mocks.seal, + readOAuthFlow: mocks.read, + sealSession: mocks.session, + sessionCookieOptions: () => ({}), + UnauthorizedError: class extends Error {}, +})) +import { GET } from './route' +import { GET as callback } from '../callback/route' +import { safeExtensionRedirect } from '@/lib/http' + +beforeEach(() => { + vi.resetAllMocks() + mocks.cookies.mockResolvedValue({ + set: vi.fn(), + get: () => ({ value: 'sealed' }), + delete: vi.fn(), + }) + mocks.seal.mockResolvedValue('flow') +}) +describe('hosted extension OAuth recipients', () => { + it('refuses an unapproved extension before creating an OAuth flow', async () => { + const response = await GET( + new Request( + `https://example.com/api/v1/auth/github/start?extension_redirect=https://${unapproved}.chromiumapp.org/comic-code`, + ), + ) + expect(response.status).toBe(403) + expect(mocks.seal).not.toHaveBeenCalled() + }) + it('starts OAuth for the configured extension', async () => { + expect( + ( + await GET( + new Request( + `https://example.com/api/v1/auth/github/start?extension_redirect=https://${approved}.chromiumapp.org/comic-code`, + ), + ) + ).status, + ).toBe(302) + expect(mocks.seal).toHaveBeenCalledWith( + expect.objectContaining({ + extensionRedirect: `https://${approved}.chromiumapp.org/comic-code`, + }), + ) + }) + it('rechecks the approved recipient before exchanging an older sealed flow', async () => { + mocks.read.mockResolvedValue({ + state: 'state', + verifier: 'verifier', + extensionRedirect: `https://${unapproved}.chromiumapp.org/comic-code`, + }) + expect( + ( + await callback( + new Request( + 'https://example.com/api/v1/auth/github/callback?code=test&state=state', + ), + ) + ).status, + ).toBe(403) + expect(mocks.exchange).not.toHaveBeenCalled() + expect(mocks.session).not.toHaveBeenCalled() + }) + it('permits web login without an extension recipient', async () => { + expect( + ( + await GET( + new Request( + 'https://example.com/api/v1/auth/github/start?return_to=/workspace', + ), + ) + ).status, + ).toBe(302) + }) + it('rejects extension callback URLs containing credentials or another port', () => { + expect( + safeExtensionRedirect( + `https://user:pass@${approved}.chromiumapp.org/comic-code`, + [approved], + ), + ).toBeUndefined() + expect( + safeExtensionRedirect( + `https://${approved}.chromiumapp.org:444/comic-code`, + [approved], + ), + ).toBeUndefined() + }) +}) diff --git a/apps/web/src/app/api/v1/auth/github/start/route.ts b/apps/web/src/app/api/v1/auth/github/start/route.ts index d20341c..15d55a2 100644 --- a/apps/web/src/app/api/v1/auth/github/start/route.ts +++ b/apps/web/src/app/api/v1/auth/github/start/route.ts @@ -7,14 +7,18 @@ import { sealOAuthFlow, sessionCookieOptions, } from '@/lib/auth/session' -import { safeExtensionRedirect, safeReturnTo } from '@/lib/http' +import { jsonNoStore, safeExtensionRedirect, safeReturnTo } from '@/lib/http' +import { getServerEnv } from '@/lib/env' export async function GET(request: Request) { const requestUrl = new URL(request.url) const returnTo = safeReturnTo(requestUrl.searchParams.get('return_to')) const extensionRedirect = safeExtensionRedirect( requestUrl.searchParams.get('extension_redirect'), + getServerEnv().ALLOWED_EXTENSION_IDS, ) + if (requestUrl.searchParams.has('extension_redirect') && !extensionRedirect) + return jsonNoStore({ error: 'extension_not_allowed' }, { status: 403 }) const { state, verifier, challenge } = createOAuthValues() const flow = await sealOAuthFlow({ kind: 'oauth', diff --git a/apps/web/src/app/api/v1/explanations/[id]/artwork/route.test.ts b/apps/web/src/app/api/v1/explanations/[id]/artwork/route.test.ts new file mode 100644 index 0000000..edc1845 --- /dev/null +++ b/apps/web/src/app/api/v1/explanations/[id]/artwork/route.test.ts @@ -0,0 +1,195 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { sampleAnalysis, getSampleExplanation } from '@comic-code/comic/sample' + +const mocks = vi.hoisted(() => ({ + session: vi.fn(), + owned: vi.fn(), + access: vi.fn(), + installation: vi.fn(), + artwork: vi.fn(), + compose: vi.fn(), + upload: vi.fn(), + complete: vi.fn(), + remove: vi.fn(), + fail: vi.fn(), + audit: vi.fn(), +})) +vi.mock('@comic-code/comic', () => ({ + generateByokPanelArtwork: mocks.artwork, + composeComic: mocks.compose, +})) +vi.mock('@comic-code/database', () => ({ + getOwnedExplanation: mocks.owned, + completeExplanation: mocks.complete, + failExplanation: mocks.fail, + recordAuditEvent: mocks.audit, + removeArtifacts: mocks.remove, + uploadComicArtifact: mocks.upload, +})) +vi.mock('@/lib/auth/session', () => ({ + requireRequestSession: mocks.session, + UnauthorizedError: class extends Error {}, +})) +vi.mock('@/lib/env', () => ({ + getServerEnv: () => ({ NEXT_PUBLIC_APP_URL: 'https://example.com' }), +})) +vi.mock('@/lib/server', () => ({ + databaseClient: () => ({}), + githubClient: () => ({ + assertUserCanReadRepository: mocks.access, + getInstallationId: mocks.installation, + }), + publicExplanation: async (row: unknown) => row, +})) + +import { HttpError } from '@/lib/http' +import { POST } from './route' + +const secret = 'dummy-provider-image-key-never-store' +const row = { + id: 'comic', + status: 'completed', + analysis: sampleAnalysis, + final_artifact_path: 'old.png', + selected_files: ['src/form.ts'], + github_owner: 'owner', + github_repository: 'repo', +} +const context = { params: Promise.resolve({ id: 'comic' }) } +const request = (provider = 'openai') => + new Request('https://example.com/api/v1/explanations/comic/artwork', { + method: 'POST', + headers: { + origin: 'https://example.com', + 'content-type': 'application/json', + }, + body: JSON.stringify({ provider, apiKey: secret }), + }) + +beforeEach(() => { + vi.resetAllMocks() + mocks.session.mockResolvedValue({ + userId: 'user', + accessToken: 'github-session', + }) + mocks.owned.mockResolvedValue(row) + mocks.access.mockResolvedValue({ isPrivate: false }) + mocks.artwork.mockResolvedValue([]) + mocks.compose.mockResolvedValue(Buffer.from('composed PNG')) + mocks.upload.mockResolvedValue('new.png') + mocks.complete.mockResolvedValue(undefined) + mocks.remove.mockResolvedValue(undefined) + mocks.fail.mockResolvedValue(undefined) + mocks.audit.mockResolvedValue(undefined) +}) + +describe('hosted image BYOK boundary', () => { + it('requires a session before loading a comic or calling an image provider', async () => { + mocks.session.mockRejectedValue( + new HttpError(401, 'authentication_required'), + ) + expect((await POST(request(), context)).status).toBe(401) + expect(mocks.owned).not.toHaveBeenCalled() + expect(mocks.artwork).not.toHaveBeenCalled() + }) + it.each(['openai', 'gemini'])( + 'updates artwork with %s while retaining captions, evidence and selected files', + async (provider) => { + const response = await POST(request(provider), context) + expect(response.status).toBe(200) + expect(mocks.access).toHaveBeenCalledWith( + 'github-session', + 'owner', + 'repo', + ) + expect(mocks.artwork).toHaveBeenCalledWith( + expect.objectContaining({ provider, apiKey: secret }), + expect.objectContaining({ + ...sampleAnalysis, + artworkProvider: `${provider}_byok`, + }), + ) + expect(mocks.complete).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + selectedFiles: row.selected_files, + artifactPath: 'new.png', + }), + ) + expect(mocks.remove).toHaveBeenCalledWith(expect.anything(), ['old.png']) + expect(JSON.stringify(mocks.complete.mock.calls)).not.toContain(secret) + expect(JSON.stringify(mocks.audit.mock.calls)).not.toContain(secret) + }, + ) + + it('records the actual twelve-panel image count', async () => { + mocks.owned.mockResolvedValue({ + ...row, + analysis: getSampleExplanation(12).analysis, + }) + expect((await POST(request(), context)).status).toBe(200) + expect(mocks.audit).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + metadata: expect.objectContaining({ imageCount: 12 }), + }), + ) + }) + + it('cleans rejected concurrent artwork without replacing the current comic', async () => { + mocks.complete.mockRejectedValue( + Object.assign(new Error('artwork_conflict'), { + code: 'artwork_conflict', + }), + ) + expect((await POST(request(), context)).status).toBe(409) + expect(mocks.remove).toHaveBeenCalledExactlyOnceWith(expect.anything(), [ + 'new.png', + ]) + expect(mocks.fail).not.toHaveBeenCalled() + }) + + it('checks ownership and current private-repository access before any provider call', async () => { + mocks.access.mockRejectedValue({ status: 403 }) + expect((await POST(request(), context)).status).toBe(403) + expect(mocks.owned).toHaveBeenCalledWith(expect.anything(), 'comic', 'user') + expect(mocks.artwork).not.toHaveBeenCalled() + expect(mocks.upload).not.toHaveBeenCalled() + }) + + it('preserves an existing comic on provider failure without returning or logging an upstream key', async () => { + const errors = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined) + mocks.artwork.mockRejectedValue({ + code: 'image_provider_quota_reached', + details: { responseBody: secret }, + }) + const response = await POST(request(), context) + expect(response.status).toBe(429) + expect(await response.text()).not.toContain(secret) + expect(JSON.stringify(errors.mock.calls)).not.toContain(secret) + expect(mocks.complete).not.toHaveBeenCalled() + expect(mocks.fail).not.toHaveBeenCalled() + expect(mocks.remove).not.toHaveBeenCalled() + errors.mockRestore() + }) + + it('cleans a newly uploaded artifact if saving fails, keeping the old artifact', async () => { + const errors = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined) + mocks.complete.mockRejectedValue(new Error('database unavailable')) + expect((await POST(request(), context)).status).toBe(500) + expect(mocks.remove).toHaveBeenCalledExactlyOnceWith(expect.anything(), [ + 'new.png', + ]) + expect(mocks.fail).not.toHaveBeenCalled() + errors.mockRestore() + }) + + it('rejects obsolete provider credentials before generating images', async () => { + expect((await POST(request('cloudflare'), context)).status).toBe(400) + expect(mocks.artwork).not.toHaveBeenCalled() + }) +}) diff --git a/apps/web/src/app/api/v1/explanations/[id]/artwork/route.ts b/apps/web/src/app/api/v1/explanations/[id]/artwork/route.ts index 782c154..e099ce4 100644 --- a/apps/web/src/app/api/v1/explanations/[id]/artwork/route.ts +++ b/apps/web/src/app/api/v1/explanations/[id]/artwork/route.ts @@ -5,15 +5,13 @@ import { failExplanation, getOwnedExplanation, recordAuditEvent, - recordUsage, removeArtifacts, uploadComicArtifact, } from '@comic-code/database' import { regenerateArtworkRequestSchema } from '@comic-code/contracts' -import { githubRequestStatus, preparePullRequest } from '@comic-code/github' +import { githubRequestStatus } from '@comic-code/github' import { requireRequestSession } from '@/lib/auth/session' -import { getServerEnv } from '@/lib/env' import { assertSameOrigin, HttpError, @@ -29,6 +27,7 @@ type RouteContext = { params: Promise<{ id: string }> } export async function POST(request: Request, context: RouteContext) { let stage = 'request' let explanationId: string | undefined + let preserveExistingComic = false try { assertSameOrigin(request) const session = await requireRequestSession(request) @@ -43,6 +42,10 @@ export async function POST(request: Request, context: RouteContext) { explanationId = id const database = databaseClient() const row = await getOwnedExplanation(database, id, session.userId) + preserveExistingComic = + row.status === 'completed' && + Boolean(row.analysis) && + Boolean(row.final_artifact_path) if (!['completed', 'failed'].includes(row.status) || !row.analysis) { throw new HttpError(409, 'explanation_not_ready') } @@ -58,62 +61,21 @@ export async function POST(request: Request, context: RouteContext) { await github.getInstallationId(row.github_owner, row.github_repository) } - stage = 'code_preparation' - const prepared = await preparePullRequest({ - client: github, - coordinate: { - owner: row.github_owner, - repository: row.github_repository, - pullRequestNumber: row.pull_request_number, - }, - expectedHeadSha: row.head_sha, - selectedFiles: row.selected_files, - allowPublicFallback: !access.isPrivate, - fallbackAccessToken: session.accessToken, - }) - - // Load native image tooling only after authentication and repository access - // checks. This keeps credentials and provider work outside unauthenticated - // requests and avoids loading Sharp in routes that will be rejected early. + // Illustrate the existing storyboard. No raw source or additional analysis + // request is needed; repository access above still protects private comics. stage = 'runtime_dependencies' - const { - analyzeCloudflareComic, - cloudflareAnalysisModel, - cloudflareImageModel, - composeComic, - createSafetyIdentifier, - generateCloudflarePanelArtwork, - } = await import('@comic-code/comic') - - stage = 'code_analysis' - const analyzed = await analyzeCloudflareComic( - { - title: prepared.maskedTitle, - description: prepared.maskedDescription, - baseSha: prepared.snapshot.baseSha, - headSha: prepared.snapshot.headSha, - evidence: prepared.evidence, - excludedFiles: prepared.excludedFiles, - safetyIdentifier: createSafetyIdentifier( - session.userId, - getServerEnv().SAFETY_IDENTIFIER_SECRET, - ), - }, - { - accountId: parsed.data.accountId, - apiToken: parsed.data.apiToken, - }, + const { composeComic, generateByokPanelArtwork } = await import( + '@comic-code/comic' ) const analysis = { - ...analyzed.analysis, - artworkProvider: 'cloudflare_byok', - } as const + ...row.analysis, + artworkProvider: `${parsed.data.provider}_byok` as + | 'openai_byok' + | 'gemini_byok', + artworkModel: parsed.data.model, + } stage = 'image_generation' - const artwork = await generateCloudflarePanelArtwork({ - accountId: parsed.data.accountId, - apiToken: parsed.data.apiToken, - analysis, - }) + const artwork = await generateByokPanelArtwork(parsed.data, analysis) stage = 'composition' const comic = await composeComic(analysis, artwork) const artifactPath = await uploadComicArtifact( @@ -128,10 +90,11 @@ export async function POST(request: Request, context: RouteContext) { explanationId: id, analysis, excludedFiles: analysis.excludedFiles, - selectedFiles: prepared.selectedFiles, + selectedFiles: row.selected_files, artifactPath, + expectedArtifactPath: row.final_artifact_path, progressMessage: - 'Comic ready · code analyzed and illustrated with your Cloudflare credits', + 'Comic ready · illustrated with your own image API key', }) } catch (error) { await removeArtifacts(database, [artifactPath]).catch(() => undefined) @@ -143,28 +106,14 @@ export async function POST(request: Request, context: RouteContext) { () => undefined, ) } - await recordUsage(database, { - explanationId: id, - userId: session.userId, - model: `${cloudflareAnalysisModel}:byok`, - imageModel: `${cloudflareImageModel}:byok`, - inputTokens: - analyzed.usage.analysis.inputTokens + - analyzed.usage.verification.inputTokens, - outputTokens: - analyzed.usage.analysis.outputTokens + - analyzed.usage.verification.outputTokens, - imageCount: 4, - retryCount: 0, - }).catch(() => undefined) await recordAuditEvent(database, { explanationId: id, actorUserId: session.userId, eventType: 'byok_artwork_generated', metadata: { - provider: 'cloudflare', - codeAnalyzed: true, - imageCount: 4, + provider: parsed.data.provider, + model: parsed.data.model, + imageCount: analysis.panels.length, }, }).catch(() => undefined) @@ -178,11 +127,14 @@ export async function POST(request: Request, context: RouteContext) { typeof error.code === 'string' ? error.code : undefined + if (providerCode === 'artwork_conflict') + return routeErrorResponse(new HttpError(409, 'artwork_conflict')) if ( providerCode === 'image_provider_auth_failed' || providerCode === 'image_provider_quota_reached' || providerCode === 'image_provider_unavailable' || - providerCode === 'cloudflare_analysis_failed' + providerCode === 'image_provider_model_unavailable' || + providerCode === 'image_provider_rejected' ) { const status = providerCode === 'image_provider_auth_failed' @@ -190,30 +142,14 @@ export async function POST(request: Request, context: RouteContext) { : providerCode === 'image_provider_quota_reached' ? 429 : 502 - const details = - error && typeof error === 'object' && 'details' in error - ? (error.details as { - model?: string - status?: number - statusText?: string - responseBody?: string - }) - : undefined - const providerStatus = details?.status - ? `${details.status}${details.statusText ? ` ${details.statusText}` : ''}` - : 'request failed' - const detail = - `Cloudflare Workers AI ${providerStatus}${details?.model ? ` for ${details.model}` : ''}: ${details?.responseBody?.trim() || providerCode}`.slice( - 0, - 4_000, - ) - if (explanationId) { + const detail = providerCode + if (explanationId && !preserveExistingComic) { await failExplanation(databaseClient(), { explanationId, errorCode: providerCode, errorDetail: detail, }).catch((failure) => { - console.error('Could not persist Cloudflare failure', { + console.error('Could not persist image failure', { explanationId, errorMessage: failure instanceof Error @@ -222,11 +158,9 @@ export async function POST(request: Request, context: RouteContext) { }) }) } - console.error('Cloudflare BYOK request failed', { + console.error('Image BYOK request failed', { stage, providerCode, - providerStatus, - model: details?.model, }) return routeErrorResponse(new HttpError(status, providerCode, detail)) } @@ -242,32 +176,26 @@ export async function POST(request: Request, context: RouteContext) { } if ( error instanceof Error && - error.message.includes('no executable code evidence') + error.message.includes('no readable executable source') ) { return routeErrorResponse(new HttpError(400, 'no_executable_code')) } - console.error('Cloudflare BYOK request failed', { + console.error('Image BYOK request failed', { stage, errorName: error instanceof Error ? error.name : 'UnknownError', - errorMessage: - error instanceof Error ? error.message.slice(0, 200) : 'unknown', }) if ( explanationId && - [ - 'runtime_dependencies', - 'code_analysis', - 'image_generation', - 'composition', - ].includes(stage) + !preserveExistingComic && + ['runtime_dependencies', 'image_generation', 'composition'].includes( + stage, + ) ) { const prefix = stage === 'runtime_dependencies' ? 'Comic Code image runtime error:' : `Comic Code artwork error during ${stage}:` - const detail = `${prefix} ${ - error instanceof Error ? error.message : 'Unknown runtime failure' - }`.slice(0, 4_000) + const detail = `${prefix} Please retry; your existing comic is preserved.` await failExplanation(databaseClient(), { explanationId, errorCode: diff --git a/apps/web/src/app/api/v1/explanations/route.test.ts b/apps/web/src/app/api/v1/explanations/route.test.ts new file mode 100644 index 0000000..ee20dc9 --- /dev/null +++ b/apps/web/src/app/api/v1/explanations/route.test.ts @@ -0,0 +1,259 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => ({ + analyze: vi.fn(), + github: { + assertUserCanReadRepository: vi.fn(), + getRepositorySnapshot: vi.fn(), + }, + prepareRepository: vi.fn(), + createExplanation: vi.fn(), + getExisting: vi.fn(), + countRecent: vi.fn(), + saveScan: vi.fn(), + saveAnalysis: vi.fn(), + fail: vi.fn(), + setRun: vi.fn(), + trigger: vi.fn(), + idempotency: vi.fn(), +})) + +vi.mock('@trigger.dev/sdk', () => ({ + idempotencyKeys: { create: vi.fn(async (key) => key) }, + tasks: { trigger: mocks.trigger }, +})) +vi.mock('@comic-code/comic', () => ({ + createDeterministicComicAnalysis: mocks.analyze, + createSafetyIdentifier: () => 'safe', +})) +vi.mock('@comic-code/github', () => ({ + prepareRepository: mocks.prepareRepository, + githubRequestStatus: (error: { status?: number }) => error?.status, +})) +vi.mock('@comic-code/database', () => ({ + createExplanation: mocks.createExplanation, + getExplanationByIdempotencyKey: mocks.getExisting, + countRecentExplanations: mocks.countRecent, + saveRepositoryScan: mocks.saveScan, + saveExplanationAnalysis: mocks.saveAnalysis, + failExplanation: mocks.fail, + setExplanationTriggerRun: mocks.setRun, + recordAuditEvent: vi.fn(async () => undefined), +})) +vi.mock('@/lib/auth/session', () => ({ + requireRequestSession: async () => ({ + userId: 'user', + accessToken: 'test-token', + }), + UnauthorizedError: class extends Error {}, +})) +vi.mock('@/lib/env', () => ({ + getServerEnv: () => ({ + SAFETY_IDENTIFIER_SECRET: 'test-secret', + NEXT_PUBLIC_APP_URL: 'https://example.com', + }), +})) +vi.mock('@/lib/server', () => ({ + databaseClient: () => ({}), + githubClient: () => mocks.github, + explanationIdempotencyKey: mocks.idempotency, + publicExplanation: async (row: unknown) => row, +})) + +import { POST } from './route' + +const sha = 'a'.repeat(40) +function request(commitSha: string | null = sha, panelCount = 4) { + return new Request('https://example.com/api/v1/explanations', { + method: 'POST', + headers: { + origin: 'https://example.com', + 'content-type': 'application/json', + }, + body: JSON.stringify({ + owner: 'owner', + repository: 'repo', + ref: 'feature/fix', + commitSha: commitSha ?? undefined, + panelCount, + }), + }) +} + +beforeEach(() => { + vi.resetAllMocks() + mocks.analyze.mockReturnValue({ claims: [] }) + mocks.github.assertUserCanReadRepository.mockResolvedValue({ + isPrivate: false, + }) + // Inspection captured SHA a; the branch can now point at SHA b. + mocks.github.getRepositorySnapshot.mockResolvedValue({ + owner: 'owner', + repository: 'repo', + defaultBranch: 'main', + resolvedRef: sha, + commitSha: sha, + }) + mocks.getExisting.mockResolvedValue(null) + mocks.idempotency.mockImplementation((_user, input) => + input.forceRegenerate ? 'retry-key' : 'stable-key', + ) + mocks.countRecent.mockResolvedValue(0) + mocks.prepareRepository.mockResolvedValue({ + snapshot: { + owner: 'owner', + repository: 'repo', + resolvedRef: 'feature/fix', + commitSha: sha, + }, + maskedDescription: '', + evidence: [], + excludedFiles: [], + selectedFiles: ['src/index.ts'], + totalTreeFiles: 1, + excludedFileCount: 0, + scannedCharacters: 100, + }) + mocks.createExplanation.mockResolvedValue({ + id: 'explanation', + trigger_run_id: null, + status: 'queued', + }) + mocks.saveScan.mockResolvedValue(undefined) + mocks.saveAnalysis.mockResolvedValue(undefined) + mocks.fail.mockResolvedValue(undefined) + mocks.setRun.mockResolvedValue(undefined) + mocks.trigger.mockResolvedValue({ id: 'run' }) +}) + +describe('captured repository generation and dispatch recovery', () => { + it('keeps the selected twelve-panel count in analysis and recovery metadata', async () => { + expect((await POST(request(sha, 12))).status).toBe(202) + expect(mocks.analyze).toHaveBeenCalledWith( + expect.objectContaining({ panelCount: 12 }), + ) + expect(mocks.saveScan).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + scanSummary: expect.objectContaining({ panelCount: 12 }), + }), + ) + expect(mocks.trigger).toHaveBeenCalledWith( + 'generate-comic', + { explanationId: 'explanation' }, + expect.anything(), + ) + }) + it('uses the inspected commit even after the branch moves', async () => { + const response = await POST(request()) + expect(response.status).toBe(202) + expect(mocks.github.getRepositorySnapshot).toHaveBeenCalledWith( + expect.objectContaining({ ref: sha }), + true, + 'test-token', + ) + expect(mocks.prepareRepository).toHaveBeenCalledWith( + expect.objectContaining({ + expectedCommitSha: sha, + coordinate: expect.objectContaining({ ref: 'feature/fix' }), + }), + ) + expect(mocks.createExplanation).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ commitSha: sha, resolvedRef: 'feature/fix' }), + ) + }) + + it('rejects generation without an inspected SHA', async () => { + const response = await POST(request('invalid')) + expect(response.status).toBe(400) + expect(mocks.trigger).not.toHaveBeenCalled() + }) + + it('rejects a missing inspected SHA before GitHub or dispatch', async () => { + expect((await POST(request(null))).status).toBe(400) + expect(mocks.github.getRepositorySnapshot).not.toHaveBeenCalled() + expect(mocks.trigger).not.toHaveBeenCalled() + }) + + it('rejects an unexpected commit returned by GitHub', async () => { + mocks.github.getRepositorySnapshot.mockResolvedValue({ + commitSha: 'b'.repeat(40), + }) + expect((await POST(request())).status).toBe(409) + expect(mocks.prepareRepository).not.toHaveBeenCalled() + expect(mocks.trigger).not.toHaveBeenCalled() + }) + + it('marks a dispatch failure retryable and allows the next ordinary request', async () => { + mocks.trigger.mockRejectedValueOnce(new Error('dispatch unavailable')) + expect((await POST(request())).status).toBe(500) + expect(mocks.fail).toHaveBeenCalledWith(expect.anything(), { + explanationId: 'explanation', + errorCode: 'generation_dispatch_failed', + onlyUndispatched: true, + }) + mocks.getExisting.mockResolvedValue({ id: 'explanation', status: 'failed' }) + mocks.createExplanation.mockResolvedValue({ + id: 'retry-explanation', + trigger_run_id: null, + status: 'queued', + }) + expect((await POST(request())).status).toBe(202) + expect(mocks.trigger).toHaveBeenLastCalledWith( + 'generate-comic', + { explanationId: 'retry-explanation' }, + expect.objectContaining({ idempotencyKey: 'retry-key' }), + ) + }) + + it('marks a persistence failure before dispatch retryable', async () => { + mocks.saveScan.mockRejectedValueOnce(new Error('database unavailable')) + expect((await POST(request())).status).toBe(500) + expect(mocks.fail).toHaveBeenCalled() + expect(mocks.trigger).not.toHaveBeenCalled() + }) + + it('recovers an interrupted row with analysis but no recorded run', async () => { + mocks.getExisting.mockResolvedValue({ + expires_at: new Date(Date.now() + 86400000).toISOString(), + id: 'interrupted', + status: 'illustrating', + trigger_run_id: null, + analysis: { claims: [] }, + }) + expect((await POST(request())).status).toBe(200) + expect(mocks.trigger).toHaveBeenCalledWith( + 'generate-comic', + { explanationId: 'interrupted' }, + expect.objectContaining({ idempotencyKey: 'stable-key' }), + ) + expect(mocks.createExplanation).not.toHaveBeenCalled() + }) + + it('creates a fresh record instead of returning an expired completed comic', async () => { + mocks.getExisting.mockResolvedValue({ + id: 'expired', + status: 'completed', + expires_at: '2000-01-01T00:00:00.000Z', + }) + expect((await POST(request())).status).toBe(202) + expect(mocks.createExplanation).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ idempotencyKey: 'retry-key' }), + ) + expect(mocks.trigger).toHaveBeenCalled() + }) + + it('reuses a successfully dispatched explanation without duplicating the job', async () => { + mocks.getExisting.mockResolvedValue({ + expires_at: new Date(Date.now() + 86400000).toISOString(), + id: 'existing', + status: 'illustrating', + trigger_run_id: 'run', + }) + expect((await POST(request())).status).toBe(200) + expect(mocks.trigger).not.toHaveBeenCalled() + expect(mocks.createExplanation).not.toHaveBeenCalled() + }) +}) diff --git a/apps/web/src/app/api/v1/explanations/route.ts b/apps/web/src/app/api/v1/explanations/route.ts index 81f47b4..e188583 100644 --- a/apps/web/src/app/api/v1/explanations/route.ts +++ b/apps/web/src/app/api/v1/explanations/route.ts @@ -1,17 +1,25 @@ import { idempotencyKeys, tasks } from '@trigger.dev/sdk' +import { + createDeterministicComicAnalysis, + createSafetyIdentifier, +} from '@comic-code/comic' import { createExplanationRequestSchema } from '@comic-code/contracts' import { countRecentExplanations, createExplanation, + failExplanation, getExplanationByIdempotencyKey, recordAuditEvent, + saveExplanationAnalysis, + saveRepositoryScan, setExplanationTriggerRun, } from '@comic-code/database' -import { githubRequestStatus, selectEligibleFiles } from '@comic-code/github' +import { githubRequestStatus, prepareRepository } from '@comic-code/github' import type { generateComicTask } from '@/trigger/generate-comic' import { requireRequestSession } from '@/lib/auth/session' +import { getServerEnv } from '@/lib/env' import { assertSameOrigin, HttpError, @@ -25,13 +33,39 @@ import { publicExplanation, } from '@/lib/server' +export const maxDuration = 300 + +async function dispatchExplanation( + database: ReturnType, + explanationId: string, + idempotencyKey: string, +) { + const triggerIdempotencyKey = await idempotencyKeys.create(idempotencyKey, { + scope: 'global', + }) + const handle = await tasks.trigger( + 'generate-comic', + { explanationId }, + { + idempotencyKey: triggerIdempotencyKey, + idempotencyKeyTTL: '30d', + tags: [`explanation_${explanationId}`], + }, + ) + await setExplanationTriggerRun(database, explanationId, handle.id) + return handle.id +} + export async function POST(request: Request) { + let pendingExplanationId: string | undefined try { assertSameOrigin(request) const session = await requireRequestSession(request) - const parsedRequest = createExplanationRequestSchema.parse( + const parsed = createExplanationRequestSchema.safeParse( await request.json(), ) + if (!parsed.success) throw new HttpError(400, 'invalid_generation_request') + const parsedRequest = parsed.data const github = githubClient() const access = await github.assertUserCanReadRepository( session.accessToken, @@ -39,62 +73,33 @@ export async function POST(request: Request) { parsedRequest.repository, ) const allowPublicFallback = !access.isPrivate - const coordinate = { - owner: parsedRequest.owner, - repository: parsedRequest.repository, - pullRequestNumber: parsedRequest.pullRequestNumber, - } - const [snapshot, changedFiles] = await Promise.all([ - github.getPullRequestSnapshot( - coordinate, + const snapshot = await github + .getRepositorySnapshot( + { ...parsedRequest, ref: parsedRequest.commitSha }, allowPublicFallback, session.accessToken, - ), - github.listChangedFiles( - coordinate, - allowPublicFallback, - session.accessToken, - ), - ]).catch((error: unknown) => { - if (access.isPrivate) { - throw new HttpError(403, 'github_app_installation_required') - } - throw error - }) - if ( - snapshot.headSha.toLowerCase() !== parsedRequest.headSha.toLowerCase() - ) { - throw new HttpError(409, 'pull_request_changed') - } - - const selection = selectEligibleFiles( - changedFiles, - parsedRequest.selectedFiles, - ) + ) + .catch((error: unknown) => { + if (access.isPrivate) { + throw new HttpError(403, 'github_app_installation_required') + } + throw error + }) if ( - parsedRequest.selectedFiles && - selection.eligible.length !== new Set(parsedRequest.selectedFiles).size + snapshot.commitSha.toLowerCase() !== parsedRequest.commitSha.toLowerCase() ) { - throw new HttpError(400, 'invalid_selected_files') - } - if (selection.eligible.length === 0) { - throw new HttpError(400, 'no_executable_code') + throw new HttpError(409, 'repository_changed') } - const changedLines = selection.eligible.reduce( - (sum, file) => sum + file.changes, - 0, - ) - if (changedLines > 3_000) { - throw new HttpError(413, 'change_too_large') - } - const resolvedRequest = { ...parsedRequest, - selectedFiles: selection.eligible.map((file) => file.path), + owner: snapshot.owner, + repository: snapshot.repository, + ref: parsedRequest.ref ?? snapshot.defaultBranch, } - const idempotencyKey = explanationIdempotencyKey( + let idempotencyKey = explanationIdempotencyKey( session.userId, resolvedRequest, + snapshot.commitSha, ) const database = databaseClient() const existing = await getExplanationByIdempotencyKey( @@ -102,10 +107,45 @@ export async function POST(request: Request) { idempotencyKey, session.userId, ) + if ( + existing && + Date.parse(existing.expires_at) > Date.now() && + existing.status !== 'failed' && + existing.status !== 'canceled' + ) { + if ( + !existing.trigger_run_id && + existing.status !== 'completed' && + existing.analysis + ) { + // Recover rows persisted before a process interruption. Trigger's key + // prevents a second job if the first dispatch was already accepted. + pendingExplanationId = existing.id + existing.trigger_run_id = await dispatchExplanation( + database, + existing.id, + idempotencyKey, + ) + pendingExplanationId = undefined + } + if (existing.trigger_run_id || existing.status === 'completed') { + return jsonNoStore( + { explanation: await publicExplanation(existing) }, + { status: 200 }, + ) + } + // An interrupted scan without analysis cannot be dispatched safely. + await failExplanation(database, { + explanationId: existing.id, + errorCode: 'generation_dispatch_failed', + onlyUndispatched: true, + }) + } if (existing) { - return jsonNoStore( - { explanation: await publicExplanation(existing) }, - { status: 200 }, + idempotencyKey = explanationIdempotencyKey( + session.userId, + { ...resolvedRequest, forceRegenerate: true }, + snapshot.commitSha, ) } @@ -116,39 +156,81 @@ export async function POST(request: Request) { ) if (recentCount >= 25) throw new HttpError(429, 'daily_quota_reached') + // Scan while the authenticated GitHub OAuth token is available. Trigger + // payloads intentionally contain only the explanation UUID, so deferring + // this step would force public repositories onto GitHub's tiny anonymous + // rate limit whenever the App is not installed on that repository. + const prepared = await prepareRepository({ + client: github, + coordinate: resolvedRequest, + expectedCommitSha: snapshot.commitSha, + allowPublicFallback, + fallbackAccessToken: session.accessToken, + }) + const analysis = createDeterministicComicAnalysis({ + repository: `${prepared.snapshot.owner}/${prepared.snapshot.repository}`, + description: prepared.maskedDescription, + ref: prepared.snapshot.resolvedRef, + commitSha: prepared.snapshot.commitSha, + panelCount: parsedRequest.panelCount, + evidence: prepared.evidence, + excludedFiles: prepared.excludedFiles, + safetyIdentifier: createSafetyIdentifier( + session.userId, + getServerEnv().SAFETY_IDENTIFIER_SECRET, + ), + }) + const scanSummary = { + panelCount: parsedRequest.panelCount, + totalTreeFiles: prepared.totalTreeFiles, + selectedFileCount: prepared.selectedFiles.length, + excludedFileCount: prepared.excludedFileCount, + scannedCharacters: prepared.scannedCharacters, + commitSha: prepared.snapshot.commitSha, + ref: prepared.snapshot.resolvedRef, + } const explanation = await createExplanation(database, { userId: session.userId, request: resolvedRequest, - baseSha: snapshot.baseSha, + commitSha: snapshot.commitSha, + resolvedRef: resolvedRequest.ref, isPrivate: access.isPrivate, idempotencyKey, + scanSummary, + }) + if (!explanation.trigger_run_id) pendingExplanationId = explanation.id + await saveRepositoryScan(database, { + explanationId: explanation.id, + selectedFiles: prepared.selectedFiles, + excludedFiles: prepared.excludedFiles, + scanSummary, }) + await saveExplanationAnalysis(database, { + explanationId: explanation.id, + analysis, + }) + explanation.analysis = analysis + explanation.selected_files = prepared.selectedFiles + explanation.excluded_files = prepared.excludedFiles + explanation.status = 'illustrating' + explanation.progress_percent = 60 + explanation.progress_message = 'Storyboard verified; creating artwork' if (!explanation.trigger_run_id) { - const triggerIdempotencyKey = await idempotencyKeys.create( + explanation.trigger_run_id = await dispatchExplanation( + database, + explanation.id, idempotencyKey, - { - scope: 'global', - }, ) - const handle = await tasks.trigger( - 'generate-comic', - { explanationId: explanation.id }, - { - idempotencyKey: triggerIdempotencyKey, - idempotencyKeyTTL: '30d', - tags: [`explanation_${explanation.id}`], - }, - ) - await setExplanationTriggerRun(database, explanation.id, handle.id) - explanation.trigger_run_id = handle.id + pendingExplanationId = undefined } await recordAuditEvent(database, { explanationId: explanation.id, actorUserId: session.userId, - eventType: 'generation_requested', + eventType: 'repository_generation_requested', metadata: { - selectedFileCount: resolvedRequest.selectedFiles.length, - changedLines, + ref: parsedRequest.ref ?? snapshot.defaultBranch, + commitSha: snapshot.commitSha, + creatorCreditsUsed: false, }, }).catch(() => undefined) @@ -157,6 +239,13 @@ export async function POST(request: Request) { { status: 202 }, ) } catch (error) { + if (pendingExplanationId) { + await failExplanation(databaseClient(), { + explanationId: pendingExplanationId, + errorCode: 'generation_dispatch_failed', + onlyUndispatched: true, + }).catch(() => undefined) + } const status = githubRequestStatus(error) if (status === 401) { return routeErrorResponse(new HttpError(401, 'github_reconnect_required')) diff --git a/apps/web/src/app/api/v1/github/pull-request/route.ts b/apps/web/src/app/api/v1/github/pull-request/route.ts deleted file mode 100644 index eb3be87..0000000 --- a/apps/web/src/app/api/v1/github/pull-request/route.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { - githubRequestStatus, - parseGitHubPullRequestUrl, - selectEligibleFiles, -} from '@comic-code/github' - -import { requireRequestSession } from '@/lib/auth/session' -import { HttpError, jsonNoStore, routeErrorResponse } from '@/lib/http' -import { githubClient } from '@/lib/server' - -export async function GET(request: Request) { - try { - const session = await requireRequestSession(request) - const url = new URL(request.url).searchParams.get('url') - const coordinate = url ? parseGitHubPullRequestUrl(url) : null - if (!coordinate) throw new HttpError(400, 'invalid_pull_request_url') - - const github = githubClient() - const access = await github.assertUserCanReadRepository( - session.accessToken, - coordinate.owner, - coordinate.repository, - ) - const allowPublicFallback = !access.isPrivate - const [snapshot, files] = await Promise.all([ - github.getPullRequestSnapshot( - coordinate, - allowPublicFallback, - session.accessToken, - ), - github.listChangedFiles( - coordinate, - allowPublicFallback, - session.accessToken, - ), - ]).catch((error: unknown) => { - if (access.isPrivate) { - throw new HttpError(403, 'github_app_installation_required') - } - throw error - }) - const { eligible, excluded } = selectEligibleFiles(files) - if (eligible.length === 0) { - throw new HttpError(400, 'no_executable_code') - } - - return jsonNoStore({ - pullRequest: { - ...coordinate, - title: snapshot.title, - htmlUrl: snapshot.htmlUrl, - isPrivate: access.isPrivate, - baseSha: snapshot.baseSha, - headSha: snapshot.headSha, - files: eligible.slice(0, 20).map((file) => ({ - path: file.path, - status: file.status, - additions: file.additions, - deletions: file.deletions, - changes: file.changes, - })), - excludedFileCount: excluded.length, - selectedChangedLines: eligible - .slice(0, 20) - .reduce((sum, file) => sum + file.changes, 0), - }, - }) - } catch (error) { - const status = githubRequestStatus(error) - if (status === 401) { - return routeErrorResponse(new HttpError(401, 'github_reconnect_required')) - } - if (status === 403) { - return routeErrorResponse(new HttpError(403, 'github_access_denied')) - } - if (status === 404) { - return routeErrorResponse(new HttpError(404, 'repository_not_found')) - } - return routeErrorResponse(error) - } -} diff --git a/apps/web/src/app/api/v1/github/repository/route.ts b/apps/web/src/app/api/v1/github/repository/route.ts new file mode 100644 index 0000000..1478a0e --- /dev/null +++ b/apps/web/src/app/api/v1/github/repository/route.ts @@ -0,0 +1,82 @@ +import { + githubRequestStatus, + parseGitHubRepositoryUrl, + selectRepositoryFiles, +} from '@comic-code/github' + +import { detectedLanguages } from '@/lib/repository-summary' + +import { requireRequestSession } from '@/lib/auth/session' +import { HttpError, jsonNoStore, routeErrorResponse } from '@/lib/http' +import { githubClient } from '@/lib/server' + +export async function GET(request: Request) { + try { + const session = await requireRequestSession(request) + const url = new URL(request.url).searchParams.get('url') + const coordinate = url ? parseGitHubRepositoryUrl(url) : null + if (!coordinate) throw new HttpError(400, 'invalid_repository_url') + + const github = githubClient() + const access = await github.assertUserCanReadRepository( + session.accessToken, + coordinate.owner, + coordinate.repository, + ) + const allowPublicFallback = !access.isPrivate + const snapshot = await github + .getRepositorySnapshot( + coordinate, + allowPublicFallback, + session.accessToken, + true, + ) + .catch((error: unknown) => { + if (access.isPrivate) { + throw new HttpError(403, 'github_app_installation_required') + } + throw error + }) + const tree = await github.listRepositoryFiles( + snapshot, + allowPublicFallback, + session.accessToken, + ) + const selection = selectRepositoryFiles(tree) + if (selection.selected.length === 0) { + throw new HttpError(400, 'no_executable_code') + } + + return jsonNoStore({ + repository: { + owner: snapshot.owner, + repository: snapshot.repository, + description: snapshot.description, + htmlUrl: snapshot.htmlUrl, + isPrivate: snapshot.isPrivate, + defaultBranch: snapshot.defaultBranch, + ref: snapshot.resolvedRef, + commitSha: snapshot.commitSha, + totalFiles: tree.length, + selectedFileCount: selection.selected.length, + excludedFileCount: selection.excluded.length, + representativeFiles: selection.selected.map((file) => file.path), + languages: detectedLanguages( + selection.selected.map((file) => file.path), + ), + }, + }) + } catch (error) { + const status = githubRequestStatus(error) + if (status === 401) { + return routeErrorResponse(new HttpError(401, 'github_reconnect_required')) + } + if (status === 403) { + return routeErrorResponse(new HttpError(403, 'github_access_denied')) + } + if (status === 404) { + return routeErrorResponse(new HttpError(404, 'repository_not_found')) + } + return routeErrorResponse(error) + } +} diff --git a/apps/web/src/app/extension/page.tsx b/apps/web/src/app/extension/page.tsx new file mode 100644 index 0000000..cfa2234 --- /dev/null +++ b/apps/web/src/app/extension/page.tsx @@ -0,0 +1,69 @@ +import Link from 'next/link' +import { BrandMark } from '@/components/brand-mark' + +export default function ExtensionPreviewPage() { + return ( +
+ +
+
+

+ A small panel. +
+ A clearer picture. +

+

+ Explore the Chrome side panel in your browser. Switch between the + story, its source files, and the evidence behind every panel. +

+
+ Sample mode. Zero API calls. +

+ This is the built extension with illustrative data. It doesn’t + contact GitHub or image providers, store credentials, or require + Chrome permissions. +

+
+
    +
  • Try the Explain, Story and Evidence tabs.
  • +
  • Use “View sample story” to see the comic.
  • +
  • + Choose twelve panels for a detailed story, or four for a quick + view. +
  • +
  • + In Story, open “Use your own images · no API key”. Load sample + artwork or choose your own files, compose the comic and download + it. +
  • +
  • + Expand “API key / BYOK” to see the image provider, model and key + fields. Key entry is disabled in this sample; use the installed + extension for real AI generation. +
  • +
+
+
+
+ + + + Comic Code · Chrome side panel preview +
+