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 * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
24import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts";
25import { AcpProviderCapabilitiesV2 } from "@t3tools/provider-acp/server/adapter";
26import type { ProviderInstance } from "@t3tools/provider-core/server/driver";
27import * as ProviderAuthService from "./ProviderAuthService.ts";
28import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
29
30const instanceId = ProviderInstanceId.make("antigravity-personal");
31const otherInstanceId = ProviderInstanceId.make("antigravity-work");
32const unsupportedInstanceId = ProviderInstanceId.make("codex");
33const driverKind = ProviderDriverKind.make("antigravity");
34const owner = "paired-client-owner";
35const otherOwner = "paired-client-other";
36const flowId = "test-sign-in-flow";
37const callbackUrl = "http://127.0.0.1:48123/?state=test-state&code=test-code";
38const now = "2026-09-02T00:00:00.000Z";
39const idleAuthState: ProviderAuthState = {
40 instanceId,
41 phase: "idle",
42 flowId: null,
43 authorizationUrl: null,
44 expiresAt: null,
45 message: null,
46};
47const 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
55function 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
77const nowUtc = DateTime.makeUnsafe(now);
78
79function 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
95function 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
114function 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
121const 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
321const 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
348const 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
390const 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
401describe("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("does not log out or consume the command when stopping a session fails", () =>
683 Effect.gen(function* () {
684 const { service, actions, released } = yield* makeHarness({
685 threads: [makeThread("active")],
686 sessions: new Map([[ThreadId.make("active"), [makeSession("active-session")]]]),
687 stopError: true,
688 });
689 const error = yield* Effect.flip(
690 service.tryHandlePromptCommand({ instanceId, text: "/logout", hasAttachments: false }),
691 );
692
693 assert.instanceOf(error, ProviderSetupError);
694 assert.strictEqual(error.operation, "stopSessions");
695 assert.notInclude(error.detail, "private process diagnostics");
696 assert.deepStrictEqual(released, []);
697 assert.deepStrictEqual(actions, [
698 "close-gate",
699 "list-threads",
700 "sessions:active",
701 "stop:active-session",
702 ]);
703 }),
704 );
705});
706
707it.effect("queued logout prompts resolve the current controller after provider replacement", () =>
708 Effect.gen(function* () {
709 const entered = yield* Deferred.make<void>();
710 const release = yield* Deferred.make<void>();
711 const lookup = yield* Deferred.make<void>();
712 let observeLookup = false;
713 const harness = yield* makeHarness({
714 beforeLogout: Deferred.succeed(entered, undefined).pipe(
715 Effect.andThen(Deferred.await(release)),
716 ),
717 onLookup: Effect.suspend(() =>
718 observeLookup ? Deferred.succeed(lookup, undefined).pipe(Effect.asVoid) : Effect.void,
719 ),
720 });
721 const first = yield* harness.service.logout({ instanceId }).pipe(Effect.forkChild);
722 yield* Deferred.await(entered);
723 observeLookup = true;
724 const queued = yield* harness.service
725 .tryHandlePromptCommand({ instanceId, text: "/logout", hasAttachments: false })
726 .pipe(Effect.forkChild);
727 yield* Deferred.await(lookup);
728 let replacementLoggedOut = false;
729 harness.replaceAuth({
730 ...harness.auth,
731 logout: (stopSessions) =>
732 stopSessions.pipe(
733 Effect.andThen(
734 Effect.sync(() => {
735 replacementLoggedOut = true;
736 return idleAuthState;
737 }),
738 ),
739 ),
740 });
741 yield* Deferred.succeed(release, undefined);
742 yield* Fiber.join(first);
743 assert.isTrue(yield* Fiber.join(queued));
744 assert.isTrue(replacementLoggedOut);
745 assert.strictEqual(harness.actions.filter((action) => action === "native-logout").length, 1);
746 }).pipe(Effect.scoped),
747);
748
749it.effect.each(["start", "logout", "prompt"] as const)(
750 "%s uses the same credential controller for shared exclusion and mutation during replacement",
751 (action) =>
752 Effect.gen(function* () {
753 const checked = yield* Deferred.make<void>();
754 const continueCheck = yield* Deferred.make<void>();
755 const replacementPeerId = ProviderInstanceId.make("replacement-shared-peer");
756 const harness = yield* makeHarness({
757 sharedCredentials: true,
758 sharedBusyEffect: Deferred.succeed(checked, undefined).pipe(
759 Effect.andThen(Deferred.await(continueCheck)),
760 Effect.as(false),
761 ),
762 ...sessionThreads([
763 makeSession("old-shared", "ready", otherInstanceId),
764 makeSession("replacement-shared", "ready", replacementPeerId),
765 ]),
766 });
767 harness.addInstance(
768 makeInstance({
769 instanceId: replacementPeerId,
770 enabled: true,
771 auth: {
772 ...harness.auth,
773 credentialBinding: { owner: "provider", key: "replacement-binding" },
774 isChangingCredentials: Effect.succeed(true),
775 invalidate: Effect.die(
776 "The unrelated replacement credential binding must stay intact.",
777 ),
778 },
779 }),
780 );
781 const operation =
782 action === "start"
783 ? harness.service.start({ instanceId }, owner)
784 : action === "logout"
785 ? harness.service.logout({ instanceId })
786 : harness.service.tryHandlePromptCommand({
787 instanceId,
788 text: "/logout",
789 hasAttachments: false,
790 });
791 const running = yield* operation.pipe(Effect.forkChild);
792 yield* Deferred.await(checked);
793 let replacementMutations = 0;
794 harness.replaceAuth({
795 ...harness.auth,
796 credentialBinding: { owner: "provider", key: "replacement-binding" },
797 start: () =>
798 Effect.sync(() => {
799 replacementMutations++;
800 return waitingAuthState;
801 }),
802 logout: () =>
803 Effect.sync(() => {
804 replacementMutations++;
805 return idleAuthState;
806 }),
807 });
808 yield* Deferred.succeed(continueCheck, undefined);
809 yield* Fiber.join(running);
810 assert.equal(replacementMutations, 0);
811 assert.include(harness.actions, action === "start" ? "start-sign-in" : "native-logout");
812 assert.isFalse(harness.sessions.has(ThreadId.make("old-shared")));
813 assert.isTrue(harness.sessions.has(ThreadId.make("replacement-shared")));
814 const blocked = yield* Effect.flip(harness.service.logout({ instanceId }));
815 assert.include(blocked.detail, "shared sign-in");
816 assert.equal(replacementMutations, 0);
817 }).pipe(Effect.scoped),
818);
819
820it.effect.each(["selection", "drain"] as const)(
821 "preserves replacement peer sessions when credentials change during session %s",
822 (phase) =>
823 Effect.gen(function* () {
824 const entered = yield* Deferred.make<void>();
825 const proceed = yield* Deferred.make<void>();
826 const block = Deferred.succeed(entered, undefined).pipe(
827 Effect.andThen(Deferred.await(proceed)),
828 );
829 const harness = yield* makeHarness({
830 sharedCredentials: true,
831 ...sessionThreads([
832 makeSession("target-draining"),
833 makeSession("peer-replacement", "ready", otherInstanceId),
834 makeSession("peer-persisted", "running", otherInstanceId),
835 ]),
836 ...(phase === "selection" ? { beforeListSessions: block } : { beforeStop: block }),
837 });
838 const logout = yield* harness.service.logout({ instanceId }).pipe(Effect.forkChild);
839 yield* Deferred.await(entered);
840 harness.replaceInstance(
841 makeInstance({
842 instanceId: otherInstanceId,
843 enabled: true,
844 auth: {
845 ...harness.auth,
846 credentialBinding: { owner: "provider", key: "replacement-credentials" },
847 invalidate: Effect.die("The replacement peer's credentials must not be invalidated."),
848 },
849 }),
850 );
851 yield* Deferred.succeed(proceed, undefined);
852 yield* Fiber.join(logout);
853 assert.isTrue(harness.sessions.has(ThreadId.make("peer-replacement")));
854 assert.notInclude(harness.actions, "stop:peer-replacement");
855 assert.notInclude(harness.actions, "stop:peer-persisted");
856 assert.isFalse(harness.sessions.has(ThreadId.make("target-draining")));
857 assert.include(harness.actions, "native-logout");
858 }).pipe(Effect.scoped),
859);