Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(chrome-extension): add shared messaging and storage layer

Richie McIlroy345e46e321df
diff --git a/apps/chrome-extension/src/chrome.d.ts b/apps/chrome-extension/src/chrome.d.ts
new file mode 100644
index 000000000..6a8a9b0a6
--- /dev/null
+++ b/apps/chrome-extension/src/chrome.d.ts
@@ -0,0 +1,12 @@
+// Chrome API typings come from @types/chrome; this file only declares the
+// Vite-specific module shapes the extension relies on.
+interface ImportMeta {
+ readonly env: {
+ readonly MODE: string;
+ };
+}
+
+declare module "*.css?inline" {
+ const content: string;
+ export default content;
+}
diff --git a/apps/chrome-extension/src/shared/api.ts b/apps/chrome-extension/src/shared/api.ts
new file mode 100644
index 000000000..25aded7b9
--- /dev/null
+++ b/apps/chrome-extension/src/shared/api.ts
@@ -0,0 +1,223 @@
+import type { Extension, Video } from "@cap/web-domain";
+
+import type {
+ BootstrapData,
+ ExtensionAuth,
+ ExtensionSettings,
+ InstantRecordingCreation,
+} from "./types";
+
+// The JSON request body matches the encoded side of the server schema, so
+// contract drift fails to compile instead of surfacing at runtime.
+type CreateInstantRecordingInput =
+ typeof Video.InstantRecordingCreateInput.Encoded;
+
+// A hung request would otherwise leave the recorder UI stuck with no way out
+// (the floating bar shows "creating" until the start call settles).
+const API_REQUEST_TIMEOUT_MS = 30_000;
+const AUTH_CHECK_TIMEOUT_MS = 10_000;
+
+// Literal copies of the contract paths. A value import of @cap/web-domain
+// would drag the effect runtime into every extension bundle, so the import
+// above is type-only and these `satisfies` checks make any drift from the
+// contract fail to compile instead of surfacing at runtime.
+const EXTENSION_HTTP_PREFIX =
+ "/extension" satisfies typeof Extension.EXTENSION_HTTP_PREFIX;
+
+const ExtensionApiPaths = {
+ startAuth: "/auth/start",
+ approveAuth: "/auth/approve",
+ revokeAuth: "/auth/revoke",
+ bootstrap: "/bootstrap",
+ createInstantRecording: "/instant-recordings",
+ updateInstantRecordingProgress: "/instant-recordings/progress",
+ deleteInstantRecording: (videoId: string) =>
+ `/instant-recordings/${encodeURIComponent(videoId)}` as const,
+} as const satisfies typeof Extension.ExtensionApiPaths;
+
+// The web app mounts the HTTP API under /api (web-domain Http/Api.ts).
+const EXTENSION_API_PREFIX = `/api${EXTENSION_HTTP_PREFIX}`;
+
+const extensionApiPath = (path: string) => `${EXTENSION_API_PREFIX}${path}`;
+
+const apiUrl = (settings: ExtensionSettings, path: string) =>
+ new URL(path, settings.apiBaseUrl).toString();
+
+const checkAuthStartRoute = async (
+ settings: ExtensionSettings,
+ url: URL,
+ redirectUri: string,
+) => {
+ try {
+ const response = await fetch(url, {
+ redirect: "manual",
+ signal: AbortSignal.timeout(AUTH_CHECK_TIMEOUT_MS),
+ });
+ if (response.type === "opaqueredirect" || response.status === 302) return;
+ if (response.ok) return;
+ throw new Error(`${response.status} ${await response.text()}`);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ throw new Error(
+ `Could not reach Cap extension auth at ${url.origin}. Start the local web server with pnpm dev:extension and make sure the extension Options Cap URL is ${settings.apiBaseUrl}. Redirect URI: ${redirectUri}. ${message}`,
+ );
+ }
+};
+
+// Carries the HTTP status so callers can tell a definitive server answer
+// (the request was processed and rejected) from a failure where the request
+// may never have arrived.
+export class ApiRequestError extends Error {
+ readonly status: number;
+
+ constructor(status: number, message: string) {
+ super(message || `Request failed with status ${status}`);
+ this.name = "ApiRequestError";
+ this.status = status;
+ }
+}
+
+const requestJson = async <TResponse>({
+ settings,
+ auth,
+ path,
+ method,
+ body,
+}: {
+ settings: ExtensionSettings;
+ auth: ExtensionAuth;
+ path: string;
+ method: "GET" | "POST" | "DELETE";
+ body?: unknown;
+}) => {
+ const response = await fetch(apiUrl(settings, path), {
+ method,
+ headers: {
+ Authorization: `Bearer ${auth.authApiKey}`,
+ "Content-Type": "application/json",
+ },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ signal: AbortSignal.timeout(API_REQUEST_TIMEOUT_MS),
+ });
+
+ if (!response.ok) {
+ throw new ApiRequestError(response.status, await response.text());
+ }
+
+ return (await response.json()) as TResponse;
+};
+
+export const createAuthStart = async (settings: ExtensionSettings) => {
+ const redirectUri = chrome.identity.getRedirectURL();
+ const state = crypto.randomUUID();
+ const url = new URL(
+ apiUrl(settings, extensionApiPath(ExtensionApiPaths.startAuth)),
+ );
+ url.searchParams.set("redirectUri", redirectUri);
+ url.searchParams.set("state", state);
+
+ await checkAuthStartRoute(settings, url, redirectUri);
+
+ return { redirectUri, state, url: url.toString() };
+};
+
+export const parseAuthResponse = (responseUrl: string, state: string) => {
+ const hash = new URL(responseUrl).hash.slice(1);
+ const params = new URLSearchParams(hash);
+ if (params.get("state") !== state) {
+ throw new Error("Auth state did not match");
+ }
+
+ // The consent page's Cancel link redirects back with an error in the
+ // fragment instead of a key.
+ const error = params.get("error");
+ if (error) {
+ throw new Error(
+ error === "access_denied"
+ ? "Sign-in was canceled."
+ : `Sign-in failed: ${error}`,
+ );
+ }
+
+ const authApiKey = params.get("authApiKey");
+ const userId = params.get("userId");
+ if (!authApiKey || !userId) {
+ throw new Error("Auth response did not include a token");
+ }
+
+ return { authApiKey, userId };
+};
+
+export const revokeAuth = (settings: ExtensionSettings, auth: ExtensionAuth) =>
+ requestJson<{ success: boolean }>({
+ settings,
+ auth,
+ path: extensionApiPath(ExtensionApiPaths.revokeAuth),
+ method: "POST",
+ });
+
+export const fetchBootstrap = (
+ settings: ExtensionSettings,
+ auth: ExtensionAuth,
+) =>
+ requestJson<BootstrapData>({
+ settings,
+ auth,
+ path: extensionApiPath(ExtensionApiPaths.bootstrap),
+ method: "GET",
+ });
+
+export const createInstantRecording = ({
+ settings,
+ auth,
+ input,
+}: {
+ settings: ExtensionSettings;
+ auth: ExtensionAuth;
+ input: CreateInstantRecordingInput;
+}) =>
+ requestJson<InstantRecordingCreation>({
+ settings,
+ auth,
+ path: extensionApiPath(ExtensionApiPaths.createInstantRecording),
+ method: "POST",
+ body: input,
+ });
+
+export const updateUploadProgress = ({
+ settings,
+ auth,
+ videoId,
+ uploaded,
+ total,
+}: {
+ settings: ExtensionSettings;
+ auth: ExtensionAuth;
+ videoId: string;
+ uploaded: number;
+ total: number;
+}) =>
+ requestJson<{ success: boolean }>({
+ settings,
+ auth,
+ path: extensionApiPath(ExtensionApiPaths.updateInstantRecordingProgress),
+ method: "POST",
+ body: {
+ videoId,
+ uploaded,
+ total,
+ updatedAt: new Date().toISOString(),
+ },
+ });
+
+export const deleteInstantRecording = (
+ settings: ExtensionSettings,
+ auth: ExtensionAuth,
+ videoId: string,
+) =>
+ requestJson<{ success: boolean }>({
+ settings,
+ auth,
+ path: extensionApiPath(ExtensionApiPaths.deleteInstantRecording(videoId)),
+ method: "DELETE",
+ });
diff --git a/apps/chrome-extension/src/shared/cap-brand.tsx b/apps/chrome-extension/src/shared/cap-brand.tsx
new file mode 100644
index 000000000..d5e21ecdb
--- /dev/null
+++ b/apps/chrome-extension/src/shared/cap-brand.tsx
@@ -0,0 +1,57 @@
+import type { SVGProps } from "react";
+
+export const CapBrand = (props: SVGProps<SVGSVGElement>) => (
+ <svg
+ className="brand-logo"
+ xmlns="http://www.w3.org/2000/svg"
+ fill="none"
+ viewBox="0 0 103 40"
+ aria-label="Cap"
+ {...props}
+ >
+ <title>Cap</title>
+ <path
+ fill="#4785FF"
+ d="M20 36c8.837 0 16-7.163 16-16S28.837 4 20 4 4 11.164 4 20s7.164 16 16 16"
+ />
+ <path
+ fill="#ADC9FF"
+ d="M20 33c7.18 0 13-5.82 13-13S27.18 7 20 7 7 12.82 7 20s5.82 13 13 13"
+ />
+ <path
+ fill="#fff"
+ d="M20 30c5.523 0 10-4.477 10-10s-4.477-10-10-10-10 4.477-10 10 4.477 10 10 10"
+ />
+ <path
+ fill="currentColor"
+ d="M58.416 30.448c-5.404 0-9.212-3.864-9.212-10.36 0-6.384 3.668-10.416 9.268-10.416 5.068 0 7.784 2.66 8.624 7.168l-3.808.196c-.476-2.604-2.072-4.2-4.816-4.2-3.388 0-5.488 2.828-5.488 7.252 0 4.48 2.156 7.196 5.46 7.196 2.94 0 4.508-1.708 4.956-4.564l3.808.196c-.784 4.676-3.752 7.532-8.792 7.532m16.23-.112c-3.137 0-5.209-1.484-5.209-4.088 0-2.576 1.596-3.948 4.872-4.592l4.956-.98c0-2.1-.98-3.192-2.856-3.192-1.764 0-2.716.812-3.052 2.324l-3.668-.168c.588-3.136 2.996-4.928 6.72-4.928 4.256 0 6.44 2.24 6.44 6.216v5.432c0 .812.28 1.036.84 1.036h.476V30c-.224.056-.812.112-1.288.112-1.624 0-2.828-.588-3.136-2.436-.728 1.596-2.632 2.66-5.096 2.66m.727-2.604c2.38 0 3.892-1.512 3.892-3.78v-.84l-3.864.784c-1.596.308-2.24.98-2.24 2.016 0 1.176.784 1.82 2.212 1.82M86.874 34.2V15.048h3.444l.056 2.212c.868-1.652 2.52-2.548 4.48-2.548 4.256 0 6.356 3.5 6.356 7.812s-2.128 7.812-6.384 7.812c-1.904 0-3.556-.924-4.368-2.38V34.2zm7.112-6.776c2.184 0 3.5-1.82 3.5-4.9s-1.316-4.9-3.5-4.9-3.528 1.652-3.528 4.9 1.316 4.9 3.528 4.9"
+ />
+ </svg>
+);
+
+export const DoodleBoilFilter = ({ id = "boil" }: { id?: string }) => (
+ <filter id={id} x="-15%" y="-15%" width="130%" height="130%">
+ <feTurbulence
+ type="fractalNoise"
+ baseFrequency="0.05"
+ numOctaves="2"
+ seed="1"
+ result="noise"
+ >
+ <animate
+ attributeName="seed"
+ values="1;3;5;7"
+ dur="0.6s"
+ repeatCount="indefinite"
+ calcMode="discrete"
+ />
+ </feTurbulence>
+ <feDisplacementMap
+ in="SourceGraphic"
+ in2="noise"
+ scale="3"
+ xChannelSelector="R"
+ yChannelSelector="G"
+ />
+ </filter>
+);
diff --git a/apps/chrome-extension/src/shared/format-duration.ts b/apps/chrome-extension/src/shared/format-duration.ts
new file mode 100644
index 000000000..8ec62b380
--- /dev/null
+++ b/apps/chrome-extension/src/shared/format-duration.ts
@@ -0,0 +1,17 @@
+// Live timers (recording bars) count up from 0:00 and truncate so the
+// display never runs ahead of the actual elapsed time.
+export const formatDuration = (durationMs: number) => {
+ const totalSeconds = Math.max(0, Math.floor(durationMs / 1000));
+ const minutes = Math.floor(totalSeconds / 60);
+ const seconds = totalSeconds % 60;
+ return `${minutes}:${seconds.toString().padStart(2, "0")}`;
+};
+
+// Finished recordings round to the nearest second and never show 0:00 — a
+// sub-second capture still represents real data.
+export const formatRecordedDuration = (durationMs: number) => {
+ const totalSeconds = Math.max(1, Math.round(durationMs / 1000));
+ const minutes = Math.floor(totalSeconds / 60);
+ const seconds = totalSeconds % 60;
+ return `${minutes}:${seconds.toString().padStart(2, "0")}`;
+};
diff --git a/apps/chrome-extension/src/shared/messages.test.ts b/apps/chrome-extension/src/shared/messages.test.ts
new file mode 100644
index 000000000..51eb884fb
--- /dev/null
+++ b/apps/chrome-extension/src/shared/messages.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vitest";
+import {
+ isOffscreenRequest,
+ isOverlayMessage,
+ isRecordingStatusBroadcast,
+ isServiceWorkerRequest,
+} from "./messages";
+
+describe("extension message contracts", () => {
+ it("routes popup requests only to the service worker", () => {
+ const message = { target: "service-worker", type: "bootstrap" };
+ expect(isServiceWorkerRequest(message)).toBe(true);
+ expect(isOffscreenRequest(message)).toBe(false);
+ });
+
+ it("routes recording requests only to the offscreen document", () => {
+ const message = { target: "offscreen", type: "get-recording-status" };
+ expect(isOffscreenRequest(message)).toBe(true);
+ expect(isServiceWorkerRequest(message)).toBe(false);
+ });
+
+ it("accepts overlay messages without runtime targets", () => {
+ expect(isOverlayMessage({ type: "overlay-hide" })).toBe(true);
+ expect(isOverlayMessage({ type: "overlay-enter-auto-pip" })).toBe(true);
+ expect(isOverlayMessage({ type: "overlay-exit-auto-pip" })).toBe(true);
+ expect(
+ isOverlayMessage({ target: "offscreen", type: "overlay-hide" }),
+ ).toBe(true);
+ expect(isOverlayMessage({ type: "bootstrap" })).toBe(false);
+ });
+
+ it("routes recording status broadcasts separately from requests", () => {
+ const message = {
+ target: "recording-status",
+ type: "recording-status-changed",
+ status: { phase: "completed", videoId: "v", shareUrl: "https://cap.so" },
+ };
+ expect(isRecordingStatusBroadcast(message)).toBe(true);
+ expect(isServiceWorkerRequest(message)).toBe(false);
+ expect(isOffscreenRequest(message)).toBe(false);
+ expect(
+ isRecordingStatusBroadcast({
+ target: "recording-status",
+ type: "bootstrap",
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/apps/chrome-extension/src/shared/messages.ts b/apps/chrome-extension/src/shared/messages.ts
new file mode 100644
index 000000000..c3beac4df
--- /dev/null
+++ b/apps/chrome-extension/src/shared/messages.ts
@@ -0,0 +1,41 @@
+import type {
+ OffscreenRequest,
+ OverlayMessage,
+ RecordingStatusBroadcast,
+ ServiceWorkerRequest,
+} from "./types";
+
+const hasType = (message: unknown): message is { type: string } =>
+ !!message &&
+ typeof message === "object" &&
+ "type" in message &&
+ typeof message.type === "string";
+
+const hasTarget = <TTarget extends string>(
+ message: unknown,
+ target: TTarget,
+): message is { target: TTarget; type: string } =>
+ hasType(message) && "target" in message && message.target === target;
+
+export const isServiceWorkerRequest = (
+ message: unknown,
+): message is ServiceWorkerRequest => hasTarget(message, "service-worker");
+
+export const isOffscreenRequest = (
+ message: unknown,
+): message is OffscreenRequest => hasTarget(message, "offscreen");
+
+export const isOverlayMessage = (message: unknown): message is OverlayMessage =>
+ hasType(message) &&
+ (message.type === "overlay-settings" ||
+ message.type === "overlay-enter-auto-pip" ||
+ message.type === "overlay-exit-auto-pip" ||
+ message.type === "overlay-hide" ||
+ message.type === "overlay-panel-toggle" ||
+ message.type === "overlay-panel-hide");
+
+export const isRecordingStatusBroadcast = (
+ message: unknown,
+): message is RecordingStatusBroadcast =>
+ hasTarget(message, "recording-status") &&
+ message.type === "recording-status-changed";
diff --git a/apps/chrome-extension/src/shared/page-nav.ts b/apps/chrome-extension/src/shared/page-nav.ts
new file mode 100644
index 000000000..8f247e912
--- /dev/null
+++ b/apps/chrome-extension/src/shared/page-nav.ts
@@ -0,0 +1,48 @@
+export const PAGE_NAV_LINKS = [
+ { id: "welcome", label: "Welcome", href: "welcome.html" },
+ { id: "how-it-works", label: "How it works", href: "how-it-works.html" },
+ { id: "camera", label: "Camera access", href: "camera-permission.html" },
+ { id: "options", label: "Options", href: "options.html" },
+] as const;
+
+export type PageNavId = (typeof PAGE_NAV_LINKS)[number]["id"];
+
+export const mountPageNav = (active: PageNavId) => {
+ if (document.querySelector(".page-nav")) return;
+
+ const nav = document.createElement("nav");
+ nav.className = "page-nav";
+ nav.setAttribute("aria-label", "Cap extension pages");
+
+ const inner = document.createElement("div");
+ inner.className = "page-nav-inner";
+
+ const brand = document.createElement("a");
+ brand.className = "page-nav-brand";
+ brand.href = "welcome.html";
+ brand.setAttribute("aria-label", "Cap");
+ const logo = document.createElement("img");
+ logo.src = "icons/icon-32.png";
+ logo.alt = "";
+ logo.width = 26;
+ logo.height = 26;
+ brand.append(logo);
+
+ const links = document.createElement("div");
+ links.className = "page-nav-links";
+ for (const link of PAGE_NAV_LINKS) {
+ const anchor = document.createElement("a");
+ anchor.className =
+ link.id === active ? "page-nav-link is-active" : "page-nav-link";
+ anchor.href = link.href;
+ anchor.textContent = link.label;
+ if (link.id === active) {
+ anchor.setAttribute("aria-current", "page");
+ }
+ links.append(anchor);
+ }
+
+ inner.append(brand, links);
+ nav.append(inner);
+ document.body.prepend(nav);
+};
diff --git a/apps/chrome-extension/src/shared/paper.css b/apps/chrome-extension/src/shared/paper.css
new file mode 100644
index 000000000..a576336e1
--- /dev/null
+++ b/apps/chrome-extension/src/shared/paper.css
@@ -0,0 +1,446 @@
+@font-face {
+ font-family: "Neue Montreal";
+ src: url("/fonts/NeueMontreal-Regular.otf") format("opentype");
+ font-weight: 400;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: "Neue Montreal";
+ src: url("/fonts/NeueMontreal-Italic.otf") format("opentype");
+ font-weight: 400;
+ font-style: italic;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: "Neue Montreal";
+ src: url("/fonts/NeueMontreal-Medium.otf") format("opentype");
+ font-weight: 500;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: "Neue Montreal";
+ src: url("/fonts/NeueMontreal-Bold.otf") format("opentype");
+ font-weight: 700;
+ font-style: normal;
+ font-display: swap;
+}
+
+*,
+*:before,
+*:after {
+ box-sizing: border-box;
+}
+
+:root {
+ --paper: #fbfaf7;
+ --ink: #20242c;
+ --ink-soft: #8b8f98;
+ --accent: #4785ff;
+ --track: #dcdcd4;
+ --error: #e5484d;
+ --success: #2f9e69;
+}
+
+html,
+body {
+ height: 100%;
+}
+
+body {
+ margin: 0;
+ min-height: 100dvh;
+ display: flex;
+ flex-direction: column;
+ background: var(--paper);
+ color: var(--ink);
+ font-family:
+ "Neue Montreal", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
+ "Segoe UI", sans-serif;
+ -webkit-font-smoothing: antialiased;
+}
+
+h1,
+h2,
+p {
+ margin: 0;
+}
+
+.page-nav {
+ position: sticky;
+ top: 0;
+ z-index: 20;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ height: 64px;
+ flex: 0 0 64px;
+ border-bottom: 1.5px solid var(--track);
+ background: rgba(251, 250, 247, 0.92);
+ backdrop-filter: blur(10px);
+}
+
+.page-nav-inner {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ width: min(760px, calc(100vw - 48px));
+}
+
+.page-nav-brand {
+ display: flex;
+ align-items: center;
+ border-radius: 9px;
+ line-height: 0;
+}
+
+.page-nav-brand img {
+ width: 26px;
+ height: 26px;
+ border-radius: 7px;
+}
+
+.page-nav-brand:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 3px;
+}
+
+.page-nav-links {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px;
+ border: 1.5px solid var(--track);
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.65);
+}
+
+.page-nav-link {
+ display: inline-flex;
+ align-items: center;
+ padding: 5px 13px;
+ border-radius: 999px;
+ color: var(--ink-soft);
+ font-size: 13px;
+ font-weight: 500;
+ white-space: nowrap;
+ text-decoration: none;
+ transition:
+ background 0.18s ease,
+ color 0.18s ease;
+}
+
+.page-nav-link:hover {
+ color: var(--ink);
+}
+
+.page-nav-link:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 1px;
+}
+
+.page-nav-link.is-active {
+ background: var(--ink);
+ color: var(--paper);
+}
+
+.stage {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ text-align: center;
+ padding: 48px 24px 24px;
+}
+
+.brand {
+ margin-bottom: 40px;
+ animation: fade-up 0.5s ease both;
+}
+
+.brand-logo {
+ height: 26px;
+ width: auto;
+ color: var(--ink);
+}
+
+.doodle {
+ width: 128px;
+ height: auto;
+ animation: fade-up 0.5s ease 0.05s both;
+}
+
+.doodle-boil {
+ filter: url(#boil);
+}
+
+.doodle-stroke {
+ fill: none;
+ stroke: var(--ink);
+ stroke-width: 4.5;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+
+.spark {
+ fill: none;
+ stroke: var(--accent);
+ stroke-width: 3.5;
+ stroke-linecap: round;
+ opacity: 0;
+ transform-box: fill-box;
+ transform-origin: center;
+ animation: spark-pop 0.5s ease forwards;
+}
+
+.stage h1 {
+ margin-top: 26px;
+ font-size: 26px;
+ font-weight: 500;
+ letter-spacing: -0.01em;
+ animation: fade-up 0.5s ease 0.1s both;
+}
+
+.lede {
+ margin-top: 8px;
+ max-width: 440px;
+ font-size: 15px;
+ line-height: 1.5;
+ color: var(--ink-soft);
+ animation: fade-up 0.5s ease 0.15s both;
+}
+
+.card {
+ display: grid;
+ gap: 14px;
+ padding: 20px;
+ border: 1.5px solid var(--track);
+ border-radius: 16px;
+ background: rgba(255, 255, 255, 0.65);
+ text-align: left;
+ animation: fade-up 0.5s ease both;
+}
+
+.card h2 {
+ font-size: 12px;
+ font-weight: 500;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--ink-soft);
+}
+
+.cta {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 42px;
+ padding: 0 24px;
+ 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;
+ transition:
+ background 0.2s ease,
+ color 0.2s ease,
+ opacity 0.2s ease;
+}
+
+.cta:hover:not(:disabled) {
+ background: var(--ink);
+ color: var(--paper);
+}
+
+.cta:disabled {
+ cursor: not-allowed;
+ opacity: 0.45;
+}
+
+.cta.ghost {
+ border-color: var(--track);
+ color: var(--ink-soft);
+}
+
+.cta.ghost:hover:not(:disabled) {
+ background: transparent;
+ border-color: var(--ink-soft);
+ color: var(--ink);
+}
+
+.cta[hidden] {
+ display: none;
+}
+
+.paper-pill {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 42px;
+ padding: 8px 20px;
+ border: 1.5px solid var(--ink);
+ border-radius: 999px;
+ color: var(--ink);
+ font-size: 14px;
+ font-weight: 500;
+ line-height: 1.4;
+ animation: fade-up 0.4s ease both;
+}
+
+.paper-pill.success {
+ border-color: var(--success);
+ color: var(--success);
+}
+
+.paper-pill.error {
+ border-color: var(--error);
+ border-radius: 16px;
+ color: var(--error);
+ text-align: left;
+}
+
+.paper-pill[hidden] {
+ display: none;
+}
+
+.check-mini {
+ width: 16px;
+ height: 16px;
+ flex: 0 0 auto;
+ overflow: visible;
+}
+
+.check-mini-path {
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 3;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+ stroke-dasharray: 1;
+ stroke-dashoffset: 1;
+ animation: draw 0.4s ease 0.15s forwards;
+}
+
+.field {
+ display: grid;
+ gap: 6px;
+ text-align: left;
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--ink);
+}
+
+.field > span {
+ color: var(--ink-soft);
+}
+
+.field input,
+.field select {
+ min-height: 40px;
+ padding: 0 12px;
+ border: 1.5px solid var(--track);
+ border-radius: 10px;
+ background: #ffffff;
+ color: var(--ink);
+ font: inherit;
+ font-size: 14px;
+ transition: border-color 0.15s ease;
+}
+
+.field input:focus,
+.field select:focus {
+ outline: none;
+ border-color: var(--ink);
+}
+
+.footnote {
+ padding: 0 24px 28px;
+ text-align: center;
+ font-size: 12.5px;
+ color: var(--ink-soft);
+ animation: fade-up 0.5s ease 0.25s both;
+}
+
+@keyframes draw {
+ to {
+ stroke-dashoffset: 0;
+ }
+}
+
+@keyframes fade-in {
+ to {
+ opacity: 1;
+ }
+}
+
+@keyframes fade-up {
+ from {
+ opacity: 0;
+ transform: translateY(10px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+@keyframes bob {
+ 0%,
+ 100% {
+ transform: translateY(0);
+ }
+ 50% {
+ transform: translateY(-4px);
+ }
+}
+
+@keyframes spark-pop {
+ from {
+ opacity: 0;
+ transform: scale(0.2);
+ }
+ 60% {
+ opacity: 1;
+ transform: scale(1.2);
+ }
+ to {
+ opacity: 1;
+ transform: scale(1);
+ }
+}
+
+@keyframes march {
+ from {
+ stroke-dashoffset: 0;
+ }
+ to {
+ stroke-dashoffset: -6.2;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .doodle-boil {
+ filter: none;
+ }
+
+ .brand,
+ .doodle,
+ .stage h1,
+ .lede,
+ .card,
+ .paper-pill,
+ .check-mini-path,
+ .spark,
+ .footnote {
+ animation-duration: 0.01ms;
+ animation-delay: 0s;
+ }
+}
diff --git a/apps/chrome-extension/src/shared/preferences.test.ts b/apps/chrome-extension/src/shared/preferences.test.ts
new file mode 100644
index 000000000..696632ae8
--- /dev/null
+++ b/apps/chrome-extension/src/shared/preferences.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from "vitest";
+import {
+ reconcileRememberedDevices,
+ rememberCameraSelection,
+} from "./preferences";
+import type { CameraDevice, ExtensionSettings } from "./types";
+
+const camera: CameraDevice = {
+ deviceId: "camera-1",
+ groupId: "group-1",
+ label: "Studio Camera",
+};
+
+const settings: ExtensionSettings = {
+ apiBaseUrl: "https://cap.so",
+ capture: {
+ recordingMode: "fullscreen",
+ camera: null,
+ microphone: null,
+ },
+ webcam: {
+ enabled: false,
+ deviceId: null,
+ position: "bottom-left",
+ size: 230,
+ shape: "round",
+ mirror: false,
+ },
+ microphone: {
+ enabled: false,
+ deviceId: null,
+ },
+ systemAudio: {
+ enabled: true,
+ },
+ sounds: {
+ enabled: true,
+ },
+};
+
+describe("camera preferences", () => {
+ it("clears the remembered camera when camera is explicitly disabled", () => {
+ const selected = rememberCameraSelection(settings, camera.deviceId, [
+ camera,
+ ]);
+
+ expect(
+ rememberCameraSelection(selected, null, [camera]).capture.camera,
+ ).toBeNull();
+ });
+
+ it("does not restore the remembered camera when webcam preview was disabled", () => {
+ const selected = rememberCameraSelection(settings, camera.deviceId, [
+ camera,
+ ]);
+ const inactive = {
+ ...selected,
+ webcam: {
+ ...selected.webcam,
+ enabled: false,
+ deviceId: null,
+ },
+ };
+
+ const reconciled = reconcileRememberedDevices(inactive, [camera], []);
+
+ expect(reconciled.webcam.enabled).toBe(false);
+ expect(reconciled.webcam.deviceId).toBeNull();
+ });
+
+ it("restores the remembered camera when webcam preview is enabled without an active device", () => {
+ const selected = rememberCameraSelection(settings, camera.deviceId, [
+ camera,
+ ]);
+ const missingDevice = {
+ ...selected,
+ webcam: {
+ ...selected.webcam,
+ enabled: true,
+ deviceId: null,
+ },
+ };
+
+ const reconciled = reconcileRememberedDevices(missingDevice, [camera], []);
+
+ expect(reconciled.webcam.enabled).toBe(true);
+ expect(reconciled.webcam.deviceId).toBe(camera.deviceId);
+ });
+});
diff --git a/apps/chrome-extension/src/shared/preferences.ts b/apps/chrome-extension/src/shared/preferences.ts
new file mode 100644
index 000000000..cab50d1ee
--- /dev/null
+++ b/apps/chrome-extension/src/shared/preferences.ts
@@ -0,0 +1,180 @@
+import {
+ type CameraDevice,
+ DEFAULT_CAMERA_DEVICE_ID,
+ DEFAULT_MICROPHONE_DEVICE_ID,
+ type DevicePreference,
+ type ExtensionSettings,
+ type MicrophoneDevice,
+ type RecordingMode,
+} from "./types";
+
+type DeviceWithIdentity = CameraDevice | MicrophoneDevice;
+
+const cleanText = (value: string | null | undefined) => {
+ const trimmed = value?.trim();
+ return trimmed && trimmed.length > 0 ? trimmed : null;
+};
+
+const rememberDevice = (
+ deviceId: string,
+ devices: DeviceWithIdentity[],
+): DevicePreference => {
+ const device = devices.find((item) => item.deviceId === deviceId);
+ return {
+ deviceId,
+ label: cleanText(device?.label),
+ groupId: cleanText(device?.groupId),
+ updatedAt: Date.now(),
+ };
+};
+
+const findRememberedDevice = (
+ preference: DevicePreference | null,
+ devices: DeviceWithIdentity[],
+) => {
+ if (!preference) return null;
+
+ const exactMatch = devices.find(
+ (device) => device.deviceId === preference.deviceId,
+ );
+ if (exactMatch) return exactMatch;
+
+ const groupMatch = preference.groupId
+ ? devices.find((device) => cleanText(device.groupId) === preference.groupId)
+ : null;
+ if (groupMatch) return groupMatch;
+
+ return preference.label
+ ? (devices.find((device) => cleanText(device.label) === preference.label) ??
+ null)
+ : null;
+};
+
+const resolveDeviceId = ({
+ currentDeviceId,
+ preference,
+ devices,
+ defaultDeviceId,
+}: {
+ currentDeviceId: string | null;
+ preference: DevicePreference | null;
+ devices: DeviceWithIdentity[];
+ defaultDeviceId: string;
+}) => {
+ if (!currentDeviceId || currentDeviceId === defaultDeviceId) {
+ return currentDeviceId;
+ }
+
+ if (devices.some((device) => device.deviceId === currentDeviceId)) {
+ return currentDeviceId;
+ }
+
+ return (
+ findRememberedDevice(preference, devices)?.deviceId ??
+ devices[0]?.deviceId ??
+ currentDeviceId
+ );
+};
+
+export const rememberRecordingMode = (
+ settings: ExtensionSettings,
+ recordingMode: RecordingMode,
+): ExtensionSettings => ({
+ ...settings,
+ capture: {
+ ...settings.capture,
+ recordingMode,
+ },
+});
+
+export const rememberCameraSelection = (
+ settings: ExtensionSettings,
+ cameraId: string | null,
+ devices: CameraDevice[],
+): ExtensionSettings => ({
+ ...settings,
+ capture: {
+ ...settings.capture,
+ camera: cameraId ? rememberDevice(cameraId, devices) : null,
+ },
+ webcam: {
+ ...settings.webcam,
+ enabled: Boolean(cameraId),
+ deviceId: cameraId,
+ },
+});
+
+export const rememberMicrophoneSelection = (
+ settings: ExtensionSettings,
+ microphoneId: string | null,
+ devices: MicrophoneDevice[],
+): ExtensionSettings => ({
+ ...settings,
+ capture: {
+ ...settings.capture,
+ microphone: microphoneId
+ ? rememberDevice(microphoneId, devices)
+ : settings.capture.microphone,
+ },
+ microphone: {
+ enabled: microphoneId !== null,
+ deviceId:
+ microphoneId === null || microphoneId === DEFAULT_MICROPHONE_DEVICE_ID
+ ? null
+ : microphoneId,
+ },
+});
+
+export const reconcileRememberedDevices = (
+ settings: ExtensionSettings,
+ cameras: CameraDevice[],
+ microphones: MicrophoneDevice[],
+) => {
+ const restoredCameraId =
+ settings.webcam.enabled && !settings.webcam.deviceId
+ ? (findRememberedDevice(settings.capture.camera, cameras)?.deviceId ??
+ null)
+ : null;
+ const cameraId =
+ restoredCameraId ??
+ resolveDeviceId({
+ currentDeviceId: settings.webcam.deviceId,
+ preference: settings.capture.camera,
+ devices: cameras,
+ defaultDeviceId: DEFAULT_CAMERA_DEVICE_ID,
+ });
+ const activeMicrophoneId =
+ settings.microphone.enabled &&
+ settings.microphone.deviceId !== null &&
+ settings.microphone.deviceId !== DEFAULT_MICROPHONE_DEVICE_ID
+ ? settings.microphone.deviceId
+ : null;
+ const microphoneId = resolveDeviceId({
+ currentDeviceId: activeMicrophoneId,
+ preference: settings.capture.microphone,
+ devices: microphones,
+ defaultDeviceId: DEFAULT_MICROPHONE_DEVICE_ID,
+ });
+
+ if (
+ cameraId === settings.webcam.deviceId &&
+ microphoneId === activeMicrophoneId
+ ) {
+ return settings;
+ }
+
+ return {
+ ...settings,
+ webcam: {
+ ...settings.webcam,
+ deviceId: cameraId,
+ enabled: restoredCameraId
+ ? true
+ : settings.webcam.enabled && Boolean(cameraId),
+ },
+ microphone: {
+ ...settings.microphone,
+ deviceId: microphoneId,
+ },
+ };
+};
diff --git a/apps/chrome-extension/src/shared/runtime.ts b/apps/chrome-extension/src/shared/runtime.ts
new file mode 100644
index 000000000..d36940fe2
--- /dev/null
+++ b/apps/chrome-extension/src/shared/runtime.ts
@@ -0,0 +1,12 @@
+import type { ServiceWorkerRequest, ServiceWorkerResponse } from "./types";
+
+export const sendServiceWorkerMessage = (message: ServiceWorkerRequest) =>
+ new Promise<ServiceWorkerResponse>((resolve, reject) => {
+ chrome.runtime.sendMessage(message, (response) => {
+ if (chrome.runtime.lastError) {
+ reject(new Error(chrome.runtime.lastError.message ?? "Message failed"));
+ return;
+ }
+ resolve(response as ServiceWorkerResponse);
+ });
+ });
diff --git a/apps/chrome-extension/src/shared/storage-keys.ts b/apps/chrome-extension/src/shared/storage-keys.ts
new file mode 100644
index 000000000..15dfd812d
--- /dev/null
+++ b/apps/chrome-extension/src/shared/storage-keys.ts
@@ -0,0 +1,7 @@
+// Storage keys shared with the content bootstrap script. The bootstrap is
+// injected into every page and must stay a few KB of dependency-free code,
+// so it imports the keys it needs from here instead of pulling in the full
+// storage module. Everything else keeps importing them via ./storage, which
+// re-exports these constants, so both sides always agree on the key names.
+export const RECORDING_STATE_KEY = "cap-extension-recording-state";
+export const SHARED_UI_STATE_KEY = "cap-extension-shared-ui-state";
diff --git a/apps/chrome-extension/src/shared/storage.test.ts b/apps/chrome-extension/src/shared/storage.test.ts
new file mode 100644
index 000000000..f60cf32d7
--- /dev/null
+++ b/apps/chrome-extension/src/shared/storage.test.ts
@@ -0,0 +1,116 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import {
+ type FailedRecording,
+ loadFailedRecordings,
+ loadOverlayTokens,
+ loadSharedUiState,
+ registerOverlayToken,
+ updateSharedUiState,
+ upsertFailedRecording,
+} from "./storage";
+
+// chrome.storage resolves callbacks asynchronously, which is what lets
+// concurrent read-modify-write calls interleave (both read before either
+// writes). The fake reproduces that timing so the tests fail without the
+// per-key write queue in storage.ts.
+const createAsyncStorageArea = () => {
+ const data = new Map<string, unknown>();
+ return {
+ get(keys: string[], callback: (items: Record<string, unknown>) => void) {
+ const snapshot: Record<string, unknown> = {};
+ for (const key of keys) {
+ if (data.has(key)) snapshot[key] = data.get(key);
+ }
+ setTimeout(() => callback(snapshot), 0);
+ },
+ set(items: Record<string, unknown>, callback: () => void) {
+ setTimeout(() => {
+ for (const [key, value] of Object.entries(items)) {
+ data.set(key, value);
+ }
+ callback();
+ }, 0);
+ },
+ remove(keys: string[] | string, callback: () => void) {
+ setTimeout(() => {
+ for (const key of Array.isArray(keys) ? keys : [keys]) {
+ data.delete(key);
+ }
+ callback();
+ }, 0);
+ },
+ };
+};
+
+const failedRecording = (sessionId: string): FailedRecording => ({
+ sessionId,
+ videoId: null,
+ shareUrl: null,
+ mimeType: "video/webm",
+ subpath: null,
+ durationMs: 1000,
+ width: null,
+ height: null,
+ fps: null,
+ totalBytes: 1024,
+ createdAt: Date.now(),
+ message: null,
+});
+
+beforeEach(() => {
+ (globalThis as { chrome?: unknown }).chrome = {
+ storage: {
+ local: createAsyncStorageArea(),
+ session: createAsyncStorageArea(),
+ },
+ };
+});
+
+describe("storage read-modify-write serialization", () => {
+ it("keeps every overlay token registered by concurrent calls", async () => {
+ await Promise.all([
+ registerOverlayToken("token-a"),
+ registerOverlayToken("token-b"),
+ registerOverlayToken("token-c"),
+ ]);
+
+ const tokens = await loadOverlayTokens();
+ expect(Object.keys(tokens).sort()).toEqual([
+ "token-a",
+ "token-b",
+ "token-c",
+ ]);
+ });
+
+ it("applies concurrent shared UI state updates without dropping either", async () => {
+ await Promise.all([
+ updateSharedUiState((current) => ({
+ ...current,
+ panelOpen: true,
+ updatedAt: Date.now(),
+ })),
+ updateSharedUiState((current) => ({
+ ...current,
+ readyBarDismissed: true,
+ updatedAt: Date.now(),
+ })),
+ ]);
+
+ const state = await loadSharedUiState();
+ expect(state.panelOpen).toBe(true);
+ expect(state.readyBarDismissed).toBe(true);
+ });
+
+ it("keeps every failed recording upserted by concurrent calls", async () => {
+ await Promise.all([
+ upsertFailedRecording(failedRecording("session-a")),
+ upsertFailedRecording(failedRecording("session-b")),
+ ]);
+
+ const recordings = await loadFailedRecordings();
+ expect(recordings.map((entry) => entry.sessionId).sort()).toEqual([
+ "session-a",
+ "session-b",
+ ]);
+ });
+});
diff --git a/apps/chrome-extension/src/shared/storage.ts b/apps/chrome-extension/src/shared/storage.ts
new file mode 100644
index 000000000..5adbbb341
--- /dev/null
+++ b/apps/chrome-extension/src/shared/storage.ts
@@ -0,0 +1,807 @@
+import { RECORDING_STATE_KEY, SHARED_UI_STATE_KEY } from "./storage-keys";
+import type {
+ BootstrapData,
+ CapturePreferences,
+ DevicePreference,
+ ExtensionAuth,
+ ExtensionSettings,
+ OverlayPosition,
+ OverlayUiState,
+ PendingAuth,
+ RecordingMode,
+ SharedRecordingState,
+ SharedUiState,
+ WebcamPreviewFrame,
+} from "./types";
+
+export { RECORDING_STATE_KEY, SHARED_UI_STATE_KEY };
+
+export const SETTINGS_KEY = "cap-extension-settings";
+export const AUTH_KEY = "cap-extension-auth";
+const PENDING_AUTH_KEY = "cap-extension-pending-auth";
+const BOOTSTRAP_CACHE_KEY = "cap-extension-bootstrap-cache";
+export const OVERLAY_UI_STATE_KEY = "cap-extension-overlay-ui-state";
+export const WEBCAM_PREVIEW_DISMISSED_KEY =
+ "cap-extension-webcam-preview-dismissed";
+export const MEDIA_ACCESS_KEY = "cap-extension-media-access";
+export const FAILED_RECORDINGS_KEY = "cap-extension-failed-recordings";
+const OVERLAY_TOKENS_KEY = "cap-extension-overlay-tokens";
+const LAST_WEBCAM_PREVIEW_FRAME_KEY = "cap-extension-last-webcam-preview-frame";
+const PRODUCTION_API_BASE_URL = "https://cap.so";
+const DEFAULT_API_BASE_URL =
+ import.meta.env.MODE === "development"
+ ? "http://localhost:3000"
+ : PRODUCTION_API_BASE_URL;
+
+export type MediaAccessState = {
+ camera: boolean;
+ microphone: boolean;
+ updatedAt: number;
+};
+
+// Metadata for a recording whose upload did not complete. The captured bytes
+// stay in the IndexedDB recording spool under sessionId until the upload is
+// retried successfully or the entry is pruned.
+export type FailedRecording = {
+ sessionId: string;
+ videoId: string | null;
+ shareUrl: string | null;
+ mimeType: string;
+ subpath: string | null;
+ durationMs: number;
+ width: number | null;
+ height: number | null;
+ fps: number | null;
+ totalBytes: number;
+ createdAt: number;
+ message: string | null;
+};
+
+export const defaultSettings: ExtensionSettings = {
+ apiBaseUrl: DEFAULT_API_BASE_URL,
+ capture: {
+ recordingMode: "fullscreen",
+ camera: null,
+ microphone: null,
+ },
+ webcam: {
+ enabled: false,
+ deviceId: null,
+ position: "bottom-left",
+ size: 230,
+ shape: "round",
+ mirror: false,
+ },
+ microphone: {
+ enabled: true,
+ deviceId: null,
+ },
+ systemAudio: {
+ enabled: true,
+ },
+ sounds: {
+ enabled: true,
+ },
+};
+
+const defaultMediaAccessState: MediaAccessState = {
+ camera: false,
+ microphone: false,
+ updatedAt: 0,
+};
+
+// chrome.storage has no transactions, so concurrent read-modify-write calls
+// (parallel service-worker handlers, several extension pages) can interleave
+// and silently drop writes. Every RMW helper below funnels through this
+// per-key promise chain so updates to the same key apply one at a time
+// within a JS context. The key set is small and fixed, so the map never
+// needs pruning.
+const keyWriteQueues = new Map<string, Promise<unknown>>();
+
+const withKeyLock = <T>(key: string, task: () => Promise<T>): Promise<T> => {
+ const previous = keyWriteQueues.get(key) ?? Promise.resolve();
+ const run = previous.then(task, task);
+ keyWriteQueues.set(
+ key,
+ run.then(
+ () => undefined,
+ () => undefined,
+ ),
+ );
+ return run;
+};
+
+const getLocal = (keys: string[]) =>
+ new Promise<Record<string, unknown>>((resolve) => {
+ chrome.storage.local.get(keys, (items) => resolve(items));
+ });
+
+const setLocal = (items: Record<string, unknown>) =>
+ new Promise<void>((resolve) => {
+ chrome.storage.local.set(items, resolve);
+ });
+
+const removeLocal = (keys: string[] | string) =>
+ new Promise<void>((resolve) => {
+ chrome.storage.local.remove(keys, resolve);
+ });
+
+const getSession = (keys: string[]) =>
+ new Promise<Record<string, unknown>>((resolve) => {
+ chrome.storage.session.get(keys, (items) => resolve(items));
+ });
+
+const setSession = (items: Record<string, unknown>) =>
+ new Promise<void>((resolve) => {
+ chrome.storage.session.set(items, resolve);
+ });
+
+const removeSession = (keys: string[] | string) =>
+ new Promise<void>((resolve) => {
+ chrome.storage.session.remove(keys, resolve);
+ });
+
+export const loadSettings = async () => {
+ const result = await getLocal([SETTINGS_KEY]);
+ const saved = result[SETTINGS_KEY];
+ if (!isSettings(saved)) return defaultSettings;
+ const apiBaseUrl =
+ import.meta.env.MODE === "development" &&
+ saved.apiBaseUrl === PRODUCTION_API_BASE_URL
+ ? DEFAULT_API_BASE_URL
+ : saved.apiBaseUrl;
+ return {
+ ...defaultSettings,
+ ...saved,
+ apiBaseUrl,
+ capture: normalizeCapturePreferences(saved.capture),
+ webcam: normalizeWebcamSettings(saved.webcam),
+ microphone: normalizeMicrophoneSettings(saved.microphone),
+ systemAudio: {
+ ...defaultSettings.systemAudio,
+ ...saved.systemAudio,
+ },
+ sounds: normalizeSoundSettings(saved.sounds),
+ };
+};
+
+export const saveSettings = (settings: ExtensionSettings) =>
+ setLocal({ [SETTINGS_KEY]: settings });
+
+export const loadAuth = async () => {
+ const result = await getLocal([AUTH_KEY]);
+ const saved = result[AUTH_KEY];
+ return isAuth(saved) ? saved : null;
+};
+
+export const saveAuth = (auth: ExtensionAuth) => setLocal({ [AUTH_KEY]: auth });
+
+export const clearAuth = () => removeLocal(AUTH_KEY);
+
+export const loadPendingAuth = async () => {
+ const result = await getLocal([PENDING_AUTH_KEY]);
+ const saved = result[PENDING_AUTH_KEY];
+ return isPendingAuth(saved) ? saved : null;
+};
+
+export const loadCachedBootstrap = async () => {
+ const result = await getLocal([BOOTSTRAP_CACHE_KEY]);
+ const saved = result[BOOTSTRAP_CACHE_KEY];
+ if (isBootstrap(saved)) return saved;
+ if (isCachedBootstrap(saved)) return saved.bootstrap;
+ return null;
+};
+
+export const saveCachedBootstrap = (bootstrap: BootstrapData) =>
+ setLocal({
+ [BOOTSTRAP_CACHE_KEY]: {
+ bootstrap,
+ cachedAt: Date.now(),
+ },
+ });
+
+export const clearCachedBootstrap = () => removeLocal(BOOTSTRAP_CACHE_KEY);
+
+export const savePendingAuth = (pendingAuth: PendingAuth) =>
+ setLocal({ [PENDING_AUTH_KEY]: pendingAuth });
+
+export const clearPendingAuth = () => removeLocal(PENDING_AUTH_KEY);
+
+export const loadMediaAccessState = async () => {
+ const result = await getLocal([MEDIA_ACCESS_KEY]);
+ return normalizeMediaAccessState(result[MEDIA_ACCESS_KEY]);
+};
+
+export const updateMediaAccessState = (
+ access: Partial<Pick<MediaAccessState, "camera" | "microphone">>,
+) =>
+ withKeyLock(MEDIA_ACCESS_KEY, async () => {
+ const current = await loadMediaAccessState();
+ const next = normalizeMediaAccessState({
+ ...current,
+ ...access,
+ updatedAt: Date.now(),
+ });
+ await setLocal({ [MEDIA_ACCESS_KEY]: next });
+ return next;
+ });
+
+export const loadOverlayUiState = async () => {
+ const result = await getLocal([OVERLAY_UI_STATE_KEY]);
+ return normalizeOverlayUiState(result[OVERLAY_UI_STATE_KEY]);
+};
+
+export const saveOverlayUiState = (state: OverlayUiState) =>
+ setLocal({ [OVERLAY_UI_STATE_KEY]: state });
+
+export const updateOverlayUiState = (
+ update: (current: OverlayUiState) => OverlayUiState,
+) =>
+ withKeyLock(OVERLAY_UI_STATE_KEY, async () => {
+ const current = await loadOverlayUiState();
+ const next = normalizeOverlayUiState(update(current));
+ await saveOverlayUiState(next);
+ return next;
+ });
+
+export const loadLastWebcamPreviewFrame = async () => {
+ const result = await getSession([LAST_WEBCAM_PREVIEW_FRAME_KEY]);
+ const saved = result[LAST_WEBCAM_PREVIEW_FRAME_KEY];
+ return isWebcamPreviewFrame(saved) ? saved : null;
+};
+
+export const saveLastWebcamPreviewFrame = (frame: WebcamPreviewFrame) =>
+ setSession({ [LAST_WEBCAM_PREVIEW_FRAME_KEY]: frame });
+
+export const loadWebcamPreviewDismissed = async () => {
+ const result = await getSession([WEBCAM_PREVIEW_DISMISSED_KEY]);
+ return result[WEBCAM_PREVIEW_DISMISSED_KEY] === true;
+};
+
+export const saveWebcamPreviewDismissed = (dismissed: boolean) =>
+ setSession({ [WEBCAM_PREVIEW_DISMISSED_KEY]: dismissed });
+
+const MAX_FAILED_RECORDINGS = 5;
+
+const isFailedRecording = (value: unknown): value is FailedRecording => {
+ if (!value || typeof value !== "object") return false;
+ const candidate = value as Partial<FailedRecording>;
+ return (
+ typeof candidate.sessionId === "string" &&
+ typeof candidate.mimeType === "string" &&
+ typeof candidate.totalBytes === "number" &&
+ typeof candidate.createdAt === "number"
+ );
+};
+
+export const loadFailedRecordings = async (): Promise<FailedRecording[]> => {
+ const result = await getLocal([FAILED_RECORDINGS_KEY]);
+ const saved = result[FAILED_RECORDINGS_KEY];
+ if (!Array.isArray(saved)) return [];
+ return saved.filter(isFailedRecording);
+};
+
+// The metadata list is capped; entries pushed out by newer failures are
+// returned so the caller can also reclaim their spooled bytes in IndexedDB.
+// Silently dropping them would leave multi-GB spools stranded (and later
+// re-surfaced by the orphan sweep with videoId null, i.e. unretryable).
+export const saveFailedRecordings = async (
+ recordings: FailedRecording[],
+): Promise<{ kept: FailedRecording[]; dropped: FailedRecording[] }> => {
+ const sorted = [...recordings].sort(
+ (left, right) => right.createdAt - left.createdAt,
+ );
+ const kept = sorted.slice(0, MAX_FAILED_RECORDINGS);
+ const dropped = sorted.slice(MAX_FAILED_RECORDINGS);
+ await setLocal({ [FAILED_RECORDINGS_KEY]: kept });
+ return { kept, dropped };
+};
+
+export const upsertFailedRecording = (recording: FailedRecording) =>
+ withKeyLock(FAILED_RECORDINGS_KEY, async () => {
+ const current = await loadFailedRecordings();
+ const next = [
+ recording,
+ ...current.filter((entry) => entry.sessionId !== recording.sessionId),
+ ];
+ return saveFailedRecordings(next);
+ });
+
+export const removeFailedRecording = (sessionId: string) =>
+ withKeyLock(FAILED_RECORDINGS_KEY, async () => {
+ const current = await loadFailedRecordings();
+ const next = current.filter((entry) => entry.sessionId !== sessionId);
+ return saveFailedRecordings(next);
+ });
+
+// Identity of a recording that is currently live in the offscreen document,
+// keyed by its spool session. Persisted when the recording starts so that a
+// browser/offscreen-document crash still leaves enough metadata for the
+// orphan sweep to surface a retryable failed-recording entry (videoId,
+// subpath, dimensions) instead of a download-only one.
+export type LiveRecordingManifest = {
+ sessionId: string;
+ videoId: string;
+ shareUrl: string;
+ mimeType: string;
+ subpath: string;
+ width: number;
+ height: number;
+ fps: number;
+ startedAt: number;
+};
+
+const LIVE_RECORDING_MANIFESTS_KEY = "cap-extension-live-recordings";
+
+const isLiveRecordingManifest = (
+ value: unknown,
+): value is LiveRecordingManifest => {
+ if (!value || typeof value !== "object") return false;
+ const candidate = value as Partial<LiveRecordingManifest>;
+ return (
+ typeof candidate.sessionId === "string" &&
+ typeof candidate.videoId === "string" &&
+ typeof candidate.shareUrl === "string" &&
+ typeof candidate.mimeType === "string" &&
+ typeof candidate.subpath === "string" &&
+ typeof candidate.width === "number" &&
+ typeof candidate.height === "number" &&
+ typeof candidate.fps === "number" &&
+ typeof candidate.startedAt === "number"
+ );
+};
+
+export const loadLiveRecordingManifests = async (): Promise<
+ LiveRecordingManifest[]
+> => {
+ const result = await getLocal([LIVE_RECORDING_MANIFESTS_KEY]);
+ const saved = result[LIVE_RECORDING_MANIFESTS_KEY];
+ if (!Array.isArray(saved)) return [];
+ return saved.filter(isLiveRecordingManifest);
+};
+
+export const saveLiveRecordingManifest = (manifest: LiveRecordingManifest) =>
+ withKeyLock(LIVE_RECORDING_MANIFESTS_KEY, async () => {
+ const current = await loadLiveRecordingManifests();
+ await setLocal({
+ [LIVE_RECORDING_MANIFESTS_KEY]: [
+ manifest,
+ ...current.filter((entry) => entry.sessionId !== manifest.sessionId),
+ ],
+ });
+ });
+
+export const removeLiveRecordingManifest = (sessionId: string) =>
+ withKeyLock(LIVE_RECORDING_MANIFESTS_KEY, async () => {
+ const current = await loadLiveRecordingManifests();
+ await setLocal({
+ [LIVE_RECORDING_MANIFESTS_KEY]: current.filter(
+ (entry) => entry.sessionId !== sessionId,
+ ),
+ });
+ });
+
+// Manifests are bookkeeping for spool sessions; once a session is gone its
+// manifest is dead weight (a failed-recording entry carries its own copy of
+// the metadata).
+export const pruneLiveRecordingManifests = (
+ survivingSessionIds: ReadonlySet<string>,
+) =>
+ withKeyLock(LIVE_RECORDING_MANIFESTS_KEY, async () => {
+ const current = await loadLiveRecordingManifests();
+ const next = current.filter((entry) =>
+ survivingSessionIds.has(entry.sessionId),
+ );
+ if (next.length !== current.length) {
+ await setLocal({ [LIVE_RECORDING_MANIFESTS_KEY]: next });
+ }
+ });
+
+// Sign-in failures land in a detached launchWebAuthFlow callback with no open
+// UI to reject into; the popup reads this on its next status poll. Session
+// storage survives service-worker restarts but clears with the browser.
+const AUTH_ERROR_KEY = "cap-extension-auth-error";
+
+export const loadAuthError = async (): Promise<string | null> => {
+ const result = await getSession([AUTH_ERROR_KEY]);
+ const saved = result[AUTH_ERROR_KEY];
+ return typeof saved === "string" && saved.length > 0 ? saved : null;
+};
+
+export const saveAuthError = (message: string) =>
+ setSession({ [AUTH_ERROR_KEY]: message });
+
+export const clearAuthError = () => removeSession(AUTH_ERROR_KEY);
+
+// Tokens registered by content scripts for the extension iframes they embed.
+// chrome.storage.session survives service worker restarts but clears with the
+// browser session, matching the lifetime of the iframes themselves.
+const MAX_OVERLAY_TOKENS = 64;
+
+export const loadOverlayTokens = async (): Promise<Record<string, number>> => {
+ const result = await getSession([OVERLAY_TOKENS_KEY]);
+ const saved = result[OVERLAY_TOKENS_KEY];
+ if (!saved || typeof saved !== "object" || Array.isArray(saved)) return {};
+ const entries = Object.entries(saved as Record<string, unknown>).filter(
+ (entry): entry is [string, number] => typeof entry[1] === "number",
+ );
+ return Object.fromEntries(entries);
+};
+
+export const registerOverlayToken = async (token: string) => {
+ if (!token) return;
+ await withKeyLock(OVERLAY_TOKENS_KEY, async () => {
+ const tokens = await loadOverlayTokens();
+ tokens[token] = Date.now();
+ const pruned = Object.entries(tokens)
+ .sort((left, right) => right[1] - left[1])
+ .slice(0, MAX_OVERLAY_TOKENS);
+ await setSession({ [OVERLAY_TOKENS_KEY]: Object.fromEntries(pruned) });
+ });
+};
+
+export const isOverlayTokenRegistered = async (token: string) => {
+ if (!token) return false;
+ const tokens = await loadOverlayTokens();
+ return Object.hasOwn(tokens, token);
+};
+
+// The uploading-tab id is service-worker state, but MV3 workers restart at
+// any time; mirroring the id into session storage lets a restarted worker
+// reuse the existing tab instead of opening a duplicate.
+const UPLOAD_PROGRESS_TAB_KEY = "cap-extension-upload-progress-tab";
+
+export const loadUploadProgressTabId = async (): Promise<number | null> => {
+ const result = await getSession([UPLOAD_PROGRESS_TAB_KEY]);
+ const saved = result[UPLOAD_PROGRESS_TAB_KEY];
+ return typeof saved === "number" && Number.isFinite(saved) ? saved : null;
+};
+
+export const saveUploadProgressTabId = (tabId: number | null) =>
+ tabId === null
+ ? removeSession(UPLOAD_PROGRESS_TAB_KEY)
+ : setSession({ [UPLOAD_PROGRESS_TAB_KEY]: tabId });
+
+export const loadSharedRecordingState =
+ async (): Promise<SharedRecordingState | null> => {
+ const result = await getSession([RECORDING_STATE_KEY]);
+ const saved = result[RECORDING_STATE_KEY];
+ return isSharedRecordingState(saved) ? saved : null;
+ };
+
+export const saveSharedRecordingState = (state: SharedRecordingState) =>
+ setSession({ [RECORDING_STATE_KEY]: state });
+
+export const loadSharedUiState = async (): Promise<SharedUiState> => {
+ const result = await getSession([SHARED_UI_STATE_KEY]);
+ return normalizeSharedUiState(result[SHARED_UI_STATE_KEY]);
+};
+
+export const saveSharedUiState = (state: SharedUiState) =>
+ setSession({ [SHARED_UI_STATE_KEY]: state });
+
+export const updateSharedUiState = (
+ update: (current: SharedUiState) => SharedUiState,
+) =>
+ withKeyLock(SHARED_UI_STATE_KEY, async () => {
+ const current = await loadSharedUiState();
+ const updated = update(current);
+ // Callers signal "no change" by returning the object they were given;
+ // skipping the write keeps high-frequency callers (the per-status panel
+ // sync) from fanning storage.onChanged events out to every open tab.
+ if (updated === current) return current;
+ const next = normalizeSharedUiState(updated);
+ await saveSharedUiState(next);
+ return next;
+ });
+
+const isSettings = (value: unknown): value is ExtensionSettings => {
+ if (!value || typeof value !== "object") return false;
+ const candidate = value as Partial<ExtensionSettings>;
+ return (
+ typeof candidate.apiBaseUrl === "string" &&
+ typeof candidate.webcam === "object" &&
+ candidate.webcam !== null
+ );
+};
+
+const isWebcamPreviewFrame = (value: unknown): value is WebcamPreviewFrame => {
+ if (!value || typeof value !== "object") return false;
+ const candidate = value as Partial<WebcamPreviewFrame>;
+ const dimensions = candidate.dimensions;
+ return (
+ typeof candidate.dataUrl === "string" &&
+ candidate.dataUrl.startsWith("data:image/") &&
+ typeof candidate.capturedAt === "number" &&
+ Number.isFinite(candidate.capturedAt) &&
+ !!dimensions &&
+ typeof dimensions === "object" &&
+ typeof dimensions.width === "number" &&
+ typeof dimensions.height === "number" &&
+ Number.isFinite(dimensions.width) &&
+ Number.isFinite(dimensions.height) &&
+ dimensions.width > 0 &&
+ dimensions.height > 0
+ );
+};
+
+const normalizeRecordingMode = (value: unknown): RecordingMode =>
+ value === "tab" ||
+ value === "fullscreen" ||
+ value === "window" ||
+ value === "camera"
+ ? value
+ : defaultSettings.capture.recordingMode;
+
+const normalizeDevicePreference = (value: unknown): DevicePreference | null => {
+ if (!value || typeof value !== "object") return null;
+ const candidate = value as Partial<DevicePreference>;
+ if (
+ typeof candidate.deviceId !== "string" ||
+ candidate.deviceId.trim().length === 0
+ ) {
+ return null;
+ }
+
+ return {
+ deviceId: candidate.deviceId,
+ label:
+ typeof candidate.label === "string" && candidate.label.trim().length > 0
+ ? candidate.label
+ : null,
+ groupId:
+ typeof candidate.groupId === "string" &&
+ candidate.groupId.trim().length > 0
+ ? candidate.groupId
+ : null,
+ updatedAt:
+ typeof candidate.updatedAt === "number" &&
+ Number.isFinite(candidate.updatedAt)
+ ? candidate.updatedAt
+ : 0,
+ };
+};
+
+const normalizeCapturePreferences = (value: unknown): CapturePreferences => {
+ const capture =
+ value && typeof value === "object"
+ ? (value as Partial<CapturePreferences>)
+ : {};
+
+ return {
+ recordingMode: normalizeRecordingMode(capture.recordingMode),
+ camera: normalizeDevicePreference(capture.camera),
+ microphone: normalizeDevicePreference(capture.microphone),
+ };
+};
+
+const normalizeWebcamShape = (
+ value: unknown,
+): ExtensionSettings["webcam"]["shape"] => {
+ if (value === "round" || value === "full" || value === "square") {
+ return value;
+ }
+ if (value === "circle") {
+ return "round";
+ }
+ if (value === "rounded") {
+ return "square";
+ }
+ return defaultSettings.webcam.shape;
+};
+
+const normalizeWebcamSettings = (
+ value: unknown,
+): ExtensionSettings["webcam"] => {
+ const webcam =
+ value && typeof value === "object"
+ ? (value as Partial<ExtensionSettings["webcam"]>)
+ : {};
+ const size =
+ typeof webcam.size === "number" && Number.isFinite(webcam.size)
+ ? webcam.size
+ : defaultSettings.webcam.size;
+ const position =
+ webcam.position === "top-left" ||
+ webcam.position === "top-right" ||
+ webcam.position === "bottom-left" ||
+ webcam.position === "bottom-right"
+ ? webcam.position
+ : defaultSettings.webcam.position;
+ const deviceId =
+ typeof webcam.deviceId === "string" && webcam.deviceId.trim().length > 0
+ ? webcam.deviceId
+ : null;
+
+ return {
+ enabled:
+ typeof webcam.enabled === "boolean"
+ ? webcam.enabled
+ : defaultSettings.webcam.enabled,
+ deviceId,
+ position,
+ size: Math.max(120, Math.min(420, size)),
+ shape: normalizeWebcamShape(webcam.shape),
+ mirror: typeof webcam.mirror === "boolean" ? webcam.mirror : false,
+ };
+};
+
+const normalizeMicrophoneSettings = (
+ value: unknown,
+): ExtensionSettings["microphone"] => {
+ const microphone =
+ value && typeof value === "object"
+ ? (value as Partial<ExtensionSettings["microphone"]>)
+ : {};
+ return {
+ enabled:
+ typeof microphone.enabled === "boolean"
+ ? microphone.enabled
+ : defaultSettings.microphone.enabled,
+ deviceId:
+ typeof microphone.deviceId === "string" &&
+ microphone.deviceId.trim().length > 0
+ ? microphone.deviceId
+ : null,
+ };
+};
+
+const normalizeSoundSettings = (
+ value: unknown,
+): ExtensionSettings["sounds"] => {
+ const sounds =
+ value && typeof value === "object"
+ ? (value as Partial<ExtensionSettings["sounds"]>)
+ : {};
+
+ return {
+ enabled:
+ typeof sounds.enabled === "boolean"
+ ? sounds.enabled
+ : defaultSettings.sounds.enabled,
+ };
+};
+
+const normalizeMediaAccessState = (value: unknown): MediaAccessState => {
+ const access =
+ value && typeof value === "object"
+ ? (value as Partial<MediaAccessState>)
+ : {};
+
+ return {
+ camera:
+ typeof access.camera === "boolean"
+ ? access.camera
+ : defaultMediaAccessState.camera,
+ microphone:
+ typeof access.microphone === "boolean"
+ ? access.microphone
+ : defaultMediaAccessState.microphone,
+ updatedAt:
+ typeof access.updatedAt === "number" && Number.isFinite(access.updatedAt)
+ ? access.updatedAt
+ : defaultMediaAccessState.updatedAt,
+ };
+};
+
+const normalizeOverlayPosition = (value: unknown): OverlayPosition | null => {
+ if (!value || typeof value !== "object") return null;
+ const candidate = value as Partial<OverlayPosition>;
+ if (
+ typeof candidate.x !== "number" ||
+ typeof candidate.y !== "number" ||
+ typeof candidate.viewportWidth !== "number" ||
+ typeof candidate.viewportHeight !== "number" ||
+ typeof candidate.updatedAt !== "number" ||
+ !Number.isFinite(candidate.x) ||
+ !Number.isFinite(candidate.y) ||
+ !Number.isFinite(candidate.viewportWidth) ||
+ !Number.isFinite(candidate.viewportHeight) ||
+ !Number.isFinite(candidate.updatedAt)
+ ) {
+ return null;
+ }
+
+ return {
+ x: candidate.x,
+ y: candidate.y,
+ viewportWidth: Math.max(1, candidate.viewportWidth),
+ viewportHeight: Math.max(1, candidate.viewportHeight),
+ updatedAt: candidate.updatedAt,
+ };
+};
+
+const RECORDING_PHASES = new Set([
+ "idle",
+ "creating",
+ "recording",
+ "paused",
+ "uploading",
+ "completed",
+ "error",
+]);
+
+const isSharedRecordingState = (
+ value: unknown,
+): value is SharedRecordingState => {
+ if (!value || typeof value !== "object") return false;
+ const candidate = value as Partial<SharedRecordingState>;
+ const status = candidate.status as { phase?: unknown } | undefined;
+ return (
+ !!status &&
+ typeof status === "object" &&
+ typeof status.phase === "string" &&
+ RECORDING_PHASES.has(status.phase) &&
+ typeof candidate.updatedAt === "number" &&
+ Number.isFinite(candidate.updatedAt)
+ );
+};
+
+const normalizeSharedUiState = (value: unknown): SharedUiState => {
+ const state =
+ value && typeof value === "object" ? (value as Partial<SharedUiState>) : {};
+
+ return {
+ panelOpen: state.panelOpen === true,
+ readyBarDismissed: state.readyBarDismissed === true,
+ updatedAt:
+ typeof state.updatedAt === "number" && Number.isFinite(state.updatedAt)
+ ? state.updatedAt
+ : 0,
+ };
+};
+
+const normalizeOverlayUiState = (value: unknown): OverlayUiState => {
+ const state =
+ value && typeof value === "object"
+ ? (value as Partial<OverlayUiState>)
+ : {};
+
+ return {
+ webcamPosition: normalizeOverlayPosition(state.webcamPosition),
+ recordingBarPosition: normalizeOverlayPosition(state.recordingBarPosition),
+ };
+};
+
+const isAuth = (value: unknown): value is ExtensionAuth => {
+ if (!value || typeof value !== "object") return false;
+ const candidate = value as Partial<ExtensionAuth>;
+ return (
+ typeof candidate.authApiKey === "string" &&
+ typeof candidate.userId === "string"
+ );
+};
+
+const isPendingAuth = (value: unknown): value is PendingAuth => {
+ if (!value || typeof value !== "object") return false;
+ const candidate = value as Partial<PendingAuth>;
+ return (
+ typeof candidate.state === "string" &&
+ typeof candidate.redirectUri === "string" &&
+ typeof candidate.startedAt === "number"
+ );
+};
+
+const isBootstrap = (value: unknown): value is BootstrapData => {
+ if (!value || typeof value !== "object") return false;
+ const candidate = value as Partial<BootstrapData>;
+ return (
+ typeof candidate.user === "object" &&
+ candidate.user !== null &&
+ typeof candidate.organization === "object" &&
+ candidate.organization !== null &&
+ typeof candidate.plan === "object" &&
+ candidate.plan !== null
+ );
+};
+
+const isCachedBootstrap = (
+ value: unknown,
+): value is { bootstrap: BootstrapData; cachedAt: number } => {
+ if (!value || typeof value !== "object") return false;
+ const candidate = value as {
+ bootstrap?: unknown;
+ cachedAt?: unknown;
+ };
+ return isBootstrap(candidate.bootstrap);
+};
diff --git a/apps/chrome-extension/src/shared/types.ts b/apps/chrome-extension/src/shared/types.ts
new file mode 100644
index 000000000..c90c4f3db
--- /dev/null
+++ b/apps/chrome-extension/src/shared/types.ts
@@ -0,0 +1,486 @@
+import type {
+ DetectedDisplayRecordingMode,
+ RecordingPipeline,
+ UploadStatus,
+ VideoId,
+} from "@cap/recorder-core";
+import type { Extension, Video } from "@cap/web-domain";
+
+export const DEFAULT_CAMERA_DEVICE_ID = "__cap_default_camera__";
+export const DEFAULT_MICROPHONE_DEVICE_ID = "__cap_default_microphone__";
+
+export type CameraDevice = {
+ deviceId: string;
+ label: string;
+ groupId: string;
+};
+
+export type MicrophoneDevice = {
+ deviceId: string;
+ label: string;
+ groupId: string;
+};
+
+// Derived from recorder-core's display-mode union so the two cannot drift.
+export type RecordingMode = DetectedDisplayRecordingMode | "camera";
+
+export type DevicePreference = {
+ deviceId: string;
+ label: string | null;
+ groupId: string | null;
+ updatedAt: number;
+};
+
+export type CapturePreferences = {
+ recordingMode: RecordingMode;
+ camera: DevicePreference | null;
+ microphone: DevicePreference | null;
+};
+
+export type WebcamShape = "round" | "square" | "full";
+export type WebcamPosition =
+ | "top-left"
+ | "top-right"
+ | "bottom-left"
+ | "bottom-right";
+
+export type WebcamSettings = {
+ enabled: boolean;
+ deviceId: string | null;
+ position: WebcamPosition;
+ size: number;
+ shape: WebcamShape;
+ mirror: boolean;
+};
+
+export type OverlayPosition = {
+ x: number;
+ y: number;
+ viewportWidth: number;
+ viewportHeight: number;
+ updatedAt: number;
+};
+
+export type OverlayUiState = {
+ webcamPosition: OverlayPosition | null;
+ recordingBarPosition: OverlayPosition | null;
+};
+
+export type WebcamPreviewFrame = {
+ dataUrl: string;
+ dimensions: {
+ width: number;
+ height: number;
+ };
+ capturedAt: number;
+};
+
+export type MicrophoneSettings = {
+ enabled: boolean;
+ deviceId: string | null;
+};
+
+export type SystemAudioSettings = {
+ enabled: boolean;
+};
+
+export type SoundSettings = {
+ enabled: boolean;
+};
+
+export type ExtensionSettings = {
+ apiBaseUrl: string;
+ capture: CapturePreferences;
+ webcam: WebcamSettings;
+ microphone: MicrophoneSettings;
+ systemAudio: SystemAudioSettings;
+ sounds: SoundSettings;
+};
+
+export type ExtensionAuth = {
+ authApiKey: string;
+ userId: string;
+};
+
+export type PendingAuth = {
+ state: string;
+ redirectUri: string;
+ startedAt: number;
+};
+
+// Derived from the server schema so contract drift fails to compile instead
+// of surfacing at runtime.
+export type BootstrapData = typeof Extension.ExtensionBootstrapSuccess.Type;
+
+export type RecordingPlan = BootstrapData["plan"];
+
+export type RecordingCaptureSource = {
+ requestedMode: RecordingMode;
+ detectedMode: RecordingMode | null;
+ displaySurface: string | null;
+ label: string | null;
+ tabId?: number;
+};
+
+// Aggregated upload progress: statuses are broadcast and persisted to session
+// storage frequently, so they carry totals instead of a per-part chunk array
+// that grows by one entry per ~5MB for the length of the recording.
+export type UploadSummary = {
+ totalBytes: number;
+ uploadedBytes: number;
+ totalChunks: number;
+ completedChunks: number;
+ failedChunks: number;
+};
+
+export type RecordingStatus =
+ | {
+ phase: "idle";
+ }
+ | {
+ phase: "creating";
+ }
+ | {
+ phase: "recording" | "paused" | "uploading";
+ videoId?: VideoId;
+ startedAt: number;
+ durationMs: number;
+ updatedAt: number;
+ uploadStatus?: UploadStatus;
+ upload?: UploadSummary;
+ }
+ | {
+ phase: "completed";
+ videoId: VideoId;
+ shareUrl: string;
+ }
+ | {
+ phase: "error";
+ message: string;
+ videoId?: VideoId;
+ // Set when the upload completed but the confirmation was lost: the
+ // video may still process server-side, so the user should verify
+ // before retrying.
+ shareUrl?: string;
+ // Set when the recording data is still spooled locally and can be
+ // retried or downloaded from the upload page.
+ recoverable?: boolean;
+ };
+
+export type StartRecordingRequest = {
+ target: "offscreen";
+ type: "start-recording";
+ mode: RecordingMode;
+ settings: ExtensionSettings;
+ auth: ExtensionAuth;
+ bootstrap: BootstrapData;
+ tabId?: number;
+ tabStreamId?: string;
+};
+
+export type StopRecordingRequest = {
+ target: "offscreen";
+ type: "stop-recording";
+};
+
+export type PauseRecordingRequest = {
+ target: "offscreen";
+ type: "pause-recording";
+};
+
+export type ResumeRecordingRequest = {
+ target: "offscreen";
+ type: "resume-recording";
+};
+
+export type GetRecordingStatusRequest = {
+ target: "offscreen";
+ type: "get-recording-status";
+};
+
+export type ConnectCameraPreviewRequest = {
+ target: "offscreen";
+ type: "connect-camera-preview";
+ sessionId: string;
+ settings: WebcamSettings;
+ offer: RTCSessionDescriptionInit;
+};
+
+export type DisconnectCameraPreviewRequest = {
+ target: "offscreen";
+ type: "disconnect-camera-preview";
+ sessionId: string;
+};
+
+export type DisconnectCameraPreviewsRequest = {
+ target: "offscreen";
+ type: "disconnect-camera-previews";
+};
+
+export type AcknowledgeErrorRequest = {
+ target: "offscreen";
+ type: "acknowledge-error";
+};
+
+export type RetryUploadRequest = {
+ target: "offscreen";
+ type: "retry-upload";
+ videoId: string;
+};
+
+export type OffscreenRequest =
+ | StartRecordingRequest
+ | StopRecordingRequest
+ | PauseRecordingRequest
+ | ResumeRecordingRequest
+ | GetRecordingStatusRequest
+ | ConnectCameraPreviewRequest
+ | DisconnectCameraPreviewRequest
+ | DisconnectCameraPreviewsRequest
+ | AcknowledgeErrorRequest
+ | RetryUploadRequest;
+
+export type OffscreenResponse =
+ | {
+ ok: true;
+ status?: RecordingStatus;
+ answer?: RTCSessionDescriptionInit;
+ }
+ | {
+ ok: false;
+ error: string;
+ // True when the user dismissed the capture picker rather than the
+ // recording failing; callers skip the error UI for cancellations.
+ canceled?: boolean;
+ };
+
+export type ServiceWorkerRequest =
+ | {
+ target: "service-worker";
+ type: "auth-start";
+ }
+ | {
+ target: "service-worker";
+ type: "auth-revoke";
+ }
+ | {
+ target: "service-worker";
+ type: "bootstrap";
+ }
+ | {
+ target: "service-worker";
+ type: "get-overlay-settings";
+ }
+ | {
+ target: "service-worker";
+ type: "get-camera-devices";
+ }
+ | {
+ target: "service-worker";
+ type: "camera-devices-updated";
+ devices: CameraDevice[];
+ }
+ | {
+ target: "service-worker";
+ type: "start-recording";
+ mode: RecordingMode;
+ }
+ | {
+ target: "service-worker";
+ type: "stop-recording";
+ }
+ | {
+ target: "service-worker";
+ type: "pause-recording";
+ }
+ | {
+ target: "service-worker";
+ type: "resume-recording";
+ }
+ | {
+ target: "service-worker";
+ type: "get-recording-status";
+ }
+ | {
+ target: "service-worker";
+ type: "open-options";
+ }
+ | {
+ target: "service-worker";
+ type: "open-how-it-works";
+ }
+ | {
+ target: "service-worker";
+ type: "close-extension-ui";
+ }
+ | {
+ target: "service-worker";
+ type: "settings-updated";
+ settings: ExtensionSettings;
+ }
+ | {
+ target: "service-worker";
+ type: "close-webcam-preview";
+ }
+ | {
+ target: "service-worker";
+ type: "connect-camera-preview";
+ sessionId: string;
+ settings: WebcamSettings;
+ offer: RTCSessionDescriptionInit;
+ }
+ | {
+ target: "service-worker";
+ type: "disconnect-camera-preview";
+ sessionId: string;
+ }
+ | {
+ target: "service-worker";
+ type: "webcam-preview-ready";
+ }
+ | {
+ target: "service-worker";
+ type: "recording-capture-source";
+ source: RecordingCaptureSource;
+ }
+ | {
+ target: "service-worker";
+ type: "webcam-preview-error";
+ reason: CameraPreviewErrorReason;
+ message: string;
+ }
+ | {
+ // Camera preview iframe → service worker → embedding tab's content
+ // script. The iframe must not window.postMessage these to its parent:
+ // the parent is the recorded page, which could read webcam frames out
+ // of the message stream.
+ target: "service-worker";
+ type: "camera-preview-event";
+ token: string;
+ event: CameraPreviewEvent;
+ }
+ | {
+ // Content scripts announce the token their extension iframes (camera
+ // preview, recorder panel) carry in their URL hash. The service
+ // worker only honours camera requests from frames whose token was
+ // registered this way, which web pages cannot do.
+ target: "service-worker";
+ type: "register-overlay-token";
+ token: string;
+ }
+ | {
+ target: "service-worker";
+ type: "validate-overlay-token";
+ token: string;
+ }
+ | {
+ target: "service-worker";
+ type: "retry-upload";
+ videoId: string;
+ };
+
+export type ServiceWorkerResponse =
+ | {
+ ok: true;
+ auth?: ExtensionAuth | null;
+ authPending?: boolean;
+ // Terminal failure of the most recent sign-in attempt; the popup
+ // shows it once the pending state clears.
+ authError?: string | null;
+ bootstrap?: BootstrapData;
+ cameraDevices?: CameraDevice[];
+ status?: RecordingStatus;
+ settings?: ExtensionSettings;
+ plan?: RecordingPlan;
+ answer?: RTCSessionDescriptionInit;
+ valid?: boolean;
+ }
+ | {
+ ok: false;
+ error: string;
+ canceled?: boolean;
+ };
+
+export type OverlayMessage =
+ | {
+ type: "overlay-settings";
+ settings: WebcamSettings;
+ recording: boolean;
+ }
+ | {
+ type: "overlay-enter-auto-pip";
+ }
+ | {
+ type: "overlay-exit-auto-pip";
+ }
+ | {
+ type: "overlay-hide";
+ }
+ | {
+ type: "overlay-panel-toggle";
+ }
+ | {
+ type: "overlay-panel-hide";
+ };
+
+export type RecordingStatusBroadcast = {
+ target: "recording-status";
+ type: "recording-status-changed";
+ status: RecordingStatus;
+};
+
+// Mirrored into chrome.storage.session by the service worker so every tab's
+// floating UI reads the exact same recording state instead of each tab
+// round-tripping for its own copy.
+export type SharedRecordingState = {
+ status: RecordingStatus;
+ plan: RecordingPlan | null;
+ updatedAt: number;
+};
+
+// Cross-tab UI state: the recorder panel and the ready bar stay in lockstep
+// across every tab instead of tracking open/dismissed per tab.
+export type SharedUiState = {
+ panelOpen: boolean;
+ readyBarDismissed: boolean;
+ updatedAt: number;
+};
+
+export type CameraPreviewErrorReason =
+ | "permissions-policy"
+ | "permission"
+ | "not-found"
+ | "in-use"
+ | "unknown";
+
+// Events the camera preview iframe reports to the overlay that embeds it.
+// They travel iframe → service worker → chrome.tabs.sendMessage so the host
+// page never sees them; webcam frames in particular must not transit
+// window.postMessage where the recorded page could listen.
+export type CameraPreviewEvent =
+ | { type: "ready" }
+ | { type: "metadata"; dimensions: { width: number; height: number } }
+ | { type: "session"; sessionId: string }
+ | { type: "frame"; frame: WebcamPreviewFrame }
+ | { type: "error"; reason: CameraPreviewErrorReason; message: string }
+ | { type: "pip-state"; active: boolean; supported: boolean }
+ | { type: "drag-start"; clientX: number; clientY: number }
+ | { type: "drag-move"; clientX: number; clientY: number }
+ | { type: "drag-end" };
+
+// Shape of the relayed message a content script receives for the preview
+// iframe it embeds; the token scopes it to that tab's overlay.
+export type CameraPreviewEventRelay = {
+ source: "cap-extension-camera-preview";
+ token: string;
+ event: CameraPreviewEvent;
+};
+
+export type InstantRecordingCreation =
+ typeof Video.InstantRecordingCreateSuccess.Type;
+
+export type RecorderSession = {
+ videoId: VideoId;
+ shareUrl: string;
+ pipeline: RecordingPipeline;
+};
diff --git a/apps/chrome-extension/src/shared/webrtc.ts b/apps/chrome-extension/src/shared/webrtc.ts
new file mode 100644
index 000000000..631e4f2ef
--- /dev/null
+++ b/apps/chrome-extension/src/shared/webrtc.ts
@@ -0,0 +1,34 @@
+// WebRTC plumbing shared by every camera-preview peer (offscreen document,
+// content-script overlay, and the preview page).
+
+export const toSessionDescriptionInit = (
+ description: RTCSessionDescription | null,
+): RTCSessionDescriptionInit => {
+ if (!description) throw new Error("Missing session description");
+ return {
+ type: description.type,
+ sdp: description.sdp,
+ };
+};
+
+export const waitForIceGatheringComplete = (peer: RTCPeerConnection) =>
+ new Promise<void>((resolve) => {
+ if (peer.iceGatheringState === "complete") {
+ resolve();
+ return;
+ }
+
+ const handleIceGatheringStateChange = () => {
+ if (peer.iceGatheringState !== "complete") return;
+ peer.removeEventListener(
+ "icegatheringstatechange",
+ handleIceGatheringStateChange,
+ );
+ resolve();
+ };
+
+ peer.addEventListener(
+ "icegatheringstatechange",
+ handleIceGatheringStateChange,
+ );
+ });