@theoremjs/react 0.3.5-next.1029.g543179b → 0.3.5-next.1031.g1faef7b
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +84 -4
- package/client/decision-images.d.ts +1 -1
- package/client/decision-images.js +1 -1
- package/client/ink-waveform.d.ts +1 -1
- package/client/ink-waveform.js +1 -1
- package/client/live/live-video-view.d.ts +38 -0
- package/client/live/live-video-view.js +19 -0
- package/client/live/live-video.d.ts +63 -3
- package/client/live/live-video.js +95 -18
- package/components/live/use-live-call.d.ts +14 -2
- package/components/live/use-live-call.js +32 -1
- package/components/live/use-live-runner-controls.d.ts +3 -1
- package/components/live/use-live-runner-controls.js +3 -2
- package/components/live/use-live-session-client.js +18 -0
- package/live.d.ts +7 -3
- package/live.js +3 -1
- package/package.json +3 -3
- package/ui/ChatComposerBar.d.ts +6 -1
- package/ui/ChatComposerBar.js +19 -4
- package/ui/ConsoleFrame.d.ts +1 -1
- package/ui/LiveCallTile.d.ts +14 -0
- package/ui/LiveCallTile.js +17 -9
- package/ui/LiveCaptionsPanel.d.ts +4 -0
- package/ui/LiveCaptionsPanel.js +5 -3
- package/ui/LiveMicToggle.d.ts +6 -0
- package/ui/LiveMicToggle.js +10 -0
- package/ui/LiveRunner.d.ts +21 -0
- package/ui/LiveRunner.js +34 -22
- package/ui/LiveVideoPreview.d.ts +16 -6
- package/ui/LiveVideoPreview.js +35 -14
- package/ui/TheoremChat.d.ts +5 -1
- package/ui/TheoremChat.js +9 -8
- package/ui/arrive.d.ts +1 -1
- package/ui/labels.d.ts +4 -0
- package/ui/labels.js +4 -0
- package/ui/live-slots.d.ts +43 -0
- package/ui/live-slots.js +34 -0
package/README.md
CHANGED
|
@@ -148,7 +148,7 @@ The profile, the keys, and the system prompt stay on the server. The browser rec
|
|
|
148
148
|
| --- | --- |
|
|
149
149
|
| `@theoremjs/react` | Hooks, transports, and client logic |
|
|
150
150
|
| `@theoremjs/react/ui` | `TheoremChat`, `TheoremHost`, `TheoremDecision`, `TheoremEmbedding`, and their parts |
|
|
151
|
-
| `@theoremjs/react/live` | `useLiveCall`, `LiveRunner` and `
|
|
151
|
+
| `@theoremjs/react/live` | `useLiveCall`, `LiveRunner`, `LiveCallTile` and `LiveVideoPreview`, the voice and video call and its UI |
|
|
152
152
|
| `@theoremjs/react/server` | `@theoremjs/web/server`: the handlers and the stores they use |
|
|
153
153
|
| `@theoremjs/react/ui/theme` | `theoremTheme`, the base for your own Astryx theme |
|
|
154
154
|
| `@theoremjs/react/ui/icons` | The icon set of the theme |
|
|
@@ -178,6 +178,7 @@ To draw your own figures like the trace panel does, `@theoremjs/react/ui` also e
|
|
|
178
178
|
| `chatRef` | Sends a message, stops a reply, or focuses the composer from your code. See below. |
|
|
179
179
|
| `composer` | `false` leaves the composer out. The chat is the transcript alone, and your own control sends through `chatRef`. Default: `true`. |
|
|
180
180
|
| `composerLayout` | `'stacked'` or `'row'`. In `'row'`, the field, the mic and send share one line, and text that wraps moves the field onto its own line. Above them, a pill shows the reply in progress, with its stop button, and a pill shows each background call. While a reply runs or a step waits, Enter queues a draft and send opens the send menu. Default: `'stacked'`. |
|
|
181
|
+
| `composerEmptyAction` | Shows in place of the send button while the composer has nothing to send, for example a button that starts a call. It never replaces stop or the send menu. `TheoremChatComposer` and `ChatComposerBar` take it as `emptyAction`. Default: the send button. |
|
|
181
182
|
| `composerIcons` | The glyphs the `'row'` composer draws: `working`, before the working pill's text; `backgroundJob`, before each background call's name; `stop`, in the working pill's stop button. Each one you leave out keeps Theorem's. See [The row composer's look](#the-row-composers-look). |
|
|
182
183
|
| `media` | Which media from tools the chat shows. `'sent'` shows only what a tool sent to the person. `'all'` also shows what only the model read, for an evaluation view. Default: `'sent'`. See [Tool media](#tool-media). |
|
|
183
184
|
| `resolveMedia` | Turns a tool's reference into an address the page can load. See [Tool media](#tool-media). |
|
|
@@ -494,7 +495,9 @@ const call = useLiveCall({ iface, connection: () => ({ profile: 'support.voice'
|
|
|
494
495
|
<LiveRunner call={call} />
|
|
495
496
|
```
|
|
496
497
|
|
|
497
|
-
This code opens `wss://<your host>/api/live/relay?profile=<id>`. To send your own message to the relay, add `openMessage`. To use your own socket, add `createSocket`.
|
|
498
|
+
This code opens `wss://<your host>/api/live/relay?profile=<id>`. To send your own message to the relay, add `openMessage`. To use your own socket, add `createSocket`. The call asks `createSocket` for each open, the first and each reconnect, and waits when it returns a promise: see [Tune the call](https://github.com/masudl-hub/theoremai/blob/main/web/README.md#tune-the-call).
|
|
499
|
+
|
|
500
|
+
To get the messages your relay sends with `liveHostEnvelope`, give `useLiveCall` an `onHostMessage`. See [Send the page your own messages](https://github.com/masudl-hub/theoremai/blob/main/web/README.md#send-the-page-your-own-messages).
|
|
498
501
|
|
|
499
502
|
`LiveRunner` also accepts `theme`, `mode`, `labels`, `media`, `resolveMedia`, `mediaViewer`, and `trace`. Its captions show the media a tool returns as the chat does: see [Tool media](#tool-media). Tool gates in a call appear in a dialog over the call.
|
|
500
503
|
|
|
@@ -522,7 +525,7 @@ Three more values for `useLiveCall` come from the page. The profile declares eac
|
|
|
522
525
|
| --- | --- | --- |
|
|
523
526
|
| `options` | `inputs.options` | The value chosen for each option. It is read when the call starts. A value that changes during a call takes the call up again with it when the profile has resumption on; otherwise the next call has it. |
|
|
524
527
|
| `context` | `inputs.context` with `from: ['client']` | Any JSON the agent should know, such as the page the person is on. |
|
|
525
|
-
| `pageTools` | A function tool with `answeredBy: 'page'` | A function for each page tool, by name. It returns `{ output }
|
|
528
|
+
| `pageTools` | A function tool with `answeredBy: 'page'` | A function for each page tool, by name. It returns `{ output }`, or `{ failed: { code, message?, details? } }` when it cannot do the call. |
|
|
526
529
|
|
|
527
530
|
`stated` is a fourth value, for a page you trust as yourself. It says the `path` and the `options` from `identity.options` that choose the call's prompt lines, and the server reads it only with `pageStatesTurn` set. A change during a call takes the call up again, as an option does. `TheoremChat` takes the same prop, on each turn.
|
|
528
531
|
|
|
@@ -558,8 +561,9 @@ To make the agent speak first, set `live.greeting` on the profile. The page send
|
|
|
558
561
|
Use `live.sessionResumption` to reconnect after a dropped connection or a provider time limit.
|
|
559
562
|
The client stores the native checkpoint beside portable history. It sends both when it opens the next session.
|
|
560
563
|
|
|
561
|
-
The runner shows `reconnecting`.
|
|
564
|
+
The runner shows `reconnecting`. By default it tries five times, after 0.5, 1, 2, 4, and 8 seconds.
|
|
562
565
|
If all attempts fail, it reports a `network` error.
|
|
566
|
+
To change the waits, give `useLiveCall` a `reconnectDelaysMs`. To end the call at the provider's time limit, set `resumeOnEnded: false`. `useLiveCall` takes every option in [Tune the call](https://github.com/masudl-hub/theoremai/blob/main/web/README.md#tune-the-call).
|
|
563
567
|
The relay receives the absence duration. If the profile sets `live.resumed`, the agent announces its return after the configured `afterMs`.
|
|
564
568
|
|
|
565
569
|
The kernel validates native state before resumption. A protocol, provider, model, connection, key slot, or history mismatch rebuilds from portable history.
|
|
@@ -568,6 +572,82 @@ A rebuilt session with history does not repeat the initial greeting.
|
|
|
568
572
|
|
|
569
573
|
A failed call does not reconnect. Without `live.sessionResumption`, a provider-ended call is complete.
|
|
570
574
|
|
|
575
|
+
### The camera
|
|
576
|
+
|
|
577
|
+
Use the `video` option of `useLiveCall` when the model needs frames at another rate or size, or when your code needs each frame the model saw. Each field you leave out keeps Theorem's value.
|
|
578
|
+
|
|
579
|
+
| Field | What it sets | Default |
|
|
580
|
+
| --- | --- | --- |
|
|
581
|
+
| `frameIntervalMs` | How often a frame goes to the model, in milliseconds. A new value during a call takes effect at once. | `400` |
|
|
582
|
+
| `mimeType`, `quality` | The image type and the encoder quality (0 to 1). | `image/jpeg`, `0.62` |
|
|
583
|
+
| `camera` | The camera track constraints, except `facingMode`. | Ideal 640 by 480 |
|
|
584
|
+
| `initialFacingMode` | `'user'` or `'environment'`. | `'user'` |
|
|
585
|
+
| `onFrame` | Called with each frame after it was sent: `id`, `bytes`, `data`, `mimeType`, `width`, `height`, `capturedAt`, `facingMode`. A frame that could not be sent is not reported. | None |
|
|
586
|
+
|
|
587
|
+
A value that a timer or the encoder cannot use throws a `config` error.
|
|
588
|
+
|
|
589
|
+
#### Take the camera's picture
|
|
590
|
+
|
|
591
|
+
`call.grabFrame()` returns the camera's picture now, encoded as a sent frame is. It returns `null` while the camera is off or before its first picture. The frame is not sent. A page tool can call it, for example a tool that keeps the picture and answers with its id:
|
|
592
|
+
|
|
593
|
+
```tsx
|
|
594
|
+
const callRef = useRef<LiveCall | null>(null);
|
|
595
|
+
const call = useLiveCall({
|
|
596
|
+
iface,
|
|
597
|
+
connection,
|
|
598
|
+
pageTools: {
|
|
599
|
+
capture_frame: async () => {
|
|
600
|
+
const frame = callRef.current?.grabFrame() ?? null;
|
|
601
|
+
if (!frame) return { failed: { code: 'camera_off', message: 'The camera is off.' } };
|
|
602
|
+
return { output: { photoId: await savePhoto(frame.bytes, frame.mimeType) } };
|
|
603
|
+
},
|
|
604
|
+
},
|
|
605
|
+
});
|
|
606
|
+
callRef.current = call;
|
|
607
|
+
```
|
|
608
|
+
|
|
609
|
+
To have the person approve the tool before it runs, give the tool `permission: 'session_consent'` (ask once) or `'always_confirm'` (ask each time) where you register it. The call view shows the prompt before the page runs the tool.
|
|
610
|
+
|
|
611
|
+
To show a snapshot control in `LiveRunner`, give `useLiveCall` an `onSnapshot`. Without it, no snapshot control is shown. `LiveCallTile` never shows it. The control shows while the camera is on. When the person presses it, `onSnapshot` gets the camera's picture, or `null` before the first one. Theorem keeps nothing and sends nothing for it. Your function decides, for example `call.handleSendText('Keep this picture.')`. To hide the control, leave `onSnapshot` out, or drop the `'snapshot'` control in the `controls` slot. Your own call view reads `call.snapshotAvailable` (`true` when `onSnapshot` is set) and calls `call.handleSnapshot()` when the person presses its control.
|
|
612
|
+
|
|
613
|
+
### Change what the call view draws
|
|
614
|
+
|
|
615
|
+
Use `slots` when your call view needs other parts than Theorem's. Each slot is a `LiveSlot`:
|
|
616
|
+
|
|
617
|
+
- Leave a slot out to keep Theorem's part.
|
|
618
|
+
- Set it to `null` to draw nothing there.
|
|
619
|
+
- Set it to a function `(call, standard) => ReactNode`. It gets the call and Theorem's part, so it can keep it, wrap it, or replace it.
|
|
620
|
+
|
|
621
|
+
| Component | Slots |
|
|
622
|
+
| --- | --- |
|
|
623
|
+
| `LiveRunner` | `landing`, `header`, `notices`, `waveform`, `controls`, `captions`, `gate` |
|
|
624
|
+
| `LiveCallTile` | `media`, `time`, `controls`, `gate` |
|
|
625
|
+
|
|
626
|
+
`controls` is a `LiveControlsSlot`. Its function gets the call and Theorem's controls as `{ id, node }`, in order, so you can reorder, remove, or add one. `captions: null` also removes the captions panel and its toggle. `LiveRunner` also takes `captionsDefaultOpen`. Default: `true`.
|
|
627
|
+
|
|
628
|
+
```tsx
|
|
629
|
+
<LiveRunner
|
|
630
|
+
call={call}
|
|
631
|
+
slots={{
|
|
632
|
+
notices: null,
|
|
633
|
+
controls: (_call, controls) => controls.filter((c) => c.id !== 'video').map((c) => c.node),
|
|
634
|
+
}}
|
|
635
|
+
/>
|
|
636
|
+
```
|
|
637
|
+
|
|
638
|
+
`LiveRunner` and `LiveCallTile` take `video` for the camera preview:
|
|
639
|
+
|
|
640
|
+
- `aspectRatio`: the box's width over its height. Default: `4 / 3`.
|
|
641
|
+
- `fit`: `'cover'` or `'contain'`. Default: `'cover'`.
|
|
642
|
+
- `mirrorUserCamera`: `false` never mirrors the user-facing camera. Default: `true`.
|
|
643
|
+
- `overlay`: a function that draws over the picture, such as marks the model placed on a frame.
|
|
644
|
+
|
|
645
|
+
The overlay gets a `LiveVideoView`: the video element, the frame size (`frameWidth`, `frameHeight`), the facing mode, whether the preview is mirrored, the fit, and the aspect ratio. The overlay draws again when the frame size changes. Its box takes no clicks. Give a child `pointer-events: auto` to make it take clicks. To place a point of a sent frame, call `liveFramePointInPreview(point, view)` with the overlay's view. It takes the point as fractions of the frame (0 to 1) and returns fractions of the box. A point that `cover` crops is outside 0 to 1. Sent frames are never mirrored, so a mark made on a frame lands on the same spot in the mirrored preview.
|
|
646
|
+
|
|
647
|
+
To draw the camera preview in your own call view, give `LiveVideoPreview` the call's `videoPreview` element and `videoFacingMode`, with the same `aspectRatio`, `fit`, `mirrorUserCamera`, and `overlay`. Draw it only while `videoPreview` is not `null`.
|
|
648
|
+
|
|
649
|
+
`LiveCaptionsPanel` takes `composer` and `empty`. Each one replaces the text composer or the empty state. `null` draws nothing.
|
|
650
|
+
|
|
571
651
|
### Your relay
|
|
572
652
|
|
|
573
653
|
The relay is server code. To authenticate the conversation and resume a call in your relay, see [Your relay](https://github.com/masudl-hub/theoremai/blob/main/web/README.md#your-relay).
|
|
@@ -19,7 +19,7 @@ export declare function imageSrc(image: DecisionAsset): string;
|
|
|
19
19
|
export declare function namedImages(images: DecisionImages, state: DecisionJson): DecisionImages;
|
|
20
20
|
/**
|
|
21
21
|
* The field a dropped file becomes: its reference, unused by any image or field, and the field
|
|
22
|
-
* named after it, such as `
|
|
22
|
+
* named after it, such as `photo` holding `<photo>`.
|
|
23
23
|
*/
|
|
24
24
|
export declare function imageField(file: string, images: DecisionImages, fields: readonly string[]): {
|
|
25
25
|
key: string;
|
|
@@ -45,7 +45,7 @@ export function namedImages(images, state) {
|
|
|
45
45
|
}
|
|
46
46
|
/**
|
|
47
47
|
* The field a dropped file becomes: its reference, unused by any image or field, and the field
|
|
48
|
-
* named after it, such as `
|
|
48
|
+
* named after it, such as `photo` holding `<photo>`.
|
|
49
49
|
*/
|
|
50
50
|
export function imageField(file, images, fields) {
|
|
51
51
|
const reference = imageName(file, [...Object.keys(images), ...fields.map((key) => `<${key}>`)]);
|
package/client/ink-waveform.d.ts
CHANGED
|
@@ -13,5 +13,5 @@ export declare function computeInkBarTargets(args: {
|
|
|
13
13
|
outputLevel: number;
|
|
14
14
|
frozen?: boolean;
|
|
15
15
|
}): number[];
|
|
16
|
-
/** Smooth toward targets each animation frame
|
|
16
|
+
/** Smooth toward targets each animation frame. */
|
|
17
17
|
export declare function stepInkBarHeights(current: number[], targets: number[], alpha?: number): number[];
|
package/client/ink-waveform.js
CHANGED
|
@@ -62,7 +62,7 @@ export function computeInkBarTargets(args) {
|
|
|
62
62
|
return Math.min(1, Math.max(0.06, height));
|
|
63
63
|
});
|
|
64
64
|
}
|
|
65
|
-
/** Smooth toward targets each animation frame
|
|
65
|
+
/** Smooth toward targets each animation frame. */
|
|
66
66
|
export function stepInkBarHeights(current, targets, alpha = 0.14) {
|
|
67
67
|
return current.map((value, index) => value + (targets[index] - value) * alpha);
|
|
68
68
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import type { LiveFacingMode } from './live-video.js';
|
|
3
|
+
/** How the camera preview fills its box: `cover` crops the picture, `contain` shows all of it. */
|
|
4
|
+
export type LiveVideoFit = 'cover' | 'contain';
|
|
5
|
+
/** What a camera overlay is drawn over: the live picture, and how the preview shows it. */
|
|
6
|
+
export type LiveVideoView = {
|
|
7
|
+
/** The capture element. */
|
|
8
|
+
video: HTMLVideoElement;
|
|
9
|
+
/** The size of each sent frame, in pixels; `0` until the camera's first picture. */
|
|
10
|
+
frameWidth: number;
|
|
11
|
+
frameHeight: number;
|
|
12
|
+
facingMode: LiveFacingMode;
|
|
13
|
+
/** `true` when the preview is drawn mirrored (the user-facing camera); sent frames never are. */
|
|
14
|
+
mirrored: boolean;
|
|
15
|
+
fit: LiveVideoFit;
|
|
16
|
+
/** The preview box's width over its height. */
|
|
17
|
+
aspectRatio: number;
|
|
18
|
+
};
|
|
19
|
+
/** A camera overlay: drawn over the preview, in a box that takes no clicks; give a child `pointer-events: auto` to make it take them. */
|
|
20
|
+
export type LiveVideoOverlay = (view: LiveVideoView) => ReactNode;
|
|
21
|
+
/**
|
|
22
|
+
* Where a point of a sent frame shows in the preview box. Pass the overlay's view as `view`. `x` and `y` are fractions of the frame
|
|
23
|
+
* (0 to 1, from its top left); the answer is fractions of the box, which fall outside 0 to 1 for
|
|
24
|
+
* a point that `cover` crops away. A frame with no size yet maps as the box itself.
|
|
25
|
+
*/
|
|
26
|
+
export declare function liveFramePointInPreview(point: {
|
|
27
|
+
x: number;
|
|
28
|
+
y: number;
|
|
29
|
+
}, view: {
|
|
30
|
+
frameWidth: number;
|
|
31
|
+
frameHeight: number;
|
|
32
|
+
aspectRatio: number;
|
|
33
|
+
fit: LiveVideoFit;
|
|
34
|
+
mirrored: boolean;
|
|
35
|
+
}): {
|
|
36
|
+
x: number;
|
|
37
|
+
y: number;
|
|
38
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where a point of a sent frame shows in the preview box. Pass the overlay's view as `view`. `x` and `y` are fractions of the frame
|
|
3
|
+
* (0 to 1, from its top left); the answer is fractions of the box, which fall outside 0 to 1 for
|
|
4
|
+
* a point that `cover` crops away. A frame with no size yet maps as the box itself.
|
|
5
|
+
*/
|
|
6
|
+
export function liveFramePointInPreview(point, view) {
|
|
7
|
+
const x = view.mirrored ? 1 - point.x : point.x;
|
|
8
|
+
if (view.frameWidth <= 0 || view.frameHeight <= 0)
|
|
9
|
+
return { x, y: point.y };
|
|
10
|
+
const frameRatio = view.frameWidth / view.frameHeight;
|
|
11
|
+
const wider = frameRatio > view.aspectRatio;
|
|
12
|
+
const scaleByHeight = view.fit === 'cover' ? wider : !wider;
|
|
13
|
+
if (scaleByHeight) {
|
|
14
|
+
const shown = frameRatio / view.aspectRatio;
|
|
15
|
+
return { x: (x - 0.5) * shown + 0.5, y: point.y };
|
|
16
|
+
}
|
|
17
|
+
const shown = view.aspectRatio / frameRatio;
|
|
18
|
+
return { x, y: (point.y - 0.5) * shown + 0.5 };
|
|
19
|
+
}
|
|
@@ -1,10 +1,70 @@
|
|
|
1
1
|
export type LiveFacingMode = 'user' | 'environment';
|
|
2
|
+
/** One camera frame the call sent to the model, for a host that pins marks to the frame the model saw. */
|
|
3
|
+
export type LiveVideoFrame = {
|
|
4
|
+
/** Unique to this frame. */
|
|
5
|
+
id: string;
|
|
6
|
+
/** The encoded image, as sent. */
|
|
7
|
+
bytes: Uint8Array;
|
|
8
|
+
/** The same image, base64, as it went on the wire. */
|
|
9
|
+
data: string;
|
|
10
|
+
mimeType: string;
|
|
11
|
+
/** The frame's size in pixels: the camera's whole picture, not the cropped preview. */
|
|
12
|
+
width: number;
|
|
13
|
+
height: number;
|
|
14
|
+
/** When it was captured, in epoch milliseconds. */
|
|
15
|
+
capturedAt: number;
|
|
16
|
+
facingMode: LiveFacingMode;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* How a live call captures the camera. Each field left out keeps Theorem's value. A change to
|
|
20
|
+
* `frameIntervalMs` during a call takes effect at once; the rest are read when the camera starts.
|
|
21
|
+
*/
|
|
22
|
+
export type LiveVideoOptions = {
|
|
23
|
+
/** How often a frame is sent, in milliseconds. Default `400`. */
|
|
24
|
+
frameIntervalMs?: number;
|
|
25
|
+
/** The image type frames are encoded as, for `canvas.toDataURL`. Default `image/jpeg`. */
|
|
26
|
+
mimeType?: string;
|
|
27
|
+
/** The encoder quality, 0 to 1, for a lossy `mimeType`. Default `0.62`. */
|
|
28
|
+
quality?: number;
|
|
29
|
+
/**
|
|
30
|
+
* The camera track the call asks the browser for. `facingMode` is the call's own (see
|
|
31
|
+
* `initialFacingMode`). Default: ideal `640` by `480`.
|
|
32
|
+
*/
|
|
33
|
+
camera?: Omit<MediaTrackConstraints, 'facingMode'>;
|
|
34
|
+
/** The camera the call starts on. Default `user`. */
|
|
35
|
+
initialFacingMode?: LiveFacingMode;
|
|
36
|
+
/** Called with each frame after it was sent; a frame the call could not send is not reported. */
|
|
37
|
+
onFrame?: (frame: LiveVideoFrame) => void;
|
|
38
|
+
};
|
|
2
39
|
export type LiveVideoCapture = {
|
|
3
40
|
stop: () => void;
|
|
4
41
|
readonly video: HTMLVideoElement;
|
|
5
42
|
facingMode: () => LiveFacingMode;
|
|
6
43
|
flip: () => Promise<LiveFacingMode>;
|
|
44
|
+
/** Sends frames this often from now on; `undefined` goes back to Theorem's interval. */
|
|
45
|
+
setFrameIntervalMs: (ms: number | undefined) => void;
|
|
46
|
+
/** The camera's picture now, encoded as sent frames are, but not sent; `null` before the first picture. */
|
|
47
|
+
grab: () => LiveVideoFrame | null;
|
|
48
|
+
};
|
|
49
|
+
/** `options` with Theorem's value for each field left out; a value that cannot work is a `config` error. */
|
|
50
|
+
export declare function resolveVideoOptions(options?: LiveVideoOptions): {
|
|
51
|
+
frameIntervalMs: number;
|
|
52
|
+
mimeType: string;
|
|
53
|
+
quality: number;
|
|
54
|
+
camera: Omit<MediaTrackConstraints, "facingMode">;
|
|
55
|
+
initialFacingMode: LiveFacingMode;
|
|
7
56
|
};
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
57
|
+
/** The frame a data URL holds, or null when it has no image (a canvas with no size). */
|
|
58
|
+
export declare function liveVideoFrame(args: {
|
|
59
|
+
dataUrl: string;
|
|
60
|
+
width: number;
|
|
61
|
+
height: number;
|
|
62
|
+
facingMode: LiveFacingMode;
|
|
63
|
+
capturedAt: number;
|
|
64
|
+
id: string;
|
|
65
|
+
}): LiveVideoFrame | null;
|
|
66
|
+
/**
|
|
67
|
+
* Starts the camera, and calls `send` with each frame. `send` says whether the frame went;
|
|
68
|
+
* `options.onFrame` hears each one that did.
|
|
69
|
+
*/
|
|
70
|
+
export declare function startLiveVideoCapture(send: (data: string, mimeType: string) => boolean, options?: LiveVideoOptions): Promise<LiveVideoCapture>;
|
|
@@ -1,15 +1,67 @@
|
|
|
1
|
-
import { TheoremError } from '@theoremjs/agents';
|
|
2
|
-
|
|
3
|
-
const
|
|
4
|
-
|
|
1
|
+
import { TheoremError, TIMER_MAX_MS } from '@theoremjs/agents';
|
|
2
|
+
import { base64ToBytes } from '@theoremjs/agents/kernel';
|
|
3
|
+
const DEFAULT_FRAME_INTERVAL_MS = 400;
|
|
4
|
+
const DEFAULT_QUALITY = 0.62;
|
|
5
|
+
const DEFAULT_MIME_TYPE = 'image/jpeg';
|
|
6
|
+
const DEFAULT_CAMERA = {
|
|
7
|
+
width: { ideal: 640 },
|
|
8
|
+
height: { ideal: 480 },
|
|
9
|
+
};
|
|
10
|
+
/** A frame interval a timer can hold, else a `config` error. */
|
|
11
|
+
function checkFrameIntervalMs(ms) {
|
|
12
|
+
if (!Number.isSafeInteger(ms) || ms < 1 || ms > TIMER_MAX_MS) {
|
|
13
|
+
// labels-exempt: builder config error at setup; no user sees it
|
|
14
|
+
throw new TheoremError('config', `live video frameIntervalMs is not valid: ${ms}`);
|
|
15
|
+
}
|
|
16
|
+
return ms;
|
|
17
|
+
}
|
|
18
|
+
/** `options` with Theorem's value for each field left out; a value that cannot work is a `config` error. */
|
|
19
|
+
export function resolveVideoOptions(options = {}) {
|
|
20
|
+
const quality = options.quality ?? DEFAULT_QUALITY;
|
|
21
|
+
if (!Number.isFinite(quality) || quality < 0 || quality > 1) {
|
|
22
|
+
// labels-exempt: builder config error at setup; no user sees it
|
|
23
|
+
throw new TheoremError('config', `live video quality is not valid: ${quality}`);
|
|
24
|
+
}
|
|
25
|
+
return {
|
|
26
|
+
frameIntervalMs: checkFrameIntervalMs(options.frameIntervalMs ?? DEFAULT_FRAME_INTERVAL_MS),
|
|
27
|
+
mimeType: options.mimeType ?? DEFAULT_MIME_TYPE,
|
|
28
|
+
quality,
|
|
29
|
+
camera: options.camera ?? DEFAULT_CAMERA,
|
|
30
|
+
initialFacingMode: options.initialFacingMode ?? 'user',
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function openCamera(facing, camera) {
|
|
5
34
|
return navigator.mediaDevices.getUserMedia({
|
|
6
|
-
video: { facingMode: { ideal: facing }
|
|
35
|
+
video: { ...camera, facingMode: { ideal: facing } },
|
|
7
36
|
audio: false,
|
|
8
37
|
});
|
|
9
38
|
}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
39
|
+
/** The frame a data URL holds, or null when it has no image (a canvas with no size). */
|
|
40
|
+
export function liveVideoFrame(args) {
|
|
41
|
+
const comma = args.dataUrl.indexOf(',');
|
|
42
|
+
const data = comma === -1 ? '' : args.dataUrl.slice(comma + 1);
|
|
43
|
+
if (!data)
|
|
44
|
+
return null;
|
|
45
|
+
const mimeType = args.dataUrl.slice('data:'.length, args.dataUrl.indexOf(';'));
|
|
46
|
+
return {
|
|
47
|
+
id: args.id,
|
|
48
|
+
bytes: base64ToBytes(data),
|
|
49
|
+
data,
|
|
50
|
+
mimeType,
|
|
51
|
+
width: args.width,
|
|
52
|
+
height: args.height,
|
|
53
|
+
capturedAt: args.capturedAt,
|
|
54
|
+
facingMode: args.facingMode,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Starts the camera, and calls `send` with each frame. `send` says whether the frame went;
|
|
59
|
+
* `options.onFrame` hears each one that did.
|
|
60
|
+
*/
|
|
61
|
+
export function startLiveVideoCapture(send, options) {
|
|
62
|
+
const resolved = resolveVideoOptions(options);
|
|
63
|
+
let frameIntervalMs = resolved.frameIntervalMs;
|
|
64
|
+
return openCamera(resolved.initialFacingMode, resolved.camera).then((stream) => {
|
|
13
65
|
const video = document.createElement('video');
|
|
14
66
|
video.srcObject = stream;
|
|
15
67
|
video.muted = true;
|
|
@@ -23,33 +75,47 @@ export function startLiveVideoCapture(onFrame, options) {
|
|
|
23
75
|
throw new TheoremError('unsupported', 'no 2d canvas for live video'); // labels-exempt: internal diagnostic
|
|
24
76
|
}
|
|
25
77
|
let timer = null;
|
|
78
|
+
let playing = false;
|
|
26
79
|
let stopped = false;
|
|
27
|
-
let state = { stream, facing:
|
|
28
|
-
const
|
|
80
|
+
let state = { stream, facing: resolved.initialFacingMode };
|
|
81
|
+
const grab = () => {
|
|
29
82
|
if (stopped || video.videoWidth === 0)
|
|
30
|
-
return;
|
|
83
|
+
return null;
|
|
31
84
|
canvas.width = video.videoWidth;
|
|
32
85
|
canvas.height = video.videoHeight;
|
|
33
86
|
context.drawImage(video, 0, 0);
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
87
|
+
return liveVideoFrame({
|
|
88
|
+
dataUrl: canvas.toDataURL(resolved.mimeType, resolved.quality),
|
|
89
|
+
width: canvas.width,
|
|
90
|
+
height: canvas.height,
|
|
91
|
+
facingMode: state.facing,
|
|
92
|
+
capturedAt: Date.now(),
|
|
93
|
+
id: crypto.randomUUID(),
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
const capture = () => {
|
|
97
|
+
const frame = grab();
|
|
98
|
+
if (frame && send(frame.data, frame.mimeType))
|
|
99
|
+
options?.onFrame?.(frame);
|
|
38
100
|
};
|
|
39
101
|
const startTimer = () => {
|
|
40
102
|
if (timer || stopped)
|
|
41
103
|
return;
|
|
42
|
-
timer = setInterval(capture,
|
|
104
|
+
timer = setInterval(capture, frameIntervalMs);
|
|
43
105
|
};
|
|
44
|
-
void video.play().then(
|
|
106
|
+
void video.play().then(() => {
|
|
107
|
+
playing = true;
|
|
108
|
+
startTimer();
|
|
109
|
+
});
|
|
45
110
|
return {
|
|
46
111
|
video,
|
|
112
|
+
grab,
|
|
47
113
|
facingMode: () => state.facing,
|
|
48
114
|
flip: async () => {
|
|
49
115
|
if (stopped)
|
|
50
116
|
return state.facing;
|
|
51
117
|
const nextFacing = state.facing === 'user' ? 'environment' : 'user';
|
|
52
|
-
const nextStream = await openCamera(nextFacing);
|
|
118
|
+
const nextStream = await openCamera(nextFacing, resolved.camera);
|
|
53
119
|
for (const track of state.stream.getTracks())
|
|
54
120
|
track.stop();
|
|
55
121
|
state = { stream: nextStream, facing: nextFacing };
|
|
@@ -57,6 +123,17 @@ export function startLiveVideoCapture(onFrame, options) {
|
|
|
57
123
|
await video.play();
|
|
58
124
|
return nextFacing;
|
|
59
125
|
},
|
|
126
|
+
setFrameIntervalMs: (ms) => {
|
|
127
|
+
const next = checkFrameIntervalMs(ms ?? DEFAULT_FRAME_INTERVAL_MS);
|
|
128
|
+
if (next === frameIntervalMs)
|
|
129
|
+
return;
|
|
130
|
+
frameIntervalMs = next;
|
|
131
|
+
if (timer)
|
|
132
|
+
clearInterval(timer);
|
|
133
|
+
timer = null;
|
|
134
|
+
if (playing)
|
|
135
|
+
startTimer();
|
|
136
|
+
},
|
|
60
137
|
stop: () => {
|
|
61
138
|
stopped = true;
|
|
62
139
|
if (timer)
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { LiveProfileInterface } from '@theoremjs/agents/interface';
|
|
2
2
|
import type { LiveCallOptions, LiveConnection } from '@theoremjs/web/client';
|
|
3
3
|
import { type LiveCaptionState, type LiveCaptionTurn } from '../../client/live/live-captions.js';
|
|
4
|
+
import { type LiveVideoFrame, type LiveVideoOptions } from '../../client/live/live-video.js';
|
|
4
5
|
/** What `useLiveCall` takes: the profile, what the call opens, and the host's part in the call. */
|
|
5
6
|
export type LiveCallInput = {
|
|
6
7
|
iface: LiveProfileInterface;
|
|
@@ -9,6 +10,14 @@ export type LiveCallInput = {
|
|
|
9
10
|
* returns its draft as the relay's open message.
|
|
10
11
|
*/
|
|
11
12
|
connection: () => LiveConnection | Promise<LiveConnection>;
|
|
13
|
+
/** How the call captures the camera; see {@link LiveVideoOptions}. */
|
|
14
|
+
video?: LiveVideoOptions;
|
|
15
|
+
/**
|
|
16
|
+
* What the snapshot control does. Left out, the call shows no snapshot control. Pressed while
|
|
17
|
+
* the camera is on, it gets the camera's picture, or `null` before the first one. Theorem keeps
|
|
18
|
+
* and sends nothing for it: the host sends the session what it chooses.
|
|
19
|
+
*/
|
|
20
|
+
onSnapshot?: (frame: LiveVideoFrame | null) => void;
|
|
12
21
|
} & LiveCallOptions;
|
|
13
22
|
/** One live call: its state, captions, and controls. `LiveRunner` draws it. */
|
|
14
23
|
export type LiveCall = ReturnType<typeof useLiveCall>;
|
|
@@ -17,7 +26,7 @@ export type LiveCall = ReturnType<typeof useLiveCall>;
|
|
|
17
26
|
* long as the component that calls this hook, so a host that calls it above its
|
|
18
27
|
* routes keeps the call while the person moves between pages.
|
|
19
28
|
*/
|
|
20
|
-
export declare function useLiveCall({ iface, connection, ...options }: LiveCallInput): {
|
|
29
|
+
export declare function useLiveCall({ iface, connection, video, ...options }: LiveCallInput): {
|
|
21
30
|
iface: LiveProfileInterface;
|
|
22
31
|
handle: string;
|
|
23
32
|
traces: import("@theoremjs/web/client").TraceFeed;
|
|
@@ -41,9 +50,12 @@ export declare function useLiveCall({ iface, connection, ...options }: LiveCallI
|
|
|
41
50
|
textDraft: string;
|
|
42
51
|
toolActive: boolean;
|
|
43
52
|
videoAvailable: boolean;
|
|
44
|
-
videoFacingMode: import("../../
|
|
53
|
+
videoFacingMode: import("../../live.js").LiveFacingMode;
|
|
45
54
|
videoPreview: HTMLVideoElement | null;
|
|
46
55
|
voiceAvailable: boolean;
|
|
56
|
+
snapshotAvailable: boolean;
|
|
57
|
+
grabFrame: () => LiveVideoFrame | null;
|
|
58
|
+
handleSnapshot: () => void;
|
|
47
59
|
canRestart: boolean;
|
|
48
60
|
gatePrompt: import("@theoremjs/web/client").LiveToolGatePrompt | null;
|
|
49
61
|
setTextDraft: import("react").Dispatch<import("react").SetStateAction<string>>;
|
|
@@ -2,6 +2,7 @@ import { liveIngressEnabledFromSpec } from '@theoremjs/agents';
|
|
|
2
2
|
import { createTraceFeed, liveState } from '@theoremjs/web/client';
|
|
3
3
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
4
4
|
import { stashLiveCaptionCall, } from "../../client/live/live-captions.js";
|
|
5
|
+
import { resolveVideoOptions, } from "../../client/live/live-video.js";
|
|
5
6
|
import { usePageToolWarnings } from "../../hooks/use-page-tool-warnings.js";
|
|
6
7
|
import { useLiveRunnerControls } from "./use-live-runner-controls.js";
|
|
7
8
|
import { useLiveRunnerGate, useLiveRunnerUiState } from "./use-live-runner-ui.js";
|
|
@@ -62,7 +63,7 @@ function useLiveCallLifecycle(controls, captionsRef, sessionActive, videoAvailab
|
|
|
62
63
|
* long as the component that calls this hook, so a host that calls it above its
|
|
63
64
|
* routes keeps the call while the person moves between pages.
|
|
64
65
|
*/
|
|
65
|
-
export function useLiveCall({ iface, connection, ...options }) {
|
|
66
|
+
export function useLiveCall({ iface, connection, video, ...options }) {
|
|
66
67
|
const ui = useLiveRunnerUiState(iface.labels);
|
|
67
68
|
const gate = useLiveRunnerGate({
|
|
68
69
|
setCaptions: ui.setCaptions,
|
|
@@ -71,6 +72,8 @@ export function useLiveCall({ iface, connection, ...options }) {
|
|
|
71
72
|
});
|
|
72
73
|
const connectionRef = useRef(connection);
|
|
73
74
|
connectionRef.current = connection;
|
|
75
|
+
const videoOptionsRef = useRef(video);
|
|
76
|
+
videoOptionsRef.current = video;
|
|
74
77
|
const voiceAvailable = liveIngressEnabledFromSpec(iface.live.ingress, 'audio');
|
|
75
78
|
const videoAvailable = liveIngressEnabledFromSpec(iface.live.ingress, 'video');
|
|
76
79
|
const textAvailable = liveIngressEnabledFromSpec(iface.live.ingress, 'text');
|
|
@@ -90,6 +93,14 @@ export function useLiveCall({ iface, connection, ...options }) {
|
|
|
90
93
|
effort: options.effort,
|
|
91
94
|
context: options.context,
|
|
92
95
|
pageTools: options.pageTools,
|
|
96
|
+
reconnectDelaysMs: options.reconnectDelaysMs,
|
|
97
|
+
connectTimeoutMs: options.connectTimeoutMs,
|
|
98
|
+
resumeOnEnded: options.resumeOnEnded,
|
|
99
|
+
audio: options.audio,
|
|
100
|
+
onTurnEvent: options.onTurnEvent,
|
|
101
|
+
onSessionClosing: options.onSessionClosing,
|
|
102
|
+
onSessionReady: options.onSessionReady,
|
|
103
|
+
onHostMessage: options.onHostMessage,
|
|
93
104
|
voiceAvailable,
|
|
94
105
|
traces,
|
|
95
106
|
handleLiveTurnEvent: gate.handleLiveTurnEvent,
|
|
@@ -117,6 +128,7 @@ export function useLiveCall({ iface, connection, ...options }) {
|
|
|
117
128
|
clientRef,
|
|
118
129
|
videoCaptureRef: ui.videoCaptureRef,
|
|
119
130
|
connectionRef,
|
|
131
|
+
videoOptionsRef,
|
|
120
132
|
statusRef: ui.statusRef,
|
|
121
133
|
isMutedRef: ui.isMutedRef,
|
|
122
134
|
sessionPermissionsRef: ui.sessionPermissionsRef,
|
|
@@ -162,7 +174,23 @@ export function useLiveCall({ iface, connection, ...options }) {
|
|
|
162
174
|
useEffect(() => {
|
|
163
175
|
clientRef.current?.setStated(statedJson === undefined ? undefined : JSON.parse(statedJson));
|
|
164
176
|
}, [clientRef, statedJson]);
|
|
177
|
+
// why: A video option that cannot work throws here, at setup, not later as a camera failure.
|
|
178
|
+
if (video)
|
|
179
|
+
resolveVideoOptions(video);
|
|
180
|
+
// why: A new rate reaches the running camera at once, as the host's own tool may set it mid-call.
|
|
181
|
+
const frameIntervalMs = video?.frameIntervalMs;
|
|
182
|
+
useEffect(() => {
|
|
183
|
+
if (ui.isVideoOn)
|
|
184
|
+
ui.videoCaptureRef.current?.setFrameIntervalMs(frameIntervalMs);
|
|
185
|
+
}, [frameIntervalMs, ui.isVideoOn, ui.videoCaptureRef]);
|
|
165
186
|
usePageToolWarnings(iface.tools.page, options.pageTools);
|
|
187
|
+
const videoCaptureRef = ui.videoCaptureRef;
|
|
188
|
+
const grabFrame = useCallback(() => videoCaptureRef.current?.grab() ?? null, [videoCaptureRef]);
|
|
189
|
+
const onSnapshotRef = useRef(options.onSnapshot);
|
|
190
|
+
onSnapshotRef.current = options.onSnapshot;
|
|
191
|
+
const handleSnapshot = useCallback(() => {
|
|
192
|
+
onSnapshotRef.current?.(grabFrame());
|
|
193
|
+
}, [grabFrame]);
|
|
166
194
|
return {
|
|
167
195
|
iface,
|
|
168
196
|
handle: iface.identity.handle,
|
|
@@ -187,6 +215,9 @@ export function useLiveCall({ iface, connection, ...options }) {
|
|
|
187
215
|
videoFacingMode: ui.videoFacingMode,
|
|
188
216
|
videoPreview: ui.videoPreview,
|
|
189
217
|
voiceAvailable,
|
|
218
|
+
snapshotAvailable: options.onSnapshot !== undefined,
|
|
219
|
+
grabFrame,
|
|
220
|
+
handleSnapshot,
|
|
190
221
|
// why: Also after ending (or failing) before the first connect, so the call can't get stuck.
|
|
191
222
|
canRestart: !ui.sessionActive &&
|
|
192
223
|
ui.status !== 'connecting' &&
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import type { LiveConnection, LiveConnectPhase, LiveSessionClient, LiveSessionStatus } from '@theoremjs/web/client';
|
|
2
2
|
import { type Dispatch, type MutableRefObject, type SetStateAction } from 'react';
|
|
3
3
|
import { type LiveCaptionState } from '../../client/live/live-captions.js';
|
|
4
|
-
import { type LiveFacingMode, type LiveVideoCapture } from '../../client/live/live-video.js';
|
|
4
|
+
import { type LiveFacingMode, type LiveVideoCapture, type LiveVideoOptions } from '../../client/live/live-video.js';
|
|
5
5
|
/** Media + session lifecycle handlers for LiveRunner. */
|
|
6
6
|
export declare function useLiveRunnerControls(args: {
|
|
7
7
|
clientRef: MutableRefObject<LiveSessionClient | null>;
|
|
8
8
|
videoCaptureRef: MutableRefObject<LiveVideoCapture | null>;
|
|
9
9
|
connectionRef: MutableRefObject<() => LiveConnection | Promise<LiveConnection>>;
|
|
10
|
+
/** The host's camera options, read when the camera starts; `onFrame` is read at each frame. */
|
|
11
|
+
videoOptionsRef: MutableRefObject<LiveVideoOptions | undefined>;
|
|
10
12
|
statusRef: MutableRefObject<LiveSessionStatus>;
|
|
11
13
|
isMutedRef: MutableRefObject<boolean>;
|
|
12
14
|
sessionPermissionsRef: MutableRefObject<string[]>;
|
|
@@ -47,8 +47,9 @@ export function useLiveRunnerControls(args) {
|
|
|
47
47
|
return;
|
|
48
48
|
}
|
|
49
49
|
try {
|
|
50
|
-
const capture = await startLiveVideoCapture((
|
|
51
|
-
args.
|
|
50
|
+
const capture = await startLiveVideoCapture((data, mimeType) => args.clientRef.current?.sendVideo(data, mimeType) ?? false, {
|
|
51
|
+
...args.videoOptionsRef.current,
|
|
52
|
+
onFrame: (frame) => args.videoOptionsRef.current?.onFrame?.(frame),
|
|
52
53
|
});
|
|
53
54
|
args.videoCaptureRef.current = capture;
|
|
54
55
|
args.setVideoPreview(capture.video);
|
|
@@ -57,7 +57,24 @@ export function useLiveSessionClient(bindings) {
|
|
|
57
57
|
model: b.model,
|
|
58
58
|
effort: b.effort,
|
|
59
59
|
context: b.context,
|
|
60
|
+
reconnectDelaysMs: b.reconnectDelaysMs,
|
|
61
|
+
connectTimeoutMs: b.connectTimeoutMs,
|
|
62
|
+
resumeOnEnded: b.resumeOnEnded,
|
|
63
|
+
audio: b.audio,
|
|
60
64
|
voiceIngress: b.voiceAvailable,
|
|
65
|
+
onSessionClosing: (timeLeftMs) => {
|
|
66
|
+
bindingsRef.current.onSessionClosing?.(timeLeftMs);
|
|
67
|
+
},
|
|
68
|
+
onSessionReady: (info) => {
|
|
69
|
+
bindingsRef.current.onSessionReady?.(info);
|
|
70
|
+
},
|
|
71
|
+
...(b.onHostMessage
|
|
72
|
+
? {
|
|
73
|
+
onHostMessage: (message) => {
|
|
74
|
+
bindingsRef.current.onHostMessage?.(message);
|
|
75
|
+
},
|
|
76
|
+
}
|
|
77
|
+
: {}),
|
|
61
78
|
onConnectPhase: (phase) => {
|
|
62
79
|
b.setConnectPhase(phase);
|
|
63
80
|
},
|
|
@@ -68,6 +85,7 @@ export function useLiveSessionClient(bindings) {
|
|
|
68
85
|
onLiveTranscript(text, isUser, meta, bindingsRef.current);
|
|
69
86
|
},
|
|
70
87
|
onTurnEvent: (event) => {
|
|
88
|
+
bindingsRef.current.onTurnEvent?.(event);
|
|
71
89
|
// why: An `unsupported` event is the host's to read; Theorem's UI shows nothing for it.
|
|
72
90
|
if (event.type === 'unsupported')
|
|
73
91
|
return;
|