The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { RegistryContext } from "@effect/atom-react"; |
| 2 | import { |
| 3 | DEFAULT_SERVER_SETTINGS, |
| 4 | EnvironmentId, |
| 5 | ProviderInstanceId, |
| 6 | type ServerSettings, |
| 7 | type ServerSettingsPatch, |
| 8 | } from "@t3tools/contracts"; |
| 9 | import { |
| 10 | AVAILABLE_CONNECTION_STATE, |
| 11 | type SupervisorConnectionState, |
| 12 | } from "@t3tools/client-runtime/connection"; |
| 13 | import * as Cause from "effect/Cause"; |
| 14 | import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; |
| 15 | import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; |
| 16 | import type { ReactNode } from "react"; |
| 17 | import { describe, expect, it, vi } from "vite-plus/test"; |
| 18 | |
| 19 | import { act, render, type Screen } from "../../test/render"; |
| 20 | |
| 21 | const state = vi.hoisted(() => ({ |
| 22 | catalog: null as unknown as Atom.Writable<{ |
| 23 | readonly isReady: boolean; |
| 24 | readonly entries: ReadonlyMap<string, unknown>; |
| 25 | }>, |
| 26 | settings: new Map<string, unknown>(), |
| 27 | connections: new Map< |
| 28 | EnvironmentId, |
| 29 | Atom.Writable<AsyncResult.AsyncResult<SupervisorConnectionState>> |
| 30 | >(), |
| 31 | persist: vi.fn(), |
| 32 | })); |
| 33 | |
| 34 | vi.mock(import("~/connection/catalog"), async (original) => { |
| 35 | const actual = await original(); |
| 36 | const { Atom } = await import("effect/reactivity"); |
| 37 | state.catalog = Atom.keepAlive( |
| 38 | Atom.make<{ readonly isReady: boolean; readonly entries: ReadonlyMap<string, unknown> }>({ |
| 39 | isReady: true, |
| 40 | entries: new Map(), |
| 41 | }), |
| 42 | ); |
| 43 | return { |
| 44 | ...actual, |
| 45 | environmentCatalog: { |
| 46 | ...actual.environmentCatalog, |
| 47 | catalogValueAtom: state.catalog as never, |
| 48 | stateAtom: ((id: EnvironmentId) => state.connections.get(id)) as never, |
| 49 | }, |
| 50 | }; |
| 51 | }); |
| 52 | vi.mock("~/localApi", () => ({ |
| 53 | ensureLocalApi: () => ({ |
| 54 | persistence: { |
| 55 | getClientSettings: async () => ({ favorites: [{ provider, model }] }), |
| 56 | }, |
| 57 | }), |
| 58 | })); |
| 59 | |
| 60 | vi.mock(import("~/state/server"), async (original) => { |
| 61 | const actual = await original(); |
| 62 | const Effect = await import("effect/Effect"); |
| 63 | return { |
| 64 | ...actual, |
| 65 | serverEnvironment: { |
| 66 | ...actual.serverEnvironment, |
| 67 | settingsValueAtom: ((id: EnvironmentId) => state.settings.get(id)) as never, |
| 68 | updateSettings: { |
| 69 | ...actual.serverEnvironment.updateSettings, |
| 70 | run: (_registry: unknown, input: unknown) => |
| 71 | Effect.promise( |
| 72 | () => |
| 73 | state.persist(input) as Promise< |
| 74 | AsyncResult.Success<ServerSettings> | AsyncResult.Failure<ServerSettings, Error> |
| 75 | >, |
| 76 | ).pipe( |
| 77 | Effect.flatMap((result) => |
| 78 | result._tag === "Failure" |
| 79 | ? Effect.failCause(result.cause) |
| 80 | : Effect.succeed(result.value), |
| 81 | ), |
| 82 | ), |
| 83 | } as never, |
| 84 | }, |
| 85 | }; |
| 86 | }); |
| 87 | vi.mock(import("~/state/use-atom-command"), async (original) => ({ |
| 88 | ...(await original()), |
| 89 | useAtomCommand: (() => state.persist) as never, |
| 90 | })); |
| 91 | |
| 92 | import { appAtomRegistry } from "~/rpc/atomRegistry"; |
| 93 | import { |
| 94 | ensureClientSettingsHydrated, |
| 95 | startModelPreferencesMigration, |
| 96 | useToggleEnvironmentModelFavorite, |
| 97 | } from "./useSettings"; |
| 98 | |
| 99 | const primaryId = EnvironmentId.make("primary"); |
| 100 | const remoteId = EnvironmentId.make("remote"); |
| 101 | const provider = ProviderInstanceId.make("codex_work"); |
| 102 | const model = "gpt-6.1-sol"; |
| 103 | const initialSettings = { |
| 104 | ...DEFAULT_SERVER_SETTINGS, |
| 105 | favorites: [], |
| 106 | providerModelPreferences: {}, |
| 107 | } satisfies ServerSettings; |
| 108 | interface Write { |
| 109 | environmentId: EnvironmentId; |
| 110 | patch: ServerSettingsPatch; |
| 111 | finish: (success?: boolean) => void; |
| 112 | } |
| 113 | |
| 114 | const settingsAtom = (id: EnvironmentId) => |
| 115 | state.settings.get(id) as Atom.Writable<ServerSettings | null>; |
| 116 | |
| 117 | function FavoriteEditor({ |
| 118 | environmentId, |
| 119 | toggles, |
| 120 | onClicked, |
| 121 | }: { |
| 122 | environmentId: EnvironmentId; |
| 123 | toggles: Array<() => Promise<void>>; |
| 124 | onClicked: (pending: Promise<void>) => void; |
| 125 | }) { |
| 126 | const toggle = useToggleEnvironmentModelFavorite(environmentId); |
| 127 | const onClick = () => toggle(provider, model); |
| 128 | toggles.push(onClick); |
| 129 | return <button onClick={() => onClicked(onClick())}>Toggle favorite</button>; |
| 130 | } |
| 131 | |
| 132 | async function setup() { |
| 133 | await using stack = new AsyncDisposableStack(); |
| 134 | const registry = stack.adopt(AtomRegistry.make(), (registry) => registry.dispose()); |
| 135 | state.settings.clear(); |
| 136 | state.connections.clear(); |
| 137 | const durable = new Map<EnvironmentId, ServerSettings>(); |
| 138 | const toggles: Array<() => Promise<void>> = []; |
| 139 | const writes: Write[] = []; |
| 140 | let pendingClick: Promise<void> | undefined; |
| 141 | for (const id of [primaryId, remoteId]) { |
| 142 | state.settings.set(id, Atom.make<ServerSettings | null>(initialSettings)); |
| 143 | durable.set(id, initialSettings); |
| 144 | } |
| 145 | state.persist.mockReset().mockImplementation( |
| 146 | ({ |
| 147 | environmentId, |
| 148 | input, |
| 149 | }: { |
| 150 | environmentId: EnvironmentId; |
| 151 | input: { patch: ServerSettingsPatch }; |
| 152 | }) => |
| 153 | new Promise((resolve) => { |
| 154 | writes.push({ |
| 155 | environmentId, |
| 156 | patch: input.patch, |
| 157 | finish: (success = true) => { |
| 158 | if (!success) { |
| 159 | resolve(AsyncResult.failure(Cause.fail(new Error("save failed")))); |
| 160 | return; |
| 161 | } |
| 162 | const settings = applyServerSettingsPatch(durable.get(environmentId)!, input.patch); |
| 163 | durable.set(environmentId, settings); |
| 164 | resolve(AsyncResult.success(settings)); |
| 165 | }, |
| 166 | }); |
| 167 | }), |
| 168 | ); |
| 169 | |
| 170 | const environment = stack.move(); |
| 171 | let screen: Screen | undefined; |
| 172 | const show = async (ui: ReactNode) => { |
| 173 | const tree = <RegistryContext.Provider value={registry}>{ui}</RegistryContext.Provider>; |
| 174 | if (screen) await screen.rerender(tree); |
| 175 | else screen = environment.use(await render(tree)); |
| 176 | }; |
| 177 | |
| 178 | return { |
| 179 | registry, |
| 180 | durable, |
| 181 | toggles, |
| 182 | writes, |
| 183 | show, |
| 184 | mount: (environmentId = primaryId) => |
| 185 | show( |
| 186 | <FavoriteEditor |
| 187 | environmentId={environmentId} |
| 188 | toggles={toggles} |
| 189 | onClicked={(pending) => { |
| 190 | pendingClick = pending; |
| 191 | }} |
| 192 | />, |
| 193 | ), |
| 194 | click(): Promise<void> { |
| 195 | screen!.container.querySelector("button")!.click(); |
| 196 | return pendingClick!; |
| 197 | }, |
| 198 | [Symbol.asyncDispose]: () => environment.disposeAsync(), |
| 199 | }; |
| 200 | } |
| 201 | |
| 202 | describe("environment favorite toggles", () => { |
| 203 | it.each([false, true])( |
| 204 | "toggles twice before any server echo when initially favorited=%s", |
| 205 | async (initiallyFavorited) => { |
| 206 | await using fixture = await setup(); |
| 207 | const { registry, durable, writes, mount, click } = fixture; |
| 208 | const favorites = initiallyFavorited ? [{ provider, model }] : []; |
| 209 | const settings = { ...initialSettings, favorites }; |
| 210 | registry.set(settingsAtom(primaryId), settings); |
| 211 | durable.set(primaryId, settings); |
| 212 | await mount(); |
| 213 | const first = click(); |
| 214 | const second = click(); |
| 215 | await act(async () => {}); |
| 216 | expect(writes.map((write) => write.patch.setModelFavorites?.[0]?.favorite)).toEqual([ |
| 217 | !initiallyFavorited, |
| 218 | initiallyFavorited, |
| 219 | ]); |
| 220 | writes[0]!.finish(); |
| 221 | await first; |
| 222 | writes[1]!.finish(); |
| 223 | await second; |
| 224 | expect(durable.get(primaryId)!.favorites).toEqual(favorites); |
| 225 | }, |
| 226 | ); |
| 227 | |
| 228 | it("preserves an acknowledged add when a later remove fails before its echo", async () => { |
| 229 | await using fixture = await setup(); |
| 230 | const { durable, writes, mount, click } = fixture; |
| 231 | await mount(); |
| 232 | const first = click(); |
| 233 | await act(async () => {}); |
| 234 | writes[0]!.finish(); |
| 235 | await first; |
| 236 | const failed = click(); |
| 237 | await act(async () => {}); |
| 238 | writes[1]!.finish(false); |
| 239 | await failed; |
| 240 | const retry = click(); |
| 241 | await act(async () => {}); |
| 242 | writes[2]!.finish(); |
| 243 | await retry; |
| 244 | expect(durable.get(primaryId)!.favorites).toEqual([]); |
| 245 | }); |
| 246 | |
| 247 | it("does not reuse another environment's pending intent for the same model", async () => { |
| 248 | await using fixture = await setup(); |
| 249 | const { durable, writes, mount, click } = fixture; |
| 250 | await mount(); |
| 251 | const primary = click(); |
| 252 | await mount(remoteId); |
| 253 | const remote = click(); |
| 254 | await act(async () => {}); |
| 255 | writes[0]!.finish(); |
| 256 | await primary; |
| 257 | writes[1]!.finish(); |
| 258 | await remote; |
| 259 | expect(durable.get(primaryId)!.favorites).toEqual([{ provider, model }]); |
| 260 | expect(durable.get(remoteId)!.favorites).toEqual([{ provider, model }]); |
| 261 | }); |
| 262 | |
| 263 | it("reads the latest server state even when the click callback predates its echo", async () => { |
| 264 | await using fixture = await setup(); |
| 265 | const { registry, durable, toggles, writes, mount } = fixture; |
| 266 | await mount(); |
| 267 | const previousClick = toggles.at(-1)!; |
| 268 | const updated = { ...initialSettings, favorites: [{ provider, model }] }; |
| 269 | durable.set(primaryId, updated); |
| 270 | await act(() => registry.set(settingsAtom(primaryId), updated)); |
| 271 | const clicked = previousClick(); |
| 272 | await act(async () => {}); |
| 273 | writes[0]!.finish(); |
| 274 | await clicked; |
| 275 | expect(durable.get(primaryId)!.favorites).toEqual([]); |
| 276 | }); |
| 277 | }); |
| 278 | |
| 279 | describe("legacy model preferences migration", () => { |
| 280 | it.each(["succeeds", "fails"] as const)( |
| 281 | "waits for connection and retries only after reconnect when the first save %s", |
| 282 | async (outcome) => { |
| 283 | await using _fixture = await setup(); |
| 284 | const environmentId = EnvironmentId.make(`migration-${outcome}`); |
| 285 | const otherId = EnvironmentId.make(`other-${outcome}`); |
| 286 | for (const id of [environmentId, otherId]) { |
| 287 | state.settings.set( |
| 288 | id, |
| 289 | Atom.keepAlive(Atom.make<ServerSettings | null>(DEFAULT_SERVER_SETTINGS)), |
| 290 | ); |
| 291 | state.connections.set( |
| 292 | id, |
| 293 | Atom.keepAlive( |
| 294 | Atom.make<AsyncResult.AsyncResult<SupervisorConnectionState>>( |
| 295 | AsyncResult.success(AVAILABLE_CONNECTION_STATE), |
| 296 | ), |
| 297 | ), |
| 298 | ); |
| 299 | } |
| 300 | let finishFirstSave = () => {}; |
| 301 | const firstSave = new Promise((resolve) => { |
| 302 | finishFirstSave = () => |
| 303 | resolve( |
| 304 | outcome === "succeeds" |
| 305 | ? AsyncResult.success(DEFAULT_SERVER_SETTINGS) |
| 306 | : AsyncResult.failure(Cause.fail(new Error("save failed"))), |
| 307 | ); |
| 308 | }); |
| 309 | state.persist |
| 310 | .mockReturnValueOnce(firstSave) |
| 311 | .mockResolvedValue(AsyncResult.success(DEFAULT_SERVER_SETTINGS)); |
| 312 | const connect = (id: EnvironmentId, generation: number) => |
| 313 | appAtomRegistry.set( |
| 314 | state.connections.get(id)!, |
| 315 | AsyncResult.success({ |
| 316 | ...AVAILABLE_CONNECTION_STATE, |
| 317 | desired: true, |
| 318 | generation, |
| 319 | phase: "connected", |
| 320 | }), |
| 321 | ); |
| 322 | const pushSettings = (id = environmentId) => |
| 323 | appAtomRegistry.set(settingsAtom(id), { ...DEFAULT_SERVER_SETTINGS }); |
| 324 | const migration = (id: EnvironmentId) => ({ |
| 325 | environmentId: id, |
| 326 | input: { patch: { migrateModelPreferences: { favorites: [{ provider, model }] } } }, |
| 327 | }); |
| 328 | |
| 329 | appAtomRegistry.set(state.catalog, { |
| 330 | isReady: true, |
| 331 | entries: new Map([ |
| 332 | [environmentId, {}], |
| 333 | [otherId, {}], |
| 334 | ]), |
| 335 | }); |
| 336 | using _migration = { [Symbol.dispose]: startModelPreferencesMigration() }; |
| 337 | await ensureClientSettingsHydrated(); |
| 338 | pushSettings(); |
| 339 | expect(state.persist).not.toHaveBeenCalled(); |
| 340 | |
| 341 | connect(environmentId, 1); |
| 342 | expect(state.persist).toHaveBeenCalledExactlyOnceWith(migration(environmentId)); |
| 343 | pushSettings(); |
| 344 | expect(state.persist).toHaveBeenCalledTimes(1); |
| 345 | finishFirstSave(); |
| 346 | await firstSave; |
| 347 | pushSettings(); |
| 348 | pushSettings(); |
| 349 | expect(state.persist).toHaveBeenCalledTimes(1); |
| 350 | |
| 351 | connect(otherId, 7); |
| 352 | expect(state.persist).toHaveBeenLastCalledWith(migration(otherId)); |
| 353 | pushSettings(otherId); |
| 354 | expect(state.persist).toHaveBeenCalledTimes(2); |
| 355 | |
| 356 | appAtomRegistry.set( |
| 357 | state.connections.get(environmentId)!, |
| 358 | AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE, generation: 1 }), |
| 359 | ); |
| 360 | pushSettings(); |
| 361 | expect(state.persist).toHaveBeenCalledTimes(2); |
| 362 | connect(environmentId, 2); |
| 363 | pushSettings(); |
| 364 | expect(state.persist.mock.calls).toEqual([ |
| 365 | [migration(environmentId)], |
| 366 | [migration(otherId)], |
| 367 | [migration(environmentId)], |
| 368 | ]); |
| 369 | }, |
| 370 | ); |
| 371 | }); |