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

usePromptSuggestion.ts

55 lines2.5 KB

1import type { EnvironmentId, RunId } from "@t3tools/contracts";
2import { useSyncExternalStore } from "react";
3​
4import type { Thread } from "../../types";
5import { useMediaQuery } from "../../hooks/useMediaQuery";
6import { useServerConfigs } from "../../state/entities";
7import { orchestrationEnvironment } from "../../state/orchestration";
8import { useEnvironmentQuery } from "../../state/query";
9​
10// Dismissed suggestions, keyed by environment and run, shared by every mounted composer and kept
11// across remounts. Run ids derive from thread ids, which can repeat across environments.
12let dismissedKeys: ReadonlySet<string> = new Set();
13const listeners = new Set<() => void>();
14const subscribeDismissed = (listener: () => void) => {
15 listeners.add(listener);
16 return () => listeners.delete(listener);
17};
18const readDismissed = () => dismissedKeys;
19const dismissKey = (environmentId: EnvironmentId, runId: RunId) => `${environmentId}\u0000${runId}`;
20​
21/**
22 * The provider's predicted next prompt, while the run that produced it is the thread's latest
23 * completed run and Escape has not dismissed it.
24 */
25export function usePromptSuggestion(
26 environmentId: EnvironmentId,
27 thread: Thread | undefined,
28): { readonly suggestion: string | null; readonly dismiss: () => void } {
29 // Older servers decode the missing setting as false, so true also proves the method exists.
30 const enabled = useServerConfigs().get(environmentId)?.settings.promptSuggestionsEnabled === true;
31 // Tab is the only way to accept one, so skip devices with no mouse or trackpad at all.
32 const hasFinePointer = useMediaQuery("(any-pointer: fine)");
33 const { data } = useEnvironmentQuery(
34 // A local draft has no run, and so no suggestion, until its first send.
35 enabled && hasFinePointer && thread?.latestRun
36 ? orchestrationEnvironment.v2.promptSuggestion({
37 environmentId,
38 input: { threadId: thread.id },
39 })
40 : null,
41 );
42 const dismissed = useSyncExternalStore(subscribeDismissed, readDismissed);
43 const latestRun = thread?.latestRun;
44 const offered =
45 data && latestRun?.runId === data.runId && latestRun.status === "completed" ? data : null;
46 return {
47 suggestion:
48 offered && !dismissed.has(dismissKey(environmentId, offered.runId)) ? offered.text : null,
49 dismiss: () => {
50 if (offered === null) return;
51 dismissedKeys = new Set(dismissedKeys).add(dismissKey(environmentId, offered.runId));
52 for (const listener of listeners) listener();
53 },
54 };