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 { assert, describe, it } from "@effect/vitest"; |
| 2 | import { |
| 3 | ProviderDriverKind, |
| 4 | ProviderInstanceId, |
| 5 | ProviderSessionId, |
| 6 | ProviderSetupError, |
| 7 | ProviderThreadId, |
| 8 | ThreadId, |
| 9 | type OrchestrationV2ProviderSession, |
| 10 | type OrchestrationV2ThreadShell, |
| 11 | type ProviderAuthState, |
| 12 | } from "@t3tools/contracts"; |
| 13 | import * as DateTime from "effect/DateTime"; |
| 14 | import * as Effect from "effect/Effect"; |
| 15 | import * as Deferred from "effect/Deferred"; |
| 16 | import * as Fiber from "effect/Fiber"; |
| 17 | import * as Layer from "effect/Layer"; |
| 18 | import * as PubSub from "effect/PubSub"; |
| 19 | import * as Queue from "effect/Queue"; |
| 20 | import * as Stream from "effect/Stream"; |
| 21 | import * as SubscriptionRef from "effect/SubscriptionRef"; |
| 22 | |
| 23 | import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; |
| 24 | import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts"; |
| 25 | import { AcpProviderCapabilitiesV2 } from "@t3tools/provider-acp/server/adapter"; |
| 26 | import type { ProviderInstance } from "@t3tools/provider-core/server/driver"; |
| 27 | import * as ProviderAuthService from "./ProviderAuthService.ts"; |
| 28 | import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts"; |
| 29 | |
| 30 | const instanceId = ProviderInstanceId.make("antigravity-personal"); |
| 31 | const otherInstanceId = ProviderInstanceId.make("antigravity-work"); |
| 32 | const unsupportedInstanceId = ProviderInstanceId.make("codex"); |
| 33 | const driverKind = ProviderDriverKind.make("antigravity"); |
| 34 | const owner = "paired-client-owner"; |
| 35 | const otherOwner = "paired-client-other"; |
| 36 | const flowId = "test-sign-in-flow"; |
| 37 | const callbackUrl = "http://127.0.0.1:48123/?state=test-state&code=test-code"; |
| 38 | const now = "2026-09-02T00:00:00.000Z"; |
| 39 | const idleAuthState: ProviderAuthState = { |
| 40 | instanceId, |
| 41 | phase: "idle", |
| 42 | flowId: null, |
| 43 | authorizationUrl: null, |
| 44 | expiresAt: null, |
| 45 | message: null, |
| 46 | }; |
| 47 | const waitingAuthState: ProviderAuthState = { |
| 48 | ...idleAuthState, |
| 49 | phase: "waiting", |
| 50 | flowId, |
| 51 | authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=test-state", |
| 52 | expiresAt: "2026-09-02T00:05:00.000Z", |
| 53 | }; |
| 54 | |
| 55 | function makeInstance(input: { |
| 56 | instanceId: ProviderInstanceId; |
| 57 | enabled: boolean; |
| 58 | auth?: ProviderAuthService.ProviderAuthController; |
| 59 | }): ProviderInstance { |
| 60 | return { |
| 61 | ...input, |
| 62 | driverKind, |
| 63 | displayName: undefined, |
| 64 | continuationIdentity: { driverKind, continuationKey: input.instanceId }, |
| 65 | get snapshot(): never { |
| 66 | throw new Error("Auth routing must not refresh the provider snapshot."); |
| 67 | }, |
| 68 | get orchestrationAdapter(): never { |
| 69 | throw new Error("Auth routing must not start an adapter session."); |
| 70 | }, |
| 71 | get textGeneration(): never { |
| 72 | throw new Error("Auth routing must not generate text."); |
| 73 | }, |
| 74 | }; |
| 75 | } |
| 76 | |
| 77 | const nowUtc = DateTime.makeUnsafe(now); |
| 78 | |
| 79 | function makeThread( |
| 80 | thread: string, |
| 81 | input: { readonly providerInstanceId?: ProviderInstanceId; readonly active?: boolean } = {}, |
| 82 | ): OrchestrationV2ThreadShell { |
| 83 | const shell: Pick< |
| 84 | OrchestrationV2ThreadShell, |
| 85 | "id" | "providerInstanceId" | "activeProviderThreadId" |
| 86 | > = { |
| 87 | id: ThreadId.make(thread), |
| 88 | providerInstanceId: input.providerInstanceId ?? instanceId, |
| 89 | activeProviderThreadId: |
| 90 | input.active === false ? null : ProviderThreadId.make(`${thread}:native`), |
| 91 | }; |
| 92 | return shell as unknown as OrchestrationV2ThreadShell; |
| 93 | } |
| 94 | |
| 95 | function makeSession( |
| 96 | session: string, |
| 97 | status: OrchestrationV2ProviderSession["status"] = "ready", |
| 98 | providerInstanceId = instanceId, |
| 99 | ): OrchestrationV2ProviderSession { |
| 100 | return { |
| 101 | id: ProviderSessionId.make(session), |
| 102 | driver: driverKind, |
| 103 | providerInstanceId, |
| 104 | status, |
| 105 | cwd: "/workspace", |
| 106 | model: null, |
| 107 | capabilities: AcpProviderCapabilitiesV2, |
| 108 | createdAt: nowUtc, |
| 109 | updatedAt: nowUtc, |
| 110 | lastError: null, |
| 111 | }; |
| 112 | } |
| 113 | |
| 114 | function sessionThreads(list: ReadonlyArray<OrchestrationV2ProviderSession>) { |
| 115 | return { |
| 116 | threads: list.map((session) => makeThread(session.id)), |
| 117 | sessions: new Map(list.map((session) => [ThreadId.make(session.id), [session]])), |
| 118 | }; |
| 119 | } |
| 120 | |
| 121 | const makeHarness = Effect.fn("ProviderAuthService.test.makeHarness")(function* ( |
| 122 | input: { |
| 123 | enabled?: boolean; |
| 124 | threads?: ReadonlyArray<OrchestrationV2ThreadShell>; |
| 125 | sessions?: ReadonlyMap<ThreadId, ReadonlyArray<OrchestrationV2ProviderSession>>; |
| 126 | shellError?: boolean; |
| 127 | stopError?: boolean; |
| 128 | logoutError?: ProviderSetupError; |
| 129 | sharedCredentials?: boolean; |
| 130 | sharedBusy?: boolean; |
| 131 | sharedBusyEffect?: Effect.Effect<boolean>; |
| 132 | responds?: boolean; |
| 133 | beforeLogout?: Effect.Effect<void>; |
| 134 | beforeStop?: Effect.Effect<void>; |
| 135 | beforeListSessions?: Effect.Effect<void>; |
| 136 | onLookup?: Effect.Effect<void>; |
| 137 | onListThreads?: (instances: ProviderInstance[]) => void; |
| 138 | } = {}, |
| 139 | ) { |
| 140 | const actions: string[] = []; |
| 141 | const registryChanges = yield* PubSub.unbounded<void>(); |
| 142 | const threads = input.threads ?? []; |
| 143 | const sessions = new Map( |
| 144 | [...(input.sessions?.entries() ?? [])].map(([threadId, list]) => [threadId, [...list]]), |
| 145 | ); |
| 146 | const released: string[] = []; |
| 147 | const idle = idleAuthState; |
| 148 | let state = idle; |
| 149 | let flowOwner: string | undefined; |
| 150 | let gateClosed = false; |
| 151 | |
| 152 | const checkOwner = Effect.fn("ProviderAuthService.test.checkOwner")(function* ( |
| 153 | ownerSessionId: string, |
| 154 | requestedFlowId: string, |
| 155 | operation: string, |
| 156 | ) { |
| 157 | if (ownerSessionId !== flowOwner || requestedFlowId !== state.flowId) { |
| 158 | return yield* new ProviderSetupError({ |
| 159 | instanceId, |
| 160 | operation, |
| 161 | detail: "This sign-in belongs to another client or has expired.", |
| 162 | }); |
| 163 | } |
| 164 | }); |
| 165 | |
| 166 | const auth: ProviderAuthService.ProviderAuthController = { |
| 167 | ...(input.sharedCredentials |
| 168 | ? { credentialBinding: { owner: "provider" as const, key: "shared" } } |
| 169 | : {}), |
| 170 | ...(input.responds |
| 171 | ? { |
| 172 | respond: Effect.fn(function* (ownerSessionId, request) { |
| 173 | yield* checkOwner(ownerSessionId, request.flowId, "respond"); |
| 174 | actions.push(`respond:${request.response.type}`); |
| 175 | return state; |
| 176 | }), |
| 177 | } |
| 178 | : {}), |
| 179 | start: Effect.fn(function* (ownerSessionId, stopSessions) { |
| 180 | gateClosed = true; |
| 181 | actions.push("close-gate"); |
| 182 | yield* stopSessions ?? Effect.void; |
| 183 | flowOwner = ownerSessionId; |
| 184 | state = waitingAuthState; |
| 185 | actions.push("start-sign-in"); |
| 186 | return state; |
| 187 | }), |
| 188 | complete: Effect.fn(function* (ownerSessionId, request) { |
| 189 | yield* checkOwner(ownerSessionId, request.flowId, "complete"); |
| 190 | if (request.callbackUrl !== callbackUrl) { |
| 191 | return yield* new ProviderSetupError({ |
| 192 | instanceId, |
| 193 | operation: "complete", |
| 194 | detail: "The redirect URL does not match this sign-in.", |
| 195 | }); |
| 196 | } |
| 197 | state = { ...idle, flowId, phase: "succeeded" }; |
| 198 | return state; |
| 199 | }), |
| 200 | cancel: Effect.fn(function* (ownerSessionId, requestedFlowId) { |
| 201 | yield* checkOwner(ownerSessionId, requestedFlowId, "cancel"); |
| 202 | state = { ...idle, flowId, phase: "cancelled" }; |
| 203 | return state; |
| 204 | }), |
| 205 | logout: Effect.fn(function* (stopSessions) { |
| 206 | gateClosed = true; |
| 207 | actions.push("close-gate"); |
| 208 | yield* stopSessions; |
| 209 | if (input.logoutError) return yield* input.logoutError; |
| 210 | yield* input.beforeLogout ?? Effect.void; |
| 211 | actions.push("native-logout"); |
| 212 | state = idle; |
| 213 | flowOwner = undefined; |
| 214 | return state; |
| 215 | }), |
| 216 | subscribe: (ownerSessionId) => |
| 217 | Stream.fromEffect(Effect.sync(() => (ownerSessionId === flowOwner ? state : idle))), |
| 218 | isLogoutPrompt: (text, hasAttachments) => !hasAttachments && text.trim() === "/logout", |
| 219 | }; |
| 220 | const instances = [ |
| 221 | makeInstance({ instanceId, enabled: input.enabled ?? true, auth }), |
| 222 | makeInstance({ instanceId: unsupportedInstanceId, enabled: true }), |
| 223 | ...(input.sharedCredentials |
| 224 | ? [ |
| 225 | makeInstance({ |
| 226 | instanceId: otherInstanceId, |
| 227 | enabled: true, |
| 228 | auth: { |
| 229 | ...auth, |
| 230 | isChangingCredentials: |
| 231 | input.sharedBusyEffect ?? Effect.succeed(input.sharedBusy ?? false), |
| 232 | invalidate: Effect.sync(() => { |
| 233 | actions.push("invalidate-shared"); |
| 234 | }), |
| 235 | }, |
| 236 | }), |
| 237 | ] |
| 238 | : []), |
| 239 | ]; |
| 240 | const service = yield* ProviderAuthService.makeProviderAuthService.pipe( |
| 241 | Effect.provide( |
| 242 | Layer.mergeAll( |
| 243 | Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({ |
| 244 | getInstance: (id) => |
| 245 | Effect.gen(function* () { |
| 246 | const found = instances.find((instance) => instance.instanceId === id); |
| 247 | yield* input.onLookup ?? Effect.void; |
| 248 | return found; |
| 249 | }), |
| 250 | listInstances: Effect.succeed(instances), |
| 251 | subscribeChanges: PubSub.subscribe(registryChanges), |
| 252 | }), |
| 253 | Layer.mock(ProjectionStore.ProjectionStoreV2)({ |
| 254 | getRecoveryThreadIds: () => |
| 255 | Effect.gen(function* () { |
| 256 | assert.isTrue(gateClosed); |
| 257 | actions.push("list-threads"); |
| 258 | input.onListThreads?.(instances); |
| 259 | yield* input.beforeListSessions ?? Effect.void; |
| 260 | return yield* input.shellError |
| 261 | ? Effect.fail( |
| 262 | new ProjectionStore.ProjectionStoreReadError({ |
| 263 | threadId: ThreadId.make("shell"), |
| 264 | cause: new Error("private database diagnostics"), |
| 265 | }), |
| 266 | ) |
| 267 | : Effect.succeed(threads.map((thread) => thread.id)); |
| 268 | }), |
| 269 | getThreadRecords: (threadId) => |
| 270 | Effect.sync(() => { |
| 271 | actions.push(`sessions:${threadId}`); |
| 272 | return { |
| 273 | providerSessions: sessions.get(threadId) ?? [], |
| 274 | } as never; |
| 275 | }), |
| 276 | }), |
| 277 | Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ |
| 278 | release: ({ providerSessionId, reason }) => |
| 279 | Effect.gen(function* () { |
| 280 | assert.isTrue(gateClosed); |
| 281 | actions.push(`stop:${providerSessionId}`); |
| 282 | yield* input.beforeStop ?? Effect.void; |
| 283 | if (input.stopError) { |
| 284 | return yield* new ProviderSessionManager.ProviderSessionReleaseError({ |
| 285 | providerSessionId, |
| 286 | reason, |
| 287 | cause: new Error("private process diagnostics"), |
| 288 | }); |
| 289 | } |
| 290 | released.push(providerSessionId); |
| 291 | for (const [threadId, list] of sessions) { |
| 292 | const remaining = list.filter((session) => session.id !== providerSessionId); |
| 293 | if (remaining.length === 0) sessions.delete(threadId); |
| 294 | else sessions.set(threadId, remaining); |
| 295 | } |
| 296 | }), |
| 297 | }), |
| 298 | ), |
| 299 | ), |
| 300 | ); |
| 301 | return { |
| 302 | service, |
| 303 | actions, |
| 304 | released, |
| 305 | sessions, |
| 306 | auth, |
| 307 | addInstance: (instance: ProviderInstance) => instances.push(instance), |
| 308 | replaceInstance: (replacement: ProviderInstance) => { |
| 309 | const index = instances.findIndex( |
| 310 | (instance) => instance.instanceId === replacement.instanceId, |
| 311 | ); |
| 312 | assert.isAtLeast(index, 0); |
| 313 | instances[index] = replacement; |
| 314 | }, |
| 315 | replaceAuth: (next: ProviderAuthService.ProviderAuthController) => { |
| 316 | instances[0] = makeInstance({ instanceId, enabled: input.enabled ?? true, auth: next }); |
| 317 | }, |
| 318 | }; |
| 319 | }); |
| 320 | |
| 321 | const makeStreamingController = Effect.fn("ProviderAuthService.test.makeStreamingController")( |
| 322 | function* (flowOwner: string) { |
| 323 | const state = yield* SubscriptionRef.make(idleAuthState); |
| 324 | const close = yield* Deferred.make<void>(); |
| 325 | const closedSubscriptions = yield* Queue.unbounded<string>(); |
| 326 | const unused = () => Effect.die("Unexpected auth operation in a subscription test."); |
| 327 | const auth: ProviderAuthService.ProviderAuthController = { |
| 328 | start: unused, |
| 329 | complete: unused, |
| 330 | cancel: unused, |
| 331 | logout: unused, |
| 332 | subscribe: (ownerSessionId) => |
| 333 | SubscriptionRef.changes(state).pipe( |
| 334 | Stream.map((current) => (ownerSessionId === flowOwner ? current : idleAuthState)), |
| 335 | Stream.interruptWhen(Deferred.await(close)), |
| 336 | Stream.ensuring(Queue.offer(closedSubscriptions, ownerSessionId)), |
| 337 | ), |
| 338 | }; |
| 339 | return { |
| 340 | auth, |
| 341 | state, |
| 342 | closedSubscriptions, |
| 343 | close: Deferred.succeed(close, undefined), |
| 344 | }; |
| 345 | }, |
| 346 | ); |
| 347 | |
| 348 | const makeSubscriptionHarness = Effect.fn("ProviderAuthService.test.makeSubscriptionHarness")( |
| 349 | function* (initial: ProviderInstance, replaceDuringFirstLookup?: ProviderInstance) { |
| 350 | const changes = yield* PubSub.unbounded<void>(); |
| 351 | let current: ProviderInstance | undefined = initial; |
| 352 | let pendingReplacement = replaceDuringFirstLookup; |
| 353 | let subscribed = false; |
| 354 | const service = yield* ProviderAuthService.makeProviderAuthService.pipe( |
| 355 | Effect.provide( |
| 356 | Layer.mergeAll( |
| 357 | Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({ |
| 358 | subscribeChanges: Effect.gen(function* () { |
| 359 | const subscription = yield* PubSub.subscribe(changes); |
| 360 | subscribed = true; |
| 361 | return subscription; |
| 362 | }), |
| 363 | getInstance: () => |
| 364 | Effect.gen(function* () { |
| 365 | const instance = current; |
| 366 | if (pendingReplacement) { |
| 367 | assert.isTrue(subscribed, "Registry changes must be subscribed before lookup."); |
| 368 | current = pendingReplacement; |
| 369 | pendingReplacement = undefined; |
| 370 | yield* PubSub.publish(changes, undefined); |
| 371 | } |
| 372 | return instance; |
| 373 | }), |
| 374 | }), |
| 375 | Layer.mock(ProjectionStore.ProjectionStoreV2)({}), |
| 376 | Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}), |
| 377 | ), |
| 378 | ), |
| 379 | ); |
| 380 | return { |
| 381 | service, |
| 382 | replace: Effect.fn(function* (replacement: ProviderInstance | undefined) { |
| 383 | current = replacement; |
| 384 | yield* PubSub.publish(changes, undefined); |
| 385 | }), |
| 386 | }; |
| 387 | }, |
| 388 | ); |
| 389 | |
| 390 | const observeAuth = Effect.fn("ProviderAuthService.test.observeAuth")(function* ( |
| 391 | stream: Stream.Stream<ProviderAuthState, ProviderSetupError>, |
| 392 | ) { |
| 393 | const states = yield* Queue.unbounded<ProviderAuthState>(); |
| 394 | const fiber = yield* stream.pipe( |
| 395 | Stream.runForEach((state) => Queue.offer(states, state)), |
| 396 | Effect.forkScoped, |
| 397 | ); |
| 398 | return { states, fiber }; |
| 399 | }); |
| 400 | |
| 401 | describe("ProviderAuthService", () => { |
| 402 | it.effect( |
| 403 | "stops sessions sharing credentials and invalidates their processes before logout", |
| 404 | () => |
| 405 | Effect.gen(function* () { |
| 406 | const { service, actions, sessions } = yield* makeHarness({ |
| 407 | sharedCredentials: true, |
| 408 | ...sessionThreads([ |
| 409 | makeSession("target"), |
| 410 | makeSession("shared", "ready", otherInstanceId), |
| 411 | makeSession("unrelated", "ready", unsupportedInstanceId), |
| 412 | ]), |
| 413 | }); |
| 414 | yield* service.logout({ instanceId }); |
| 415 | assert.deepStrictEqual([...sessions.keys()], [ThreadId.make("unrelated")]); |
| 416 | assert.isBelow(actions.indexOf("stop:shared"), actions.indexOf("invalidate-shared")); |
| 417 | assert.isBelow(actions.indexOf("invalidate-shared"), actions.indexOf("native-logout")); |
| 418 | }), |
| 419 | ); |
| 420 | it.effect("rejects overlapping changes to a shared sign-in", () => |
| 421 | Effect.gen(function* () { |
| 422 | const { service, actions } = yield* makeHarness({ |
| 423 | sharedCredentials: true, |
| 424 | sharedBusy: true, |
| 425 | }); |
| 426 | for (const task of [service.start({ instanceId }, owner), service.logout({ instanceId })]) { |
| 427 | const error = yield* task.pipe(Effect.flip); |
| 428 | assert.include(error.detail, "shared sign-in"); |
| 429 | } |
| 430 | assert.deepStrictEqual(actions, []); |
| 431 | }), |
| 432 | ); |
| 433 | it.effect("routes typed interactions to the flow owner and rejects unsupported controllers", () => |
| 434 | Effect.gen(function* () { |
| 435 | const { service, actions } = yield* makeHarness({ responds: true }); |
| 436 | yield* service.start({ instanceId }, owner); |
| 437 | const request = { |
| 438 | instanceId, |
| 439 | flowId, |
| 440 | interactionId: "consent", |
| 441 | response: { type: "browser" as const, action: "accept" as const }, |
| 442 | }; |
| 443 | const rejected = yield* service.respond(request, otherOwner).pipe(Effect.flip); |
| 444 | assert.strictEqual(rejected.operation, "respond"); |
| 445 | yield* service.respond(request, owner); |
| 446 | assert.strictEqual(actions.at(-1), "respond:browser"); |
| 447 | const unsupported = yield* makeHarness(); |
| 448 | const error = yield* unsupported.service.respond(request, owner).pipe(Effect.flip); |
| 449 | assert.include(error.detail, "does not accept"); |
| 450 | }), |
| 451 | ); |
| 452 | |
| 453 | it.effect("keeps sign-in state private and accepts the owner's redirect URL", () => |
| 454 | Effect.gen(function* () { |
| 455 | const { service } = yield* makeHarness(); |
| 456 | const waiting = yield* service.start({ instanceId }, owner); |
| 457 | const ownerStates = yield* service |
| 458 | .subscribe({ instanceId }, owner) |
| 459 | .pipe(Stream.take(1), Stream.runCollect); |
| 460 | const otherStates = yield* service |
| 461 | .subscribe({ instanceId }, otherOwner) |
| 462 | .pipe(Stream.take(1), Stream.runCollect); |
| 463 | |
| 464 | assert.deepStrictEqual(ownerStates, [waiting]); |
| 465 | assert.strictEqual(otherStates[0]?.authorizationUrl, null); |
| 466 | assert.strictEqual(otherStates[0]?.flowId, null); |
| 467 | |
| 468 | const otherError = yield* Effect.flip( |
| 469 | service.complete({ instanceId, flowId, callbackUrl }, otherOwner), |
| 470 | ); |
| 471 | assert.strictEqual(otherError.operation, "complete"); |
| 472 | const complete = yield* service.complete({ instanceId, flowId, callbackUrl }, owner); |
| 473 | assert.strictEqual(complete.phase, "succeeded"); |
| 474 | assert.strictEqual(complete.authorizationUrl, null); |
| 475 | }), |
| 476 | ); |
| 477 | |
| 478 | it.effect("lets only the flow owner cancel sign-in", () => |
| 479 | Effect.gen(function* () { |
| 480 | const { service } = yield* makeHarness(); |
| 481 | yield* service.start({ instanceId }, owner); |
| 482 | const error = yield* Effect.flip(service.cancel({ instanceId, flowId }, otherOwner)); |
| 483 | assert.strictEqual(error.operation, "cancel"); |
| 484 | |
| 485 | const cancelled = yield* service.cancel({ instanceId, flowId }, owner); |
| 486 | assert.strictEqual(cancelled.phase, "cancelled"); |
| 487 | assert.strictEqual(cancelled.authorizationUrl, null); |
| 488 | }), |
| 489 | ); |
| 490 | |
| 491 | it.effect.each([ |
| 492 | { change: "enable", initialEnabled: false, closeBeforeReplacement: true }, |
| 493 | { change: "config", initialEnabled: true, closeBeforeReplacement: false }, |
| 494 | ])( |
| 495 | "keeps private auth subscriptions current after an instance $change change", |
| 496 | ({ initialEnabled, closeBeforeReplacement }) => |
| 497 | Effect.gen(function* () { |
| 498 | const first = yield* makeStreamingController(owner); |
| 499 | const replacement = yield* makeStreamingController(otherOwner); |
| 500 | yield* SubscriptionRef.set(first.state, waitingAuthState); |
| 501 | const { service, replace } = yield* makeSubscriptionHarness( |
| 502 | makeInstance({ instanceId, enabled: initialEnabled, auth: first.auth }), |
| 503 | ); |
| 504 | const firstClient = yield* observeAuth(service.subscribe({ instanceId }, owner)); |
| 505 | const secondClient = yield* observeAuth(service.subscribe({ instanceId }, otherOwner)); |
| 506 | assert.deepStrictEqual(yield* Queue.take(firstClient.states), waitingAuthState); |
| 507 | assert.deepStrictEqual(yield* Queue.take(secondClient.states), idleAuthState); |
| 508 | |
| 509 | if (closeBeforeReplacement) { |
| 510 | yield* first.close; |
| 511 | const closed = yield* Queue.takeN(first.closedSubscriptions, 2); |
| 512 | assert.deepStrictEqual(new Set(closed), new Set([owner, otherOwner])); |
| 513 | } |
| 514 | yield* replace(makeInstance({ instanceId, enabled: true, auth: replacement.auth })); |
| 515 | assert.deepStrictEqual(yield* Queue.take(firstClient.states), idleAuthState); |
| 516 | assert.deepStrictEqual(yield* Queue.take(secondClient.states), idleAuthState); |
| 517 | if (!closeBeforeReplacement) { |
| 518 | const closed = yield* Queue.takeN(first.closedSubscriptions, 2); |
| 519 | assert.deepStrictEqual(new Set(closed), new Set([owner, otherOwner])); |
| 520 | } |
| 521 | |
| 522 | const staleState: ProviderAuthState = { ...idleAuthState, phase: "cancelled" }; |
| 523 | yield* SubscriptionRef.set(first.state, staleState); |
| 524 | const newWaiting: ProviderAuthState = { |
| 525 | ...waitingAuthState, |
| 526 | flowId: "replacement-flow", |
| 527 | authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=replacement-state", |
| 528 | }; |
| 529 | yield* SubscriptionRef.set(replacement.state, newWaiting); |
| 530 | assert.deepStrictEqual(yield* Queue.take(firstClient.states), idleAuthState); |
| 531 | assert.deepStrictEqual(yield* Queue.take(secondClient.states), newWaiting); |
| 532 | }), |
| 533 | ); |
| 534 | |
| 535 | it.effect("does not miss a replacement during the first instance lookup", () => |
| 536 | Effect.gen(function* () { |
| 537 | const first = yield* makeStreamingController(owner); |
| 538 | const replacement = yield* makeStreamingController(owner); |
| 539 | yield* SubscriptionRef.set(replacement.state, waitingAuthState); |
| 540 | const { service } = yield* makeSubscriptionHarness( |
| 541 | makeInstance({ instanceId, enabled: false, auth: first.auth }), |
| 542 | makeInstance({ instanceId, enabled: true, auth: replacement.auth }), |
| 543 | ); |
| 544 | |
| 545 | const states = yield* service.subscribe({ instanceId }, owner).pipe( |
| 546 | Stream.filter((state) => state.phase === "waiting"), |
| 547 | Stream.take(1), |
| 548 | Stream.runCollect, |
| 549 | ); |
| 550 | |
| 551 | assert.deepStrictEqual(states, [waitingAuthState]); |
| 552 | }), |
| 553 | ); |
| 554 | |
| 555 | it.effect("ends the subscription with a setup error when the instance is removed", () => |
| 556 | Effect.gen(function* () { |
| 557 | const controller = yield* makeStreamingController(owner); |
| 558 | const { service, replace } = yield* makeSubscriptionHarness( |
| 559 | makeInstance({ instanceId, enabled: true, auth: controller.auth }), |
| 560 | ); |
| 561 | const { states, fiber } = yield* observeAuth(service.subscribe({ instanceId }, owner)); |
| 562 | assert.deepStrictEqual(yield* Queue.take(states), idleAuthState); |
| 563 | |
| 564 | yield* replace(undefined); |
| 565 | const error = yield* Effect.flip(Fiber.join(fiber)); |
| 566 | |
| 567 | assert.instanceOf(error, ProviderSetupError); |
| 568 | assert.strictEqual(error.instanceId, instanceId); |
| 569 | assert.strictEqual(error.operation, "subscribe"); |
| 570 | assert.include(error.detail, "no longer available"); |
| 571 | assert.strictEqual(yield* Queue.take(controller.closedSubscriptions), owner); |
| 572 | }), |
| 573 | ); |
| 574 | |
| 575 | it.effect.each([ |
| 576 | { id: ProviderInstanceId.make("missing"), detail: "no longer available" }, |
| 577 | { id: unsupportedInstanceId, detail: "does not support sign-in" }, |
| 578 | ])("rejects setup for unavailable or unsupported instance $id", ({ id, detail }) => |
| 579 | Effect.gen(function* () { |
| 580 | const { service, actions } = yield* makeHarness(); |
| 581 | const operations: Effect.Effect< |
| 582 | ProviderAuthState | ReadonlyArray<ProviderAuthState>, |
| 583 | ProviderSetupError |
| 584 | >[] = [ |
| 585 | service.start({ instanceId: id }, owner), |
| 586 | service.complete({ instanceId: id, flowId, callbackUrl }, owner), |
| 587 | service.cancel({ instanceId: id, flowId }, owner), |
| 588 | service.logout({ instanceId: id }), |
| 589 | Stream.runCollect(service.subscribe({ instanceId: id }, owner)), |
| 590 | ]; |
| 591 | for (const operation of operations) { |
| 592 | const error = yield* Effect.flip(operation); |
| 593 | assert.instanceOf(error, ProviderSetupError); |
| 594 | assert.strictEqual(error.instanceId, id); |
| 595 | assert.include(error.detail, detail); |
| 596 | } |
| 597 | assert.deepStrictEqual(actions, []); |
| 598 | }), |
| 599 | ); |
| 600 | |
| 601 | it.effect("stops every live session on the instance before native logout", () => |
| 602 | Effect.gen(function* () { |
| 603 | const { service, actions, released } = yield* makeHarness({ |
| 604 | threads: [ |
| 605 | makeThread("running"), |
| 606 | makeThread("starting"), |
| 607 | makeThread("idle", { active: false }), |
| 608 | makeThread("other-instance", { providerInstanceId: otherInstanceId }), |
| 609 | ], |
| 610 | sessions: new Map([ |
| 611 | [ |
| 612 | ThreadId.make("running"), |
| 613 | [ |
| 614 | makeSession("running-session", "running"), |
| 615 | makeSession("stopped-session", "stopped"), |
| 616 | makeSession("errored-session", "error"), |
| 617 | makeSession("foreign-session", "ready", otherInstanceId), |
| 618 | ], |
| 619 | ], |
| 620 | [ThreadId.make("starting"), [makeSession("starting-session", "starting")]], |
| 621 | [ThreadId.make("idle"), [makeSession("idle-session")]], |
| 622 | [ |
| 623 | ThreadId.make("other-instance"), |
| 624 | [makeSession("other-session", "ready", otherInstanceId)], |
| 625 | ], |
| 626 | ]), |
| 627 | }); |
| 628 | const state = yield* service.logout({ instanceId }); |
| 629 | |
| 630 | assert.strictEqual(state.phase, "idle"); |
| 631 | assert.deepStrictEqual(actions, [ |
| 632 | "close-gate", |
| 633 | "list-threads", |
| 634 | "sessions:running", |
| 635 | "stop:running-session", |
| 636 | "sessions:starting", |
| 637 | "stop:starting-session", |
| 638 | "sessions:idle", |
| 639 | "stop:idle-session", |
| 640 | "sessions:other-instance", |
| 641 | "native-logout", |
| 642 | ]); |
| 643 | assert.deepStrictEqual(released, ["running-session", "starting-session", "idle-session"]); |
| 644 | }), |
| 645 | ); |
| 646 | |
| 647 | it.effect( |
| 648 | "releases a shared native session once after a thread's selected provider changes", |
| 649 | () => |
| 650 | Effect.gen(function* () { |
| 651 | const shared = makeSession("shared-native-session"); |
| 652 | const { service, released } = yield* makeHarness({ |
| 653 | threads: [ |
| 654 | makeThread("changed-selection", { providerInstanceId: otherInstanceId }), |
| 655 | makeThread("same-session"), |
| 656 | ], |
| 657 | sessions: new Map([ |
| 658 | [ThreadId.make("changed-selection"), [shared]], |
| 659 | [ThreadId.make("same-session"), [shared]], |
| 660 | ]), |
| 661 | }); |
| 662 | |
| 663 | yield* service.logout({ instanceId }); |
| 664 | |
| 665 | assert.deepStrictEqual(released, [shared.id]); |
| 666 | }), |
| 667 | ); |
| 668 | |
| 669 | it.effect("does not log out when the thread shell cannot be read", () => |
| 670 | Effect.gen(function* () { |
| 671 | const { service, actions } = yield* makeHarness({ shellError: true }); |
| 672 | const error = yield* Effect.flip(service.logout({ instanceId })); |
| 673 | |
| 674 | assert.instanceOf(error, ProviderSetupError); |
| 675 | assert.strictEqual(error.instanceId, instanceId); |
| 676 | assert.strictEqual(error.operation, "stopSessions"); |
| 677 | assert.notInclude(error.detail, "private database diagnostics"); |
| 678 | assert.deepStrictEqual(actions, ["close-gate", "list-threads"]); |
| 679 | }), |
| 680 | ); |
| 681 | |
| 682 | it.effect("refuses a chat sign-out that no person sent", () => |
| 683 | Effect.gen(function* () { |
| 684 | const { service, actions } = yield* makeHarness({}); |
| 685 | const error = yield* Effect.flip( |
| 686 | service.tryHandlePromptCommand({ |
| 687 | instanceId, |
| 688 | text: "/logout", |
| 689 | hasAttachments: false, |
| 690 | sentByPerson: false, |
| 691 | }), |
| 692 | ); |
| 693 | |
| 694 | assert.strictEqual(error.operation, "logout"); |
| 695 | assert.deepStrictEqual(actions, []); |
| 696 | // Any other prompt still goes to the provider. |
| 697 | assert.isFalse( |
| 698 | yield* service.tryHandlePromptCommand({ |
| 699 | instanceId, |
| 700 | text: "hello", |
| 701 | hasAttachments: false, |
| 702 | sentByPerson: false, |
| 703 | }), |
| 704 | ); |
| 705 | }), |
| 706 | ); |
| 707 | |
| 708 | it.effect("does not log out or consume the command when stopping a session fails", () => |
| 709 | Effect.gen(function* () { |
| 710 | const { service, actions, released } = yield* makeHarness({ |
| 711 | threads: [makeThread("active")], |
| 712 | sessions: new Map([[ThreadId.make("active"), [makeSession("active-session")]]]), |
| 713 | stopError: true, |
| 714 | }); |
| 715 | const error = yield* Effect.flip( |
| 716 | service.tryHandlePromptCommand({ |
| 717 | instanceId, |
| 718 | text: "/logout", |
| 719 | hasAttachments: false, |
| 720 | sentByPerson: true, |
| 721 | }), |
| 722 | ); |
| 723 | |
| 724 | assert.instanceOf(error, ProviderSetupError); |
| 725 | assert.strictEqual(error.operation, "stopSessions"); |
| 726 | assert.notInclude(error.detail, "private process diagnostics"); |
| 727 | assert.deepStrictEqual(released, []); |
| 728 | assert.deepStrictEqual(actions, [ |
| 729 | "close-gate", |
| 730 | "list-threads", |
| 731 | "sessions:active", |
| 732 | "stop:active-session", |
| 733 | ]); |
| 734 | }), |
| 735 | ); |
| 736 | }); |
| 737 | |
| 738 | it.effect("queued logout prompts resolve the current controller after provider replacement", () => |
| 739 | Effect.gen(function* () { |
| 740 | const entered = yield* Deferred.make<void>(); |
| 741 | const release = yield* Deferred.make<void>(); |
| 742 | const lookup = yield* Deferred.make<void>(); |
| 743 | let observeLookup = false; |
| 744 | const harness = yield* makeHarness({ |
| 745 | beforeLogout: Deferred.succeed(entered, undefined).pipe( |
| 746 | Effect.andThen(Deferred.await(release)), |
| 747 | ), |
| 748 | onLookup: Effect.suspend(() => |
| 749 | observeLookup ? Deferred.succeed(lookup, undefined).pipe(Effect.asVoid) : Effect.void, |
| 750 | ), |
| 751 | }); |
| 752 | const first = yield* harness.service.logout({ instanceId }).pipe(Effect.forkChild); |
| 753 | yield* Deferred.await(entered); |
| 754 | observeLookup = true; |
| 755 | const queued = yield* harness.service |
| 756 | .tryHandlePromptCommand({ |
| 757 | instanceId, |
| 758 | text: "/logout", |
| 759 | hasAttachments: false, |
| 760 | sentByPerson: true, |
| 761 | }) |
| 762 | .pipe(Effect.forkChild); |
| 763 | yield* Deferred.await(lookup); |
| 764 | let replacementLoggedOut = false; |
| 765 | harness.replaceAuth({ |
| 766 | ...harness.auth, |
| 767 | logout: (stopSessions) => |
| 768 | stopSessions.pipe( |
| 769 | Effect.andThen( |
| 770 | Effect.sync(() => { |
| 771 | replacementLoggedOut = true; |
| 772 | return idleAuthState; |
| 773 | }), |
| 774 | ), |
| 775 | ), |
| 776 | }); |
| 777 | yield* Deferred.succeed(release, undefined); |
| 778 | yield* Fiber.join(first); |
| 779 | assert.isTrue(yield* Fiber.join(queued)); |
| 780 | assert.isTrue(replacementLoggedOut); |
| 781 | assert.strictEqual(harness.actions.filter((action) => action === "native-logout").length, 1); |
| 782 | }), |
| 783 | ); |
| 784 | |
| 785 | it.effect.each(["start", "logout", "prompt"] as const)( |
| 786 | "%s uses the same credential controller for shared exclusion and mutation during replacement", |
| 787 | (action) => |
| 788 | Effect.gen(function* () { |
| 789 | const checked = yield* Deferred.make<void>(); |
| 790 | const continueCheck = yield* Deferred.make<void>(); |
| 791 | const replacementPeerId = ProviderInstanceId.make("replacement-shared-peer"); |
| 792 | const harness = yield* makeHarness({ |
| 793 | sharedCredentials: true, |
| 794 | sharedBusyEffect: Deferred.succeed(checked, undefined).pipe( |
| 795 | Effect.andThen(Deferred.await(continueCheck)), |
| 796 | Effect.as(false), |
| 797 | ), |
| 798 | ...sessionThreads([ |
| 799 | makeSession("old-shared", "ready", otherInstanceId), |
| 800 | makeSession("replacement-shared", "ready", replacementPeerId), |
| 801 | ]), |
| 802 | }); |
| 803 | harness.addInstance( |
| 804 | makeInstance({ |
| 805 | instanceId: replacementPeerId, |
| 806 | enabled: true, |
| 807 | auth: { |
| 808 | ...harness.auth, |
| 809 | credentialBinding: { owner: "provider", key: "replacement-binding" }, |
| 810 | isChangingCredentials: Effect.succeed(true), |
| 811 | invalidate: Effect.die( |
| 812 | "The unrelated replacement credential binding must stay intact.", |
| 813 | ), |
| 814 | }, |
| 815 | }), |
| 816 | ); |
| 817 | const operation = |
| 818 | action === "start" |
| 819 | ? harness.service.start({ instanceId }, owner) |
| 820 | : action === "logout" |
| 821 | ? harness.service.logout({ instanceId }) |
| 822 | : harness.service.tryHandlePromptCommand({ |
| 823 | instanceId, |
| 824 | text: "/logout", |
| 825 | hasAttachments: false, |
| 826 | sentByPerson: true, |
| 827 | }); |
| 828 | const running = yield* operation.pipe(Effect.forkChild); |
| 829 | yield* Deferred.await(checked); |
| 830 | let replacementMutations = 0; |
| 831 | harness.replaceAuth({ |
| 832 | ...harness.auth, |
| 833 | credentialBinding: { owner: "provider", key: "replacement-binding" }, |
| 834 | start: () => |
| 835 | Effect.sync(() => { |
| 836 | replacementMutations++; |
| 837 | return waitingAuthState; |
| 838 | }), |
| 839 | logout: () => |
| 840 | Effect.sync(() => { |
| 841 | replacementMutations++; |
| 842 | return idleAuthState; |
| 843 | }), |
| 844 | }); |
| 845 | yield* Deferred.succeed(continueCheck, undefined); |
| 846 | yield* Fiber.join(running); |
| 847 | assert.equal(replacementMutations, 0); |
| 848 | assert.include(harness.actions, action === "start" ? "start-sign-in" : "native-logout"); |
| 849 | assert.isFalse(harness.sessions.has(ThreadId.make("old-shared"))); |
| 850 | assert.isTrue(harness.sessions.has(ThreadId.make("replacement-shared"))); |
| 851 | const blocked = yield* Effect.flip(harness.service.logout({ instanceId })); |
| 852 | assert.include(blocked.detail, "shared sign-in"); |
| 853 | assert.equal(replacementMutations, 0); |
| 854 | }), |
| 855 | ); |
| 856 | |
| 857 | it.effect.each(["selection", "drain"] as const)( |
| 858 | "preserves replacement peer sessions when credentials change during session %s", |
| 859 | (phase) => |
| 860 | Effect.gen(function* () { |
| 861 | const entered = yield* Deferred.make<void>(); |
| 862 | const proceed = yield* Deferred.make<void>(); |
| 863 | const block = Deferred.succeed(entered, undefined).pipe( |
| 864 | Effect.andThen(Deferred.await(proceed)), |
| 865 | ); |
| 866 | const harness = yield* makeHarness({ |
| 867 | sharedCredentials: true, |
| 868 | ...sessionThreads([ |
| 869 | makeSession("target-draining"), |
| 870 | makeSession("peer-replacement", "ready", otherInstanceId), |
| 871 | makeSession("peer-persisted", "running", otherInstanceId), |
| 872 | ]), |
| 873 | ...(phase === "selection" ? { beforeListSessions: block } : { beforeStop: block }), |
| 874 | }); |
| 875 | const logout = yield* harness.service.logout({ instanceId }).pipe(Effect.forkChild); |
| 876 | yield* Deferred.await(entered); |
| 877 | harness.replaceInstance( |
| 878 | makeInstance({ |
| 879 | instanceId: otherInstanceId, |
| 880 | enabled: true, |
| 881 | auth: { |
| 882 | ...harness.auth, |
| 883 | credentialBinding: { owner: "provider", key: "replacement-credentials" }, |
| 884 | invalidate: Effect.die("The replacement peer's credentials must not be invalidated."), |
| 885 | }, |
| 886 | }), |
| 887 | ); |
| 888 | yield* Deferred.succeed(proceed, undefined); |
| 889 | yield* Fiber.join(logout); |
| 890 | assert.isTrue(harness.sessions.has(ThreadId.make("peer-replacement"))); |
| 891 | assert.notInclude(harness.actions, "stop:peer-replacement"); |
| 892 | assert.notInclude(harness.actions, "stop:peer-persisted"); |
| 893 | assert.isFalse(harness.sessions.has(ThreadId.make("target-draining"))); |
| 894 | assert.include(harness.actions, "native-logout"); |
| 895 | }), |
| 896 | ); |