Personal AI, On Personal Devices
Python
Fix hand tracking desktop setup and chat lifecycle
Elliot Slusky70102d67bbd4
diff --git a/docs/user-guide/chat-simple.md b/docs/user-guide/chat-simple.mdindex 7871d176..c70bfb66 100644--- a/docs/user-guide/chat-simple.md+++ b/docs/user-guide/chat-simple.md@@ -143,9 +143,11 @@ actions. Do not run or wrap that script as an OpenJarvis tool.Microphone transcription requires the Speech-to-Text setting and a configuredspeech backend. Offline transcription requires a local backend and model; a remoteprovider can send audio off-device. Camera hand tracking is optional in-**Settings → Hand tracking**: it asks for camera permission only when started,-detects landmarks and basic gestures locally, and stops when stopped or when the-settings page closes. The first camera action briefly requests permission to reveal+**Settings → Hand tracking → Open hand tracking in chat**, or the **Hand tracking**+button above the chat input. Opening the panel does not start capture. It detects+landmarks and basic gestures locally, and stops when stopped, when the panel closes,+when you leave chat, or when the app/tab is hidden. Returning does not restart the+camera. The first camera action briefly requests permission to revealcamera names, then immediately stops that temporary stream. Select the intendeddevice (for example, **Integrated Webcam**) from the camera list before pressing**Start camera**. Open palm can optionally focus the chat input; gestures neverdiff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex aadcd167..80afcea6 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -46,6 +46,7 @@"@types/react": "^19.3.0","@types/react-dom": "^19.3.0","@vitejs/plugin-react": "^6.1.2",+ "happy-dom": "^20.14.6","typescript": "~7.0.2","vite": "^8.3.4","vite-plugin-pwa": "^2.0.0",@@ -3378,6 +3379,16 @@"integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==","license": "MIT"},+ "node_modules/@types/node": {+ "version": "26.6.5",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz",+ "integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==",+ "devOptional": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~8.9.0"+ }+ },"node_modules/@types/react": {"version": "19.3.0","resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",@@ -3423,6 +3434,23 @@"integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==","license": "MIT"},+ "node_modules/@types/whatwg-mimetype": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz",+ "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/ws": {+ "version": "8.18.2",+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz",+ "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@typescript/typescript-aix-ppc64": {"version": "7.0.2","resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",@@ -4108,6 +4136,19 @@"devOptional": true,"license": "MIT"},+ "node_modules/buffer-image-size": {+ "version": "0.6.4",+ "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz",+ "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ },+ "engines": {+ "node": ">=4.0"+ }+ },"node_modules/call-bind": {"version": "1.0.9","resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz",@@ -5347,6 +5388,38 @@"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==","license": "ISC"},+ "node_modules/happy-dom": {+ "version": "20.14.6",+ "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.14.6.tgz",+ "integrity": "sha512-5DDsf4QmEIlRL6NkCv/fxSjYHHkZceL/IaYQdJc2h3G7DRTEai++VTjbfL0LB9geW2VrA3+vrjF3Efx+OTtX0Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": ">=20.0.0",+ "@types/whatwg-mimetype": "^3.0.2",+ "@types/ws": "^8.18.1",+ "buffer-image-size": "^0.6.4",+ "entities": "^7.0.1",+ "whatwg-mimetype": "^3.0.0",+ "ws": "^8.21.0"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/happy-dom/node_modules/entities": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",+ "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=0.12"+ },+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },"node_modules/has-bigints": {"version": "1.1.0","resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz",@@ -9124,6 +9197,13 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/undici-types": {+ "version": "8.9.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",+ "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",+ "devOptional": true,+ "license": "MIT"+ },"node_modules/unicode-canonical-property-names-ecmascript": {"version": "2.0.1","resolved": "https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-2.0.1.tgz",@@ -9906,6 +9986,16 @@"integrity": "sha512-rLcLXA2sx6+9dE88NHFubwTtGxpK4yYBLj6qHPdFoCaLr0cXGb4efOqtKLlm4loGA4OEKHIQKMKzZkKyOh5ctw==","license": "Apache-2.0"},+ "node_modules/whatwg-mimetype": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz",+ "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/which-boxed-primitive": {"version": "1.1.1","resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz",@@ -10289,6 +10379,28 @@"workbox-core": "7.4.1"}},+ "node_modules/ws": {+ "version": "8.22.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",+ "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },"node_modules/yallist": {"version": "3.1.1","resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex c8ca2111..5b5f19e1 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -55,6 +55,7 @@"@types/react": "^19.3.0","@types/react-dom": "^19.3.0","@vitejs/plugin-react": "^6.1.2",+ "happy-dom": "^20.14.6","typescript": "~7.0.2","vite": "^8.3.4","vite-plugin-pwa": "^2.0.0",diff --git a/frontend/src-tauri/Entitlements.plist b/frontend/src-tauri/Entitlements.plistindex da5ee242..724656aa 100644--- a/frontend/src-tauri/Entitlements.plist+++ b/frontend/src-tauri/Entitlements.plist@@ -8,6 +8,8 @@<true/><key>com.apple.security.network.server</key><true/>+ <key>com.apple.security.device.camera</key>+ <true/><key>com.apple.security.files.user-selected.read-write</key><true/><key>com.apple.security.cs.allow-jit</key>diff --git a/frontend/src-tauri/Info.plist b/frontend/src-tauri/Info.plistindex 794e7a46..a4faca0f 100644--- a/frontend/src-tauri/Info.plist+++ b/frontend/src-tauri/Info.plist@@ -2,6 +2,8 @@<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>+ <key>NSCameraUsageDescription</key>+ <string>Use your selected camera for optional on-device hand tracking in chat. Frames are not recorded or sent to a server.</string><key>NSAppTransportSecurity</key><dict><!-- The desktop API URL is user-configurable, so it cannot be representeddiff --git a/frontend/src-tauri/tauri.conf.json b/frontend/src-tauri/tauri.conf.jsonindex d68eb5ac..262c5c0d 100644--- a/frontend/src-tauri/tauri.conf.json+++ b/frontend/src-tauri/tauri.conf.json@@ -24,7 +24,7 @@}],"security": {- "csp": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; connect-src 'self' http: https: ws: wss:; img-src 'self' data: blob:; media-src 'self' blob:"+ "csp": "default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; connect-src 'self' http: https: ws: wss:; img-src 'self' data: blob:; media-src 'self' blob:"}},"bundle": {diff --git a/frontend/src/components/Chat/ChatArea.tsx b/frontend/src/components/Chat/ChatArea.tsxindex ed886b0e..5e1c8536 100644--- a/frontend/src/components/Chat/ChatArea.tsx+++ b/frontend/src/components/Chat/ChatArea.tsx@@ -2,6 +2,7 @@ import { useRef, useEffect, useState, useCallback } from 'react';import { useNavigate } from 'react-router';import { MessageBubble } from './MessageBubble';import { InputArea } from './InputArea';+import { ChatHandTracking } from './ChatHandTracking';import { StreamingDots } from './StreamingDots';import { useAppStore } from '../../lib/store';import { shouldAutoplayFinishedReply, useTtsStore } from '../../lib/tts';@@ -255,6 +256,7 @@ export function ChatArea() {</div>)}</div>+ <ChatHandTracking /><InputArea /></div>);diff --git a/frontend/src/components/Chat/ChatHandTracking.tsx b/frontend/src/components/Chat/ChatHandTracking.tsxnew file mode 100644index 00000000..e3b3da0b--- /dev/null+++ b/frontend/src/components/Chat/ChatHandTracking.tsx@@ -0,0 +1,41 @@+import { Hand } from 'lucide-react';+import { useSearchParams } from 'react-router';+import { HandTrackingPanel } from '../HandTrackingPanel';++/** Keep the opt-in camera and its focus target on the same route. */+export function ChatHandTracking() {+ const [searchParams, setSearchParams] = useSearchParams();+ const open = searchParams.get('handTracking') === '1';++ const togglePanel = () => {+ const next = new URLSearchParams(searchParams);+ if (open) next.delete('handTracking');+ else next.set('handTracking', '1');+ setSearchParams(next, { replace: true });+ };++ return (+ <div className="shrink-0 px-4 max-w-[var(--chat-max-width)] w-full mx-auto">+ <button+ type="button"+ aria-expanded={open}+ aria-controls="chat-hand-tracking"+ onClick={togglePanel}+ className="flex items-center gap-1.5 text-xs py-2 cursor-pointer"+ style={{ color: 'var(--color-text-secondary)' }}+ >+ <Hand size={14} />+ {open ? 'Close hand tracking (stops camera)' : 'Hand tracking'}+ </button>+ {open && (+ <div id="chat-hand-tracking" className="max-h-[45vh] overflow-y-auto pb-3">+ <HandTrackingPanel />+ <p className="text-xs mt-2" style={{ color: 'var(--color-text-tertiary)' }}>+ Camera access starts only when you choose a camera. Closing this panel,+ leaving chat, or hiding the app stops it; returning does not restart it.+ </p>+ </div>+ )}+ </div>+ );+}diff --git a/frontend/src/components/HandTrackingPanel.desktop.test.ts b/frontend/src/components/HandTrackingPanel.desktop.test.tsnew file mode 100644index 00000000..1e851adc--- /dev/null+++ b/frontend/src/components/HandTrackingPanel.desktop.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';+import nativeConfig from '../../src-tauri/tauri.conf.json?raw';+import infoPlist from '../../src-tauri/Info.plist?raw';+import entitlements from '../../src-tauri/Entitlements.plist?raw';++describe('packaged desktop hand tracking prerequisites', () => {+ it('allows local WASM compilation without permitting JavaScript eval or remote scripts', () => {+ const config = JSON.parse(nativeConfig);+ const directives = config.app.security.csp.split(';').map((part: string) => part.trim().split(/\s+/));+ const scriptSources = directives.find(([name]: string[]) => name === 'script-src')?.slice(1);+ expect(scriptSources).toContain("'wasm-unsafe-eval'");+ expect(scriptSources).toContain("'self'");+ expect(scriptSources).not.toContain("'unsafe-eval'");+ expect(scriptSources).not.toContain('*');+ expect(scriptSources).not.toContain('https:');+ });++ it('declares camera use for macOS permission prompts and hardened runtime', () => {+ expect(infoPlist).toMatch(/<key>NSCameraUsageDescription<\/key>\s*<string>[^<]+<\/string>/);+ expect(entitlements).toMatch(/<key>com\.apple\.security\.device\.camera<\/key>\s*<true\s*\/>/);+ });+});diff --git a/frontend/src/components/HandTrackingPanel.tsx b/frontend/src/components/HandTrackingPanel.tsxindex 00e082bf..6d885ab8 100644--- a/frontend/src/components/HandTrackingPanel.tsx+++ b/frontend/src/components/HandTrackingPanel.tsx@@ -8,7 +8,7 @@ import simdLoaderUrl from '@mediapipe/tasks-vision/vision_wasm_internal.js?url';import simdWasmUrl from '@mediapipe/tasks-vision/vision_wasm_internal.wasm?url';import noSimdLoaderUrl from '@mediapipe/tasks-vision/vision_wasm_nosimd_internal.js?url';import noSimdWasmUrl from '@mediapipe/tasks-vision/vision_wasm_nosimd_internal.wasm?url';-import { Camera, Hand, LoaderCircle, StopCircle } from 'lucide-react';+import { Camera, Hand, StopCircle } from 'lucide-react';const HAND_CONNECTIONS = [[0, 1], [1, 2], [2, 3], [3, 4],@@ -85,21 +85,27 @@ export function HandTrackingPanel() {const generationRef = useRef(0);const previousGestureRef = useRef<string>('');- const stopTracking = useCallback(() => {+ const releaseTracking = useCallback(() => {generationRef.current += 1;if (frameRef.current !== null) cancelAnimationFrame(frameRef.current);frameRef.current = null;- detectorRef.current?.close();+ const detector = detectorRef.current;detectorRef.current = null;+ // Camera cleanup must still run if the WASM runtime failed during shutdown.+ try { detector?.close(); } catch { /* Already failed/closed. */ }streamRef.current?.getTracks().forEach((track) => track.stop());streamRef.current = null;if (videoRef.current) videoRef.current.srcObject = null;+ }, []);++ const stopTracking = useCallback(() => {+ releaseTracking();setLandmarks([]);setGesture('No hand detected');previousGestureRef.current = '';setState('idle');setError('');- }, []);+ }, [releaseTracking]);const chooseCamera = useCallback(async () => {if (!navigator.mediaDevices?.getUserMedia) {@@ -174,8 +180,10 @@ export function HandTrackingPanel() {if (!video) throw new Error('Camera preview is unavailable.');video.srcObject = stream;await video.play();+ if (generationRef.current !== generation) return;const fileset = await localVisionFileset();+ if (generationRef.current !== generation) return;const detector = await HandLandmarker.createFromOptions(fileset, {baseOptions: {modelAssetPath: new URL('/models/hand_landmarker.task', window.location.origin).href,@@ -206,7 +214,15 @@ export function HandTrackingPanel() {video.currentTime !== lastVideoTime) {lastVideoTime = video.currentTime;- const result = currentDetector.detectForVideo(video, performance.now());+ let result;+ try {+ result = currentDetector.detectForVideo(video, performance.now());+ } catch {+ stopTracking();+ setError('Hand tracking stopped after a camera or detector error. Start the camera to try again.');+ setState('error');+ return;+ }const detectedHands = result.landmarks;const currentGesture = detectedHands.length? classifyHandGesture(detectedHands[0])@@ -232,11 +248,7 @@ export function HandTrackingPanel() {frameRef.current = requestAnimationFrame(detectFrame);} catch (cause) {if (generationRef.current !== generation) return;- streamRef.current?.getTracks().forEach((track) => track.stop());- streamRef.current = null;- if (videoRef.current) videoRef.current.srcObject = null;- detectorRef.current?.close();- detectorRef.current = null;+ releaseTracking();setError(cause instanceof DOMException && cause.name === 'NotAllowedError'? 'Camera permission was denied. Allow camera access in system settings, then try again.'@@ -246,14 +258,20 @@ export function HandTrackingPanel() {);setState('error');}- }, [selectedCameraId]);+ }, [selectedCameraId, releaseTracking, stopTracking]);- useEffect(() => () => {- generationRef.current += 1;- if (frameRef.current !== null) cancelAnimationFrame(frameRef.current);- detectorRef.current?.close();- streamRef.current?.getTracks().forEach((track) => track.stop());- }, []);+ useEffect(() => {+ const onVisibilityChange = () => {+ if (document.hidden) stopTracking();+ };+ document.addEventListener('visibilitychange', onVisibilityChange);+ window.addEventListener('pagehide', stopTracking);+ return () => {+ document.removeEventListener('visibilitychange', onVisibilityChange);+ window.removeEventListener('pagehide', stopTracking);+ releaseTracking();+ };+ }, [releaseTracking, stopTracking]);const updateFocusOption = (enabled: boolean) => {setFocusOnOpenPalm(enabled);@@ -331,54 +349,54 @@ export function HandTrackingPanel() {</div>)}- {(state === 'active' || state === 'starting') && (- <div className="flex flex-col sm:flex-row items-start gap-4 mt-4">- <div className="relative w-full sm:w-64 aspect-video overflow-hidden rounded-lg bg-black">- <video- ref={videoRef}- muted- playsInline- aria-label="Live camera preview for hand tracking"- className="absolute inset-0 w-full h-full object-cover"- style={{ transform: 'scaleX(-1)' }}- />- <svg- aria-hidden="true"- viewBox="0 0 1 1"- preserveAspectRatio="none"- className="absolute inset-0 w-full h-full"- style={{ transform: 'scaleX(-1)' }}- >- {landmarks.map((hand, handIndex) => (- <g key={handIndex}>- {HAND_CONNECTIONS.map(([start, end]) => (- <line- key={`${start}-${end}`}- x1={hand[start].x}- y1={hand[start].y}- x2={hand[end].x}- y2={hand[end].y}- stroke="#34d399"- strokeWidth="0.009"- />- ))}- {hand.map((point, pointIndex) => (- <circle key={pointIndex} cx={point.x} cy={point.y} r="0.014" fill="#fbbf24" />- ))}- </g>- ))}- </svg>- </div>- <div aria-live="polite" className="flex items-center gap-2 text-xs" style={{ color: 'var(--color-text-secondary)' }}>- <Hand size={15} style={{ color: landmarks.length ? 'var(--color-success)' : 'var(--color-text-tertiary)' }} />- {state === 'starting'- ? 'Starting local hand tracker…'- : landmarks.length- ? `${landmarks.length} hand${landmarks.length === 1 ? '' : 's'} — ${gesture}`- : 'No hand detected'}- </div>+ {/* Keep the ref available even when camera permission resolves before React+ commits the starting state. An empty video never starts capture. */}+ <div className={state === 'active' || state === 'starting' ? 'flex flex-col sm:flex-row items-start gap-4 mt-4' : 'hidden'}>+ <div className="relative w-full sm:w-64 aspect-video overflow-hidden rounded-lg bg-black">+ <video+ ref={videoRef}+ muted+ playsInline+ aria-label="Live camera preview for hand tracking"+ className="absolute inset-0 w-full h-full object-cover"+ style={{ transform: 'scaleX(-1)' }}+ />+ <svg+ aria-hidden="true"+ viewBox="0 0 1 1"+ preserveAspectRatio="none"+ className="absolute inset-0 w-full h-full"+ style={{ transform: 'scaleX(-1)' }}+ >+ {landmarks.map((hand, handIndex) => (+ <g key={handIndex}>+ {HAND_CONNECTIONS.map(([start, end]) => (+ <line+ key={`${start}-${end}`}+ x1={hand[start].x}+ y1={hand[start].y}+ x2={hand[end].x}+ y2={hand[end].y}+ stroke="#34d399"+ strokeWidth="0.009"+ />+ ))}+ {hand.map((point, pointIndex) => (+ <circle key={pointIndex} cx={point.x} cy={point.y} r="0.014" fill="#fbbf24" />+ ))}+ </g>+ ))}+ </svg></div>- )}+ <div aria-live="polite" className="flex items-center gap-2 text-xs" style={{ color: 'var(--color-text-secondary)' }}>+ <Hand size={15} style={{ color: landmarks.length ? 'var(--color-success)' : 'var(--color-text-tertiary)' }} />+ {state === 'starting'+ ? 'Starting local hand tracker…'+ : landmarks.length+ ? `${landmarks.length} hand${landmarks.length === 1 ? '' : 's'} — ${gesture}`+ : 'No hand detected'}+ </div>+ </div>{state === 'error' && (<p role="alert" className="text-xs mt-3" style={{ color: 'var(--color-error)' }}>{error}</p>diff --git a/frontend/src/pages/ChatPage.hand-tracking.test.tsx b/frontend/src/pages/ChatPage.hand-tracking.test.tsxnew file mode 100644index 00000000..bf70686c--- /dev/null+++ b/frontend/src/pages/ChatPage.hand-tracking.test.tsx@@ -0,0 +1,247 @@+// @vitest-environment happy-dom+// @vitest-environment-options { "url": "http://localhost:5173" }+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { createMemoryRouter, RouterProvider } from 'react-router';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { ChatPage } from './ChatPage';+import { useAppStore } from '../lib/store';++const vision = vi.hoisted(() => ({+ create: vi.fn(),+ detect: vi.fn(),+ close: vi.fn(),+}));+const send = vi.hoisted(() => vi.fn());++vi.mock('@mediapipe/tasks-vision', () => ({+ FilesetResolver: {+ isSimdSupported: vi.fn().mockResolvedValue(true),+ forVisionTasks: vi.fn().mockResolvedValue({}),+ },+ HandLandmarker: { createFromOptions: vision.create },+}));+vi.mock('../lib/connectors-api', () => ({ listConnectors: vi.fn().mockResolvedValue([]) }));+vi.mock('../lib/sse', () => ({ streamChat: send, streamResearch: send }));+vi.mock('../components/Chat/MessageBubble', () => ({ MessageBubble: () => null }));+vi.mock('../hooks/useSpeech', () => ({+ useSpeech: () => ({ state: 'idle', error: null, available: false }),+}));++function openPalm() {+ const points = Array.from({ length: 21 }, () => ({ x: 0.5, y: 0.7, z: 0 }));+ points[0].y = 0.8;+ points[3].x = 0.6;+ points[4].x = 0.8;+ for (const tip of [8, 12, 16, 20]) points[tip].y = 0.2;+ for (const pip of [6, 10, 14, 18]) points[pip].y = 0.5;+ return points;+}++function mockStream() {+ const stop = vi.fn();+ const stream = new MediaStream();+ Object.defineProperty(stream, 'getTracks', { value: () => [{ stop }] });+ return { stop, stream };+}++let root: Root;+let container: HTMLDivElement;+let router: ReturnType<typeof createMemoryRouter>;+let frames: Map<number, FrameRequestCallback>;+let camera: ReturnType<typeof mockStream>;+let permission: ReturnType<typeof mockStream>;+let getUserMedia: ReturnType<typeof vi.fn>;+let hidden: boolean;+let videoTime: number;++beforeEach(() => {+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+ localStorage.clear();+ vi.clearAllMocks();+ useAppStore.setState({+ selectedModel: 'test-model', modelLoading: false, systemPanelOpen: false,+ deepResearch: false, activeId: null, messages: [],+ streamState: { ...useAppStore.getState().streamState, isStreaming: false },+ });+ hidden = false;+ videoTime = 0;+ vi.spyOn(document, 'hidden', 'get').mockImplementation(() => hidden);+ vi.spyOn(HTMLMediaElement.prototype, 'play').mockResolvedValue();+ // happy-dom exposes media elements but does not define their readiness constants.+ Object.defineProperty(HTMLMediaElement, 'HAVE_CURRENT_DATA', { configurable: true, value: 2 });+ vi.spyOn(HTMLMediaElement.prototype, 'readyState', 'get').mockReturnValue(2);+ vi.spyOn(HTMLMediaElement.prototype, 'currentTime', 'get').mockImplementation(() => videoTime);+ frames = new Map();+ let id = 0;+ vi.stubGlobal('requestAnimationFrame', vi.fn((callback: FrameRequestCallback) => {+ frames.set(++id, callback);+ return id;+ }));+ vi.stubGlobal('cancelAnimationFrame', vi.fn((frame: number) => frames.delete(frame)));+ // Catch accidental backend/model downloads rather than making real requests.+ vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new Error('Unexpected network request'))));+ permission = mockStream();+ camera = mockStream();+ getUserMedia = vi.fn().mockResolvedValueOnce(permission.stream).mockResolvedValue(camera.stream);+ Object.defineProperty(navigator, 'mediaDevices', {+ configurable: true,+ value: {+ getUserMedia,+ enumerateDevices: vi.fn().mockResolvedValue([+ { kind: 'videoinput', deviceId: 'phone', label: 'Phone camera' },+ { kind: 'videoinput', deviceId: 'webcam', label: 'Integrated Webcam' },+ ]),+ },+ });+ vision.create.mockResolvedValue({ detectForVideo: vision.detect, close: vision.close });+ vision.detect.mockReturnValue({ landmarks: [openPalm()] });+ container = document.createElement('div');+ document.body.append(container);+ root = createRoot(container);+});++afterEach(async () => {+ await act(async () => root?.unmount());+ router?.dispose();+ container?.remove();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++async function mount(path = '/?handTracking=1') {+ router = createMemoryRouter([+ { path: '/', element: <ChatPage /> },+ { path: '/settings', element: <div>Settings</div> },+ ], { initialEntries: [path] });+ await act(async () => root.render(<RouterProvider router={router} />));+}++function button(text: string) {+ const result = [...container.querySelectorAll('button')].find((node) => node.textContent?.trim() === text);+ expect(result, `Button: ${text}`).toBeDefined();+ return result!;+}++async function click(text: string) {+ await act(async () => button(text).click());+}++async function start() {+ await click('Choose camera');+ expect(permission.stop).toHaveBeenCalledOnce();+ await click('Start camera');+ expect(container.querySelector('[role="alert"]')?.textContent).toBeUndefined();+}++async function frame() {+ const [id, callback] = frames.entries().next().value!;+ frames.delete(id);+ videoTime += 1;+ await act(async () => callback(performance.now()));+}++describe('chat hand tracking route and camera lifecycle', () => {+ it('opens without permission and focuses the real chat input only after opt-in, without sending', async () => {+ await mount('/');+ expect(container.querySelector('video')).toBeNull();+ await click('Hand tracking');+ expect(getUserMedia).not.toHaveBeenCalled();+ const focusOption = container.querySelector<HTMLInputElement>('input[type="checkbox"]')!;+ expect(focusOption.checked).toBe(false);+ await start();+ button('Stop camera').focus();+ await frame();+ expect(document.activeElement).toBe(button('Stop camera'));+ await act(async () => focusOption.click());+ vision.detect.mockReturnValueOnce({ landmarks: [] });+ await frame();+ await frame();+ expect(document.activeElement).toBe(container.querySelector('textarea'));+ expect(getUserMedia).toHaveBeenNthCalledWith(1, { video: true, audio: false });+ expect(getUserMedia).toHaveBeenNthCalledWith(2, { video: { deviceId: { exact: 'webcam' } }, audio: false });+ expect(send).not.toHaveBeenCalled();+ expect(useAppStore.getState().messages).toEqual([]);+ await click('Close hand tracking (stops camera)');+ expect(camera.stop).toHaveBeenCalledOnce();+ expect(vision.close).toHaveBeenCalledOnce();+ expect(frames.size).toBe(0);+ await click('Hand tracking');+ expect(getUserMedia).toHaveBeenCalledTimes(2);+ });++ it('stops on route changes and does not resume on returning to chat', async () => {+ await mount();+ await start();+ await act(async () => { await router.navigate('/settings'); });+ expect(camera.stop).toHaveBeenCalledOnce();+ expect(vision.close).toHaveBeenCalledOnce();+ expect(frames.size).toBe(0);+ await act(async () => { await router.navigate('/?handTracking=1'); });+ expect(getUserMedia).toHaveBeenCalledTimes(2);+ expect(container.querySelector('video')?.srcObject).toBeFalsy();+ });++ it.each(['hidden', 'pagehide', 'stop'])('stops capture on %s and requires another start', async (reason) => {+ await mount();+ await start();+ await act(async () => {+ if (reason === 'hidden') {+ hidden = true;+ document.dispatchEvent(new Event('visibilitychange'));+ } else if (reason === 'pagehide') window.dispatchEvent(new Event('pagehide'));+ else button('Stop camera').click();+ });+ expect(camera.stop).toHaveBeenCalledOnce();+ expect(vision.close).toHaveBeenCalledOnce();+ expect(frames.size).toBe(0);+ await act(async () => {+ hidden = false;+ document.dispatchEvent(new Event('visibilitychange'));+ });+ expect(getUserMedia).toHaveBeenCalledTimes(2);+ expect(button('Start camera')).toBeDefined();+ });++ it('closes a permission stream that arrives after leaving chat', async () => {+ let resolvePermission!: (stream: MediaStream) => void;+ getUserMedia.mockReset().mockReturnValue(new Promise((resolve) => { resolvePermission = resolve; }));+ await mount();+ await click('Choose camera');+ await act(async () => { await router.navigate('/settings'); });+ await act(async () => resolvePermission(permission.stream));+ expect(permission.stop).toHaveBeenCalledOnce();+ expect(vision.create).not.toHaveBeenCalled();+ });++ it('stops the camera immediately and closes a detector that finishes loading after cancellation', async () => {+ let resolveDetector!: (detector: unknown) => void;+ vision.create.mockReturnValueOnce(new Promise((resolve) => { resolveDetector = resolve; }));+ await mount();+ await start();+ await click('Close hand tracking (stops camera)');+ expect(camera.stop).toHaveBeenCalledOnce();+ await act(async () => resolveDetector({ close: vision.close }));+ expect(vision.close).toHaveBeenCalledOnce();+ expect(frames.size).toBe(0);+ });++ it('reports permission denial without loading the detector', async () => {+ getUserMedia.mockReset().mockRejectedValue(new DOMException('Denied', 'NotAllowedError'));+ await mount();+ await click('Choose camera');+ expect(container.querySelector('[role="alert"]')?.textContent).toContain('Camera permission was denied');+ expect(vision.create).not.toHaveBeenCalled();+ });++ it('releases the camera if inference or detector cleanup fails', async () => {+ vision.detect.mockImplementationOnce(() => { throw new Error('WASM failed'); });+ vision.close.mockImplementationOnce(() => { throw new Error('Already failed'); });+ await mount();+ await start();+ await frame();+ expect(camera.stop).toHaveBeenCalledOnce();+ expect(frames.size).toBe(0);+ expect(container.querySelector('[role="alert"]')?.textContent).toContain('Hand tracking stopped');+ });+});diff --git a/frontend/src/pages/SettingsPage.cloud-providers.test.tsx b/frontend/src/pages/SettingsPage.cloud-providers.test.tsxindex 2e35fe7f..fdf2b400 100644--- a/frontend/src/pages/SettingsPage.cloud-providers.test.tsx+++ b/frontend/src/pages/SettingsPage.cloud-providers.test.tsx@@ -1,4 +1,5 @@import { renderToStaticMarkup } from 'react-dom/server';+import { MemoryRouter } from 'react-router';import { describe, expect, it, vi } from 'vitest';describe('desktop cloud provider settings', () => {@@ -6,7 +7,7 @@ describe('desktop cloud provider settings', () => {vi.stubGlobal('localStorage', { getItem: () => null });vi.stubGlobal('window', { __TAURI_INTERNALS__: {} });const { SettingsPage } = await import('./SettingsPage');- const html = renderToStaticMarkup(<SettingsPage />);+ const html = renderToStaticMarkup(<MemoryRouter><SettingsPage /></MemoryRouter>);expect(html).toContain('Atlas Cloud');const atlasKeyInput = html.match(/<input[^>]*placeholder="Atlas Cloud API key"[^>]*>/)?.[0];diff --git a/frontend/src/pages/SettingsPage.tsx b/frontend/src/pages/SettingsPage.tsxindex db57947d..db6bda27 100644--- a/frontend/src/pages/SettingsPage.tsx+++ b/frontend/src/pages/SettingsPage.tsx@@ -1,4 +1,5 @@import { useState, useEffect, useCallback, useRef } from 'react';+import { Link } from 'react-router';import {Palette,Globe,@@ -21,7 +22,6 @@ import {Wifi,} from 'lucide-react';import { useAppStore, type ThemeMode } from '../lib/store';-import { HandTrackingPanel } from '../components/HandTrackingPanel';import {checkHealth,fetchSpeechHealth,@@ -942,7 +942,15 @@ export function SettingsPage() {{/* Hand tracking */}<Section title="Hand tracking">- <HandTrackingPanel />+ <SettingRow label="Camera gestures" description="Open camera controls alongside the chat input. Camera access requires an explicit action and stops when you close the panel or leave chat.">+ <Link+ to="/?handTracking=1"+ className="text-xs underline"+ style={{ color: 'var(--color-accent)' }}+ >+ Open hand tracking in chat+ </Link>+ </SettingRow></Section>{/* Data */}