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
| 1 | import { useAtomValue } from "@effect/atom-react"; |
| 2 | import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; |
| 3 | import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection"; |
| 4 | import * as Option from "effect/Option"; |
| 5 | import type { EnvironmentPresentation } from "../../state/environments"; |
| 6 | import type { ServerProvider } from "@t3tools/contracts"; |
| 7 | import { |
| 8 | scopedThreadKey, |
| 9 | scopeProjectRef, |
| 10 | scopeThreadRef, |
| 11 | } from "@t3tools/client-runtime/environment"; |
| 12 | import { createModelSelection } from "@t3tools/shared/model"; |
| 13 | import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings"; |
| 14 | import { |
| 15 | EnvironmentId, |
| 16 | ProjectId, |
| 17 | ProviderDriverKind, |
| 18 | ProviderInstanceId, |
| 19 | } from "@t3tools/contracts"; |
| 20 | import { expect, it, vi } from "vite-plus/test"; |
| 21 | |
| 22 | import { act, render } from "../../../test/render"; |
| 23 | import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; |
| 24 | import { useDraftEnvironmentRouting } from "./useDraftEnvironmentRouting"; |
| 25 | import { appAtomRegistry, AppAtomRegistryProvider } from "../../rpc/atomRegistry"; |
| 26 | import { draftFanoutSelectionsAtom } from "./chatViewSend"; |
| 27 | |
| 28 | const resources = vi.hoisted(() => ({ |
| 29 | projects: [] as EnvironmentProject[], |
| 30 | pickedEnvironmentId: null as EnvironmentId | null, |
| 31 | refreshSelection: vi.fn<(ids: readonly EnvironmentId[]) => Promise<EnvironmentId | null>>(), |
| 32 | })); |
| 33 | vi.mock("../../hooks/useLoadBalancedEnvironment", () => ({ |
| 34 | useLoadBalancedEnvironment: () => ({ |
| 35 | pending: false, |
| 36 | failed: false, |
| 37 | environmentId: resources.pickedEnvironmentId, |
| 38 | refresh: () => {}, |
| 39 | refreshSelection: resources.refreshSelection, |
| 40 | }), |
| 41 | })); |
| 42 | vi.mock("../../state/entities", () => ({ |
| 43 | useProjects: () => resources.projects, |
| 44 | readProject: (ref: { environmentId: EnvironmentId; projectId: ProjectId }) => |
| 45 | resources.projects.find( |
| 46 | (project) => project.environmentId === ref.environmentId && project.id === ref.projectId, |
| 47 | ) ?? null, |
| 48 | })); |
| 49 | vi.mock("../../hooks/useScratchProject", () => ({ useScratchProject: () => ({}) })); |
| 50 | |
| 51 | function setup() { |
| 52 | resources.refreshSelection.mockReset(); |
| 53 | resources.projects = []; |
| 54 | resources.pickedEnvironmentId = null; |
| 55 | const a = EnvironmentId.make("machine-a"); |
| 56 | const b = EnvironmentId.make("machine-b"); |
| 57 | const draftId = DraftId.make("fresh-routing-draft"); |
| 58 | const projectId = ProjectId.make("project"); |
| 59 | const store = useComposerDraftStore.getState(); |
| 60 | store.clearDraftThread(draftId); |
| 61 | store.setProjectDraftThreadId(scopeProjectRef(a, projectId), draftId, { |
| 62 | environmentSelection: "auto", |
| 63 | loadBalancedEnvironmentId: a, |
| 64 | }); |
| 65 | store.setPrompt(draftId, "Keep this prompt"); |
| 66 | const provider: ServerProvider = { |
| 67 | instanceId: ProviderInstanceId.make("codex"), |
| 68 | driver: ProviderDriverKind.make("codex"), |
| 69 | enabled: true, |
| 70 | installed: true, |
| 71 | status: "ready", |
| 72 | auth: { status: "authenticated" }, |
| 73 | availability: "available", |
| 74 | version: null, |
| 75 | checkedAt: "2026-11-10T01:00:00.000Z", |
| 76 | models: [], |
| 77 | slashCommands: [], |
| 78 | skills: [], |
| 79 | }; |
| 80 | const input: Parameters<typeof useDraftEnvironmentRouting>[0] = { |
| 81 | draftId, |
| 82 | draftThread: store.getDraftSession(draftId), |
| 83 | envLocked: false, |
| 84 | automaticEnvironment: true, |
| 85 | logicalProjectEnvironments: [a, b].map((environmentId) => ({ |
| 86 | environmentId, |
| 87 | projectId, |
| 88 | label: environmentId, |
| 89 | isPrimary: environmentId === a, |
| 90 | machine: "desktop", |
| 91 | })), |
| 92 | environmentById: new Map( |
| 93 | [a, b].map((id): [EnvironmentId, EnvironmentPresentation] => [ |
| 94 | id, |
| 95 | { |
| 96 | environmentId: id, |
| 97 | label: id, |
| 98 | displayUrl: null, |
| 99 | relayManaged: false, |
| 100 | entry: { |
| 101 | target: new PrimaryConnectionTarget({ |
| 102 | environmentId: id, |
| 103 | label: id, |
| 104 | httpBaseUrl: "http://localhost:3000", |
| 105 | wsBaseUrl: "ws://localhost:3000", |
| 106 | }), |
| 107 | profile: Option.none(), |
| 108 | enabled: true, |
| 109 | }, |
| 110 | connection: { phase: "connected", error: null, traceId: null }, |
| 111 | refusedRouteIds: [], |
| 112 | serverConfig: null, |
| 113 | }, |
| 114 | ]), |
| 115 | ), |
| 116 | providersByEnvironment: new Map([a, b].map((id) => [id, [provider]])), |
| 117 | loadBalancingSettings: { loadBalancingWeights: {} }, |
| 118 | referencedThreadContexts: [], |
| 119 | activeProviderInstanceId: provider.instanceId, |
| 120 | selectedProvider: provider.driver, |
| 121 | composerHasAttachments: false, |
| 122 | activeProjectKey: "project", |
| 123 | activeProjectIsScratch: false, |
| 124 | projectGroupingSettings: DEFAULT_UNIFIED_SETTINGS, |
| 125 | sendInFlightRef: { current: false }, |
| 126 | }; |
| 127 | resources.refreshSelection.mockImplementation(async (ids) => (ids.includes(b) ? b : null)); |
| 128 | return { a, b, draftId, input, store }; |
| 129 | } |
| 130 | |
| 131 | interface HarnessProps { |
| 132 | input: Parameters<typeof useDraftEnvironmentRouting>[0]; |
| 133 | onPrepared?: (ready: boolean | null) => void; |
| 134 | } |
| 135 | |
| 136 | function Harness(props: HarnessProps) { |
| 137 | return ( |
| 138 | <AppAtomRegistryProvider> |
| 139 | <RoutingProbe {...props} /> |
| 140 | </AppAtomRegistryProvider> |
| 141 | ); |
| 142 | } |
| 143 | |
| 144 | function RoutingProbe({ input, onPrepared }: HarnessProps) { |
| 145 | const routing = useDraftEnvironmentRouting(input); |
| 146 | const draft = useComposerDraftStore((state) => state.getDraftSession(input.draftId!)); |
| 147 | const selections = useAtomValue( |
| 148 | draftFanoutSelectionsAtom( |
| 149 | scopedThreadKey(scopeThreadRef(draft!.environmentId, draft!.threadId)), |
| 150 | ), |
| 151 | ); |
| 152 | return ( |
| 153 | <> |
| 154 | <output> |
| 155 | {selections?.map((selection) => selection.model).join(", ") ?? "single model"} |
| 156 | </output> |
| 157 | {input.logicalProjectEnvironments.map(({ environmentId }) => ( |
| 158 | <button |
| 159 | key={environmentId} |
| 160 | onClick={() => routing.onEnvironmentChangeStable(environmentId)} |
| 161 | > |
| 162 | Switch to {environmentId} |
| 163 | </button> |
| 164 | ))} |
| 165 | <span>{draft?.environmentId}</span> |
| 166 | <button |
| 167 | onClick={async () => { |
| 168 | const ready = await routing.refreshBeforeSend(); |
| 169 | onPrepared?.(ready); |
| 170 | }} |
| 171 | > |
| 172 | Send |
| 173 | </button> |
| 174 | </> |
| 175 | ); |
| 176 | } |
| 177 | |
| 178 | it("refreshes a stored automatic choice before sending an unsent draft", async () => { |
| 179 | const { a, b, draftId, input, store } = setup(); |
| 180 | const selections = ["model-a", "model-b"].map((model) => |
| 181 | createModelSelection(ProviderInstanceId.make("codex"), model), |
| 182 | ); |
| 183 | const threadId = input.draftThread!.threadId; |
| 184 | const destinationSelections = draftFanoutSelectionsAtom( |
| 185 | scopedThreadKey(scopeThreadRef(b, threadId)), |
| 186 | ); |
| 187 | appAtomRegistry.set(destinationSelections, null); |
| 188 | appAtomRegistry.set( |
| 189 | draftFanoutSelectionsAtom(scopedThreadKey(scopeThreadRef(a, threadId))), |
| 190 | selections, |
| 191 | ); |
| 192 | store.setDraftThreadContext(draftId, { |
| 193 | branch: "main", |
| 194 | envMode: "worktree", |
| 195 | environmentSelection: "auto", |
| 196 | }); |
| 197 | await using screen = await render( |
| 198 | <Harness input={{ ...input, draftThread: store.getDraftSession(draftId) }} />, |
| 199 | ); |
| 200 | await expect.element(screen.getByText(a)).toBeInTheDocument(); |
| 201 | await screen.getByRole("button", { name: "Send" }).click(); |
| 202 | await expect.element(screen.getByText(b)).toBeInTheDocument(); |
| 203 | expect(resources.refreshSelection).toHaveBeenCalledWith([a, b]); |
| 204 | expect(store.getDraftSession(draftId)).toMatchObject({ |
| 205 | loadBalancedEnvironmentId: b, |
| 206 | branch: "main", |
| 207 | envMode: "worktree", |
| 208 | }); |
| 209 | expect(store.getComposerDraft(draftId)?.prompt).toBe("Keep this prompt"); |
| 210 | expect(appAtomRegistry.get(destinationSelections)).toEqual(selections); |
| 211 | }); |
| 212 | |
| 213 | it.each(["manual", "attachments", "promoted"] as const)( |
| 214 | "keeps the machine for %s drafts", |
| 215 | async (kind) => { |
| 216 | const { a, draftId, input, store } = setup(); |
| 217 | if (kind === "manual") store.setDraftThreadContext(draftId, { environmentSelection: "manual" }); |
| 218 | const guardedInput = { |
| 219 | ...input, |
| 220 | automaticEnvironment: kind !== "manual", |
| 221 | composerHasAttachments: kind === "attachments", |
| 222 | draftThread: |
| 223 | kind === "promoted" |
| 224 | ? { |
| 225 | ...input.draftThread!, |
| 226 | promotedTo: { environmentId: a, threadId: input.draftThread!.threadId }, |
| 227 | } |
| 228 | : input.draftThread, |
| 229 | }; |
| 230 | await using screen = await render(<Harness input={guardedInput} />); |
| 231 | await screen.getByRole("button", { name: "Send" }).click(); |
| 232 | expect(resources.refreshSelection).not.toHaveBeenCalled(); |
| 233 | expect(store.getDraftSession(draftId)?.environmentId).toBe(a); |
| 234 | }, |
| 235 | ); |
| 236 | |
| 237 | it("does not reuse a stored choice when refreshed resources have no winner", async () => { |
| 238 | const { a, input } = setup(); |
| 239 | resources.refreshSelection.mockResolvedValue(null); |
| 240 | const onPrepared = vi.fn(); |
| 241 | await using screen = await render(<Harness input={input} onPrepared={onPrepared} />); |
| 242 | await screen.getByRole("button", { name: "Send" }).click(); |
| 243 | await expect.element(screen.getByText(a)).toBeInTheDocument(); |
| 244 | await vi.waitFor(() => expect(onPrepared).toHaveBeenCalledWith(false)); |
| 245 | }); |
| 246 | |
| 247 | it("abandons a refresh when the draft changes while resources are in flight", async () => { |
| 248 | const { a, b, draftId, input, store } = setup(); |
| 249 | let resolve!: (environmentId: EnvironmentId) => void; |
| 250 | resources.refreshSelection.mockReturnValue( |
| 251 | new Promise<EnvironmentId>((done) => { |
| 252 | resolve = done; |
| 253 | }), |
| 254 | ); |
| 255 | await using screen = await render(<Harness input={input} />); |
| 256 | await screen.getByRole("button", { name: "Send" }).click(); |
| 257 | await act(async () => { |
| 258 | store.setPrompt(draftId, "Edited while checking"); |
| 259 | resolve(b); |
| 260 | }); |
| 261 | await expect.element(screen.getByText(a)).toBeInTheDocument(); |
| 262 | expect(store.getComposerDraft(draftId)?.prompt).toBe("Edited while checking"); |
| 263 | }); |
| 264 | |
| 265 | function fanoutSetup() { |
| 266 | const routing = setup(); |
| 267 | const { a, b, draftId, input, store } = routing; |
| 268 | resources.projects = [a, b].map((environmentId) => ({ |
| 269 | environmentId, |
| 270 | id: input.draftThread!.projectId, |
| 271 | title: "Project", |
| 272 | workspaceRoot: "/workspace/project", |
| 273 | defaultModelSelection: null, |
| 274 | scripts: [], |
| 275 | createdAt: "2026-11-10T01:00:00.000Z", |
| 276 | updatedAt: "2026-11-10T01:00:00.000Z", |
| 277 | })); |
| 278 | const threadId = input.draftThread!.threadId; |
| 279 | const selectionsOn = (environmentId: EnvironmentId) => |
| 280 | draftFanoutSelectionsAtom(scopedThreadKey(scopeThreadRef(environmentId, threadId))); |
| 281 | const models = (...names: string[]) => |
| 282 | names.map((model) => createModelSelection(ProviderInstanceId.make("codex"), model)); |
| 283 | appAtomRegistry.set(selectionsOn(b), null); |
| 284 | appAtomRegistry.set(selectionsOn(a), models("gpt-6.1-sol", "gpt-6.1-luna")); |
| 285 | store.setDraftThreadContext(draftId, { |
| 286 | environmentSelection: "manual", |
| 287 | loadBalancedEnvironmentId: null, |
| 288 | branch: "main", |
| 289 | envMode: "worktree", |
| 290 | }); |
| 291 | return { ...routing, selectionsOn, models }; |
| 292 | } |
| 293 | |
| 294 | it("keeps the selected models when the draft switches machine by hand", async () => { |
| 295 | const { a, b, draftId, input, store, selectionsOn, models } = fanoutSetup(); |
| 296 | await using screen = await render( |
| 297 | <Harness |
| 298 | input={{ ...input, automaticEnvironment: false, draftThread: store.getDraftSession(draftId) }} |
| 299 | />, |
| 300 | ); |
| 301 | await expect.element(screen.getByText("gpt-6.1-sol, gpt-6.1-luna")).toBeInTheDocument(); |
| 302 | await screen.getByRole("button", { name: `Switch to ${b}` }).click(); |
| 303 | await expect.element(screen.getByText(b)).toBeInTheDocument(); |
| 304 | await expect.element(screen.getByText("gpt-6.1-sol, gpt-6.1-luna")).toBeInTheDocument(); |
| 305 | expect(store.getComposerDraft(draftId)?.prompt).toBe("Keep this prompt"); |
| 306 | |
| 307 | // Changes made on the new machine come back with the draft. |
| 308 | await act(async () => appAtomRegistry.set(selectionsOn(b), models("gpt-6.1-sol"))); |
| 309 | await screen.getByRole("button", { name: `Switch to ${a}` }).click(); |
| 310 | await expect.element(screen.getByText(a)).toBeInTheDocument(); |
| 311 | await expect.element(screen.getByText("gpt-6.1-sol", { exact: true })).toBeInTheDocument(); |
| 312 | }); |
| 313 | |
| 314 | it("keeps the selected models when automatic routing picks another machine", async () => { |
| 315 | const { b, draftId, input, store } = fanoutSetup(); |
| 316 | store.setDraftThreadContext(draftId, { environmentSelection: "auto" }); |
| 317 | resources.pickedEnvironmentId = b; |
| 318 | await using screen = await render( |
| 319 | <Harness input={{ ...input, draftThread: store.getDraftSession(draftId) }} />, |
| 320 | ); |
| 321 | await expect.element(screen.getByText(b)).toBeInTheDocument(); |
| 322 | await expect.element(screen.getByText("gpt-6.1-sol, gpt-6.1-luna")).toBeInTheDocument(); |
| 323 | }); |
| 324 | |
| 325 | it.each([ |
| 326 | { name: "takes the destination default", explicit: false, remoteDefault: true, model: "luna" }, |
| 327 | { name: "keeps a model the user picked", explicit: true, remoteDefault: true, model: "sol" }, |
| 328 | { |
| 329 | name: "keeps the last-used model without a default", |
| 330 | explicit: false, |
| 331 | remoteDefault: false, |
| 332 | model: "sol", |
| 333 | }, |
| 334 | ])("$name when the draft switches machine by hand", async ({ explicit, remoteDefault, model }) => { |
| 335 | const { b, draftId, input, store } = fanoutSetup(); |
| 336 | const codex = ProviderInstanceId.make("codex"); |
| 337 | resources.projects = resources.projects.map((project) => |
| 338 | project.environmentId === b && remoteDefault |
| 339 | ? { ...project, defaultModelSelection: createModelSelection(codex, "luna") } |
| 340 | : project, |
| 341 | ); |
| 342 | store.setStickyModelSelection(createModelSelection(codex, "sol")); |
| 343 | store.setModelSelection(draftId, createModelSelection(codex, "sol"), { explicit }); |
| 344 | await using screen = await render( |
| 345 | <Harness |
| 346 | input={{ ...input, automaticEnvironment: false, draftThread: store.getDraftSession(draftId) }} |
| 347 | />, |
| 348 | ); |
| 349 | await screen.getByRole("button", { name: `Switch to ${b}` }).click(); |
| 350 | await expect.element(screen.getByText(b)).toBeInTheDocument(); |
| 351 | const draft = store.getComposerDraft(draftId); |
| 352 | expect(draft?.activeProvider).toBe(codex); |
| 353 | expect(draft?.modelSelectionByProvider[codex]?.model).toBe(model); |
| 354 | expect(draft?.modelSelectionExplicit === true).toBe(explicit); |
| 355 | }); |