|
| 1 | +import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection"; |
| 2 | +import * as Option from "effect/Option"; |
| 3 | +import type { EnvironmentPresentation } from "../../state/environments"; |
| 4 | +import type { ServerProvider } from "@t3tools/contracts"; |
| 5 | +import { scopeProjectRef } from "@t3tools/client-runtime/environment"; |
| 6 | +import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings"; |
| 7 | +import { |
| 8 | + EnvironmentId, |
| 9 | + ProjectId, |
| 10 | + ProviderDriverKind, |
| 11 | + ProviderInstanceId, |
| 12 | +} from "@t3tools/contracts"; |
| 13 | +import { expect, it, vi } from "vite-plus/test"; |
| 14 | + |
| 15 | +import { act, render } from "../../../test/render"; |
| 16 | +import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; |
| 17 | +import { useDraftEnvironmentRouting } from "./useDraftEnvironmentRouting"; |
| 18 | + |
| 19 | +const resources = vi.hoisted(() => ({ |
| 20 | + refreshSelection: vi.fn<(ids: readonly EnvironmentId[]) => Promise<EnvironmentId | null>>(), |
| 21 | +})); |
| 22 | +vi.mock("../../hooks/useLoadBalancedEnvironment", () => ({ |
| 23 | + useLoadBalancedEnvironment: () => ({ |
| 24 | + pending: false, |
| 25 | + failed: false, |
| 26 | + environmentId: null, |
| 27 | + refresh: () => {}, |
| 28 | + refreshSelection: resources.refreshSelection, |
| 29 | + }), |
| 30 | +})); |
| 31 | +vi.mock("../../state/entities", () => ({ useProjects: () => [] })); |
| 32 | +vi.mock("../../hooks/useScratchProject", () => ({ useScratchProject: () => ({}) })); |
| 33 | + |
| 34 | +function setup() { |
| 35 | + resources.refreshSelection.mockReset(); |
| 36 | + const a = EnvironmentId.make("machine-a"); |
| 37 | + const b = EnvironmentId.make("machine-b"); |
| 38 | + const draftId = DraftId.make("fresh-routing-draft"); |
| 39 | + const projectId = ProjectId.make("project"); |
| 40 | + const store = useComposerDraftStore.getState(); |
| 41 | + store.clearDraftThread(draftId); |
| 42 | + store.setProjectDraftThreadId(scopeProjectRef(a, projectId), draftId, { |
| 43 | + environmentSelection: "auto", |
| 44 | + loadBalancedEnvironmentId: a, |
| 45 | + }); |
| 46 | + store.setPrompt(draftId, "Keep this prompt"); |
| 47 | + const provider: ServerProvider = { |
| 48 | + instanceId: ProviderInstanceId.make("codex"), |
| 49 | + driver: ProviderDriverKind.make("codex"), |
| 50 | + enabled: true, |
| 51 | + installed: true, |
| 52 | + status: "ready", |
| 53 | + auth: { status: "authenticated" }, |
| 54 | + availability: "available", |
| 55 | + version: null, |
| 56 | + checkedAt: "2026-11-10T01:00:00.000Z", |
| 57 | + models: [], |
| 58 | + slashCommands: [], |
| 59 | + skills: [], |
| 60 | + }; |
| 61 | + const input: Parameters<typeof useDraftEnvironmentRouting>[0] = { |
| 62 | + draftId, |
| 63 | + draftThread: store.getDraftSession(draftId), |
| 64 | + envLocked: false, |
| 65 | + automaticEnvironment: true, |
| 66 | + logicalProjectEnvironments: [a, b].map((environmentId) => ({ |
| 67 | + environmentId, |
| 68 | + projectId, |
| 69 | + label: environmentId, |
| 70 | + isPrimary: environmentId === a, |
| 71 | + machine: "desktop", |
| 72 | + })), |
| 73 | + environmentById: new Map( |
| 74 | + [a, b].map((id): [EnvironmentId, EnvironmentPresentation] => [ |
| 75 | + id, |
| 76 | + { |
| 77 | + environmentId: id, |
| 78 | + label: id, |
| 79 | + displayUrl: null, |
| 80 | + relayManaged: false, |
| 81 | + entry: { |
| 82 | + target: new PrimaryConnectionTarget({ |
| 83 | + environmentId: id, |
| 84 | + label: id, |
| 85 | + httpBaseUrl: "http://localhost:3000", |
| 86 | + wsBaseUrl: "ws://localhost:3000", |
| 87 | + }), |
| 88 | + profile: Option.none(), |
| 89 | + enabled: true, |
| 90 | + }, |
| 91 | + connection: { phase: "connected", error: null, traceId: null }, |
| 92 | + serverConfig: null, |
| 93 | + }, |
| 94 | + ]), |
| 95 | + ), |
| 96 | + providersByEnvironment: new Map([a, b].map((id) => [id, [provider]])), |
| 97 | + loadBalancingSettings: { loadBalancingWeights: {} }, |
| 98 | + referencedThreadContexts: [], |
| 99 | + activeProviderInstanceId: provider.instanceId, |
| 100 | + selectedProvider: provider.driver, |
| 101 | + composerHasAttachments: false, |
| 102 | + activeProjectKey: "project", |
| 103 | + activeProjectIsScratch: false, |
| 104 | + projectGroupingSettings: DEFAULT_UNIFIED_SETTINGS, |
| 105 | + sendInFlightRef: { current: false }, |
| 106 | + }; |
| 107 | + resources.refreshSelection.mockImplementation(async (ids) => (ids.includes(b) ? b : null)); |
| 108 | + return { a, b, draftId, input, store }; |
| 109 | +} |
| 110 | + |
| 111 | +function Harness({ |
| 112 | + input, |
| 113 | + onPrepared, |
| 114 | +}: { |
| 115 | + input: Parameters<typeof useDraftEnvironmentRouting>[0]; |
| 116 | + onPrepared?: (ready: boolean | null) => void; |
| 117 | +}) { |
| 118 | + const routing = useDraftEnvironmentRouting(input); |
| 119 | + const draft = useComposerDraftStore((state) => state.getDraftSession(input.draftId!)); |
| 120 | + return ( |
| 121 | + <> |
| 122 | + <span>{draft?.environmentId}</span> |
| 123 | + <button |
| 124 | + onClick={async () => { |
| 125 | + const ready = await routing.refreshBeforeSend(); |
| 126 | + onPrepared?.(ready); |
| 127 | + }} |
| 128 | + > |
| 129 | + Send |
| 130 | + </button> |
| 131 | + </> |
| 132 | + ); |
| 133 | +} |
| 134 | + |
| 135 | +it("refreshes a stored automatic choice before sending an unsent draft", async () => { |
| 136 | + const { a, b, draftId, input, store } = setup(); |
| 137 | + store.setDraftThreadContext(draftId, { |
| 138 | + branch: "main", |
| 139 | + envMode: "worktree", |
| 140 | + environmentSelection: "auto", |
| 141 | + }); |
| 142 | + await using screen = await render( |
| 143 | + <Harness input={{ ...input, draftThread: store.getDraftSession(draftId) }} />, |
| 144 | + ); |
| 145 | + await expect.element(screen.getByText(a)).toBeInTheDocument(); |
| 146 | + await screen.getByRole("button", { name: "Send" }).click(); |
| 147 | + await expect.element(screen.getByText(b)).toBeInTheDocument(); |
| 148 | + expect(resources.refreshSelection).toHaveBeenCalledWith([a, b]); |
| 149 | + expect(store.getDraftSession(draftId)).toMatchObject({ |
| 150 | + loadBalancedEnvironmentId: b, |
| 151 | + branch: "main", |
| 152 | + envMode: "worktree", |
| 153 | + }); |
| 154 | + expect(store.getComposerDraft(draftId)?.prompt).toBe("Keep this prompt"); |
| 155 | +}); |
| 156 | + |
| 157 | +it.each(["manual", "attachments", "promoted"] as const)( |
| 158 | + "keeps the machine for %s drafts", |
| 159 | + async (kind) => { |
| 160 | + const { a, draftId, input, store } = setup(); |
| 161 | + if (kind === "manual") store.setDraftThreadContext(draftId, { environmentSelection: "manual" }); |
| 162 | + const guardedInput = { |
| 163 | + ...input, |
| 164 | + automaticEnvironment: kind !== "manual", |
| 165 | + composerHasAttachments: kind === "attachments", |
| 166 | + draftThread: |
| 167 | + kind === "promoted" |
| 168 | + ? { |
| 169 | + ...input.draftThread!, |
| 170 | + promotedTo: { environmentId: a, threadId: input.draftThread!.threadId }, |
| 171 | + } |
| 172 | + : input.draftThread, |
| 173 | + }; |
| 174 | + await using screen = await render(<Harness input={guardedInput} />); |
| 175 | + await screen.getByRole("button", { name: "Send" }).click(); |
| 176 | + expect(resources.refreshSelection).not.toHaveBeenCalled(); |
| 177 | + expect(store.getDraftSession(draftId)?.environmentId).toBe(a); |
| 178 | + }, |
| 179 | +); |
| 180 | + |
| 181 | +it("does not reuse a stored choice when refreshed resources have no winner", async () => { |
| 182 | + const { a, input } = setup(); |
| 183 | + resources.refreshSelection.mockResolvedValue(null); |
| 184 | + const onPrepared = vi.fn(); |
| 185 | + await using screen = await render(<Harness input={input} onPrepared={onPrepared} />); |
| 186 | + await screen.getByRole("button", { name: "Send" }).click(); |
| 187 | + await expect.element(screen.getByText(a)).toBeInTheDocument(); |
| 188 | + await vi.waitFor(() => expect(onPrepared).toHaveBeenCalledWith(false)); |
| 189 | +}); |
| 190 | + |
| 191 | +it("abandons a refresh when the draft changes while resources are in flight", async () => { |
| 192 | + const { a, b, draftId, input, store } = setup(); |
| 193 | + let resolve!: (environmentId: EnvironmentId) => void; |
| 194 | + resources.refreshSelection.mockReturnValue( |
| 195 | + new Promise<EnvironmentId>((done) => { |
| 196 | + resolve = done; |
| 197 | + }), |
| 198 | + ); |
| 199 | + await using screen = await render(<Harness input={input} />); |
| 200 | + await screen.getByRole("button", { name: "Send" }).click(); |
| 201 | + await act(async () => { |
| 202 | + store.setPrompt(draftId, "Edited while checking"); |
| 203 | + resolve(b); |
| 204 | + }); |
| 205 | + await expect.element(screen.getByText(a)).toBeInTheDocument(); |
| 206 | + expect(store.getComposerDraft(draftId)?.prompt).toBe("Edited while checking"); |
| 207 | +}); |
0 commit comments