Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(chrome-extension): add auxiliary pages and store assets
Richie McIlroy0018386ba68d
diff --git a/apps/chrome-extension/STORE_LISTING.md b/apps/chrome-extension/STORE_LISTING.mdnew file mode 100644index 000000000..314c176b2--- /dev/null+++ b/apps/chrome-extension/STORE_LISTING.md@@ -0,0 +1,145 @@+# Chrome Web Store Listing++Everything below is ready to paste into the Chrome Web Store Developer Dashboard. Keep claims in sync with the extension version being submitted.++## Store Fields++Name: Cap - Screen Recorder & Screen Capture++Short name: Cap++Summary (132 char max, mirrors manifest description): Free, open source screen recorder. Capture your screen, tab, camera & mic in Chrome and share a video link the moment you stop.++Category: Productivity → Communication++Language: English++Website: https://cap.so++Support: https://cap.so/docs++Privacy policy: https://cap.so/privacy++## Detailed Description (paste as plain text)++Cap is the open source screen recorder for Chrome. Record your screen, a window, the current browser tab, or camera-only video. Your recording uploads while you record, so a shareable link is ready the moment you stop. No exports, no waiting, no switching tools.++WHY PEOPLE SWITCH TO CAP++Cap is a Loom alternative built on a simple idea: your recordings belong to you. Cap is fully open source, lets you connect your own storage, and gives you a fast, lightweight recorder that stays out of your way.++• Truly open source: inspect every line of code, contribute, or self-host the entire stack.+• Own your recordings: use Cap Cloud or connect your own S3 bucket. No vendor lock-in, ever.+• Instant share links: video uploads as you record, so the link is live the second you stop.+• Cap AI: auto-generated titles, summaries, clickable chapters, and searchable transcripts for every recording.+• Built for teams: comments, reactions, viewer analytics, password-protected shares, custom domains, and team workspaces.+• Switching from Loom? Import your existing Loom videos directly into Cap with the built-in importer.++WHAT YOU CAN RECORD++• Current browser tab: perfect for web app demos and bug reports.+• Full screen or a single window.+• Camera-only video for quick personal updates.+• Microphone audio, system audio (where Chrome supports it), and a webcam overlay for walkthroughs.++MADE FOR EVERYDAY VIDEO++Screen recording for async standups, code reviews, bug reports, product demos, customer support, onboarding, tutorials, design feedback, and sales outreach. Record once, share a link, and skip the meeting.++HOW IT WORKS++1. Click the Cap icon and pick tab, screen, window, or camera.+2. Choose your microphone and camera, then hit record.+3. Stop recording. Your video is already uploaded to your Cap workspace and the share link is ready.++CAP EVERYWHERE++The extension is part of the Cap platform: native desktop apps for macOS and Windows, a web recorder, and a shared library at cap.so. Recordings stay connected to your Cap account wherever you capture them.++Cap is free to get started. Upgrade to Cap Pro for unlimited recording length, Cap AI, custom domains, custom S3 storage, and team features.++Open source on GitHub: https://github.com/CapSoftware/Cap++## SEO Positioning++Primary keywords (use naturally in the description, never stuffed):++- screen recorder / screen recorder for Chrome+- screen capture / screen recording+- record browser tab+- screen recorder with camera and microphone+- webcam recorder+- video messaging / async video+- Loom alternative (used exactly once in the detailed description; never in the name, summary, or screenshot text)++Name strategy: "Cap - Screen Recorder & Screen Capture" leads with the brand and covers the two highest-volume queries, matching how the top competitor titles its listing without keyword spam.++Summary strategy: front-loads "free, open source screen recorder" (differentiator + keyword), lists capture surfaces, and ends on the instant-share-link benefit.++Review-safety notes:++- Keep every claim true for the submitted build (system audio is "where Chrome supports it").+- Do not mention competitor names in metadata fields other than the single description mention.+- Do not claim "unlimited free": free tier has limits; Pro removes them.++## Icons++`public/icons/` is generated from the brand mark `apps/web/public/logos/logo-solo.svg`:++- icon-16/32/48: full-bleed, used for toolbar and favicon contexts.+- icon-128: 96x96 artwork centered with 16px transparent padding, per Chrome Web Store icon guidelines (this is the store listing icon).+- icon-256: same padded treatment at 2x.++Regenerate with rsvg-convert:++```sh+cd apps/chrome-extension/public/icons+for s in 16 32 48; do rsvg-convert -w $s -h $s ../../../web/public/logos/logo-solo.svg -o icon-$s.png; done+rsvg-convert -w 96 -h 96 --page-width 128 --page-height 128 --top 16 --left 16 ../../../web/public/logos/logo-solo.svg -o icon-128.png+rsvg-convert -w 192 -h 192 --page-width 256 --page-height 256 --top 32 --left 32 ../../../web/public/logos/logo-solo.svg -o icon-256.png+```++## Promotional Images++Store sources live in `store-assets/`. PNGs are full-bleed with square corners, as the store requires.++- promo-small.png: 440x280 small promo tile (required).+- promo-marquee.png: 1400x560 marquee tile (optional, needed for feature placement).++The SVG sources use the Neue Montreal fonts bundled in `public/fonts`. Regenerate with a fontconfig file that points at that directory:++```sh+cat > /tmp/cap-fonts.conf <<'EOF'+<?xml version="1.0"?>+<!DOCTYPE fontconfig SYSTEM "fonts.dtd">+<fontconfig>+ <dir>/path/to/Cap/apps/chrome-extension/public/fonts</dir>+ <dir>/System/Library/Fonts</dir>+ <cachedir>/tmp/cap-fc-cache</cachedir>+</fontconfig>+EOF+cd apps/chrome-extension/store-assets+FONTCONFIG_FILE=/tmp/cap-fonts.conf rsvg-convert -w 440 -h 280 promo-small.svg -o promo-small.png+FONTCONFIG_FILE=/tmp/cap-fonts.conf rsvg-convert -w 1400 -h 560 promo-marquee.svg -o promo-marquee.png+```++## Screenshot Plan++Use 1280x800 PNG screenshots, full bleed, square corners, no padding. Capture against a real page, not a blank tab.++1. In-page recorder panel open with the recording mode selector (tab / screen / camera) visible.+2. Recording setup showing microphone and camera selectors plus the system audio toggle.+3. Recording in progress with the floating recording bar and webcam overlay on a real page.+4. Upload/completion state with the share-link handoff.+5. The Cap share page (player, transcript/chapters) after a recording is available.++## Review Notes: Permission Justifications++- activeTab and scripting: show the recording controls overlay on the page the user is recording.+- tabCapture: record the current browser tab when the user selects tab recording.+- offscreen: run capture, encoding, and upload outside the recorder panel so recordings survive closing it.+- storage: remember account session, selected devices, and recording preferences.+- identity: sign the user in to their Cap account.+- host permissions: inject the recording overlay and camera preview on pages the user chooses to record.++Submission checklist: icon present (128px padded), summary under 132 chars, at least one 1280x800 screenshot, small promo tile uploaded, privacy policy URL set, permission justifications filled in.diff --git a/apps/chrome-extension/src/how-it-works/main.ts b/apps/chrome-extension/src/how-it-works/main.tsnew file mode 100644index 000000000..55f31874b--- /dev/null+++ b/apps/chrome-extension/src/how-it-works/main.ts@@ -0,0 +1,4 @@+import { mountPageNav } from "../shared/page-nav";+import "./styles.css";++mountPageNav("how-it-works");diff --git a/apps/chrome-extension/src/how-it-works/styles.css b/apps/chrome-extension/src/how-it-works/styles.cssnew file mode 100644index 000000000..6c2209e18--- /dev/null+++ b/apps/chrome-extension/src/how-it-works/styles.css@@ -0,0 +1,185 @@+@import "../shared/paper.css";++.bolt-body {+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ animation: draw 0.9s ease 0.15s forwards;+}++.spark-1 {+ animation-delay: 1.1s;+}++.spark-2 {+ animation-delay: 1.25s;+}++.spark-3 {+ animation-delay: 1.4s;+}++.steps {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 14px;+ width: min(680px, calc(100vw - 48px));+ margin: 36px 0 0;+ padding: 0;+ list-style: none;+}++.step {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 6px;+ padding: 20px 16px 18px;+ border: 1.5px solid var(--track);+ border-radius: 16px;+ background: rgba(255, 255, 255, 0.65);+ animation: fade-up 0.5s ease both;+}++.step:nth-child(1) {+ animation-delay: 0.2s;+}++.step:nth-child(2) {+ animation-delay: 0.3s;+}++.step:nth-child(3) {+ animation-delay: 0.4s;+}++.step-doodle {+ width: 44px;+ height: 44px;+ overflow: visible;+}++.doodle-stroke-sm {+ fill: none;+ stroke: var(--ink);+ stroke-width: 3;+ stroke-linecap: round;+ stroke-linejoin: round;+}++.record-dot {+ fill: var(--accent);+ animation: record-pulse 1.8s ease-in-out 1s infinite;+}++.upload-arrow {+ fill: none;+ stroke: var(--accent);+ stroke-width: 3;+ stroke-linecap: round;+ stroke-dasharray: 2 4.2;+ animation: march 1.1s linear infinite;+}++.arrow-head {+ stroke: var(--accent);+}++.link-piece {+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ animation: draw 0.5s ease 0.6s forwards;+}++.link-piece-2 {+ animation-delay: 0.8s;+}++.link-bar {+ stroke: var(--accent);+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ animation: draw 0.35s ease 1.05s forwards;+}++.step-count {+ font-size: 12px;+ font-weight: 500;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--ink-soft);+}++.step p {+ font-size: 13.5px;+ line-height: 1.45;+ color: var(--ink);+}++.tips-card {+ width: min(680px, calc(100vw - 48px));+ margin-top: 18px;+ animation-delay: 0.5s;+}++.tips {+ display: grid;+ gap: 10px;+ margin: 0;+ padding: 0;+ list-style: none;+}++.tips li {+ display: flex;+ align-items: baseline;+ gap: 10px;+ font-size: 14px;+ line-height: 1.5;+ color: var(--ink);+}++.tip-dot {+ width: 8px;+ height: 8px;+ flex: 0 0 auto;+ border-radius: 999px;+ background: var(--accent);+ transform: translateY(-1px);+}++.footnote {+ animation-delay: 0.6s;+}++@keyframes record-pulse {+ 0%,+ 100% {+ opacity: 1;+ }+ 50% {+ opacity: 0.35;+ }+}++@media (max-width: 720px) {+ .steps {+ grid-template-columns: 1fr;+ }+}++@media (prefers-reduced-motion: reduce) {+ .step,+ .tips-card,+ .bolt-body,+ .link-piece,+ .link-piece-2,+ .link-bar {+ animation-duration: 0.01ms;+ animation-delay: 0s;+ }++ .record-dot,+ .upload-arrow {+ animation: none;+ }+}diff --git a/apps/chrome-extension/src/options/main.tsx b/apps/chrome-extension/src/options/main.tsxnew file mode 100644index 000000000..6f9fe7a14--- /dev/null+++ b/apps/chrome-extension/src/options/main.tsx@@ -0,0 +1,606 @@+import {+ deleteRecoveredRecordingSpool,+ recoverOrphanedRecordingSpools,+} from "@cap/recorder-core";+import { useCallback, useEffect, useState } from "react";+import { createRoot } from "react-dom/client";+import { CapBrand, DoodleBoilFilter } from "../shared/cap-brand";+import { formatRecordedDuration } from "../shared/format-duration";+import { mountPageNav } from "../shared/page-nav";+import { sendServiceWorkerMessage } from "../shared/runtime";+import {+ clearAuth,+ defaultSettings,+ FAILED_RECORDINGS_KEY,+ type FailedRecording,+ loadAuth,+ loadFailedRecordings,+ loadSettings,+ loadSharedRecordingState,+ removeFailedRecording,+ saveSettings,+} from "../shared/storage";+import type { ExtensionAuth, ExtensionSettings } from "../shared/types";+import "./styles.css";++mountPageNav("options");++// Spool sessions younger than this may still belong to a recording that is+// live in the offscreen document (mirrors the offscreen sweep's guard).+const SPOOL_MIN_IDLE_MS = 60 * 1000;++const formatBytes = (bytes: number) => {+ if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(2)} GB`;+ if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MB`;+ if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;+ return `${Math.max(0, Math.round(bytes))} B`;+};++const fileExtensionForMimeType = (mimeType: string) =>+ mimeType.includes("webm") ? "webm" : "mp4";++const isActiveRecordingPhase = (phase: string | undefined) =>+ phase === "creating" ||+ phase === "recording" ||+ phase === "paused" ||+ phase === "uploading";++// Every extension page shares the extension-origin IndexedDB with the+// offscreen recorder, so this page reads the recording spool directly. The+// listing pairs the failed-recording metadata with the spools that still+// hold bytes, and also surfaces spools stranded by a crash before the+// offscreen sweep could record them (those have no metadata yet).+const loadRecoveredRecordings = async (): Promise<FailedRecording[]> => {+ const [failed, spools, recordingState] = await Promise.all([+ loadFailedRecordings(),+ recoverOrphanedRecordingSpools(),+ loadSharedRecordingState().catch(() => null),+ ]);+ const spoolSessions = new Set(spools.map((spool) => spool.sessionId));+ const knownSessions = new Set(failed.map((entry) => entry.sessionId));+ const entries = failed.filter((entry) => spoolSessions.has(entry.sessionId));++ // Skip unknown spools while a recording is live anywhere: an in-flight+ // recording's spool is indistinguishable from a stranded one from here.+ if (!isActiveRecordingPhase(recordingState?.status.phase)) {+ const now = Date.now();+ for (const spool of spools) {+ if (knownSessions.has(spool.sessionId)) continue;+ if (spool.totalBytes <= 0) continue;+ if (now - spool.updatedAt < SPOOL_MIN_IDLE_MS) continue;+ entries.push({+ sessionId: spool.sessionId,+ videoId: null,+ shareUrl: null,+ mimeType: spool.mimeType,+ subpath: null,+ durationMs: 0,+ width: null,+ height: null,+ fps: null,+ totalBytes: spool.totalBytes,+ createdAt: spool.updatedAt,+ message: "The recording was interrupted before its upload finished.",+ });+ }+ }++ return entries.sort((left, right) => right.createdAt - left.createdAt);+};++type RecoveryNotice = {+ kind: "success" | "error";+ message: string;+ shareUrl?: string;+};++function RecoveredRecordingsSection() {+ const [entries, setEntries] = useState<FailedRecording[]>([]);+ const [busySession, setBusySession] = useState<string | null>(null);+ const [retryingSession, setRetryingSession] = useState<string | null>(null);+ const [notice, setNotice] = useState<RecoveryNotice | null>(null);++ const refresh = useCallback(() => {+ loadRecoveredRecordings()+ .then(setEntries)+ .catch(() => setEntries([]));+ }, []);++ useEffect(() => {+ refresh();+ const handleStorageChange = (+ changes: Record<string, chrome.storage.StorageChange>,+ areaName: string,+ ) => {+ if (areaName !== "local" || !changes[FAILED_RECORDINGS_KEY]) return;+ refresh();+ };+ chrome.storage.onChanged.addListener(handleStorageChange);+ return () => chrome.storage.onChanged.removeListener(handleStorageChange);+ }, [refresh]);++ const runAction = async (+ sessionId: string,+ task: () => Promise<RecoveryNotice | null>,+ ) => {+ if (busySession !== null) return;+ setBusySession(sessionId);+ setNotice(null);+ try {+ setNotice(await task());+ } catch (err) {+ setNotice({+ kind: "error",+ message: err instanceof Error ? err.message : String(err),+ });+ } finally {+ setBusySession(null);+ setRetryingSession(null);+ }+ };++ const download = (entry: FailedRecording) =>+ runAction(entry.sessionId, async () => {+ const spools = await recoverOrphanedRecordingSpools();+ const spool = spools.find(+ (candidate) => candidate.sessionId === entry.sessionId,+ );+ if (!spool || spool.blob.size === 0) {+ refresh();+ throw new Error("The recorded data is no longer available.");+ }+ const url = URL.createObjectURL(spool.blob);+ const anchor = document.createElement("a");+ anchor.href = url;+ anchor.download = `cap-recording-${+ entry.videoId ??+ new Date(entry.createdAt).toISOString().replace(/[:.]/g, "-")+ }.${fileExtensionForMimeType(entry.mimeType)}`;+ anchor.click();+ window.setTimeout(() => URL.revokeObjectURL(url), 10_000);+ return null;+ });++ const remove = (entry: FailedRecording) =>+ runAction(entry.sessionId, async () => {+ await deleteRecoveredRecordingSpool(entry.sessionId);+ await removeFailedRecording(entry.sessionId).catch(() => undefined);+ refresh();+ return null;+ });++ const retry = (entry: FailedRecording) => {+ const videoId = entry.videoId;+ if (!videoId) return;+ setRetryingSession(entry.sessionId);+ void runAction(entry.sessionId, async () => {+ // The offscreen recorder re-uploads the whole spooled blob before this+ // resolves, so the button stays in its uploading state until then.+ const response = await sendServiceWorkerMessage({+ target: "service-worker",+ type: "retry-upload",+ videoId,+ });+ refresh();+ if (!response.ok) throw new Error(response.error);+ if (response.status?.phase === "error") {+ throw new Error(response.status.message);+ }+ return {+ kind: "success",+ message: "Upload finished.",+ shareUrl:+ response.status?.phase === "completed"+ ? response.status.shareUrl+ : (entry.shareUrl ?? undefined),+ };+ });+ };++ if (entries.length === 0 && !notice) return null;++ return (+ <section className="card card-3">+ <h2>Recovered recordings</h2>+ <p className="recovery-lede">+ These recordings never finished uploading. Their captured data is still+ on this device, so you can download it or retry the upload.+ </p>+ <ul className="recovery-list">+ {entries.map((entry) => (+ <li key={entry.sessionId} className="recovery-item">+ <div className="recovery-meta">+ <span className="recovery-title">+ {new Date(entry.createdAt).toLocaleString()}+ </span>+ <span className="recovery-detail">+ {formatBytes(entry.totalBytes)}+ {entry.durationMs > 0+ ? ` · ${formatRecordedDuration(entry.durationMs)}`+ : ""}+ {entry.videoId ? "" : " · interrupted before upload"}+ </span>+ </div>+ <div className="recovery-actions">+ {entry.videoId && (+ <button+ type="button"+ className="cta small"+ disabled={busySession !== null}+ onClick={() => retry(entry)}+ >+ {retryingSession === entry.sessionId+ ? "Uploading…"+ : "Retry upload"}+ </button>+ )}+ <button+ type="button"+ className="cta small ghost"+ disabled={busySession !== null}+ onClick={() => void download(entry)}+ >+ Download+ </button>+ <button+ type="button"+ className="cta small ghost"+ disabled={busySession !== null}+ onClick={() => void remove(entry)}+ >+ Delete+ </button>+ </div>+ </li>+ ))}+ </ul>+ {notice && (+ <p+ className={+ notice.kind === "success"+ ? "paper-pill success"+ : "paper-pill error"+ }+ >+ {notice.message}+ {notice.shareUrl && (+ <a+ className="recovery-link"+ href={notice.shareUrl}+ target="_blank"+ rel="noreferrer"+ >+ Open video+ </a>+ )}+ </p>+ )}+ </section>+ );+}++const DoodleCheckbox = ({+ label,+ checked,+ onChange,+}: {+ label: string;+ checked: boolean;+ onChange: (checked: boolean) => void;+}) => (+ <label className="doodle-check">+ <input+ type="checkbox"+ checked={checked}+ onChange={(event) => onChange(event.currentTarget.checked)}+ />+ <span className="doodle-check-box" aria-hidden="true">+ <svg viewBox="0 0 24 24" aria-hidden="true">+ <path+ className="doodle-check-mark"+ pathLength={1}+ d="M 4 13 L 9.5 18 L 20 6"+ />+ </svg>+ </span>+ {label}+ </label>+);++function App() {+ const [settings, setSettings] = useState<ExtensionSettings>(defaultSettings);+ const [auth, setAuth] = useState<ExtensionAuth | null>(null);+ const [saved, setSaved] = useState(false);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let disposed = false;+ Promise.all([loadSettings(), loadAuth()])+ .then(([nextSettings, nextAuth]) => {+ if (disposed) return;+ setSettings(nextSettings);+ setAuth(nextAuth);+ })+ .catch((err: unknown) => {+ if (!disposed) {+ setError(err instanceof Error ? err.message : String(err));+ }+ });+ return () => {+ disposed = true;+ };+ }, []);++ const save = async () => {+ setError(null);+ setSaved(false);+ try {+ new URL(settings.apiBaseUrl);+ await saveSettings(settings);+ await sendServiceWorkerMessage({+ target: "service-worker",+ type: "settings-updated",+ settings,+ }).catch(() => undefined);+ setSaved(true);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ }+ };++ const signOut = async () => {+ setError(null);+ const response = await sendServiceWorkerMessage({+ target: "service-worker",+ type: "auth-revoke",+ }).catch((err: unknown) => ({+ ok: false as const,+ error: err instanceof Error ? err.message : String(err),+ }));+ if (!response.ok) {+ setError(response.error);+ return;+ }+ await clearAuth();+ setAuth(null);+ };++ return (+ <>+ <main className="stage">+ <header className="brand">+ <CapBrand />+ </header>+ <svg className="doodle" viewBox="0 0 120 104" aria-hidden="true">+ <defs>+ <DoodleBoilFilter />+ </defs>+ <g className="doodle-boil">+ <path+ className="doodle-stroke slider-line line-1"+ pathLength={1}+ d="M 22 28 L 98 28"+ />+ <path+ className="doodle-stroke slider-line line-2"+ pathLength={1}+ d="M 22 54 L 98 54"+ />+ <path+ className="doodle-stroke slider-line line-3"+ pathLength={1}+ d="M 22 80 L 98 80"+ />+ <g className="slider-knob knob-1">+ <circle className="knob-circle" cx="44" cy="28" r="7.5" />+ </g>+ <g className="slider-knob knob-2">+ <circle+ className="knob-circle knob-accent"+ cx="76"+ cy="54"+ r="7.5"+ />+ </g>+ <g className="slider-knob knob-3">+ <circle className="knob-circle" cx="58" cy="80" r="7.5" />+ </g>+ </g>+ </svg>+ <h1>Recorder options</h1>+ <p className="lede">+ Tune where Cap uploads and how your camera shows up by default.+ </p>++ <div className="sheet">+ <section className="card card-1">+ <h2>Connection</h2>+ <label className="field">+ <span>Cap URL</span>+ <input+ type="url"+ value={settings.apiBaseUrl}+ onChange={(event) =>+ setSettings({+ ...settings,+ apiBaseUrl: event.currentTarget.value,+ })+ }+ />+ </label>+ </section>++ <section className="card card-2">+ <h2>Recording defaults</h2>+ <div className="field-grid">+ <label className="field">+ <span>Camera size</span>+ <input+ type="number"+ min="120"+ max="420"+ value={settings.webcam.size}+ onChange={(event) =>+ setSettings({+ ...settings,+ webcam: {+ ...settings.webcam,+ size: Number(event.currentTarget.value),+ },+ })+ }+ />+ </label>+ <label className="field">+ <span>Position</span>+ <select+ value={settings.webcam.position}+ onChange={(event) =>+ setSettings({+ ...settings,+ webcam: {+ ...settings.webcam,+ position: event.currentTarget+ .value as ExtensionSettings["webcam"]["position"],+ },+ })+ }+ >+ <option value="bottom-right">Bottom right</option>+ <option value="bottom-left">Bottom left</option>+ <option value="top-right">Top right</option>+ <option value="top-left">Top left</option>+ </select>+ </label>+ <label className="field">+ <span>Shape</span>+ <select+ value={settings.webcam.shape}+ onChange={(event) =>+ setSettings({+ ...settings,+ webcam: {+ ...settings.webcam,+ shape: event.currentTarget+ .value as ExtensionSettings["webcam"]["shape"],+ },+ })+ }+ >+ <option value="round">Round</option>+ <option value="square">Square</option>+ <option value="full">Full</option>+ </select>+ </label>+ </div>+ <div className="checks">+ <DoodleCheckbox+ label="Show camera preview by default"+ checked={settings.webcam.enabled}+ onChange={(checked) =>+ setSettings({+ ...settings,+ webcam: {+ ...settings.webcam,+ enabled: checked && Boolean(settings.webcam.deviceId),+ },+ })+ }+ />+ <DoodleCheckbox+ label="Enable microphone by default"+ checked={settings.microphone.enabled}+ onChange={(checked) =>+ setSettings({+ ...settings,+ microphone: {+ ...settings.microphone,+ enabled: checked,+ },+ })+ }+ />+ <DoodleCheckbox+ label="Enable system audio by default"+ checked={settings.systemAudio.enabled}+ onChange={(checked) =>+ setSettings({+ ...settings,+ systemAudio: {+ ...settings.systemAudio,+ enabled: checked,+ },+ })+ }+ />+ <DoodleCheckbox+ label="Play recording sounds"+ checked={settings.sounds.enabled}+ onChange={(checked) =>+ setSettings({+ ...settings,+ sounds: {+ ...settings.sounds,+ enabled: checked,+ },+ })+ }+ />+ <DoodleCheckbox+ label="Mirror webcam"+ checked={settings.webcam.mirror}+ onChange={(checked) =>+ setSettings({+ ...settings,+ webcam: {+ ...settings.webcam,+ mirror: checked,+ },+ })+ }+ />+ </div>+ </section>++ <RecoveredRecordingsSection />++ <div className="actions">+ <button type="button" className="cta" onClick={() => void save()}>+ Save changes+ </button>+ <button+ type="button"+ className="cta ghost"+ disabled={!auth}+ onClick={() => void signOut()}+ >+ Sign out+ </button>+ {saved && (+ <p className="paper-pill success">+ <svg+ className="check-mini"+ viewBox="0 0 24 24"+ aria-hidden="true"+ >+ <path+ className="check-mini-path"+ pathLength={1}+ d="M 4 13 L 9.5 18 L 20 6"+ />+ </svg>+ Saved+ </p>+ )}+ </div>+ {error && <p className="paper-pill error">{error}</p>}+ </div>+ </main>+ <p className="footnote">+ Changes apply the next time you open the recorder.+ </p>+ </>+ );+}++createRoot(document.getElementById("root") as HTMLElement).render(<App />);diff --git a/apps/chrome-extension/src/options/styles.css b/apps/chrome-extension/src/options/styles.cssnew file mode 100644index 000000000..136c8ab5d--- /dev/null+++ b/apps/chrome-extension/src/options/styles.css@@ -0,0 +1,247 @@+@import "../shared/paper.css";++#root {+ flex: 1;+ display: flex;+ flex-direction: column;+}++.slider-line {+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+}++.line-1 {+ animation: draw 0.45s ease 0.15s forwards;+}++.line-2 {+ animation: draw 0.45s ease 0.3s forwards;+}++.line-3 {+ animation: draw 0.45s ease 0.45s forwards;+}++.knob-circle {+ fill: var(--paper);+ stroke: var(--ink);+ stroke-width: 4.5;+ stroke-linecap: round;+ stroke-linejoin: round;+}++.knob-accent {+ stroke: var(--accent);+}++.slider-knob {+ opacity: 0;+ transform-box: fill-box;+ transform-origin: center;+ animation: spark-pop 0.4s ease forwards;+}++.knob-1 {+ animation-delay: 0.7s;+}++.knob-2 {+ animation:+ spark-pop 0.4s ease 0.85s forwards,+ knob-tune 5s ease-in-out 1.8s infinite;+}++.knob-3 {+ animation-delay: 1s;+}++.sheet {+ width: min(560px, calc(100vw - 48px));+ margin-top: 32px;+ display: grid;+ gap: 14px;+ justify-items: stretch;+ text-align: left;+}++.card-1 {+ animation-delay: 0.2s;+}++.card-2 {+ animation-delay: 0.3s;+}++.card-3 {+ animation-delay: 0.4s;+}++.recovery-lede {+ font-size: 13px;+ line-height: 1.5;+ color: var(--ink-soft);+}++.recovery-list {+ margin: 0;+ padding: 0;+ list-style: none;+ display: grid;+ gap: 10px;+}++.recovery-item {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ flex-wrap: wrap;+ padding: 12px 14px;+ border: 1.5px solid var(--track);+ border-radius: 12px;+ background: #ffffff;+}++.recovery-meta {+ display: grid;+ gap: 2px;+ font-size: 13px;+}++.recovery-title {+ font-weight: 500;+ color: var(--ink);+}++.recovery-detail {+ color: var(--ink-soft);+}++.recovery-actions {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-wrap: wrap;+}++.cta.small {+ min-height: 32px;+ padding: 0 14px;+ font-size: 13px;+}++.recovery-link {+ color: inherit;+ font-weight: 500;+}++.field-grid {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 12px;+}++.checks {+ display: grid;+ gap: 12px;+ padding-top: 4px;+}++.doodle-check {+ position: relative;+ display: flex;+ align-items: center;+ gap: 10px;+ font-size: 14px;+ color: var(--ink);+ cursor: pointer;+}++.doodle-check input {+ position: absolute;+ opacity: 0;+ pointer-events: none;+}++.doodle-check-box {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 22px;+ height: 22px;+ flex: 0 0 auto;+ border: 1.5px solid var(--ink);+ border-radius: 7px;+ background: #ffffff;+}++.doodle-check-box svg {+ width: 14px;+ height: 14px;+ overflow: visible;+}++.doodle-check-mark {+ fill: none;+ stroke: var(--accent);+ stroke-width: 3.5;+ stroke-linecap: round;+ stroke-linejoin: round;+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ transition: stroke-dashoffset 0.25s ease;+}++.doodle-check input:checked + .doodle-check-box .doodle-check-mark {+ stroke-dashoffset: 0;+}++.doodle-check input:focus-visible + .doodle-check-box {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}++.actions {+ display: flex;+ align-items: center;+ gap: 10px;+ animation: fade-up 0.5s ease 0.4s both;+}++.actions .paper-pill {+ min-height: 36px;+ padding: 4px 16px;+}++@keyframes knob-tune {+ 0%,+ 100% {+ transform: translateX(0);+ }+ 35% {+ transform: translateX(-16px);+ }+ 70% {+ transform: translateX(8px);+ }+}++@media (max-width: 560px) {+ .field-grid {+ grid-template-columns: 1fr;+ }+}++@media (prefers-reduced-motion: reduce) {+ .actions,+ .slider-line {+ animation-duration: 0.01ms;+ animation-delay: 0s;+ }++ .slider-knob,+ .knob-2 {+ animation: fade-in 0.01ms forwards;+ }+}diff --git a/apps/chrome-extension/src/permission/camera-permission.tsx b/apps/chrome-extension/src/permission/camera-permission.tsxnew file mode 100644index 000000000..b4220776d--- /dev/null+++ b/apps/chrome-extension/src/permission/camera-permission.tsx@@ -0,0 +1,322 @@+import { useEffect, useState } from "react";+import { createRoot } from "react-dom/client";+import { CapBrand, DoodleBoilFilter } from "../shared/cap-brand";+import { mountPageNav } from "../shared/page-nav";+import { rememberCameraSelection } from "../shared/preferences";+import { sendServiceWorkerMessage } from "../shared/runtime";+import {+ loadSettings,+ saveSettings,+ updateMediaAccessState,+} from "../shared/storage";+import type { CameraDevice, ExtensionSettings } from "../shared/types";+import { DEFAULT_CAMERA_DEVICE_ID } from "../shared/types";+import "./styles.css";++mountPageNav("camera");++type Status = "idle" | "requesting" | "ready" | "error";++const headlines: Record<Status, { title: string; lede: string }> = {+ idle: {+ title: "Camera & microphone access",+ lede: "Allow access once so Cap can show your camera preview and record your voice.",+ },+ requesting: {+ title: "Waiting for Chrome",+ lede: "Click Allow in the browser prompt up by the address bar.",+ },+ ready: {+ title: "You're all set",+ lede: "Pick the camera Cap should use. It's remembered for every recording.",+ },+ error: {+ title: "Cap needs access",+ lede: "Allow access once so Cap can show your camera preview and record your voice.",+ },+};++const toCameraDevices = (devices: MediaDeviceInfo[]): CameraDevice[] =>+ devices+ .filter(+ (device) =>+ device.kind === "videoinput" && device.deviceId.trim().length > 0,+ )+ .map((device, index) => ({+ deviceId: device.deviceId,+ groupId: device.groupId,+ label: device.label?.trim() || `Camera ${index + 1}`,+ }));++const stopStream = (stream: MediaStream) => {+ for (const track of stream.getTracks()) {+ track.stop();+ }+};++const getCameraErrorMessage = (error: unknown) => {+ if (!(error instanceof Error)) return "Camera unavailable";+ if (+ error.name === "NotAllowedError" ||+ error.message.toLowerCase().includes("permission")+ ) {+ return "Chrome did not grant camera access. Click Allow in the browser prompt.";+ }+ if (error.name === "NotFoundError") return "No camera was found.";+ if (error.name === "NotReadableError") return "Camera is already in use.";+ return error.message || "Camera unavailable";+};++const getPreferredDeviceId = (+ settings: ExtensionSettings,+ devices: CameraDevice[],+) => {+ const selectedDeviceStillExists = devices.some(+ (device) => device.deviceId === settings.webcam.deviceId,+ );+ if (+ settings.webcam.deviceId &&+ settings.webcam.deviceId !== DEFAULT_CAMERA_DEVICE_ID &&+ selectedDeviceStillExists+ ) {+ return settings.webcam.deviceId;+ }+ return devices[0]?.deviceId ?? DEFAULT_CAMERA_DEVICE_ID;+};++function App() {+ const [settings, setSettings] = useState<ExtensionSettings | null>(null);+ const [devices, setDevices] = useState<CameraDevice[]>([]);+ const [selectedDeviceId, setSelectedDeviceId] = useState<string>(+ DEFAULT_CAMERA_DEVICE_ID,+ );+ const [status, setStatus] = useState<Status>("idle");+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let disposed = false;++ Promise.all([+ loadSettings(),+ sendServiceWorkerMessage({+ target: "service-worker",+ type: "get-camera-devices",+ }).catch(() => null),+ ]).then(([nextSettings, response]) => {+ if (disposed) return;+ setSettings(nextSettings);+ const cachedDevices = response?.ok ? (response.cameraDevices ?? []) : [];+ setDevices(cachedDevices);+ setSelectedDeviceId(+ nextSettings.webcam.deviceId ??+ cachedDevices[0]?.deviceId ??+ DEFAULT_CAMERA_DEVICE_ID,+ );+ if (cachedDevices.length > 0) {+ void updateMediaAccessState({ camera: true }).catch(() => undefined);+ setStatus("ready");+ }+ });++ return () => {+ disposed = true;+ };+ }, []);++ const saveCameraSelection = async (+ nextSettings: ExtensionSettings,+ nextDevices: CameraDevice[],+ deviceId: string,+ ) => {+ const settingsToSave = rememberCameraSelection(+ nextSettings,+ deviceId,+ nextDevices,+ );+ setSettings(settingsToSave);+ setSelectedDeviceId(deviceId);+ await saveSettings(settingsToSave);+ await sendServiceWorkerMessage({+ target: "service-worker",+ type: "camera-devices-updated",+ devices: nextDevices,+ }).catch(() => undefined);+ await sendServiceWorkerMessage({+ target: "service-worker",+ type: "settings-updated",+ settings: settingsToSave,+ }).catch(() => undefined);+ };++ const requestAccess = async () => {+ if (!settings) return;+ if (!navigator.mediaDevices?.getUserMedia) {+ setStatus("error");+ setError("Camera access is not available in this browser.");+ return;+ }++ setStatus("requesting");+ setError(null);++ try {+ // Request camera and microphone together so the extension origin gets+ // both grants from one prompt; retry camera-only when no mic exists.+ const stream = await navigator.mediaDevices+ .getUserMedia({ video: true, audio: true })+ .catch((err: unknown) => {+ if (err instanceof DOMException && err.name === "NotFoundError") {+ return navigator.mediaDevices.getUserMedia({+ video: true,+ audio: false,+ });+ }+ throw err;+ });+ const cameraGranted = stream.getVideoTracks().length > 0;+ const microphoneGranted = stream.getAudioTracks().length > 0;+ stopStream(stream);+ await updateMediaAccessState({+ ...(cameraGranted ? { camera: true } : {}),+ ...(microphoneGranted ? { microphone: true } : {}),+ });++ const nextDevices = toCameraDevices(+ await navigator.mediaDevices.enumerateDevices(),+ );+ const deviceId = getPreferredDeviceId(settings, nextDevices);+ setDevices(nextDevices);+ await saveCameraSelection(settings, nextDevices, deviceId);+ setStatus("ready");+ } catch (err) {+ setStatus("error");+ setError(getCameraErrorMessage(err));+ }+ };++ const handleDeviceChange = async (deviceId: string) => {+ if (!settings) return;+ await saveCameraSelection(settings, devices, deviceId);+ };++ const { title, lede } = headlines[status];++ return (+ <>+ <main className="stage" data-mode={status}>+ <header className="brand">+ <CapBrand />+ </header>+ <svg className="doodle" viewBox="0 0 120 104" aria-hidden="true">+ <defs>+ <DoodleBoilFilter />+ </defs>+ <g className="doodle-boil">+ <path+ className="doodle-stroke camera-body"+ pathLength={1}+ d="M 30 36 L 44 36 L 50 26 L 70 26 L 76 36 L 90 36 Q 98 36 98 44 L 98 80 Q 98 88 90 88 L 30 88 Q 22 88 22 80 L 22 44 Q 22 36 30 36 Z"+ />+ <circle+ className="doodle-stroke camera-lens"+ pathLength={1}+ cx="60"+ cy="62"+ r="15"+ />+ <circle className="lens-dot" cx="60" cy="62" r="6" />+ <circle className="flash-dot" cx="88" cy="46" r="2.5" />+ <path+ className="spark spark-1"+ d="M 16 16 L 16 22 M 16 30 L 16 36 M 6 26 L 12 26 M 20 26 L 26 26"+ />+ <path+ className="spark spark-2"+ d="M 102 6 L 102 12 M 102 20 L 102 26 M 92 16 L 98 16 M 106 16 L 112 16"+ />+ <path+ className="spark spark-3"+ d="M 108 58 L 108 63 M 108 69 L 108 74 M 100 66 L 105 66 M 111 66 L 116 66"+ />+ </g>+ </svg>+ <h1>{title}</h1>+ <p className="lede">{lede}</p>++ {status === "ready" && devices.length > 0 && (+ <div className="card device-card">+ <label className="field">+ <span>Camera Cap should use</span>+ <select+ value={selectedDeviceId}+ onChange={(event) =>+ void handleDeviceChange(event.currentTarget.value)+ }+ >+ {devices.map((device) => (+ <option key={device.deviceId} value={device.deviceId}>+ {device.label}+ </option>+ ))}+ </select>+ </label>+ <p className="paper-pill success">+ <svg+ className="check-mini"+ viewBox="0 0 24 24"+ aria-hidden="true"+ >+ <path+ className="check-mini-path"+ pathLength={1}+ d="M 4 13 L 9.5 18 L 20 6"+ />+ </svg>+ Camera preview is enabled.+ </p>+ </div>+ )}++ {status === "error" && error && (+ <p className="paper-pill error">{error}</p>+ )}++ <div className="cta-row">+ <button+ type="button"+ className="cta"+ disabled={status === "requesting" || !settings}+ onClick={() => void requestAccess()}+ >+ {status === "requesting"+ ? "Waiting for Chrome…"+ : status === "ready"+ ? "Re-check access"+ : "Allow camera & microphone"}+ </button>+ {status === "ready" && (+ <button+ type="button"+ className="cta ghost"+ onClick={() => void requestAccess()}+ >+ Refresh list+ </button>+ )}+ </div>+ <svg className="wait-squiggle" viewBox="0 0 240 26" aria-hidden="true">+ <path+ className="wait-squiggle-path"+ pathLength={100}+ d="M 6 14 q 6 -7 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0 t 12 0"+ />+ </svg>+ </main>+ <p className="footnote">+ Chrome remembers this. Cap only uses your camera while you record.+ </p>+ </>+ );+}++createRoot(document.getElementById("root") as HTMLElement).render(<App />);diff --git a/apps/chrome-extension/src/permission/styles.css b/apps/chrome-extension/src/permission/styles.cssnew file mode 100644index 000000000..4e57ec149--- /dev/null+++ b/apps/chrome-extension/src/permission/styles.css@@ -0,0 +1,133 @@+@import "../shared/paper.css";++#root {+ flex: 1;+ display: flex;+ flex-direction: column;+}++.camera-body {+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ animation: draw 0.9s ease 0.15s forwards;+}++.camera-lens {+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ animation: draw 0.5s ease 0.9s forwards;+}++.lens-dot {+ fill: var(--accent);+ opacity: 0;+ animation: fade-in 0.3s ease 1.2s forwards;+}++.flash-dot {+ fill: var(--accent);+ opacity: 0;+ animation: fade-in 0.3s ease 1.35s forwards;+}++.stage[data-mode="requesting"] .lens-dot {+ opacity: 1;+ animation: lens-pulse 1.2s ease-in-out infinite;+}++.stage[data-mode="error"] .lens-dot {+ fill: var(--error);+}++.spark {+ display: none;+}++.stage[data-mode="ready"] .spark {+ display: inline;+}++.spark-1 {+ animation-delay: 0.05s;+}++.spark-2 {+ animation-delay: 0.2s;+}++.spark-3 {+ animation-delay: 0.35s;+}++.device-card {+ width: min(420px, calc(100vw - 48px));+ margin-top: 28px;+ justify-items: start;+}++.device-card .field {+ width: 100%;+}++.stage > .paper-pill.error {+ margin-top: 24px;+ max-width: 480px;+}++.cta-row {+ display: flex;+ align-items: center;+ gap: 10px;+ margin-top: 28px;+ animation: fade-up 0.5s ease 0.3s both;+}++.wait-squiggle {+ display: none;+ width: 200px;+ height: 26px;+ margin-top: 16px;+ overflow: visible;+}++.stage[data-mode="requesting"] .wait-squiggle {+ display: block;+}++.wait-squiggle-path {+ fill: none;+ stroke: var(--ink-soft);+ stroke-width: 2.5;+ stroke-linecap: round;+ stroke-dasharray: 2 4.2;+ animation: march 1.2s linear infinite;+}++@keyframes lens-pulse {+ 0%,+ 100% {+ opacity: 1;+ }+ 50% {+ opacity: 0.3;+ }+}++@media (prefers-reduced-motion: reduce) {+ .camera-body,+ .camera-lens,+ .cta-row {+ animation-duration: 0.01ms;+ animation-delay: 0s;+ }++ .lens-dot,+ .flash-dot,+ .stage[data-mode="requesting"] .lens-dot {+ animation: fade-in 0.01ms forwards;+ }++ .wait-squiggle-path {+ animation: none;+ }+}diff --git a/apps/chrome-extension/src/preview/camera-preview.tsx b/apps/chrome-extension/src/preview/camera-preview.tsxnew file mode 100644index 000000000..8f995f35e--- /dev/null+++ b/apps/chrome-extension/src/preview/camera-preview.tsx@@ -0,0 +1,648 @@+import { PictureInPicture } from "lucide-react";+import { useCallback, useEffect, useRef, useState } from "react";+import { createRoot } from "react-dom/client";+import { sendServiceWorkerMessage } from "../shared/runtime";+import type {+ CameraDevice,+ CameraPreviewErrorReason,+ CameraPreviewEvent,+ WebcamPreviewFrame,+ WebcamSettings,+} from "../shared/types";+import {+ toSessionDescriptionInit,+ waitForIceGatheringComplete,+} from "../shared/webrtc";+import "./styles.css";++const FRAME_CAPTURE_INTERVAL_MS = 700;+const FRAME_CAPTURE_MAX_WIDTH = 320;++type ParentMessage =+ | {+ source: "cap-extension-overlay";+ token: string;+ type: "settings";+ settings: WebcamSettings;+ }+ | {+ source: "cap-extension-overlay";+ token: string;+ type: "toggle-pip";+ }+ | {+ source: "cap-extension-overlay";+ token: string;+ type: "enter-pip";+ }+ | {+ source: "cap-extension-overlay";+ token: string;+ type: "exit-auto-pip";+ }+ | {+ source: "cap-extension-overlay";+ token: string;+ type: "stop";+ };++const token = decodeURIComponent(window.location.hash.slice(1));++const isParentMessage = (value: unknown): value is ParentMessage => {+ if (!value || typeof value !== "object") return false;+ const candidate = value as Partial<ParentMessage>;+ return (+ candidate.source === "cap-extension-overlay" && candidate.token === token+ );+};++// Events for the embedding overlay travel over chrome.runtime via the+// service worker, never window.parent.postMessage: the parent window is the+// recorded web page, and a postMessage stream — webcam frames above all —+// would be readable by any listener that page installs. The service worker+// validates this frame's URL and registered token before relaying to the+// embedding tab's content script.+const postParent = (event: CameraPreviewEvent) => {+ chrome.runtime.sendMessage(+ {+ target: "service-worker",+ type: "camera-preview-event",+ token,+ event,+ },+ () => {+ void chrome.runtime.lastError;+ },+ );+};++const waitForRemoteStream = (peer: RTCPeerConnection) =>+ new Promise<MediaStream>((resolve, reject) => {+ let settled = false;+ const timeout = window.setTimeout(() => {+ if (settled) return;+ settled = true;+ reject(new Error("Camera preview timed out."));+ }, 10000);++ const finish = (stream: MediaStream) => {+ if (settled) return;+ settled = true;+ window.clearTimeout(timeout);+ resolve(stream);+ };++ peer.addEventListener("track", (event) => {+ finish(event.streams[0] ?? new MediaStream([event.track]));+ });++ peer.addEventListener("connectionstatechange", () => {+ if (+ settled ||+ (peer.connectionState !== "failed" && peer.connectionState !== "closed")+ ) {+ return;+ }+ settled = true;+ window.clearTimeout(timeout);+ reject(new Error("Camera preview connection failed."));+ });+ });++const connectCameraPreview = async (+ settings: WebcamSettings,+ sessionId: string,+) => {+ const peer = new RTCPeerConnection();+ peer.addTransceiver("video", { direction: "recvonly" });+ const remoteStreamPromise = waitForRemoteStream(peer);+ await peer.setLocalDescription(await peer.createOffer());+ await waitForIceGatheringComplete(peer);++ const response = await sendServiceWorkerMessage({+ target: "service-worker",+ type: "connect-camera-preview",+ sessionId,+ settings,+ offer: toSessionDescriptionInit(peer.localDescription),+ });++ if (!response.ok) {+ peer.close();+ throw new Error(response.error);+ }+ if (!response.answer) {+ peer.close();+ throw new Error("Camera preview did not return an answer.");+ }++ await peer.setRemoteDescription(response.answer);+ return {+ peer,+ stream: await remoteStreamPromise,+ };+};++let frameCanvas: HTMLCanvasElement | null = null;++const captureVideoFrame = (+ video: HTMLVideoElement,+): WebcamPreviewFrame | null => {+ if (video.videoWidth <= 0 || video.videoHeight <= 0) return null;+ frameCanvas ??= document.createElement("canvas");+ const scale = Math.min(1, FRAME_CAPTURE_MAX_WIDTH / video.videoWidth);+ const width = Math.max(1, Math.round(video.videoWidth * scale));+ const height = Math.max(1, Math.round(video.videoHeight * scale));+ frameCanvas.width = width;+ frameCanvas.height = height;+ const context = frameCanvas.getContext("2d");+ if (!context) return null;+ context.drawImage(video, 0, 0, width, height);+ return {+ dataUrl: frameCanvas.toDataURL("image/jpeg", 0.72),+ dimensions: {+ width: video.videoWidth,+ height: video.videoHeight,+ },+ capturedAt: Date.now(),+ };+};++const stopStream = (stream: MediaStream | null) => {+ if (!stream) return;+ for (const track of stream.getTracks()) {+ track.stop();+ }+};++const disconnectCameraPreview = (sessionId: string | null) => {+ if (!sessionId) return;+ void sendServiceWorkerMessage({+ target: "service-worker",+ type: "disconnect-camera-preview",+ sessionId,+ }).catch(() => undefined);+};++const isSameWebcamSettings = (+ current: WebcamSettings | null,+ next: WebcamSettings,+) =>+ current?.enabled === next.enabled &&+ current.deviceId === next.deviceId &&+ current.position === next.position &&+ current.size === next.size &&+ current.shape === next.shape &&+ current.mirror === next.mirror;++const getCameraErrorDetails = (+ error: unknown,+): { reason: CameraPreviewErrorReason; message: string } => {+ if (!(error instanceof Error)) {+ return { reason: "unknown", message: "Camera unavailable" };+ }+ const lowerMessage = error.message.toLowerCase();+ if (error.name === "NotAllowedError" || lowerMessage.includes("permission")) {+ return {+ reason: "permission",+ message:+ "Camera permission was dismissed. Select a camera again and choose Allow.",+ };+ }+ if (error.name === "NotFoundError") {+ return { reason: "not-found", message: "Selected camera was not found." };+ }+ if (error.name === "NotReadableError") {+ return { reason: "in-use", message: "Selected camera is already in use." };+ }+ return { reason: "unknown", message: error.message || "Camera unavailable" };+};++type AutoPictureInPictureVideo = HTMLVideoElement & {+ autoPictureInPicture?: boolean;+};++const toCameraDevices = (devices: MediaDeviceInfo[]): CameraDevice[] =>+ devices+ .filter(+ (device) =>+ device.kind === "videoinput" && device.deviceId.trim().length > 0,+ )+ .map((device, index) => ({+ deviceId: device.deviceId,+ groupId: device.groupId,+ label: device.label?.trim() || `Camera ${index + 1}`,+ }));++const publishCameraDevices = async () => {+ const devices = toCameraDevices(+ await navigator.mediaDevices.enumerateDevices(),+ );+ chrome.runtime.sendMessage(+ {+ target: "service-worker",+ type: "camera-devices-updated",+ devices,+ },+ () => undefined,+ );+};++function App() {+ const [settings, setSettings] = useState<WebcamSettings | null>(null);+ const [isInPictureInPicture, setIsInPictureInPicture] = useState(false);+ const videoRef = useRef<HTMLVideoElement>(null);+ const streamRef = useRef<MediaStream | null>(null);+ const peerRef = useRef<RTCPeerConnection | null>(null);+ const activeDeviceRef = useRef<string | null>(null);+ const sessionIdRef = useRef<string | null>(null);+ const sessionCounterRef = useRef(0);+ const autoPictureInPictureRef = useRef(false);+ const autoPictureInPictureEnabledRef = useRef(false);+ const previewEnabled = Boolean(settings?.enabled && settings.deviceId);+ const isPictureInPictureSupported =+ typeof document !== "undefined" && document.pictureInPictureEnabled;++ const publishPreviewFrame = useCallback(() => {+ const currentVideo = videoRef.current;+ if (!currentVideo) return;+ const frame = captureVideoFrame(currentVideo);+ if (!frame) return;+ postParent({+ type: "frame",+ frame,+ });+ }, []);++ const setAutomaticPictureInPicture = useCallback((enabled: boolean) => {+ autoPictureInPictureEnabledRef.current = enabled;+ const currentVideo = videoRef.current as AutoPictureInPictureVideo | null;+ if (currentVideo && "autoPictureInPicture" in currentVideo) {+ currentVideo.autoPictureInPicture = enabled;+ }++ try {+ navigator.mediaSession?.setActionHandler(+ "enterpictureinpicture" as MediaSessionAction,+ enabled+ ? async () => {+ const video = videoRef.current;+ if (!video || document.pictureInPictureElement) return;+ try {+ autoPictureInPictureRef.current = true;+ await video.requestPictureInPicture();+ } catch {+ autoPictureInPictureRef.current = false;+ }+ }+ : null,+ );+ } catch {}+ }, []);++ const stopPreview = useCallback(() => {+ setAutomaticPictureInPicture(false);+ if (+ videoRef.current &&+ document.pictureInPictureElement === videoRef.current+ ) {+ document.exitPictureInPicture().catch(() => undefined);+ }+ stopStream(streamRef.current);+ peerRef.current?.close();+ disconnectCameraPreview(sessionIdRef.current);+ peerRef.current = null;+ streamRef.current = null;+ activeDeviceRef.current = null;+ sessionIdRef.current = null;+ videoRef.current?.removeAttribute("src");+ if (videoRef.current) {+ videoRef.current.srcObject = null;+ }+ setIsInPictureInPicture(false);+ postParent({+ type: "pip-state",+ active: false,+ supported: isPictureInPictureSupported,+ });+ }, [isPictureInPictureSupported, setAutomaticPictureInPicture]);++ const enterPictureInPicture = useCallback(+ async (auto: boolean) => {+ const currentVideo = videoRef.current;+ if (auto) {+ setAutomaticPictureInPicture(true);+ }+ if (!currentVideo || !isPictureInPictureSupported) return;++ try {+ if (document.pictureInPictureElement === currentVideo) {+ if (!auto) autoPictureInPictureRef.current = false;+ return;+ }+ if (document.pictureInPictureElement) return;+ await currentVideo.requestPictureInPicture();+ autoPictureInPictureRef.current = auto;+ } catch {+ autoPictureInPictureRef.current = false;+ }+ },+ [isPictureInPictureSupported, setAutomaticPictureInPicture],+ );++ const exitAutoPictureInPicture = useCallback(async () => {+ setAutomaticPictureInPicture(false);+ const currentVideo = videoRef.current;+ if (+ !currentVideo ||+ !autoPictureInPictureRef.current ||+ document.pictureInPictureElement !== currentVideo+ ) {+ return;+ }++ try {+ await document.exitPictureInPicture();+ } catch {+ autoPictureInPictureRef.current = false;+ }+ }, [setAutomaticPictureInPicture]);++ const togglePictureInPicture = useCallback(async () => {+ const currentVideo = videoRef.current;+ if (!currentVideo || !isPictureInPictureSupported) return;++ try {+ setAutomaticPictureInPicture(false);+ autoPictureInPictureRef.current = false;+ if (document.pictureInPictureElement === currentVideo) {+ await document.exitPictureInPicture();+ } else {+ await currentVideo.requestPictureInPicture();+ }+ } catch {+ autoPictureInPictureRef.current = false;+ }+ }, [isPictureInPictureSupported, setAutomaticPictureInPicture]);++ useEffect(() => {+ postParent({+ type: "ready",+ });+ postParent({+ type: "pip-state",+ active: false,+ supported: isPictureInPictureSupported,+ });+ }, [isPictureInPictureSupported]);++ useEffect(() => {+ // Control messages arrive over chrome.runtime, which the host page (and+ // other extensions) cannot speak — window messages were forgeable since+ // the token is readable from the iframe src in the page DOM. The token+ // check scopes the runtime broadcast to this tab's preview.+ const handleMessage = (message: unknown) => {+ if (!isParentMessage(message)) return false;++ if (message.type === "settings") {+ const nextSettings = message.settings;+ setSettings((current) =>+ isSameWebcamSettings(current, nextSettings) ? current : nextSettings,+ );+ window.setTimeout(publishPreviewFrame, 0);+ return false;+ }++ if (message.type === "toggle-pip") {+ void togglePictureInPicture();+ return false;+ }++ if (message.type === "enter-pip") {+ void enterPictureInPicture(true);+ return false;+ }++ if (message.type === "exit-auto-pip") {+ void exitAutoPictureInPicture();+ return false;+ }++ setSettings(null);+ stopPreview();+ return false;+ };++ chrome.runtime.onMessage.addListener(handleMessage);+ return () => chrome.runtime.onMessage.removeListener(handleMessage);+ }, [+ enterPictureInPicture,+ exitAutoPictureInPicture,+ publishPreviewFrame,+ stopPreview,+ togglePictureInPicture,+ ]);++ useEffect(() => {+ if (!previewEnabled || !settings) {+ stopPreview();+ return;+ }++ let disposed = false;++ const startPreview = async () => {+ const peerActive =+ peerRef.current &&+ peerRef.current.connectionState !== "closed" &&+ peerRef.current.connectionState !== "failed" &&+ peerRef.current.connectionState !== "disconnected";+ if (+ streamRef.current &&+ peerActive &&+ activeDeviceRef.current === settings.deviceId+ ) {+ if (+ videoRef.current &&+ videoRef.current.srcObject !== streamRef.current+ ) {+ videoRef.current.srcObject = streamRef.current;+ }+ await videoRef.current?.play().catch(() => undefined);+ return;+ }++ stopPreview();+ const sessionId = `${token}:${Date.now()}:${sessionCounterRef.current + 1}`;+ sessionCounterRef.current += 1;+ sessionIdRef.current = sessionId;+ postParent({+ type: "session",+ sessionId,+ });++ try {+ const { peer, stream } = await connectCameraPreview(+ settings,+ sessionId,+ );++ if (disposed || sessionIdRef.current !== sessionId) {+ peer.close();+ stopStream(stream);+ disconnectCameraPreview(sessionId);+ return;+ }++ peerRef.current = peer;+ streamRef.current = stream;+ activeDeviceRef.current = settings.deviceId;++ if (videoRef.current) {+ videoRef.current.srcObject = stream;+ if (autoPictureInPictureEnabledRef.current) {+ setAutomaticPictureInPicture(true);+ }+ await videoRef.current.play().catch(() => undefined);+ }+ publishPreviewFrame();+ await publishCameraDevices().catch(() => undefined);+ } catch (error) {+ if (!disposed) {+ const details = getCameraErrorDetails(error);+ stopPreview();+ postParent({+ type: "error",+ reason: details.reason,+ message: details.message,+ });+ }+ }+ };++ void startPreview();++ return () => {+ disposed = true;+ };+ }, [+ previewEnabled,+ publishPreviewFrame,+ settings,+ setAutomaticPictureInPicture,+ stopPreview,+ ]);++ useEffect(() => {+ if (!previewEnabled) return;+ const interval = window.setInterval(+ publishPreviewFrame,+ FRAME_CAPTURE_INTERVAL_MS,+ );+ return () => window.clearInterval(interval);+ }, [previewEnabled, publishPreviewFrame]);++ useEffect(() => {+ if (!videoRef.current || !isPictureInPictureSupported) {+ return;+ }++ const currentVideo = videoRef.current;+ const handlePipEnter = () => {+ setIsInPictureInPicture(true);+ postParent({+ type: "pip-state",+ active: true,+ supported: true,+ });+ };+ const handlePipLeave = () => {+ autoPictureInPictureRef.current = false;+ setAutomaticPictureInPicture(false);+ setIsInPictureInPicture(false);+ postParent({+ type: "pip-state",+ active: false,+ supported: true,+ });+ };++ currentVideo.addEventListener("enterpictureinpicture", handlePipEnter);+ currentVideo.addEventListener("leavepictureinpicture", handlePipLeave);++ return () => {+ currentVideo.removeEventListener("enterpictureinpicture", handlePipEnter);+ currentVideo.removeEventListener("leavepictureinpicture", handlePipLeave);+ };+ }, [isPictureInPictureSupported, setAutomaticPictureInPicture]);++ useEffect(() => {+ return () => {+ stopPreview();+ };+ }, [stopPreview]);++ return (+ <div+ className="camera-preview-root"+ onPointerDown={(event) => {+ if ((event.target as HTMLElement).closest("[data-pip-control]")) {+ return;+ }+ event.preventDefault();+ postParent({+ type: "drag-start",+ clientX: event.clientX,+ clientY: event.clientY,+ });+ }}+ onPointerUp={() => {+ postParent({ type: "drag-end" });+ }}+ onPointerCancel={() => {+ postParent({ type: "drag-end" });+ }}+ >+ <video+ ref={videoRef}+ autoPlay+ playsInline+ muted+ disablePictureInPicture={false}+ controlsList="nodownload nofullscreen noremoteplayback"+ data-pip={isInPictureInPicture ? "true" : "false"}+ data-mirror={settings?.mirror ? "true" : "false"}+ onLoadedMetadata={() => {+ const currentVideo = videoRef.current;+ if (!currentVideo) return;+ if (currentVideo.videoWidth > 0 && currentVideo.videoHeight > 0) {+ postParent({+ type: "metadata",+ dimensions: {+ width: currentVideo.videoWidth,+ height: currentVideo.videoHeight,+ },+ });+ publishPreviewFrame();+ }+ }}+ onLoadedData={publishPreviewFrame}+ onPlaying={publishPreviewFrame}+ />+ {isPictureInPictureSupported && !isInPictureInPicture ? (+ <button+ type="button"+ className="camera-preview-pip-button"+ data-pip-control+ aria-label="Open Picture in Picture"+ title="Picture in Picture"+ onClick={togglePictureInPicture}+ >+ <PictureInPicture size={20} aria-hidden />+ </button>+ ) : null}+ </div>+ );+}++createRoot(document.getElementById("root") as HTMLElement).render(<App />);diff --git a/apps/chrome-extension/src/preview/styles.css b/apps/chrome-extension/src/preview/styles.cssnew file mode 100644index 000000000..6cef8268e--- /dev/null+++ b/apps/chrome-extension/src/preview/styles.css@@ -0,0 +1,82 @@+:root {+ color-scheme: dark;+ background: #000;+}++html,+body,+#root {+ width: 100%;+ height: 100%;+ margin: 0;+ overflow: hidden;+ background: #000;+}++.camera-preview-root {+ position: relative;+ width: 100%;+ height: 100%;+ cursor: move;+ touch-action: none;+ user-select: none;+}++video {+ display: block;+ width: 100%;+ height: 100%;+ background: #000;+ object-fit: cover;+ pointer-events: none;+ transition: opacity 180ms ease;+}++video[data-mirror="true"] {+ transform: scaleX(-1);+}++video[data-pip="true"] {+ opacity: 0;+}++.camera-preview-pip-button {+ all: unset;+ position: absolute;+ top: 10px;+ right: 10px;+ display: flex;+ width: 36px;+ height: 36px;+ align-items: center;+ justify-content: center;+ border: 1px solid rgba(255, 255, 255, 0.18);+ border-radius: 10px;+ background: rgba(0, 0, 0, 0.58);+ box-shadow: 0 10px 28px rgba(0, 0, 0, 0.28);+ color: rgba(255, 255, 255, 0.94);+ cursor: pointer;+ opacity: 1;+ backdrop-filter: blur(14px);+ transition:+ opacity 160ms ease,+ background 160ms ease,+ transform 160ms ease;+}++.camera-preview-pip-button:hover,+.camera-preview-pip-button:focus-visible {+ background: rgba(0, 0, 0, 0.72);+ transform: translateY(-1px);+}++.camera-preview-pip-button:focus-visible {+ outline: 1px solid rgba(255, 255, 255, 0.72);+ outline-offset: 2px;+}++.camera-preview-pip-button svg {+ display: block;+ width: 20px;+ height: 20px;+}diff --git a/apps/chrome-extension/src/uploading/main.ts b/apps/chrome-extension/src/uploading/main.tsnew file mode 100644index 000000000..2e2fe9704--- /dev/null+++ b/apps/chrome-extension/src/uploading/main.ts@@ -0,0 +1,482 @@+import { recoverRecordingSpoolSession } from "@cap/recorder-core";+import { isRecordingStatusBroadcast } from "../shared/messages";+import { sendServiceWorkerMessage } from "../shared/runtime";+import {+ type FailedRecording,+ loadFailedRecordings,+ loadSharedRecordingState,+ RECORDING_STATE_KEY,+} from "../shared/storage";+import type { RecordingStatus } from "../shared/types";+import "./styles.css";++// Live updates arrive via status broadcasts and the session-storage mirror;+// the poll only reconciles drift, so it can be slow instead of forcing a+// service-worker -> offscreen round trip several times a second.+const POLL_INTERVAL_MS = 2000;+const REDIRECT_DELAY_MS = 1600;+// After a retry starts (or its message channel dies with the service+// worker), live broadcasts from the offscreen document decide the outcome.+// Only declare failure if no fresh status shows up for this long.+const RETRY_STATUS_TIMEOUT_MS = 45_000;+const RETRY_SILENT_FAILURE_MESSAGE =+ "The retry did not report any progress. It may still be running - check your Caps before retrying again.";++type ActiveStatus = Extract<+ RecordingStatus,+ { phase: "recording" | "paused" | "uploading" }+>;+type ErrorStatus = Extract<RecordingStatus, { phase: "error" }>;+type StageMode = "waiting" | "uploading" | "finalizing" | "completed" | "error";++const byId = <T extends Element>(id: string): T => {+ const element = document.getElementById(id);+ if (!element) throw new Error(`Missing element: ${id}`);+ return element as unknown as T;+};++const stage = byId<HTMLElement>("stage");+const titleElement = byId<HTMLElement>("upload-title");+const detailElement = byId<HTMLElement>("upload-detail");+const metaElement = byId<HTMLElement>("upload-meta");+const percentValue = byId<HTMLElement>("percent-value");+const squiggleProgress = byId<SVGPathElement>("squiggle-progress");+const shareLink = byId<HTMLAnchorElement>("share-link");+const errorActions = byId<HTMLElement>("error-actions");+const retryButton = byId<HTMLButtonElement>("retry-upload");+const downloadButton = byId<HTMLButtonElement>("download-recording");++const urlVideoId = new URL(window.location.href).searchParams.get("videoId");++let mode: StageMode = "waiting";+let redirecting = false;+// Locks the retry button while a retry request is in flight; live status+// renders are never suppressed by it.+let retrying = false;+// Set while a retry waits for its first fresh status: the pre-retry error is+// still mirrored in session storage and must not repaint over the retry UI.+let retryPendingFreshStatus = false;+let retryWatchdog: number | null = null;+let targetPercent = 0;+let displayedPercent = 0;+let activeStateKey = "";+let lastTitleKey = "";+let consecutivePollFailures = 0;+let currentErrorVideoId: string | null = null;+let frameHandle: number | null = null;+let lastPercentText: string | null = null;+let lastDashOffset: string | null = null;++const setMode = (next: StageMode) => {+ if (mode === next) return;+ mode = next;+ stage.dataset.mode = next;+};++const applyStageState = (key: string, title: string, detail: string) => {+ if (activeStateKey === key) return;+ activeStateKey = key;+ titleElement.textContent = title;+ detailElement.textContent = detail;+};++const formatBytes = (bytes: number) => {+ if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(2)} GB`;+ if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MB`;+ if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;+ return `${Math.max(0, Math.round(bytes))} B`;+};++// The title is driven by the status handlers (which keep firing in+// background tabs) instead of the rAF loop, which the browser suspends for+// hidden tabs and which stops once the status is terminal.+const syncTabTitle = () => {+ const percent = Math.round(targetPercent);+ const key =+ mode === "uploading" || mode === "finalizing" ? `${mode}:${percent}` : mode;+ if (key === lastTitleKey) return;+ lastTitleKey = key;+ if (mode === "completed") {+ document.title = "Ready - Cap";+ return;+ }+ if (mode === "error") {+ document.title = "Upload needs attention - Cap";+ return;+ }+ if (mode === "waiting") {+ document.title = "Uploading - Cap";+ return;+ }+ document.title = `Uploading ${percent}% - Cap`;+};++const applyPercentDom = () => {+ const percentText = `${Math.floor(displayedPercent)}%`;+ if (percentText !== lastPercentText) {+ lastPercentText = percentText;+ percentValue.textContent = percentText;+ }+ const dashOffset =+ mode === "waiting"+ ? ""+ : `${100 - Math.min(100, Math.max(0, displayedPercent))}`;+ if (dashOffset !== lastDashOffset) {+ lastDashOffset = dashOffset;+ squiggleProgress.style.strokeDashoffset = dashOffset;+ }+};++const syncFrame = () => {+ frameHandle = null;+ const delta = targetPercent - displayedPercent;+ displayedPercent =+ Math.abs(delta) < 0.05 ? targetPercent : displayedPercent + delta * 0.085;+ applyPercentDom();+ // Once a terminal status has settled there is nothing left to animate;+ // renderStatus restarts the loop when a new active status arrives.+ if (+ (mode === "completed" || mode === "error") &&+ displayedPercent === targetPercent+ ) {+ return;+ }+ frameHandle = window.requestAnimationFrame(syncFrame);+};++const ensureFrameLoop = () => {+ if (frameHandle !== null) return;+ frameHandle = window.requestAnimationFrame(syncFrame);+};++const getOverallPercent = (status: ActiveStatus) => {+ if (status.uploadStatus?.status === "uploadingVideo") {+ return status.uploadStatus.progress;+ }+ if (!status.upload || status.upload.totalBytes === 0) return 0;+ return (status.upload.uploadedBytes / status.upload.totalBytes) * 100;+};++const hideErrorActions = () => {+ currentErrorVideoId = null;+ errorActions.hidden = true;+};++const renderActiveStatus = (status: ActiveStatus) => {+ hideErrorActions();+ shareLink.hidden = true;+ targetPercent = Math.max(+ targetPercent,+ Math.min(100, getOverallPercent(status)),+ );+ const totalBytes = status.upload?.totalBytes ?? 0;+ const uploadedBytes = status.upload?.uploadedBytes ?? 0;+ metaElement.textContent =+ totalBytes > 0+ ? `${formatBytes(uploadedBytes)} of ${formatBytes(totalBytes)}`+ : "";+ metaElement.hidden = totalBytes === 0;++ if (status.phase === "recording") {+ setMode("uploading");+ applyStageState(+ "recording",+ "Still recording",+ "Your Cap streams to the cloud while you record.",+ );+ return;+ }+ if (status.phase === "paused") {+ setMode("uploading");+ applyStageState(+ "paused",+ "Recording paused",+ "What you've captured keeps uploading.",+ );+ return;+ }++ const allSegmentsDone =+ status.upload !== undefined &&+ status.upload.totalChunks > 0 &&+ status.upload.completedChunks === status.upload.totalChunks;+ if (allSegmentsDone || targetPercent >= 99.5) {+ setMode("finalizing");+ applyStageState(+ "finalizing",+ "Finishing up",+ "Stitching everything together…",+ );+ return;+ }+ setMode("uploading");+ applyStageState(+ "uploading",+ "Uploading your Cap",+ "We'll take you to it the moment it's ready.",+ );+};++const renderCompleted = (+ status: Extract<RecordingStatus, { phase: "completed" }>,+) => {+ hideErrorActions();+ targetPercent = 100;+ setMode("completed");+ applyStageState("completed", "Your Cap is ready", "Taking you there now…");+ metaElement.hidden = true;+ shareLink.href = status.shareUrl;+ shareLink.hidden = false;+ if (!redirecting) {+ redirecting = true;+ window.setTimeout(() => {+ window.location.replace(status.shareUrl);+ }, REDIRECT_DELAY_MS);+ }+};++const findFailedRecording = async (+ videoId: string | null,+): Promise<FailedRecording | null> => {+ if (!videoId) return null;+ const failed = await loadFailedRecordings().catch(+ () => [] as FailedRecording[],+ );+ return failed.find((entry) => entry.videoId === videoId) ?? null;+};++const fileExtensionForMimeType = (mimeType: string) =>+ mimeType.includes("webm") ? "webm" : "mp4";++const syncErrorActions = (status: ErrorStatus, videoId: string | null) => {+ if (!status.recoverable || !videoId) {+ hideErrorActions();+ return;+ }+ currentErrorVideoId = videoId;+ void findFailedRecording(videoId).then((entry) => {+ if (mode !== "error" || currentErrorVideoId !== videoId) return;+ errorActions.hidden = !entry;+ });+};++const renderError = (status: ErrorStatus) => {+ setMode("error");+ applyStageState(+ `error:${status.message}`,+ "Upload needs attention",+ status.message || "Something went wrong while uploading.",+ );+ const recordingId = status.videoId ?? urlVideoId;+ metaElement.textContent = recordingId ? `Recording ID: ${recordingId}` : "";+ metaElement.hidden = !recordingId;+ // When the upload finished but the confirmation was lost, the video may+ // still process server-side; the link lets the user verify.+ if (status.shareUrl) {+ shareLink.href = status.shareUrl;+ shareLink.hidden = false;+ } else {+ shareLink.hidden = true;+ }+ syncErrorActions(status, recordingId ?? null);+};++const renderWaiting = () => {+ hideErrorActions();+ shareLink.hidden = true;+ setMode("waiting");+ applyStageState("waiting", "Connecting to your recording", "One moment…");+};++const clearRetryPending = () => {+ retryPendingFreshStatus = false;+ if (retryWatchdog !== null) {+ window.clearTimeout(retryWatchdog);+ retryWatchdog = null;+ }+};++// Suppress the stale pre-retry error until the offscreen recorder publishes+// a fresh status; if none ever arrives, surface a failure rather than+// spinning forever.+const beginRetryPending = () => {+ retryPendingFreshStatus = true;+ if (retryWatchdog !== null) {+ window.clearTimeout(retryWatchdog);+ }+ retryWatchdog = window.setTimeout(() => {+ retryWatchdog = null;+ if (!retryPendingFreshStatus) return;+ retryPendingFreshStatus = false;+ renderRetryFailure(RETRY_SILENT_FAILURE_MESSAGE);+ }, RETRY_STATUS_TIMEOUT_MS);+};++const renderRetryFailure = (message: string) => {+ setMode("error");+ applyStageState(`error:${message}`, "Upload needs attention", message);+ syncTabTitle();+};++const renderStatus = (status: RecordingStatus) => {+ if (retryPendingFreshStatus) {+ // The stale pre-retry error keeps echoing from session storage and the+ // status polls until the retry publishes its first status; anything+ // non-error is that fresh status.+ if (status.phase === "error") return;+ if (+ status.phase === "recording" ||+ status.phase === "paused" ||+ status.phase === "uploading" ||+ status.phase === "completed"+ ) {+ clearRetryPending();+ }+ }+ if (status.phase === "completed") {+ renderCompleted(status);+ } else if (+ status.phase === "recording" ||+ status.phase === "paused" ||+ status.phase === "uploading"+ ) {+ renderActiveStatus(status);+ } else if (status.phase === "error") {+ renderError(status);+ } else {+ renderWaiting();+ }+ syncTabTitle();+ ensureFrameLoop();+};++const retryUpload = async () => {+ const videoId = currentErrorVideoId;+ if (!videoId || retrying) return;+ retrying = true;+ retryButton.disabled = true;+ downloadButton.disabled = true;+ // Reset the displayed progress for the new attempt; the live broadcasts+ // and the session-storage mirror drive the UI from here, exactly as+ // during the original upload.+ targetPercent = 0;+ displayedPercent = 0;+ beginRetryPending();+ try {+ const response = await sendServiceWorkerMessage({+ target: "service-worker",+ type: "retry-upload",+ videoId,+ });+ clearRetryPending();+ if (response.ok && response.status) {+ renderStatus(response.status);+ } else if (!response.ok) {+ renderRetryFailure(response.error);+ }+ } catch {+ // The message channel dies when the service worker restarts mid-retry,+ // but the upload keeps running in the offscreen document and keeps+ // broadcasting. Let those broadcasts (or the watchdog) decide the+ // outcome instead of flashing a false failure. Re-arm the watchdog+ // only while no fresh status has arrived yet.+ if (retryPendingFreshStatus) {+ beginRetryPending();+ }+ } finally {+ retrying = false;+ retryButton.disabled = false;+ downloadButton.disabled = false;+ }+};++const downloadRecording = async () => {+ const videoId = currentErrorVideoId;+ if (!videoId) return;+ downloadButton.disabled = true;+ try {+ const entry = await findFailedRecording(videoId);+ if (!entry) throw new Error("The recorded data is no longer available.");+ // The spool lives in the extension-origin IndexedDB, which this page+ // shares with the offscreen recorder.+ const orphan = await recoverRecordingSpoolSession(entry.sessionId);+ if (!orphan || orphan.blob.size === 0) {+ throw new Error("The recorded data is no longer available.");+ }+ const url = URL.createObjectURL(orphan.blob);+ const anchor = document.createElement("a");+ anchor.href = url;+ anchor.download = `cap-recording-${videoId}.${fileExtensionForMimeType(entry.mimeType)}`;+ anchor.click();+ window.setTimeout(() => URL.revokeObjectURL(url), 10_000);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ detailElement.textContent = message;+ activeStateKey = `error:${message}`;+ } finally {+ downloadButton.disabled = false;+ }+};++retryButton.addEventListener("click", () => void retryUpload());+downloadButton.addEventListener("click", () => void downloadRecording());++const pollStatus = async () => {+ try {+ const response = await sendServiceWorkerMessage({+ target: "service-worker",+ type: "get-recording-status",+ });+ if (response.ok && response.status) {+ consecutivePollFailures = 0;+ renderStatus(response.status);+ return;+ }+ consecutivePollFailures += 1;+ } catch {+ consecutivePollFailures += 1;+ }+ if (consecutivePollFailures >= 10 && mode === "waiting") {+ detailElement.textContent = "Still trying to reach the Cap extension…";+ }+};++chrome.runtime.onMessage.addListener((message) => {+ if (!isRecordingStatusBroadcast(message)) return false;+ if (!redirecting) {+ renderStatus(message.status);+ }+ return false;+});++// The service worker mirrors every status change into session storage, so+// the change events keep this page live without polling round trips.+chrome.storage.onChanged.addListener((changes, areaName) => {+ if (areaName !== "session" || !changes[RECORDING_STATE_KEY]) return;+ if (redirecting) return;+ void loadSharedRecordingState()+ .then((state) => {+ if (state && !redirecting) renderStatus(state.status);+ })+ .catch(() => undefined);+});++// Once the page settles in a terminal state there is nothing to reconcile:+// keep polling only while waiting/active (or while a retry awaits its first+// fresh status). Broadcasts and the session-storage mirror still repaint the+// page, so a settled error tab stops waking the service worker every 2s.+const shouldPoll = () => {+ if (redirecting || mode === "completed") return false;+ if (mode === "error") return retryPendingFreshStatus || retrying;+ return true;+};++renderWaiting();+syncTabTitle();+ensureFrameLoop();+void pollStatus();+window.setInterval(() => {+ if (shouldPoll()) {+ void pollStatus();+ }+}, POLL_INTERVAL_MS);diff --git a/apps/chrome-extension/src/uploading/styles.css b/apps/chrome-extension/src/uploading/styles.cssnew file mode 100644index 000000000..cce6c38f8--- /dev/null+++ b/apps/chrome-extension/src/uploading/styles.css@@ -0,0 +1,230 @@+@import "../shared/paper.css";++body {+ overflow: hidden;+}++.cloud-path {+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ animation: draw 0.9s ease 0.15s forwards;+}++.cloud-arrow {+ stroke: var(--accent);+ opacity: 0;+ animation:+ fade-in 0.4s ease 0.85s forwards,+ bob 1.9s ease-in-out 1.25s infinite;+}++.doodle-check,+.doodle-error {+ display: none;+}++.stage[data-mode="completed"] .doodle-cloud {+ display: none;+}++.stage[data-mode="completed"] .doodle-check {+ display: inline;+}++.check-path {+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ animation: draw 0.5s ease 0.1s forwards;+}++.spark-1 {+ animation-delay: 0.5s;+}++.spark-2 {+ animation-delay: 0.65s;+}++.spark-3 {+ animation-delay: 0.8s;+}++.stage[data-mode="error"] .doodle-cloud {+ display: none;+}++.stage[data-mode="error"] .doodle-error {+ display: inline;+}++.error-path {+ stroke: var(--error);+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ animation: draw 0.45s ease 0.1s forwards;+}++#upload-title {+ margin-top: 28px;+ font-size: 24px;+ font-weight: 500;+ letter-spacing: -0.01em;+ animation: fade-up 0.5s ease 0.1s both;+}++#upload-detail {+ margin-top: 8px;+ max-width: 400px;+ min-height: 22px;+ font-size: 15px;+ line-height: 1.5;+ color: var(--ink-soft);+ animation: fade-up 0.5s ease 0.15s both;+}++.squiggle-row {+ display: flex;+ align-items: center;+ gap: 14px;+ margin-top: 34px;+ animation: fade-up 0.5s ease 0.2s both;+}++.squiggle {+ width: min(340px, 64vw);+ height: 26px;+ overflow: visible;+}++.squiggle-track {+ fill: none;+ stroke: var(--track);+ stroke-width: 2.5;+ stroke-linecap: round;+ stroke-dasharray: 0.45 1.15;+}++.squiggle-progress {+ fill: none;+ stroke: var(--accent);+ stroke-width: 3.2;+ stroke-linecap: round;+ stroke-dasharray: 100;+ stroke-dashoffset: 100;+}++.stage[data-mode="waiting"] .squiggle-progress {+ stroke: var(--ink-soft);+ stroke-dasharray: 2 4.2;+ animation: march 1.2s linear infinite;+}++.stage[data-mode="error"] .squiggle-progress {+ stroke: var(--error);+}++.percent {+ min-width: 44px;+ text-align: left;+ font-size: 15px;+ font-weight: 500;+ font-variant-numeric: tabular-nums;+ transition: opacity 0.3s ease;+}++.stage[data-mode="waiting"] .percent {+ opacity: 0;+}++.upload-meta {+ margin-top: 16px;+ min-height: 18px;+ font-size: 12.5px;+ color: var(--ink-soft);+ font-variant-numeric: tabular-nums;+ word-break: break-word;+}++.share-link {+ display: none;+ align-items: center;+ justify-content: center;+ margin-top: 24px;+ min-height: 40px;+ padding: 0 22px;+ border: 1.5px solid var(--ink);+ border-radius: 999px;+ color: var(--ink);+ font-size: 14px;+ font-weight: 500;+ text-decoration: none;+ animation: fade-up 0.4s ease both;+}++.share-link:not([hidden]) {+ display: inline-flex;+}++.share-link:hover {+ background: var(--ink);+ color: var(--paper);+}++.error-actions {+ display: flex;+ flex-wrap: wrap;+ justify-content: center;+ gap: 12px;+ margin-top: 24px;+ animation: fade-up 0.4s ease both;+}++.error-actions[hidden] {+ display: none;+}++.action-button {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ min-height: 40px;+ padding: 0 22px;+ border: 1.5px solid var(--ink);+ border-radius: 999px;+ background: transparent;+ color: var(--ink);+ font-family: inherit;+ font-size: 14px;+ font-weight: 500;+ cursor: pointer;+}++.action-button:hover:not(:disabled) {+ background: var(--ink);+ color: var(--paper);+}++.action-button:disabled {+ opacity: 0.5;+ cursor: default;+}++@media (prefers-reduced-motion: reduce) {+ .cloud-arrow {+ animation: fade-in 0.01ms forwards;+ }++ .stage[data-mode="waiting"] .squiggle-progress {+ animation: none;+ }++ #upload-title,+ #upload-detail,+ .squiggle-row,+ .cloud-path,+ .check-path,+ .error-path {+ animation-duration: 0.01ms;+ animation-delay: 0s;+ }+}diff --git a/apps/chrome-extension/src/welcome/main.ts b/apps/chrome-extension/src/welcome/main.tsnew file mode 100644index 000000000..45f8d8fd0--- /dev/null+++ b/apps/chrome-extension/src/welcome/main.ts@@ -0,0 +1,46 @@+import { mountPageNav } from "../shared/page-nav";+import { sendServiceWorkerMessage } from "../shared/runtime";+import { loadAuth } from "../shared/storage";+import "./styles.css";++mountPageNav("welcome");++const byId = <T extends HTMLElement>(id: string): T => {+ const element = document.getElementById(id);+ if (!element) throw new Error(`Missing element: ${id}`);+ return element as T;+};++const stage = byId<HTMLElement>("stage");+const signInButton = byId<HTMLButtonElement>("sign-in");+const signedInPill = byId<HTMLElement>("signed-in");+const ctaNote = byId<HTMLElement>("cta-note");++let authPollId: number | null = null;++const showSignedIn = () => {+ if (authPollId !== null) {+ window.clearInterval(authPollId);+ authPollId = null;+ }+ stage.dataset.mode = "ready";+ signInButton.hidden = true;+ ctaNote.hidden = true;+ signedInPill.hidden = false;+};++const checkAuth = async () => {+ const auth = await loadAuth().catch(() => null);+ if (auth) showSignedIn();+};++signInButton.addEventListener("click", () => {+ ctaNote.hidden = false;+ void sendServiceWorkerMessage({+ target: "service-worker",+ type: "auth-start",+ }).catch(() => undefined);+});++authPollId = window.setInterval(() => void checkAuth(), 1000);+void checkAuth();diff --git a/apps/chrome-extension/src/welcome/styles.css b/apps/chrome-extension/src/welcome/styles.cssnew file mode 100644index 000000000..0de0b9283--- /dev/null+++ b/apps/chrome-extension/src/welcome/styles.css@@ -0,0 +1,237 @@+@import "../shared/paper.css";++.corner {+ position: fixed;+ top: 74px;+ right: 36px;+ display: flex;+ flex-direction: column;+ align-items: flex-end;+ gap: 2px;+ pointer-events: none;+}++.corner-arrow {+ width: 120px;+ height: auto;+ overflow: visible;+}++.corner-boil {+ filter: url(#boil-corner);+}++.corner-nudge {+ animation: nudge 2s ease-in-out 1.6s infinite;+}++.corner-arrow-path {+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ animation: draw 0.8s ease 0.5s forwards;+}++.corner-arrow-head {+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ animation: draw 0.3s ease 1.2s forwards;+}++.corner-hint {+ margin-right: 8px;+ font-size: 14px;+ font-style: italic;+ color: var(--ink-soft);+ opacity: 0;+ transform: rotate(-4deg);+ animation: fade-in 0.5s ease 1.3s forwards;+}++.doodle-pin {+ transform-box: fill-box;+ transform-origin: center;+ animation: pin-press 0.45s ease 1.45s;+}++.pin-body {+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ animation: draw 0.9s ease 0.15s forwards;+}++.pin-needle {+ stroke: var(--accent);+ stroke-dasharray: 1;+ stroke-dashoffset: 1;+ animation: draw 0.35s ease 1.05s forwards;+}++.spark-1 {+ animation-delay: 1.5s;+}++.spark-2 {+ animation-delay: 1.65s;+}++.spark-3 {+ animation-delay: 1.8s;+}++.steps {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 14px;+ width: min(680px, calc(100vw - 48px));+ margin: 36px 0 0;+ padding: 0;+ list-style: none;+}++.step {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 6px;+ padding: 20px 16px 18px;+ border: 1.5px solid var(--track);+ border-radius: 16px;+ background: rgba(255, 255, 255, 0.65);+ animation: fade-up 0.5s ease both;+}++.step:nth-child(1) {+ animation-delay: 0.2s;+}++.step:nth-child(2) {+ animation-delay: 0.3s;+}++.step:nth-child(3) {+ animation-delay: 0.4s;+}++.step-doodle {+ width: 44px;+ height: 44px;+ overflow: visible;+}++.doodle-stroke-sm {+ fill: none;+ stroke: var(--ink);+ stroke-width: 3;+ stroke-linecap: round;+ stroke-linejoin: round;+}++.record-dot {+ fill: var(--accent);+ animation: record-pulse 1.8s ease-in-out 1.4s infinite;+}++.step-count {+ font-size: 12px;+ font-weight: 500;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--ink-soft);+}++.step p {+ font-size: 13.5px;+ line-height: 1.45;+ color: var(--ink);+}++.cta-row {+ display: flex;+ align-items: center;+ justify-content: center;+ margin-top: 32px;+ min-height: 44px;+ animation: fade-up 0.5s ease 0.5s both;+}++.cta-note {+ margin-top: 14px;+ font-size: 13px;+ color: var(--ink-soft);+ animation: fade-up 0.3s ease both;+}++.footnote {+ animation-delay: 0.55s;+}++@keyframes nudge {+ 0%,+ 100% {+ transform: translate(0, 0);+ }+ 50% {+ transform: translate(4px, -6px);+ }+}++@keyframes pin-press {+ 0%,+ 100% {+ transform: translateY(0);+ }+ 45% {+ transform: translateY(5px);+ }+}++@keyframes record-pulse {+ 0%,+ 100% {+ opacity: 1;+ }+ 50% {+ opacity: 0.35;+ }+}++@media (max-width: 720px) {+ .steps {+ grid-template-columns: 1fr;+ }++ .corner {+ right: 16px;+ }++ .corner-arrow {+ width: 88px;+ }+}++@media (prefers-reduced-motion: reduce) {+ .corner-boil {+ filter: none;+ }++ .corner-nudge,+ .record-dot,+ .doodle-pin {+ animation: none;+ }++ .corner-hint {+ animation: fade-in 0.01ms forwards;+ }++ .step,+ .cta-row,+ .cta-note,+ .corner-arrow-path,+ .corner-arrow-head,+ .pin-body,+ .pin-needle {+ animation-duration: 0.01ms;+ animation-delay: 0s;+ }+}diff --git a/apps/chrome-extension/store-assets/promo-marquee.png b/apps/chrome-extension/store-assets/promo-marquee.pngnew file mode 100644index 000000000..6079f91b0Binary files /dev/null and b/apps/chrome-extension/store-assets/promo-marquee.png differdiff --git a/apps/chrome-extension/store-assets/promo-marquee.svg b/apps/chrome-extension/store-assets/promo-marquee.svgnew file mode 100644index 000000000..5ed9b81cb--- /dev/null+++ b/apps/chrome-extension/store-assets/promo-marquee.svg@@ -0,0 +1,51 @@+<svg width="1400" height="560" viewBox="0 0 1400 560" fill="none" xmlns="http://www.w3.org/2000/svg">+ <defs>+ <linearGradient id="bg" x1="0" y1="0" x2="1400" y2="560" gradientUnits="userSpaceOnUse">+ <stop stop-color="#0E1320"/>+ <stop offset="1" stop-color="#1C2B47"/>+ </linearGradient>+ <radialGradient id="glow" cx="0.28" cy="0.4" r="0.7">+ <stop stop-color="#4785FF" stop-opacity="0.18"/>+ <stop offset="1" stop-color="#4785FF" stop-opacity="0"/>+ </radialGradient>+ <linearGradient id="screen" x1="820" y1="160" x2="1300" y2="430" gradientUnits="userSpaceOnUse">+ <stop stop-color="#EAF1FF"/>+ <stop offset="1" stop-color="#DBE7FD"/>+ </linearGradient>+ </defs>+ <rect width="1400" height="560" fill="url(#bg)"/>+ <rect width="1400" height="560" fill="url(#glow)"/>+ <circle cx="156" cy="170" r="52" fill="#4785FF"/>+ <circle cx="156" cy="170" r="42.25" fill="#ADC9FF"/>+ <circle cx="156" cy="170" r="32.5" fill="#FFFFFF"/>+ <text x="232" y="203" font-family="Neue Montreal" font-weight="500" font-size="96" fill="#FFFFFF">Cap</text>+ <text x="104" y="305" font-family="Neue Montreal" font-weight="500" font-size="42" fill="#FFFFFF">The open source screen recorder</text>+ <text x="104" y="356" font-family="Neue Montreal" font-size="27" fill="#A9B6CE">Record your tab, screen, or camera in Chrome,</text>+ <text x="104" y="394" font-family="Neue Montreal" font-size="27" fill="#A9B6CE">your video uploads as you record, link ready instantly.</text>+ <rect x="106" y="436" width="216" height="48" rx="24" fill="#4785FF"/>+ <circle cx="136" cy="460" r="9" fill="#FFFFFF"/>+ <text x="156" y="468" font-family="Neue Montreal" font-weight="500" font-size="22" fill="#FFFFFF">Start recording</text>+ <rect x="790" y="96" width="520" height="368" rx="22" fill="#F8FAFC"/>+ <rect x="790" y="96" width="520" height="54" fill="#E9EDF3"/>+ <path d="M790 118c0-12.15 9.85-22 22-22h476c12.15 0 22 9.85 22 22v32H790v-32z" fill="#E9EDF3"/>+ <circle cx="824" cy="123" r="7" fill="#FF5F57"/>+ <circle cx="848" cy="123" r="7" fill="#F6BE4F"/>+ <circle cx="872" cy="123" r="7" fill="#28C840"/>+ <rect x="906" y="110" width="290" height="26" rx="13" fill="#F8FAFC"/>+ <text x="922" y="128" font-family="Neue Montreal" font-size="16" fill="#5B6B85">app.example.com/demo</text>+ <rect x="818" y="178" width="464" height="230" rx="16" fill="url(#screen)"/>+ <rect x="850" y="212" width="200" height="18" rx="9" fill="#4785FF"/>+ <rect x="850" y="252" width="310" height="16" rx="8" fill="#9DB1D1"/>+ <rect x="850" y="288" width="262" height="16" rx="8" fill="#9DB1D1"/>+ <rect x="850" y="324" width="288" height="16" rx="8" fill="#B8C8E2"/>+ <circle cx="1212" cy="346" r="46" fill="#4785FF"/>+ <circle cx="1212" cy="346" r="37.375" fill="#ADC9FF"/>+ <circle cx="1212" cy="346" r="28.75" fill="#FFFFFF"/>+ <circle cx="1212" cy="337" r="10" fill="#5B6B85"/>+ <path d="M1194 366c2-10 9-15 18-15s16 5 18 15" fill="#5B6B85"/>+ <rect x="858" y="436" width="384" height="56" rx="28" fill="#FFFFFF"/>+ <rect x="858" y="436" width="384" height="56" rx="28" stroke="#D4DEED" stroke-width="2"/>+ <circle cx="892" cy="464" r="14" fill="#28C840"/>+ <path d="M885 464l5 5 10-11" stroke="#FFFFFF" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"/>+ <text x="918" y="472" font-family="Neue Montreal" font-weight="500" font-size="22" fill="#12161F">Link copied: cap.so/s/demo</text>+</svg>diff --git a/apps/chrome-extension/store-assets/promo-small.png b/apps/chrome-extension/store-assets/promo-small.pngnew file mode 100644index 000000000..d832a7c8dBinary files /dev/null and b/apps/chrome-extension/store-assets/promo-small.png differdiff --git a/apps/chrome-extension/store-assets/promo-small.svg b/apps/chrome-extension/store-assets/promo-small.svgnew file mode 100644index 000000000..aa792d00c--- /dev/null+++ b/apps/chrome-extension/store-assets/promo-small.svg@@ -0,0 +1,20 @@+<svg width="440" height="280" viewBox="0 0 440 280" fill="none" xmlns="http://www.w3.org/2000/svg">+ <defs>+ <linearGradient id="bg" x1="0" y1="0" x2="440" y2="280" gradientUnits="userSpaceOnUse">+ <stop stop-color="#0E1320"/>+ <stop offset="1" stop-color="#1C2B47"/>+ </linearGradient>+ <radialGradient id="glow" cx="0.5" cy="0.42" r="0.65">+ <stop stop-color="#4785FF" stop-opacity="0.22"/>+ <stop offset="1" stop-color="#4785FF" stop-opacity="0"/>+ </radialGradient>+ </defs>+ <rect width="440" height="280" fill="url(#bg)"/>+ <rect width="440" height="280" fill="url(#glow)"/>+ <circle cx="150" cy="112" r="38" fill="#4785FF"/>+ <circle cx="150" cy="112" r="30.875" fill="#ADC9FF"/>+ <circle cx="150" cy="112" r="23.75" fill="#FFFFFF"/>+ <text x="206" y="136" font-family="Neue Montreal" font-weight="500" font-size="68" fill="#FFFFFF">Cap</text>+ <text x="220" y="196" text-anchor="middle" font-family="Neue Montreal" font-weight="500" font-size="20" fill="#C7D4EA">Screen recording, owned by you</text>+ <text x="220" y="231" text-anchor="middle" font-family="Neue Montreal" font-size="14" fill="#7E8DA8">Record your tab, screen, or camera. Share a link in seconds</text>+</svg>