Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadStreamHaptics.ts

80 lines2.9 KB

1// @effect-diagnostics globalDate:off - The tracker runs in an atom subscription, outside an Effect runtime.
2import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entities";
3import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
4import type { ScopedThreadRef } from "@t3tools/contracts";
5import { Atom } from "effect/reactivity";
6import * as Haptics from "expo-haptics";
7​
8import { environmentThreadDetails } from "../../state/threads";
9​
10export interface StreamingMessageMark {
11 readonly id: string;
12 readonly textLength: number;
14​
15const STREAM_HAPTIC_THROTTLE_MS = 320;
16​
17function latestStreamingAssistantMessage(
18 thread: EnvironmentThread | null,
19): StreamingMessageMark | null {
20 const messages = thread?.projection.messages ?? [];
21 for (let index = messages.length - 1; index >= 0; index -= 1) {
22 const message = messages[index];
23 if (message?.role === "assistant" && message.streaming) {
24 return { id: message.id, textLength: message.text.length };
25 }
26 }
27 return null;
29​
30/**
31 * A new stream always ticks; growth of the same stream ticks at most once per
32 * throttle window, so a fast stream reads as texture rather than a buzz.
33 */
34export function shouldTickStreamHaptic(input: {
35 readonly previous: StreamingMessageMark | null;
36 readonly latest: StreamingMessageMark | null;
37 readonly lastTickAt: number;
38 readonly now: number;
39}): boolean {
40 const { previous, latest } = input;
41 if (latest === null) return false;
42 if (previous?.id !== latest.id) return true;
43 if (latest.textLength <= previous.textLength) return false;
44 return input.now - input.lastTickAt >= STREAM_HAPTIC_THROTTLE_MS;
46​
47const streamHapticsFamily = Atom.family((key: string) => {
48 const ref = parseThreadKey(key);
49 return Atom.make((get) => {
50 // The first snapshot only seeds the mark: opening a thread mid-stream is silent.
51 let seeded = false;
52 let previous: StreamingMessageMark | null = null;
53 let lastTickAt = 0;
54 // `subscribe`, not `get`: a rebuild per streaming tick would reset the mark.
55 get.subscribe(
56 environmentThreadDetails.threadAtom(ref),
57 (thread) => {
58 const latest = latestStreamingAssistantMessage(thread);
59 const now = Date.now();
60 const tick = seeded && shouldTickStreamHaptic({ previous, latest, lastTickAt, now });
61 seeded = true;
62 previous = latest;
63 if (!tick) return;
64 lastTickAt = now;
65 void Haptics.selectionAsync();
66 },
67 { immediate: true },
68 );
69 }).pipe(Atom.withLabel(`thread-stream-haptics:${key}`));
70});
71​
72// A thread without server detail (a draft) has no reply to stream.
73const noStreamHaptics = Atom.make<void>(undefined).pipe(
74 Atom.withLabel("thread-stream-haptics:none"),
75);
76​
77/** Mount while the thread is on screen to tick haptics as its reply streams. */
78export function threadStreamHaptics(ref: ScopedThreadRef | null): Atom.Atom<void> {
79 return ref === null ? noStreamHaptics : streamHapticsFamily(threadKey(ref));