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

QueuedMessageSender.tsx

100 lines4.1 KB

1import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
2import { derivePendingRequests } from "@t3tools/client-runtime/pending-requests";
3import { useEffect, useMemo } from "react";
4import { useShallow } from "zustand/react/shallow";
5​
6import { useComposerDraftStore } from "../composerDraftStore";
7import {
8 isQueuedMessageDue,
9 latestCompletedToolActivityId,
10 useQueuedMessageStore,
11 useQueuedMessages,
12} from "../queuedMessageStore";
13import { derivePhase } from "../session-logic";
14import { useServerConfigs, useThread, useThreadStatus } from "../state/entities";
15import { useEnvironment } from "../state/environments";
16import { hasServerAcknowledgedLocalDispatch, latestTurnStartFailureId } from "./ChatView.logic";
17import { sendQueuedMessage } from "./chat/sendQueuedMessage";
18​
19/**
20 * Sends queued messages when they are due, for every thread with a queue,
21 * whether or not the thread is on screen. Mounted once at the root.
22 */
23export function QueuedMessageSender() {
24 const threadKeys = useQueuedMessageStore(
25 useShallow((state) => Object.keys(state.queuesByThreadKey)),
26 );
27 return threadKeys.map((threadKey) => <ThreadQueueSender key={threadKey} threadKey={threadKey} />);
29​
30/**
31 * Watches one thread while it has queued messages. Reading the thread keeps
32 * its detail subscribed, so tool boundaries and the end of the turn are
33 * visible while the user is elsewhere.
34 */
35function ThreadQueueSender({ threadKey }: { threadKey: string }) {
36 const threadRef = useMemo(() => parseScopedThreadKey(threadKey), [threadKey]);
37 const thread = useThread(threadRef);
38 const threadStatus = useThreadStatus(threadRef);
39 const environmentId = threadRef?.environmentId ?? null;
40 const environment = useEnvironment(environmentId);
41 const serverConfigs = useServerConfigs();
42 const serverConfigLoaded = environmentId !== null && serverConfigs.has(environmentId);
43 const rewinding = useComposerDraftStore((store) => store.rewindingThreadKeys.has(threadKey));
44 const queue = useQueuedMessages(threadKey);
45 const next = queue[0];
46 const sending = queue.some((message) => message.sending);
47 const activities = thread?.activities;
48 const latestToolActivityId = useMemo(
49 () => latestCompletedToolActivityId(activities ?? []),
50 [activities],
51 );
52 const pendingRequests = useMemo(() => derivePendingRequests(activities ?? []), [activities]);
53 const phase = derivePhase(thread?.session ?? null);
54​
55 // A send that starts a new turn leaves the thread idle until the server
56 // picks it up. Hold the next message until then, as the composer does for
57 // its own sends.
58 const lastDispatch = useQueuedMessageStore(
59 (state) => state.lastDispatchByThreadKey[threadKey]?.thread ?? null,
60 );
61 const latestUserMessageId = thread?.messages.findLast((m) => m.role === "user")?.id ?? null;
62 const waitingForServer =
63 lastDispatch !== null &&
64 !hasServerAcknowledgedLocalDispatch({
65 localDispatch: lastDispatch,
66 phase,
67 latestTurn: thread?.latestTurn ?? null,
68 latestUserMessageId,
69 session: thread?.session ?? null,
70 hasPendingApproval: pendingRequests.approvals.length > 0,
71 hasPendingUserInput: pendingRequests.userInputs.length > 0,
72 latestTurnStartFailureId: latestTurnStartFailureId(thread ?? undefined, latestUserMessageId),
73 threadError: null,
74 });
75​
76 // Approvals and questions block the agent; a steer landing on top of them
77 // would answer nothing and confuse the turn, so the queue holds until the
78 // user resolves them.
79 const blocked =
80 threadRef === null ||
81 thread === null ||
82 threadStatus !== "live" ||
83 (environment !== null && environment.connection.phase !== "connected") ||
84 !serverConfigLoaded ||
85 rewinding ||
86 sending ||
87 waitingForServer ||
88 pendingRequests.approvals.length > 0 ||
89 pendingRequests.userInputs.length > 0;
90 const due =
91 next !== undefined &&
92 !blocked &&
93 isQueuedMessageDue({ message: next, phase, latestToolActivityId });
94 const nextId = next?.id;
95 useEffect(() => {
96 if (!due || !threadRef || nextId === undefined) return;
97 void sendQueuedMessage(threadRef, nextId);
98 }, [due, nextId, threadRef]);
99 return null;