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

useLocalDispatchState.ts

68 lines2.6 KB

1import { type EnvironmentId, type MessageId, type RuntimeRequestId } from "@t3tools/contracts";
2import { useState } from "react";
3import { type ComposerSubmissionIntent } from "../../composer-logic";
4import { type SessionPhase, type Thread } from "../../types";
5import {
6 createLocalDispatchSnapshot,
7 hasServerAcknowledgedLocalDispatch,
8 type LocalDispatchSnapshot,
9} from "../ChatView.logic";
10​
11export function useLocalDispatchState(input: {
12 environmentId: EnvironmentId;
13 activeThread: Thread | undefined;
14 activeLatestRun: Thread["latestRun"] | null;
15 latestUserMessageId: MessageId | null;
16 phase: SessionPhase;
17 activePendingApproval: RuntimeRequestId | null;
18 activePendingUserInput: RuntimeRequestId | null;
19 threadError: string | null | undefined;
20}) {
21 const [localDispatch, setLocalDispatch] = useState<LocalDispatchSnapshot | null>(null);
22​
23 const resetLocalDispatch = () => {
24 setLocalDispatch(null);
25 };
26​
27 const serverAcknowledgedLocalDispatch = hasServerAcknowledgedLocalDispatch({
28 localDispatch,
29 phase: input.phase,
30 latestRun: input.activeLatestRun,
31 latestUserMessageId: input.latestUserMessageId,
32 runtime: input.activeThread?.runtime ?? null,
33 hasPendingApproval: input.activePendingApproval !== null,
34 hasPendingUserInput: input.activePendingUserInput !== null,
35 threadError: input.threadError,
36 });
37 const activeLocalDispatch = serverAcknowledgedLocalDispatch ? null : localDispatch;
38 const beginLocalDispatch = (options?: {
39 preparingWorktree?: boolean;
40 submissionIntent?: ComposerSubmissionIntent;
41 }) => {
42 const preparingWorktree = Boolean(options?.preparingWorktree);
43 setLocalDispatch((current) => {
44 const active = serverAcknowledgedLocalDispatch ? null : current;
45 if (active) {
46 const submissionIntent = options?.submissionIntent ?? active.submissionIntent;
47 return active.preparingWorktree === preparingWorktree &&
48 active.submissionIntent === submissionIntent
49 ? active
50 : { ...active, preparingWorktree, submissionIntent };
51 }
52 return createLocalDispatchSnapshot(input.activeThread, {
53 ...options,
54 environmentId: input.environmentId,
55 latestUserMessageId: input.latestUserMessageId,
56 });
57 });
58 };
59​
60 return {
61 beginLocalDispatch,
62 resetLocalDispatch,
63 localDispatchStartedAt: activeLocalDispatch?.startedAt ?? null,
64 isPreparingWorktree: activeLocalDispatch?.preparingWorktree ?? false,
65 isSendBusy: activeLocalDispatch !== null,
66 backgroundSubmissionPending: activeLocalDispatch?.submissionIntent === "background",
67 };