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

useComposerSelection.browser.test.tsx

177 lines6.6 KB

1import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
3import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
4import {
5 EnvironmentId,
6 ProviderDriverKind,
7 ProviderInstanceId,
8 ThreadId,
9 type ServerProvider,
10} from "@t3tools/contracts";
11import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
12import { createModelSelection } from "@t3tools/shared/model";
13import * as Cause from "effect/Cause";
14import { AsyncResult, Atom } from "effect/reactivity";
15import { expect, it, vi } from "vite-plus/test";
16import { page } from "vite-plus/test/browser";
17​
18const mocks = vi.hoisted(() => ({
19 setModelSelection: null as ((value: unknown) => Promise<AtomCommandResult<void, unknown>>) | null,
20}));
21​
22vi.mock(import("../../state/use-orchestration-command"), async (importOriginal) => ({
23 ...(await importOriginal()),
24 useOrchestrationCommand: (() => (value: unknown) => mocks.setModelSelection?.(value)) as never,
25}));
26​
27vi.mock(import("../../state/threads"), async (original) => {
28 const actual = await original();
29 return {
30 ...actual,
31 environmentThreadShells: {
32 ...actual.environmentThreadShells,
33 threadShellAtom: ((ref: { threadId: string }) => shellAtom(ref.threadId)) as never,
34 },
35 };
36});
37​
38import { render } from "../../../test/render";
39import { deriveEffectiveComposerModelState, useComposerDraftStore } from "../../composerDraftStore";
40import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry";
41import { useComposerSelection } from "./useComposerSelection";
42​
43// Kept alive so a shell set before the hook mounts is still there when it saves a pick.
44const shellAtom = Atom.family((_threadId: string) => Atom.make<unknown>(null).pipe(Atom.keepAlive));
45​
46function setup() {
47 const setModelSelection = vi.fn<(value: unknown) => Promise<AtomCommandResult<void, unknown>>>();
48 mocks.setModelSelection = setModelSelection;
49 return { setModelSelection };
51​
52const environmentId = EnvironmentId.make("environment-local");
53const cursor = ProviderInstanceId.make("cursor");
54const stored = createModelSelection(cursor, "claude-opus-5-5", [{ id: "effort", value: "medium" }]);
55​
56const providers: ReadonlyArray<ServerProvider> = [
57 {
58 instanceId: cursor,
59 driver: ProviderDriverKind.make("cursor"),
60 enabled: true,
61 installed: true,
62 version: null,
63 status: "ready",
64 auth: { status: "authenticated" },
65 checkedAt: "2026-01-01T00:00:00.000Z",
66 models: [{ slug: "auto-smart", name: "Auto", isCustom: false, capabilities: {} }],
67 slashCommands: [],
68 skills: [],
69 },
70];
71​
72// The hook reads only the thread's identity and stored selection.
73function cursorThread(id: string) {
74 return { environmentId, id: ThreadId.make(id), modelSelection: stored } as EnvironmentThreadShell;
76​
77function Picker(props: {
78 thread: EnvironmentThreadShell;
79 runtime: Parameters<typeof useComposerSelection>[0]["activeRuntime"];
80 model?: string;
81}) {
82 const { onProviderModelSelectStable } = useComposerSelection({
83 environmentId,
84 composerDraftTarget: scopeThreadRef(environmentId, props.thread.id),
85 draftThread: null,
86 activeThread: props.thread,
87 activeRuntime: props.runtime,
88 activeProjectSettings: { settings: { newWorktreesStartFromOrigin: false } },
89 settings: DEFAULT_UNIFIED_SETTINGS,
90 providerStatuses: providers,
91 lockedProvider: null,
92 supportsProviderSwitchingViaHandoff: true,
93 multipleModelSelections: null,
94 runtimeMode: "full-access",
95 isLocalDraftThread: false,
96 canOverrideServerThreadEnvMode: false,
97 setPendingServerThreadEnvModeEntry: () => {},
98 setPendingServerThreadStartFromOriginByThreadId: () => {},
99 scheduleComposerFocus: () => {},
100 });
101 return (
102 <button
103 type="button"
104 onClick={() => onProviderModelSelectStable(cursor, props.model ?? stored.model)}
105 >
106 Pick the model
107 </button>
108 );
110​
111it("keeps a Cursor thread's stored model and options when the user re-picks its unavailable row", async () => {
112 setup();
113 const thread = cursorThread("thread-cursor");
114 await using _screen = await render(<Picker thread={thread} runtime={null} />);
115 await page.getByRole("button", { name: "Pick the model" }).click();
116​
117 await vi.waitFor(() => {
118 const draft = useComposerDraftStore
119 .getState()
120 .getComposerDraft(scopeThreadRef(environmentId, thread.id));
121 expect(draft?.modelSelectionByProvider[cursor] ?? thread.modelSelection).toEqual(stored);
122 });
123});
124​
125it("switches back to the thread's stored model while the session runs on another instance", async () => {
126 setup();
127 const thread = cursorThread("thread-cursor-handoff");
128 const runtime = { providerInstanceId: ProviderInstanceId.make("codex") } as Parameters<
129 typeof useComposerSelection
130 >[0]["activeRuntime"];
131 await using _screen = await render(<Picker thread={thread} runtime={runtime} />);
132 await page.getByRole("button", { name: "Pick the model" }).click();
133​
134 await vi.waitFor(() => {
135 const draft = useComposerDraftStore
136 .getState()
137 .getComposerDraft(scopeThreadRef(environmentId, thread.id));
138 expect(draft?.activeProvider).toBe(cursor);
139 expect(
140 deriveEffectiveComposerModelState({
141 draft,
142 providers,
143 selectedProvider: ProviderDriverKind.make("cursor"),
144 selectedInstanceId: cursor,
145 threadModelSelection: thread.modelSelection,
146 projectModelSelection: null,
147 settings: DEFAULT_UNIFIED_SETTINGS,
148 }),
149 ).toEqual({ selectedModel: stored.model, modelOptions: { [cursor]: stored.options } });
150 });
151});
152​
153it("saves a re-picked model again when its first save failed", async () => {
154 const { setModelSelection } = setup();
155 setModelSelection
156 .mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("offline"))))
157 .mockResolvedValue(AsyncResult.success(undefined));
158 const thread = cursorThread("thread-cursor-retry");
159 appAtomRegistry.set(shellAtom(thread.id), thread);
160 await using _screen = await render(
161 <AppAtomRegistryProvider>
162 <Picker thread={thread} runtime={null} model="auto-smart" />
163 </AppAtomRegistryProvider>,
164 );
165 const pick = page.getByRole("button", { name: "Pick the model" });
166 await pick.click();
167 await vi.waitFor(() => expect(setModelSelection).toHaveBeenCalledTimes(1));
168 await pick.click();
169​
170 const autoSave = expect.objectContaining({
171 input: {
172 threadId: thread.id,
173 modelSelection: expect.objectContaining({ instanceId: cursor, model: "auto-smart" }),
174 },
175 });
176 await vi.waitFor(() => expect(setModelSelection.mock.calls).toEqual([[autoSave], [autoSave]]));
177});