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