Open History to see the last commit
1import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
3import { useState } from "react";
4
5function toThreadRef(
6 environmentId: EnvironmentId | null,
7 threadId: ThreadId | null,
8): ScopedThreadRef | null {
9 return environmentId !== null && threadId !== null
10 ? scopeThreadRef(environmentId, threadId)
11 : null;
12}
13
14/**
15 * Takes the thread object but keys on its ids: the shell changes identity on every update
16 * during a run, and effects keyed on this ref must not re-run for that.
17 */
18export function useActiveThreadRef(
19 thread: { readonly environmentId: EnvironmentId; readonly id: ThreadId } | null | undefined,
20): ScopedThreadRef | null {
21 const environmentId = thread?.environmentId ?? null;
22 const threadId = thread?.id ?? null;
23 const [ref, setRef] = useState(() => toThreadRef(environmentId, threadId));
24 if ((ref?.environmentId ?? null) !== environmentId || (ref?.threadId ?? null) !== threadId) {
25 const next = toThreadRef(environmentId, threadId);
26 setRef(next);
27 return next;
28 }
29 return ref;
30}