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* Effect.fail(
285 new ProviderSessionManager.ProviderSessionReleaseError({
286 providerSessionId,
287 reason,
288 cause: new Error("private process diagnostics"),
289 }),
290 );
291 }
292 released.push(providerSessionId);
293 for (const [threadId, list] of sessions) {
294 const remaining = list.filter((session) => session.id !== providerSessionId);
295 if (remaining.length === 0) sessions.delete(threadId);
296 else sessions.set(threadId, remaining);
297 }
298 }),
299 }),
300 ),
301 ),
302 );
303 return {
304 service,
305 actions,
306 released,
307 sessions,
308 auth,
309 addInstance: (instance: ProviderInstance) => instances.push(instance),
310 replaceInstance: (replacement: ProviderInstance) => {
311 const index = instances.findIndex(
312 (instance) => instance.instanceId === replacement.instanceId,
313 );
314 assert.isAtLeast(index, 0);
315 instances[index] = replacement;
316 },
317 replaceAuth: (next: ProviderAuthService.ProviderAuthController) => {
318 instances[0] = makeInstance({ instanceId, enabled: input.enabled ?? true, auth: next });
319 },
320 };
321});
322
323const makeStreamingController = Effect.fn("ProviderAuthService.test.makeStreamingController")(
324 function* (flowOwner: string) {
325 const state = yield* SubscriptionRef.make(idleAuthState);
326 const close = yield* Deferred.make<void>();
327 const closedSubscriptions = yield* Queue.unbounded<string>();
328 const unused = () => Effect.die("Unexpected auth operation in a subscription test.");
329 const auth: ProviderAuthService.ProviderAuthController = {
330 start: unused,
331 complete: unused,
332 cancel: unused,
333 logout: unused,
334 subscribe: (ownerSessionId) =>
335 SubscriptionRef.changes(state).pipe(
336 Stream.map((current) => (ownerSessionId === flowOwner ? current : idleAuthState)),
337 Stream.interruptWhen(Deferred.await(close)),
338 Stream.ensuring(Queue.offer(closedSubscriptions, ownerSessionId)),
339 ),
340 };
341 return {
342 auth,
343 state,
344 closedSubscriptions,
345 close: Deferred.succeed(close, undefined),
346 };
347 },
348);
349
350const makeSubscriptionHarness = Effect.fn("ProviderAuthService.test.makeSubscriptionHarness")(
351 function* (initial: ProviderInstance, replaceDuringFirstLookup?: ProviderInstance) {
352 const changes = yield* PubSub.unbounded<void>();
353 let current: ProviderInstance | undefined = initial;
354 let pendingReplacement = replaceDuringFirstLookup;
355 let subscribed = false;
356 const service = yield* ProviderAuthService.makeProviderAuthService.pipe(
357 Effect.provide(
358 Layer.mergeAll(
359 Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({
360 subscribeChanges: Effect.gen(function* () {
361 const subscription = yield* PubSub.subscribe(changes);
362 subscribed = true;
363 return subscription;
364 }),
365 getInstance: () =>
366 Effect.gen(function* () {
367 const instance = current;
368 if (pendingReplacement) {
369 assert.isTrue(subscribed, "Registry changes must be subscribed before lookup.");
370 current = pendingReplacement;
371 pendingReplacement = undefined;
372 yield* PubSub.publish(changes, undefined);
373 }
374 return instance;
375 }),
376 }),
377 Layer.mock(ProjectionStore.ProjectionStoreV2)({}),
378 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}),
379 ),
380 ),
381 );
382 return {
383 service,
384 replace: Effect.fn(function* (replacement: ProviderInstance | undefined) {
385 current = replacement;
386 yield* PubSub.publish(changes, undefined);
387 }),
388 };
389 },
390);
391
392const observeAuth = Effect.fn("ProviderAuthService.test.observeAuth")(function* (
393 stream: Stream.Stream<ProviderAuthState, ProviderSetupError>,
394) {
395 const states = yield* Queue.unbounded<ProviderAuthState>();
396 const fiber = yield* stream.pipe(
397 Stream.runForEach((state) => Queue.offer(states, state)),
398 Effect.forkScoped,
399 );
400 return { states, fiber };
401});
402
403describe("ProviderAuthService", () => {
404 it.effect(
405 "stops sessions sharing credentials and invalidates their processes before logout",
406 () =>
407 Effect.gen(function* () {
408 const { service, actions, sessions } = yield* makeHarness({
409 sharedCredentials: true,
410 ...sessionThreads([
411 makeSession("target"),
412 makeSession("shared", "ready", otherInstanceId),
413 makeSession("unrelated", "ready", unsupportedInstanceId),
414 ]),
415 });
416 yield* service.logout({ instanceId });
417 assert.deepStrictEqual([...sessions.keys()], [ThreadId.make("unrelated")]);
418 assert.isBelow(actions.indexOf("stop:shared"), actions.indexOf("invalidate-shared"));
419 assert.isBelow(actions.indexOf("invalidate-shared"), actions.indexOf("native-logout"));
420 }),
421 );
422 it.effect("rejects overlapping changes to a shared sign-in", () =>
423 Effect.gen(function* () {
424 const { service, actions } = yield* makeHarness({
425 sharedCredentials: true,
426 sharedBusy: true,
427 });
428 for (const task of [service.start({ instanceId }, owner), service.logout({ instanceId })]) {
429 const error = yield* task.pipe(Effect.flip);
430 assert.include(error.detail, "shared sign-in");
431 }
432 assert.deepStrictEqual(actions, []);
433 }),
434 );
435 it.effect("routes typed interactions to the flow owner and rejects unsupported controllers", () =>
436 Effect.gen(function* () {
437 const { service, actions } = yield* makeHarness({ responds: true });
438 yield* service.start({ instanceId }, owner);
439 const request = {
440 instanceId,
441 flowId,
442 interactionId: "consent",
443 response: { type: "browser" as const, action: "accept" as const },
444 };
445 const rejected = yield* service.respond(request, otherOwner).pipe(Effect.flip);
446 assert.strictEqual(rejected.operation, "respond");
447 yield* service.respond(request, owner);
448 assert.strictEqual(actions.at(-1), "respond:browser");
449 const unsupported = yield* makeHarness();
450 const error = yield* unsupported.service.respond(request, owner).pipe(Effect.flip);
451 assert.include(error.detail, "does not accept");
452 }),
453 );
454
455 it.effect("keeps sign-in state private and accepts the owner's redirect URL", () =>
456 Effect.gen(function* () {
457 const { service } = yield* makeHarness();
458 const waiting = yield* service.start({ instanceId }, owner);
459 const ownerStates = yield* service
460 .subscribe({ instanceId }, owner)
461 .pipe(Stream.take(1), Stream.runCollect);
462 const otherStates = yield* service
463 .subscribe({ instanceId }, otherOwner)
464 .pipe(Stream.take(1), Stream.runCollect);
465
466 assert.deepStrictEqual(ownerStates, [waiting]);
467 assert.strictEqual(otherStates[0]?.authorizationUrl, null);
468 assert.strictEqual(otherStates[0]?.flowId, null);
469
470 const otherError = yield* Effect.flip(
471 service.complete({ instanceId, flowId, callbackUrl }, otherOwner),
472 );
473 assert.strictEqual(otherError.operation, "complete");
474 const complete = yield* service.complete({ instanceId, flowId, callbackUrl }, owner);
475 assert.strictEqual(complete.phase, "succeeded");
476 assert.strictEqual(complete.authorizationUrl, null);
477 }),
478 );
479
480 it.effect("lets only the flow owner cancel sign-in", () =>
481 Effect.gen(function* () {
482 const { service } = yield* makeHarness();
483 yield* service.start({ instanceId }, owner);
484 const error = yield* Effect.flip(service.cancel({ instanceId, flowId }, otherOwner));
485 assert.strictEqual(error.operation, "cancel");
486
487 const cancelled = yield* service.cancel({ instanceId, flowId }, owner);
488 assert.strictEqual(cancelled.phase, "cancelled");
489 assert.strictEqual(cancelled.authorizationUrl, null);
490 }),
491 );
492
493 it.effect.each([
494 { change: "enable", initialEnabled: false, closeBeforeReplacement: true },
495 { change: "config", initialEnabled: true, closeBeforeReplacement: false },
496 ])(
497 "keeps private auth subscriptions current after an instance $change change",
498 ({ initialEnabled, closeBeforeReplacement }) =>
499 Effect.gen(function* () {
500 const first = yield* makeStreamingController(owner);
501 const replacement = yield* makeStreamingController(otherOwner);
502 yield* SubscriptionRef.set(first.state, waitingAuthState);
503 const { service, replace } = yield* makeSubscriptionHarness(
504 makeInstance({ instanceId, enabled: initialEnabled, auth: first.auth }),
505 );
506 const firstClient = yield* observeAuth(service.subscribe({ instanceId }, owner));
507 const secondClient = yield* observeAuth(service.subscribe({ instanceId }, otherOwner));
508 assert.deepStrictEqual(yield* Queue.take(firstClient.states), waitingAuthState);
509 assert.deepStrictEqual(yield* Queue.take(secondClient.states), idleAuthState);
510
511 if (closeBeforeReplacement) {
512 yield* first.close;
513 const closed = yield* Queue.takeN(first.closedSubscriptions, 2);
514 assert.deepStrictEqual(new Set(closed), new Set([owner, otherOwner]));
515 }
516 yield* replace(makeInstance({ instanceId, enabled: true, auth: replacement.auth }));
517 assert.deepStrictEqual(yield* Queue.take(firstClient.states), idleAuthState);
518 assert.deepStrictEqual(yield* Queue.take(secondClient.states), idleAuthState);
519 if (!closeBeforeReplacement) {
520 const closed = yield* Queue.takeN(first.closedSubscriptions, 2);
521 assert.deepStrictEqual(new Set(closed), new Set([owner, otherOwner]));
522 }
523
524 const staleState: ProviderAuthState = { ...idleAuthState, phase: "cancelled" };
525 yield* SubscriptionRef.set(first.state, staleState);
526 const newWaiting: ProviderAuthState = {
527 ...waitingAuthState,
528 flowId: "replacement-flow",
529 authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=replacement-state",
530 };
531 yield* SubscriptionRef.set(replacement.state, newWaiting);
532 assert.deepStrictEqual(yield* Queue.take(firstClient.states), idleAuthState);
533 assert.deepStrictEqual(yield* Queue.take(secondClient.states), newWaiting);
534 }),
535 );
536
537 it.effect("does not miss a replacement during the first instance lookup", () =>
538 Effect.gen(function* () {
539 const first = yield* makeStreamingController(owner);
540 const replacement = yield* makeStreamingController(owner);
541 yield* SubscriptionRef.set(replacement.state, waitingAuthState);
542 const { service } = yield* makeSubscriptionHarness(
543 makeInstance({ instanceId, enabled: false, auth: first.auth }),
544 makeInstance({ instanceId, enabled: true, auth: replacement.auth }),
545 );
546
547 const states = yield* service.subscribe({ instanceId }, owner).pipe(
548 Stream.filter((state) => state.phase === "waiting"),
549 Stream.take(1),
550 Stream.runCollect,
551 );
552
553 assert.deepStrictEqual(states, [waitingAuthState]);
554 }),
555 );
556
557 it.effect("ends the subscription with a setup error when the instance is removed", () =>
558 Effect.gen(function* () {
559 const controller = yield* makeStreamingController(owner);
560 const { service, replace } = yield* makeSubscriptionHarness(
561 makeInstance({ instanceId, enabled: true, auth: controller.auth }),
562 );
563 const { states, fiber } = yield* observeAuth(service.subscribe({ instanceId }, owner));
564 assert.deepStrictEqual(yield* Queue.take(states), idleAuthState);
565
566 yield* replace(undefined);
567 const error = yield* Effect.flip(Fiber.join(fiber));
568
569 assert.instanceOf(error, ProviderSetupError);
570 assert.strictEqual(error.instanceId, instanceId);
571 assert.strictEqual(error.operation, "subscribe");
572 assert.include(error.detail, "no longer available");
573 assert.strictEqual(yield* Queue.take(controller.closedSubscriptions), owner);
574 }),
575 );
576
577 it.effect.each([
578 { id: ProviderInstanceId.make("missing"), detail: "no longer available" },
579 { id: unsupportedInstanceId, detail: "does not support sign-in" },
580 ])("rejects setup for unavailable or unsupported instance $id", ({ id, detail }) =>
581 Effect.gen(function* () {
582 const { service, actions } = yield* makeHarness();
583 const operations: Effect.Effect<
584 ProviderAuthState | ReadonlyArray<ProviderAuthState>,
585 ProviderSetupError
586 >[] = [
587 service.start({ instanceId: id }, owner),
588 service.complete({ instanceId: id, flowId, callbackUrl }, owner),
589 service.cancel({ instanceId: id, flowId }, owner),
590 service.logout({ instanceId: id }),
591 Stream.runCollect(service.subscribe({ instanceId: id }, owner)),
592 ];
593 for (const operation of operations) {
594 const error = yield* Effect.flip(operation);
595 assert.instanceOf(error, ProviderSetupError);
596 assert.strictEqual(error.instanceId, id);
597 assert.include(error.detail, detail);
598 }
599 assert.deepStrictEqual(actions, []);
600 }),
601 );
602
603 it.effect("stops every live session on the instance before native logout", () =>
604 Effect.gen(function* () {
605 const { service, actions, released } = yield* makeHarness({
606 threads: [
607 makeThread("running"),
608 makeThread("starting"),
609 makeThread("idle", { active: false }),
610 makeThread("other-instance", { providerInstanceId: otherInstanceId }),
611 ],
612 sessions: new Map([
613 [
614 ThreadId.make("running"),
615 [
616 makeSession("running-session", "running"),
617 makeSession("stopped-session", "stopped"),
618 makeSession("errored-session", "error"),
619 makeSession("foreign-session", "ready", otherInstanceId),
620 ],
621 ],
622 [ThreadId.make("starting"), [makeSession("starting-session", "starting")]],
623 [ThreadId.make("idle"), [makeSession("idle-session")]],
624 [
625 ThreadId.make("other-instance"),
626 [makeSession("other-session", "ready", otherInstanceId)],
627 ],
628 ]),
629 });
630 const state = yield* service.logout({ instanceId });
631
632 assert.strictEqual(state.phase, "idle");
633 assert.deepStrictEqual(actions, [
634 "close-gate",
635 "list-threads",
636 "sessions:running",
637 "stop:running-session",
638 "sessions:starting",
639 "stop:starting-session",
640 "sessions:idle",
641 "stop:idle-session",
642 "sessions:other-instance",
643 "native-logout",
644 ]);
645 assert.deepStrictEqual(released, ["running-session", "starting-session", "idle-session"]);
646 }),
647 );
648
649 it.effect(
650 "releases a shared native session once after a thread's selected provider changes",
651 () =>
652 Effect.gen(function* () {
653 const shared = makeSession("shared-native-session");
654 const { service, released } = yield* makeHarness({
655 threads: [
656 makeThread("changed-selection", { providerInstanceId: otherInstanceId }),
657 makeThread("same-session"),
658 ],
659 sessions: new Map([
660 [ThreadId.make("changed-selection"), [shared]],
661 [ThreadId.make("same-session"), [shared]],
662 ]),
663 });
664
665 yield* service.logout({ instanceId });
666
667 assert.deepStrictEqual(released, [shared.id]);
668 }),
669 );
670
671 it.effect("does not log out when the thread shell cannot be read", () =>
672 Effect.gen(function* () {
673 const { service, actions } = yield* makeHarness({ shellError: true });
674 const error = yield* Effect.flip(service.logout({ instanceId }));
675
676 assert.instanceOf(error, ProviderSetupError);
677 assert.strictEqual(error.instanceId, instanceId);
678 assert.strictEqual(error.operation, "stopSessions");
679 assert.notInclude(error.detail, "private database diagnostics");
680 assert.deepStrictEqual(actions, ["close-gate", "list-threads"]);
681 }),
682 );
683
684 it.effect("does not log out or consume the command when stopping a session fails", () =>
685 Effect.gen(function* () {
686 const { service, actions, released } = yield* makeHarness({
687 threads: [makeThread("active")],
688 sessions: new Map([[ThreadId.make("active"), [makeSession("active-session")]]]),
689 stopError: true,
690 });
691 const error = yield* Effect.flip(
692 service.tryHandlePromptCommand({ instanceId, text: "/logout", hasAttachments: false }),
693 );
694
695 assert.instanceOf(error, ProviderSetupError);
696 assert.strictEqual(error.operation, "stopSessions");
697 assert.notInclude(error.detail, "private process diagnostics");
698 assert.deepStrictEqual(released, []);
699 assert.deepStrictEqual(actions, [
700 "close-gate",
701 "list-threads",
702 "sessions:active",
703 "stop:active-session",
704 ]);
705 }),
706 );
707});
708
709it.effect("queued logout prompts resolve the current controller after provider replacement", () =>
710 Effect.gen(function* () {
711 const entered = yield* Deferred.make<void>();
712 const release = yield* Deferred.make<void>();
713 const lookup = yield* Deferred.make<void>();
714 let observeLookup = false;
715 const harness = yield* makeHarness({
716 beforeLogout: Deferred.succeed(entered, undefined).pipe(
717 Effect.andThen(Deferred.await(release)),
718 ),
719 onLookup: Effect.suspend(() =>
720 observeLookup ? Deferred.succeed(lookup, undefined).pipe(Effect.asVoid) : Effect.void,
721 ),
722 });
723 const first = yield* harness.service.logout({ instanceId }).pipe(Effect.forkChild);
724 yield* Deferred.await(entered);
725 observeLookup = true;
726 const queued = yield* harness.service
727 .tryHandlePromptCommand({ instanceId, text: "/logout", hasAttachments: false })
728 .pipe(Effect.forkChild);
729 yield* Deferred.await(lookup);
730 let replacementLoggedOut = false;
731 harness.replaceAuth({
732 ...harness.auth,
733 logout: (stopSessions) =>
734 stopSessions.pipe(
735 Effect.andThen(
736 Effect.sync(() => {
737 replacementLoggedOut = true;
738 return idleAuthState;
739 }),
740 ),
741 ),
742 });
743 yield* Deferred.succeed(release, undefined);
744 yield* Fiber.join(first);
745 assert.isTrue(yield* Fiber.join(queued));
746 assert.isTrue(replacementLoggedOut);
747 assert.strictEqual(harness.actions.filter((action) => action === "native-logout").length, 1);
748 }).pipe(Effect.scoped),
749);
750
751it.effect.each(["start", "logout", "prompt"] as const)(
752 "%s uses the same credential controller for shared exclusion and mutation during replacement",
753 (action) =>
754 Effect.gen(function* () {
755 const checked = yield* Deferred.make<void>();
756 const continueCheck = yield* Deferred.make<void>();
757 const replacementPeerId = ProviderInstanceId.make("replacement-shared-peer");
758 const harness = yield* makeHarness({
759 sharedCredentials: true,
760 sharedBusyEffect: Deferred.succeed(checked, undefined).pipe(
761 Effect.andThen(Deferred.await(continueCheck)),
762 Effect.as(false),
763 ),
764 ...sessionThreads([
765 makeSession("old-shared", "ready", otherInstanceId),
766 makeSession("replacement-shared", "ready", replacementPeerId),
767 ]),
768 });
769 harness.addInstance(
770 makeInstance({
771 instanceId: replacementPeerId,
772 enabled: true,
773 auth: {
774 ...harness.auth,
775 credentialBinding: { owner: "provider", key: "replacement-binding" },
776 isChangingCredentials: Effect.succeed(true),
777 invalidate: Effect.die(
778 "The unrelated replacement credential binding must stay intact.",
779 ),
780 },
781 }),
782 );
783 const operation =
784 action === "start"
785 ? harness.service.start({ instanceId }, owner)
786 : action === "logout"
787 ? harness.service.logout({ instanceId })
788 : harness.service.tryHandlePromptCommand({
789 instanceId,
790 text: "/logout",
791 hasAttachments: false,
792 });
793 const running = yield* operation.pipe(Effect.forkChild);
794 yield* Deferred.await(checked);
795 let replacementMutations = 0;
796 harness.replaceAuth({
797 ...harness.auth,
798 credentialBinding: { owner: "provider", key: "replacement-binding" },
799 start: () =>
800 Effect.sync(() => {
801 replacementMutations++;
802 return waitingAuthState;
803 }),
804 logout: () =>
805 Effect.sync(() => {
806 replacementMutations++;
807 return idleAuthState;
808 }),
809 });
810 yield* Deferred.succeed(continueCheck, undefined);
811 yield* Fiber.join(running);
812 assert.equal(replacementMutations, 0);
813 assert.include(harness.actions, action === "start" ? "start-sign-in" : "native-logout");
814 assert.isFalse(harness.sessions.has(ThreadId.make("old-shared")));
815 assert.isTrue(harness.sessions.has(ThreadId.make("replacement-shared")));
816 const blocked = yield* Effect.flip(harness.service.logout({ instanceId }));
817 assert.include(blocked.detail, "shared sign-in");
818 assert.equal(replacementMutations, 0);
819 }).pipe(Effect.scoped),
820);
821
822it.effect.each(["selection", "drain"] as const)(
823 "preserves replacement peer sessions when credentials change during session %s",
824 (phase) =>
825 Effect.gen(function* () {
826 const entered = yield* Deferred.make<void>();
827 const proceed = yield* Deferred.make<void>();
828 const block = Deferred.succeed(entered, undefined).pipe(
829 Effect.andThen(Deferred.await(proceed)),
830 );
831 const harness = yield* makeHarness({
832 sharedCredentials: true,
833 ...sessionThreads([
834 makeSession("target-draining"),
835 makeSession("peer-replacement", "ready", otherInstanceId),
836 makeSession("peer-persisted", "running", otherInstanceId),
837 ]),
838 ...(phase === "selection" ? { beforeListSessions: block } : { beforeStop: block }),
839 });
840 const logout = yield* harness.service.logout({ instanceId }).pipe(Effect.forkChild);
841 yield* Deferred.await(entered);
842 harness.replaceInstance(
843 makeInstance({
844 instanceId: otherInstanceId,
845 enabled: true,
846 auth: {
847 ...harness.auth,
848 credentialBinding: { owner: "provider", key: "replacement-credentials" },
849 invalidate: Effect.die("The replacement peer's credentials must not be invalidated."),
850 },
851 }),
852 );
853 yield* Deferred.succeed(proceed, undefined);
854 yield* Fiber.join(logout);
855 assert.isTrue(harness.sessions.has(ThreadId.make("peer-replacement")));
856 assert.notInclude(harness.actions, "stop:peer-replacement");
857 assert.notInclude(harness.actions, "stop:peer-persisted");
858 assert.isFalse(harness.sessions.has(ThreadId.make("target-draining")));
859 assert.include(harness.actions, "native-logout");
860 }).pipe(Effect.scoped),
861);