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