← Back to Pull requests

feat: webcam tables - live stream for players, auto-captured flop with staff confirm #53

Merged
DansiDanutz merged 28 files (1006 lines) on Nov 11, 2026 00:09 UTC
View on GitHub
DansiDanutz DansiDanutz commented on Nov 10, 2026 23:59 UTC
Author

What


Until the real live-poker capture chain (docs/12) exists, a manual play-money table can now run from a webcam over the table:

  • Players watch the table live. A manual table can have a YouTube or Twitch stream link. Only the video id or channel name is stored; migration 032 adds DB checks. The table page shows the stream muted, in a sandboxed iframe. The web CSP now frames only youtube-nocookie.com and player.twitch.tv; the tablet still frames nothing.

  • The console screenshots the flop. After Close betting, the console reads the webcam once a second with the existing in-browser reader. When the same three cards are read 3 times in a row, it keeps that frame, fills the picker and shows the frame next to Confirm and settle. Nothing settles without the staff tap. The previous hand's flop left on the felt never counts. The camera can be the webcam or OBS's virtual camera, and it is remembered per table.

  • Evidence. The frame (JPEG ≤ 512 KB, SHA-256 checked before the transaction) goes into a new append-only table, manual_flop_snapshots. Each row records the settled cards, the cards the camera read, and who confirmed. The hash is also written to the round.manual_flop audit entry. Typing by hand still works and stores no snapshot.

  • Random dealing is unchanged. Simulated tables still deal a crypto-random flop every ~20 s.
  • API


  • POST /v1/admin/tables/manual {name, stream_url?}

  • PUT /v1/admin/tables/:id/manual/stream {stream_url | null} (admin/ops, manual tables only, audited)

  • POST /v1/admin/tables/:id/manual/flop {…, snapshot?: {image_base64, sha256, read_cards}}

  • GET /v1/tables/:id, /v1/lobby and the admin list return stream: {provider, id} | null
  • Tests


  • API: stream-link.test.ts (21 link cases) and manual-stream.test.ts (8 integration tests: stream set/change/remove/audit, refusal of bad links, authorization, snapshot stored, corrected card kept, hash/JPEG/size refusals that leave the hand locked). Full API suite: 409 passed.

  • Client: streamEmbed.test.ts. Web: CSP test and LiveStream render test (170 passed). Console: flopWatch.test.ts (6) and snapshot.test.ts (2).

  • E2E e2e-manual-table.test.ts now drives the automatic flow in a real browser: a fake camera shows three cards, the watcher captures them, staff confirm, the hand settles, and the stored JPEG hash matches. It passed locally against the installed Chrome (PLAYWRIGHT_CHROMIUM).

  • Independent review found 0 critical/high issues. Its 3 medium and 3 low findings are all fixed.
  • Not verified


  • Not tried against a real YouTube/Twitch stream or a physical webcam and deck.

  • reader.frame.test.ts: 2 blur cases fail locally on desktop Chrome. The reader code is unchanged here; CI uses Playwright's Chromium.
  • Diff: 1006 lines (+861 / -145) across 28 files Reviewer: DansiDanutz Review duration: 9m
    All Vouch review confidence checks passed
    Residual risk 0.46 = Change Risk (0.96) × (1 − Review Confidence (0.52)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.96 · 1006 lines diff across 28 files
    0.96
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.87 · 5 substantive comment(s)
    0.87
    Model 3 · Review Timing & Attention
    Session adequacy: 38% · Reviewer familiarity: 50%
    52%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Rapid Merge rapid_merge
    0.100
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    10 items
    vercel[bot] vercel[bot] commented on Nov 10, 2026 23:59 UTC
    Bot

    [vc]: #CWvO3xu6UCEeb346kGJILbCaUoGwNjXoG82RJCyMzMc=:eyJpc01vbm9yZXBvIjp0cnVlLCJ0eXBlIjoiZ2l0aHViIiwicHJvamVjdHMiOlt7Im5hbWUiOiJwcmVmbG9wLXN0YWdpbmctY29uc29sZSIsInByb2plY3RJZCI6InByal9OMlZWUGJ1ZFpXYWpyYlFYVlI4MFV6aUpCYVB3Iiwicm9vdERpcmVjdG9yeSI6ImFwcHMvY29uc29sZSIsImluc3BlY3RvclVybCI6Imh0dHBzOi8vdmVyY2VsLmNvbS9pcmlzZXMtcHJvamVjdHMtY2U1NDlmNjMvcHJlZmxvcC1zdGFnaW5nLWNvbnNvbGUvOXRaWlBVMW9RQng2blJ1NnBlTUNIQjhuZWVqaiIsInByZXZpZXdVcmwiOiJwcmVmbG9wLXN0YWdpbmctY29uc29sZS1naXQtZmVhLTRmMWIwMC1pcmlzZXMtcHJvamVjdHMtY2U1NDlmNjMudmVyY2VsLmFwcCIsIm5leHRDb21taXRTdGF0dXMiOiJERVBMT1lFRCIsImxpdmVGZWVkYmFjayI6eyJyZXNvbHZlZCI6MCwidW5yZXNvbHZlZCI6MCwidG90YWwiOjAsImxpbmsiOiJwcmVmbG9wLXN0YWdpbmctY29uc29sZS1naXQtZmVhLTRmMWIwMC1pcmlzZXMtcHJvamVjdHMtY2U1NDlmNjMudmVyY2VsLmFwcCJ9fSx7Im5hbWUiOiJwcmVmbG9wLXN0YWdpbmctd2ViIiwicHJvamVjdElkIjoicHJqX0VrU3Y2VEtkRkthbE9qWjE4RVhrR2NkRk13b00iLCJyb290RGlyZWN0b3J5IjoiYXBwcy93ZWIiLCJpbnNwZWN0b3JVcmwiOiJodHRwczovL3ZlcmNlbC5jb20vaXJpc2VzLXByb2plY3RzLWNlNTQ5ZjYzL3ByZWZsb3Atc3RhZ2luZy13ZWIvQzE0WTR3ZjdQOHFSR25OVk1rdzM5NFA0VlpkbyIsInByZXZpZXdVcmwiOiIiLCJuZXh0Q29tbWl0U3RhdHVzIjoiU0tJUFBFRCIsImxpdmVGZWVkYmFjayI6eyJyZXNvbHZlZCI6MCwidW5yZXNvbHZlZCI6MCwidG90YWwiOjAsImxpbmsiOiIifX0seyJuYW1lIjoicHJlZmxvcC1zdGFnaW5nLXRhYmxlIiwicHJvamVjdElkIjoicHJqX1J1OGNzRlhoSGEyZVpsbDdvSEFsc0pua3Qza2oiLCJyb290RGlyZWN0b3J5IjoiYXBwcy90YWJsZSIsImluc3BlY3RvclVybCI6Imh0dHBzOi8vdmVyY2VsLmNvbS9pcmlzZXMtcHJvamVjdHMtY2U1NDlmNjMvcHJlZmxvcC1zdGFnaW5nLXRhYmxlLzNlbkNIYmlVMWhvc3FkbWdWRVBtQWRWdENjTjYiLCJwcmV2aWV3VXJsIjoiIiwibmV4dENvbW1pdFN0YXR1cyI6IlNLSVBQRUQiLCJsaXZlRmVlZGJhY2siOnsicmVzb2x2ZWQiOjAsInVucmVzb2x2ZWQiOjAsInRvdGFsIjowLCJsaW5rIjoiIn19LHsibmFtZSI6InByZS1mbG9wIiwicHJvamVjdElkIjoicHJqX3Z1dDJmMmdJclRGU0hyMmZIS3B6Ym54emd1WjkiLCJyb290RGlyZWN0b3J5IjoiYXBwcy93ZWIiLCJpbnNwZWN0b3JVcmwiOiJodHRwczovL3ZlcmNlbC5jb20vaXJpc2VzLXByb2plY3RzLWNlNTQ5ZjYzL3ByZS1mbG9wL0JlU0FuWHRnSzludUU1VTZXSldqcEo5YnFERGIiLCJwcmV2aWV3VXJsIjoiIiwibmV4dENvbW1pdFN0YXR1cyI6IlNLSVBQRUQiLCJsaXZlRmVlZGJhY2siOnsicmVzb2x2ZWQiOjAsInVucmVzb2x2ZWQiOjAsInRvdGFsIjowLCJsaW5rIjoiIn19XSwicmVxdWVzdFJldmlld1VybCI6Imh0dHBzOi8vdmVyY2VsLmNvbS92ZXJjZWwtYWdlbnQvcmVxdWVzdC1yZXZpZXc/b3duZXI9RGFuc2lEYW51dHomcmVwbz1QcmVGbG9wJnByPTUzIn0=
    The latest updates on your projects. Learn more about Vercel for GitHub.

    | Project | Deployment | Actions | Updated |
    | :--- | :----- | :------ | :------ |
    | <a href="https://vercel.com/irises-projects-ce549f63/preflop-staging-console"><sup><img src="https://vercel.com/api/www/avatar?projectId=prj_N2VVPbudZWajrbQXVR80UziJBaPw&teamId=team_Qtajbnyu0ZBt3TGPBIbgiyg1&s=32" width="16" height="16" align="middle" alt="" /></sup></a> preflop-staging-console | !Ready Ready | Preview | <relative-time datetime="2026-11-11T00:04:00.994Z">Nov 11, 2026 12:04am UTC</relative-time> |

    <details><summary>3 Skipped Deployments</summary>

    | Project | Deployment | Actions | Updated |
    | :--- | :----- | :------ | :------ |
    | <a href="https://vercel.com/irises-projects-ce549f63/pre-flop"><sup><img src="https://vercel.com/api/www/avatar?projectId=prj_vut2f2gIrTFSHr2fHKpzbnxzguZ9&teamId=team_Qtajbnyu0ZBt3TGPBIbgiyg1&s=32" width="16" height="16" align="middle" alt="" /></sup></a> pre-flop | !Skipped Skipped | | <relative-time datetime="2026-11-11T00:04:00.993Z">Nov 11, 2026 12:04am UTC</relative-time> |
    | <a href="https://vercel.com/irises-projects-ce549f63/preflop-staging-table"><sup><img src="https://vercel.com/api/www/avatar?projectId=prj_Ru8csFXhHa2eZll7oHAlsJnkt3kj&teamId=team_Qtajbnyu0ZBt3TGPBIbgiyg1&s=32" width="16" height="16" align="middle" alt="" /></sup></a> preflop-staging-table | !Skipped Skipped | | <relative-time datetime="2026-11-11T00:04:00.994Z">Nov 11, 2026 12:04am UTC</relative-time> |
    | <a href="https://vercel.com/irises-projects-ce549f63/preflop-staging-web"><sup><img src="https://vercel.com/api/www/avatar?projectId=prj_EkSv6TKdFKalOjZ18EXkGcdFMwoM&teamId=team_Qtajbnyu0ZBt3TGPBIbgiyg1&s=32" width="16" height="16" align="middle" alt="" /></sup></a> preflop-staging-web | !Skipped Skipped | | <relative-time datetime="2026-11-11T00:04:00.994Z">Nov 11, 2026 12:04am UTC</relative-time> |
    </details>

    <a href="https://vercel.com/vercel-agent/request-review?owner=DansiDanutz&repo=PreFlop&pr=53" rel="noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://agents-vade-review.vercel.sh/request-review-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://agents-vade-review.vercel.sh/request-review-light.svg"><img src="https://agents-vade-review.vercel.sh/request-review-light.svg" alt="Request Review"></picture></a>

    greptile-apps[bot] greptile-apps[bot] commented on Nov 10, 2026 23:59 UTC
    Reviewer

    Your trial has ended. Reactivate Greptile to resume code reviews.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 10, 2026 23:59 UTC
    Bot

    <!-- codex-pull-request-review-summary -->
    <!-- codex-review-state:v1 {"code_review":{"commit_sha":"50fdf2ee18f873edbf6ec20de8fe647418719df0","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} -->

    <details>
    <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary>

    This comment shows the latest Codex review activity on this pull request.

    | Review | Status | Commit | Review trigger |
    | --- | --- | --- | --- |
    | 📝 Code Review | ✅ Completed <relative-time datetime="2026-11-11T00:01:15.227378Z">2026-11-11T00:01:15.227378Z</relative-time> | 50fdf2e | PR opened |

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review" or "@codex security review".
  • Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

    </details>

    </details>

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 11, 2026 00:01 UTC
    Code Review
    apps/console/src/portals/admin/ManualTables.tsx:1
    @@ -99,7 +101,17 @@ function ManualTableCard({ t, slaMs }: { t: ManualTable; slaMs: number }) {
               {r.state === 'LOCKED' && (
                 <div className="space-y-3">
                   {/* Keyed by the round: a new hand gets a fresh reader, so a proposal read for the previous hand can never be applied to this one. */}
    -              <WebcamReader key={r.id} onReading={(reading) => setPicked(reading.cards.slice(0, 3))} />
    +              <WebcamFlop key={r.id} tableId={t.id} previousFlop={t.last_settled?.flop ?? null} onReading={(cards) => setPicked(cards.slice(0, 3))} onCapture={(c) => { setCapture(c); setPicked(c.cards); }} />

    <sub><sub>!P2 Badge</sub></sub> Stop automatic capture when staff manually select a flop

    If staff select cards manually while the watcher is still running, a later stable camera reading unconditionally replaces their selection—even if the settlement confirmation dialog is already open. This can undo an operator's correction of a camera misread and change the cards submitted by “Settle and pay” after they opened the dialog. Pause automatic capture once manual editing or confirmation begins, or require explicit acceptance before replacing an existing selection.

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 11, 2026 00:01 UTC
    Code Review
    apps/console/src/portals/admin/WebcamFlop.tsx:1
    @@ -0,0 +1,196 @@
    +import { useEffect, useRef, useState } from 'react';
    +import { Link } from 'react-router';
    +import type { FlopSnapshot, ReadingCheck } from '@preflop/client';
    +import { Button } from '@preflop/ui';
    +import { Camera, CameraOff, Eye, EyeOff, ScanSearch } from 'lucide-react';
    +import { loadCv } from '../../lib/cards/opencv.ts';
    +import { readCards } from '../../lib/cards/reader.ts';
    +import { WATCH_INTERVAL_MS, initialWatch, nextWatch } from '../../lib/cards/flopWatch.ts';
    +import { frameSnapshot } from '../../lib/cards/snapshot.ts';
    +import { MIN_CONFIDENCE, type Reading } from '../../lib/cards/vision.ts';
    +import { cardLabel } from '../../lib/manualFlop.ts';
    +import { api } from '../../lib/api.ts';
    +import { FlopText } from '../../components/domain.tsx';
    +import { ReadingVerdicts } from '../../components/decisions.tsx';
    +import { Select } from '../../components/ui.tsx';
    +
    +/** The flop the watcher saw, with the frame it was read from. Settling it still needs a staff tap. */
    +export interface FlopCapture { cards: string[]; snapshot: FlopSnapshot; previewUrl: string }
    +
    +/**
    + * The camera chosen last at this table, so its next hand's panel opens it again without a click
    + * (sessionStorage, per table: another table never starts watching by itself).
    + */
    +const cameraKey = (tableId: string) => `pf.manual.camera.${tableId}`;
    +const rememberedCamera = (tableId: string): string | null => { try { return sessionStorage.getItem(cameraKey(tableId)); } catch { return null; } };
    +const rememberCamera = (tableId: string, id: string | null) => {
    +  try { if (id === null) sessionStorage.removeItem(cameraKey(tableId)); else sessionStorage.setItem(cameraKey(tableId), id); } catch { /* private mode: ask again next hand */ }
    +};
    +
    +const frameOf = (v: HTMLVideoElement) => {
    +  const c = document.createElement('canvas');
    +  c.width = v.videoWidth; c.height = v.videoHeight;
    +  c.getContext('2d')!.drawImage(v, 0, 0);
    +  return c;
    +};
    +const cameraError = (e: unknown) => (e instanceof Error && e.name === 'NotAllowedError'
    +  ? 'Camera access was refused. Allow the camera for this site and try again.'
    +  : `Camera unavailable: ${e instanceof Error ? e.message : String(e)}`);
    +
    +/**
    + * Camera panel (docs/19) for a hand whose betting has closed. The camera is the webcam over the table
    + * (or the streaming software's virtual camera). While "Watch for the flop" is on, the laptop reads a
    + * frame every second; once the same three cards are read three times in a row it keeps that frame and
    + * hands the flop to the operator, who confirms it. Nothing settles by itself. Recognition runs in
    + * this browser (OpenCV.js); nothing leaves the laptop until the operator confirms.
    + */
    +export function WebcamFlop({ tableId, previousFlop, onReading, onCapture }: {
    +  tableId: string;
    +  /** The last settled flop at this table: cards left on the felt are never taken for the new flop. */
    +  previousFlop: string[] | null;
    +  onReading: (cards: string[]) => void;
    +  onCapture: (c: FlopCapture) => void;
    +}) {
    +  const video = useRef<HTMLVideoElement>(null);
    +  const [stream, setStream] = useState<MediaStream | null>(null);
    +  const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
    +  const [deviceId, setDeviceId] = useState<string | null>(() => rememberedCamera(tableId));
    +  const [error, setError] = useState<string | null>(null);
    +  const [busy, setBusy] = useState<'loading' | 'reading' | null>(null);
    +  const [watching, setWatching] = useState(true);
    +  const [reading, setReading] = useState<Reading | null>(null);
    +  const [check, setCheck] = useState<ReadingCheck | null>(null);
    +  const readingNo = useRef(0);
    +  // A stream granted for a request the operator has since stopped or repeated, or after this panel is
    +  // gone, is stopped at once instead of staying live with no view and no Stop button.
    +  const request = useRef(0);
    +  const mounted = useRef(true);
    +  const captured = useRef(onCapture);
    +  captured.current = onCapture;
    +  useEffect(() => {
    +    mounted.current = true;
    +    return () => { mounted.current = false; request.current++; };
    +  }, []);
    +  useEffect(() => {
    +    if (video.current) video.current.srcObject = stream;
    +    return () => stream?.getTracks().forEach((t) => t.stop());
    +  }, [stream]);
    +
    +  const start = async (id: string | null) => {
    +    setError(null);
    +    if (!navigator.mediaDevices?.getUserMedia) { setError('This browser gives no camera access here; the console must be opened over https.'); return; }
    +    const req = ++request.current;
    +    try {
    +      const constraints = id ? { deviceId: { exact: id } } : { facingMode: 'environment' };
    +      const s = await navigator.mediaDevices.getUserMedia({ video: { ...constraints, width: { ideal: 1280 }, height: { ideal: 720 } }, audio: false });
    +      if (!mounted.current || req !== request.current) { s.getTracks().forEach((t) => t.stop()); return; }
    +      setStream(s); // the [stream] effect's cleanup stops the previous one
    +      const used = s.getVideoTracks()[0]?.getSettings().deviceId ?? id;
    +      setDeviceId(used ?? null);
    +      rememberCamera(tableId, used ?? '');
    +      const all = await navigator.mediaDevices.enumerateDevices();
    +      if (mounted.current) setDevices(all.filter((d) => d.kind === 'videoinput'));
    +    } catch (e) {
    +      if (!mounted.current || req !== request.current) return;
    +      if (id) rememberCamera(tableId, null);
    +      setError(cameraError(e));

    <sub><sub>!P2 Badge</sub></sub> Clear the selected device when a remembered camera fails

    If the remembered webcam is unplugged or an OBS virtual camera is no longer available, the automatic start fails and clears sessionStorage but leaves deviceId pointing to the unavailable device. Every subsequent “Use webcam” click calls start(deviceId) with the same exact constraint, so an available replacement camera cannot be opened; the camera selector is also hidden until a stream exists. Clear the selected device state or retry without the exact device constraint so staff can recover without reloading the page.

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 11, 2026 00:01 UTC
    Reviewer

    <!-- codex-review-receipt:v1 -->

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: 50fdf2ee18

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

    </details>

    DansiDanutz DansiDanutz commented on code on Nov 11, 2026 00:03 UTC
    Code Review
    apps/console/src/portals/admin/ManualTables.tsx:1
    @@ -99,7 +101,17 @@ function ManualTableCard({ t, slaMs }: { t: ManualTable; slaMs: number }) {
               {r.state === 'LOCKED' && (
                 <div className="space-y-3">
                   {/* Keyed by the round: a new hand gets a fresh reader, so a proposal read for the previous hand can never be applied to this one. */}
    -              <WebcamReader key={r.id} onReading={(reading) => setPicked(reading.cards.slice(0, 3))} />
    +              <WebcamFlop key={r.id} tableId={t.id} previousFlop={t.last_settled?.flop ?? null} onReading={(cards) => setPicked(cards.slice(0, 3))} onCapture={(c) => { setCapture(c); setPicked(c.cards); }} />

    Fixed in bbd9fe0: picking, clearing or applying cards by hand, or opening the settle confirmation, pauses the watcher, and a capture arriving then is ignored, so it never replaces the operator's cards.

    _🤖 Addressed by Claude Code_

    DansiDanutz DansiDanutz commented on code on Nov 11, 2026 00:03 UTC
    Code Review
    apps/console/src/portals/admin/WebcamFlop.tsx:1
    @@ -0,0 +1,196 @@
    +import { useEffect, useRef, useState } from 'react';
    +import { Link } from 'react-router';
    +import type { FlopSnapshot, ReadingCheck } from '@preflop/client';
    +import { Button } from '@preflop/ui';
    +import { Camera, CameraOff, Eye, EyeOff, ScanSearch } from 'lucide-react';
    +import { loadCv } from '../../lib/cards/opencv.ts';
    +import { readCards } from '../../lib/cards/reader.ts';
    +import { WATCH_INTERVAL_MS, initialWatch, nextWatch } from '../../lib/cards/flopWatch.ts';
    +import { frameSnapshot } from '../../lib/cards/snapshot.ts';
    +import { MIN_CONFIDENCE, type Reading } from '../../lib/cards/vision.ts';
    +import { cardLabel } from '../../lib/manualFlop.ts';
    +import { api } from '../../lib/api.ts';
    +import { FlopText } from '../../components/domain.tsx';
    +import { ReadingVerdicts } from '../../components/decisions.tsx';
    +import { Select } from '../../components/ui.tsx';
    +
    +/** The flop the watcher saw, with the frame it was read from. Settling it still needs a staff tap. */
    +export interface FlopCapture { cards: string[]; snapshot: FlopSnapshot; previewUrl: string }
    +
    +/**
    + * The camera chosen last at this table, so its next hand's panel opens it again without a click
    + * (sessionStorage, per table: another table never starts watching by itself).
    + */
    +const cameraKey = (tableId: string) => `pf.manual.camera.${tableId}`;
    +const rememberedCamera = (tableId: string): string | null => { try { return sessionStorage.getItem(cameraKey(tableId)); } catch { return null; } };
    +const rememberCamera = (tableId: string, id: string | null) => {
    +  try { if (id === null) sessionStorage.removeItem(cameraKey(tableId)); else sessionStorage.setItem(cameraKey(tableId), id); } catch { /* private mode: ask again next hand */ }
    +};
    +
    +const frameOf = (v: HTMLVideoElement) => {
    +  const c = document.createElement('canvas');
    +  c.width = v.videoWidth; c.height = v.videoHeight;
    +  c.getContext('2d')!.drawImage(v, 0, 0);
    +  return c;
    +};
    +const cameraError = (e: unknown) => (e instanceof Error && e.name === 'NotAllowedError'
    +  ? 'Camera access was refused. Allow the camera for this site and try again.'
    +  : `Camera unavailable: ${e instanceof Error ? e.message : String(e)}`);
    +
    +/**
    + * Camera panel (docs/19) for a hand whose betting has closed. The camera is the webcam over the table
    + * (or the streaming software's virtual camera). While "Watch for the flop" is on, the laptop reads a
    + * frame every second; once the same three cards are read three times in a row it keeps that frame and
    + * hands the flop to the operator, who confirms it. Nothing settles by itself. Recognition runs in
    + * this browser (OpenCV.js); nothing leaves the laptop until the operator confirms.
    + */
    +export function WebcamFlop({ tableId, previousFlop, onReading, onCapture }: {
    +  tableId: string;
    +  /** The last settled flop at this table: cards left on the felt are never taken for the new flop. */
    +  previousFlop: string[] | null;
    +  onReading: (cards: string[]) => void;
    +  onCapture: (c: FlopCapture) => void;
    +}) {
    +  const video = useRef<HTMLVideoElement>(null);
    +  const [stream, setStream] = useState<MediaStream | null>(null);
    +  const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
    +  const [deviceId, setDeviceId] = useState<string | null>(() => rememberedCamera(tableId));
    +  const [error, setError] = useState<string | null>(null);
    +  const [busy, setBusy] = useState<'loading' | 'reading' | null>(null);
    +  const [watching, setWatching] = useState(true);
    +  const [reading, setReading] = useState<Reading | null>(null);
    +  const [check, setCheck] = useState<ReadingCheck | null>(null);
    +  const readingNo = useRef(0);
    +  // A stream granted for a request the operator has since stopped or repeated, or after this panel is
    +  // gone, is stopped at once instead of staying live with no view and no Stop button.
    +  const request = useRef(0);
    +  const mounted = useRef(true);
    +  const captured = useRef(onCapture);
    +  captured.current = onCapture;
    +  useEffect(() => {
    +    mounted.current = true;
    +    return () => { mounted.current = false; request.current++; };
    +  }, []);
    +  useEffect(() => {
    +    if (video.current) video.current.srcObject = stream;
    +    return () => stream?.getTracks().forEach((t) => t.stop());
    +  }, [stream]);
    +
    +  const start = async (id: string | null) => {
    +    setError(null);
    +    if (!navigator.mediaDevices?.getUserMedia) { setError('This browser gives no camera access here; the console must be opened over https.'); return; }
    +    const req = ++request.current;
    +    try {
    +      const constraints = id ? { deviceId: { exact: id } } : { facingMode: 'environment' };
    +      const s = await navigator.mediaDevices.getUserMedia({ video: { ...constraints, width: { ideal: 1280 }, height: { ideal: 720 } }, audio: false });
    +      if (!mounted.current || req !== request.current) { s.getTracks().forEach((t) => t.stop()); return; }
    +      setStream(s); // the [stream] effect's cleanup stops the previous one
    +      const used = s.getVideoTracks()[0]?.getSettings().deviceId ?? id;
    +      setDeviceId(used ?? null);
    +      rememberCamera(tableId, used ?? '');
    +      const all = await navigator.mediaDevices.enumerateDevices();
    +      if (mounted.current) setDevices(all.filter((d) => d.kind === 'videoinput'));
    +    } catch (e) {
    +      if (!mounted.current || req !== request.current) return;
    +      if (id) rememberCamera(tableId, null);
    +      setError(cameraError(e));

    Fixed in bbd9fe0: when a remembered camera fails to open, the selected device is cleared too, so the next Use webcam opens the default camera.

    _🤖 Addressed by Claude Code_

    greptile-apps[bot] greptile-apps[bot] commented on Nov 11, 2026 00:03 UTC
    Reviewer

    Your trial has ended. Reactivate Greptile to resume code reviews.

    Reviewers
    Assignees
    DansiDanutz DansiDanutz
    Labels
    risk: medium confidence: 52.3% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 95.5% (HIGH) · Higher = larger blast radius
    95.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 52.3% · Lower = rushed or shallow review
    52.3%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 45.6% · Moderate risk
    45.6%