@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 208 lines 7.57 KB
Raw
1 import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2 import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
3 import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
4 import {
5 EnvironmentId,
6 ProviderDriverKind,
7 ProviderInstanceId,
8 ThreadId,
9 type ServerProvider,
10 } from "@t3tools/contracts";
11 import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
12 import { createModelSelection } from "@t3tools/shared/model";
13 import * as Cause from "effect/Cause";
14 import { AsyncResult, Atom } from "effect/reactivity";
15 import { expect, it, vi } from "vite-plus/test";
16 import { page } from "vite-plus/test/browser";
17
18 const mocks = vi.hoisted(() => ({
19 setModelSelection: null as ((value: unknown) => Promise<AtomCommandResult<void, unknown>>) | null,
20 }));
21
22 vi.mock(import("../../state/use-orchestration-command"), async (importOriginal) => ({
23 ...(await importOriginal()),
24 useOrchestrationCommand: (() => (value: unknown) => mocks.setModelSelection?.(value)) as never,
25 }));
26
27 vi.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
38 import { render } from "../../../test/render";
39 import { deriveEffectiveComposerModelState, useComposerDraftStore } from "../../composerDraftStore";
40 import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry";
41 import { useComposerSelection } from "./useComposerSelection";
42
43 // Kept alive so a shell set before the hook mounts is still there when it saves a pick.
44 const shellAtom = Atom.family((_threadId: string) => Atom.make<unknown>(null).pipe(Atom.keepAlive));
45
46 function setup() {
47 const setModelSelection = vi.fn<(value: unknown) => Promise<AtomCommandResult<void, unknown>>>();
48 mocks.setModelSelection = setModelSelection;
49 return { setModelSelection };
50 }
51
52 const environmentId = EnvironmentId.make("environment-local");
53 const cursor = ProviderInstanceId.make("cursor");
54 const stored = createModelSelection(cursor, "claude-opus-5-5", [{ id: "effort", value: "medium" }]);
55
56 const 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.
73 function cursorThread(id: string) {
74 return { environmentId, id: ThreadId.make(id), modelSelection: stored } as EnvironmentThreadShell;
75 }
76
77 function 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 );
109 }
110
111 it("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
125 it("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 threadStarted: true,
143 providers,
144 selectedProvider: ProviderDriverKind.make("cursor"),
145 selectedInstanceId: cursor,
146 threadModelSelection: thread.modelSelection,
147 projectModelSelection: null,
148 settings: DEFAULT_UNIFIED_SETTINGS,
149 }),
150 ).toEqual({ selectedModel: stored.model, modelOptions: { [cursor]: stored.options } });
151 });
152 });
153
154 it("saves a re-picked model again when its first save failed", async () => {
155 const { setModelSelection } = setup();
156 setModelSelection
157 .mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("offline"))))
158 .mockResolvedValue(AsyncResult.success(undefined));
159 const thread = cursorThread("thread-cursor-retry");
160 appAtomRegistry.set(shellAtom(thread.id), thread);
161 await using _screen = await render(
162 <AppAtomRegistryProvider>
163 <Picker thread={thread} runtime={null} model="auto-smart" />
164 </AppAtomRegistryProvider>,
165 );
166 const pick = page.getByRole("button", { name: "Pick the model" });
167 await pick.click();
168 await vi.waitFor(() => expect(setModelSelection).toHaveBeenCalledTimes(1));
169 await pick.click();
170
171 const autoSave = expect.objectContaining({
172 input: {
173 threadId: thread.id,
174 modelSelection: expect.objectContaining({ instanceId: cursor, model: "auto-smart" }),
175 },
176 });
177 await vi.waitFor(() => expect(setModelSelection.mock.calls).toEqual([[autoSave], [autoSave]]));
178 });
179
180 it("saves a pick of a seeded model the started thread does not show", async () => {
181 const { setModelSelection } = setup();
182 setModelSelection.mockResolvedValue(AsyncResult.success(undefined));
183 const thread = cursorThread("thread-cursor-seeded");
184 appAtomRegistry.set(shellAtom(thread.id), thread);
185 useComposerDraftStore
186 .getState()
187 .setModelSelection(
188 scopeThreadRef(environmentId, thread.id),
189 createModelSelection(cursor, "auto-smart"),
190 );
191 await using _screen = await render(
192 <AppAtomRegistryProvider>
193 <Picker thread={thread} runtime={null} model="auto-smart" />
194 </AppAtomRegistryProvider>,
195 );
196 await page.getByRole("button", { name: "Pick the model" }).click();
197
198 await vi.waitFor(() =>
199 expect(setModelSelection).toHaveBeenCalledWith(
200 expect.objectContaining({
201 input: {
202 threadId: thread.id,
203 modelSelection: expect.objectContaining({ instanceId: cursor, model: "auto-smart" }),
204 },
205 }),
206 ),
207 );
208 });