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

useReloadThreadSession.ts

65 lines2.1 KB

1import type { ScopedThreadRef } from "@t3tools/contracts";
2import {
3 isAtomCommandInterrupted,
4 squashAtomCommandFailure,
5} from "@t3tools/client-runtime/state/runtime";
6import { threadSessionReloadAvailability } from "@t3tools/client-runtime/state/thread-session";
7import { useCallback } from "react";
8​
9import { stackedThreadToast, toastManager } from "../components/ui/toast";
10import { readThreadShell } from "../state/entities";
11import { threadEnvironment } from "../state/threads";
12import { useAtomCommand } from "../state/use-atom-command";
13​
14export function useReloadThreadSession() {
15 const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, {
16 reportFailure: false,
17 });
18​
19 return useCallback(
20 async (threadRef: ScopedThreadRef) => {
21 const availability = threadSessionReloadAvailability(
22 readThreadShell(threadRef)?.session?.status ?? null,
23 );
24 if (availability === "disabled") {
25 toastManager.add(
26 stackedThreadToast({
27 type: "error",
28 title: "Could not reload agent session",
29 description: "Wait for the active turn to finish before reloading the session.",
30 }),
31 );
32 return;
33 }
34 if (availability === "hidden") return;
35​
36 const result = await stopThreadSession({
37 environmentId: threadRef.environmentId,
38 input: { threadId: threadRef.threadId, onlyIfIdle: true },
39 });
40 if (result._tag === "Failure") {
41 if (!isAtomCommandInterrupted(result)) {
42 const error = squashAtomCommandFailure(result);
43 toastManager.add(
44 stackedThreadToast({
45 type: "error",
46 title: "Could not reload agent session",
47 description: error instanceof Error ? error.message : "An error occurred.",
48 }),
49 );
50 }
51 return;
52 }
53​
54 toastManager.add(
55 stackedThreadToast({
56 type: "success",
57 title: "Agent session will reload",
58 description:
59 "Your next message will resume this thread with current provider and MCP settings.",
60 }),
61 );
62 },
63 [stopThreadSession],
64 );