Open History to see the last commit
1import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2import { EnvironmentId, RunId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
3import { useRouterState } from "@tanstack/react-router";
4import { useRef } from "react";
5import { expect, it, vi } from "vite-plus/test";
6
7import { act, render } from "../../../test/render";
8import { makeThreadFixture } from "../../test-fixtures";
9import { useTimelineRewind } from "./useTimelineRewind";
10
11const mocks = vi.hoisted(() => ({
12 waitForThreadShell: vi.fn<(threadRef: ScopedThreadRef) => Promise<boolean>>(),
13}));
14
15vi.mock(import("../../state/entities"), async (original) => ({
16 ...(await original()),
17 waitForThreadShell: mocks.waitForThreadShell,
18}));
19
20vi.mock("../../state/use-atom-command", () => ({
21 useAtomCommand: () => async () => ({ _tag: "Success" }),
22}));
23
24const environmentId = EnvironmentId.make("fork-environment");
25const sourceThreadId = ThreadId.make("source");
26const otherThreadId = ThreadId.make("other");
27const sourcePath = `/${environmentId}/${sourceThreadId}`;
28const otherPath = `/${environmentId}/${otherThreadId}`;
29
30function ForkButton({ onFinished }: { onFinished: () => void }) {
31 // Like ChatView, the rendered thread follows the committed match, not a pending navigation.
32 const pathname = useRouterState({
33 select: (state) => (state.resolvedLocation ?? state.location).pathname,
34 });
35 const routeThreadRef = {
36 environmentId,
37 threadId: pathname === sourcePath ? sourceThreadId : otherThreadId,
38 };
39 const routeThreadKey = scopedThreadKey(routeThreadRef);
40 const currentRouteThreadKeyRef = useRef<string | null>(routeThreadKey);
41 const { onForkFromRunStable } = useTimelineRewind({
42 environmentId,
43 routeThreadRef,
44 routeThreadKey,
45 currentRouteThreadKeyRef,
46 activeThread: makeThreadFixture({ ...routeThreadRef, title: "Source chat" }),
47 serverProjection: null,
48 timelineMessages: [],
49 phase: "ready",
50 isSendBusy: false,
51 isRevertingCheckpoint: false,
52 supportsConversationRollback: true,
53 activeEnvironmentUnavailable: false,
54 activeEnvironmentUnavailableLabel: null,
55 promptRef: { current: "" },
56 composerRef: { current: null },
57 composerDraftTarget: routeThreadRef,
58 setThreadError: () => {},
59 });
60 return (
61 <button
62 type="button"
63 onClick={() =>
64 void onForkFromRunStable({ sourceThreadId, runId: RunId.make("reply") }).then(onFinished)
65 }
66 >
67 Fork from this response
68 </button>
69 );
70}
71
72it.each([
73 ["while a response fork syncs", false],
74 ["before a response fork starts", true],
75])("stays in the chat the user starts opening %s", async (_, openFirst) => {
76 const otherLoaded = Promise.withResolvers<void>();
77 const waitingForShell = Promise.withResolvers<void>();
78 const shellReady = Promise.withResolvers<boolean>();
79 const finished = Promise.withResolvers<void>();
80 mocks.waitForThreadShell.mockImplementation(() => {
81 waitingForShell.resolve();
82 return shellReady.promise;
83 });
84 await using screen = await render(<ForkButton onFinished={finished.resolve} />, {
85 router: sourcePath,
86 });
87 const router = screen.router!;
88 router.routeTree.update({
89 beforeLoad: ({ location }: { location: { pathname: string } }) =>
90 location.pathname === otherPath ? otherLoaded.promise : undefined,
91 });
92 const open = () => void router.navigate({ to: otherPath });
93 if (openFirst) open();
94 await screen.getByRole("button", { name: "Fork from this response" }).click();
95 await waitingForShell.promise;
96 if (!openFirst) open();
97
98 await act(() => shellReady.resolve(true));
99 await finished.promise;
100 await act(() => otherLoaded.resolve());
101
102 await vi.waitFor(() => expect(router.state.resolvedLocation?.pathname).toBe(otherPath));
103});
104
105it("opens the response fork when the user stays in its source chat", async () => {
106 const finished = Promise.withResolvers<void>();
107 mocks.waitForThreadShell.mockResolvedValue(true);
108 await using screen = await render(<ForkButton onFinished={finished.resolve} />, {
109 router: sourcePath,
110 });
111 await screen.getByRole("button", { name: "Fork from this response" }).click();
112 await finished.promise;
113
114 const [forkRef] = mocks.waitForThreadShell.mock.lastCall!;
115 expect(screen.router!.state.location.pathname).toBe(
116 `/${forkRef.environmentId}/${forkRef.threadId}`,
117 );
118});