The best way to control Claude Code, Codex and more from any computer or phone

main
ts 668 lines 26 KB
Raw
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import * as Layer from "effect/Layer";
4 import { assert, it } from "@effect/vitest";
5 import { ProviderInstanceId, ProviderSetupError, type ProviderAuthState } from "@t3tools/contracts";
6 import * as Deferred from "effect/Deferred";
7 import * as Effect from "effect/Effect";
8 import * as Exit from "effect/Exit";
9 import * as Fiber from "effect/Fiber";
10 import * as Option from "effect/Option";
11 import * as Scope from "effect/Scope";
12 import * as Stream from "effect/Stream";
13 import * as TestClock from "effect/testing/TestClock";
14 import * as AcpErrors from "effect-acp/errors";
15 import type * as AcpSchema from "effect-acp/compat";
16
17 import {
18 makeAntigravityAuth,
19 type AntigravityAuth,
20 type AntigravityAuthRuntime,
21 } from "./AntigravityAuth.ts";
22 import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
23
24 const instanceId = ProviderInstanceId.make("antigravity-auth-test");
25 const owner = "t3-auth-session-owner";
26 const otherOwner = "t3-auth-session-other";
27 const authorizationUrl =
28 "https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A51234%2F&state=test-state";
29 const callbackUrl = "http://127.0.0.1:51234/?state=test-state&code=test-code";
30 const loginUrl =
31 "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=https%3A%2F%2Fantigravity.google%2Foauth-callback&state=login-state";
32
33 const initialized = {
34 protocolVersion: 1,
35 authMethods: [{ id: "oauth-personal", name: "Log in with Google" }],
36 agentCapabilities: { auth: { logout: {} } },
37 } satisfies AcpSchema.InitializeResponse;
38 const started: AcpSessionRuntime.AcpSessionRuntimeStartResult = {
39 sessionId: "native-session",
40 initializeResult: initialized,
41 sessionSetupResult: {
42 sessionId: "native-session",
43 models: {
44 currentModelId: "gemini-test",
45 availableModels: [{ modelId: "gemini-test", name: "Gemini test" }],
46 },
47 },
48 modelConfigId: "model",
49 };
50
51 const phase = (auth: AntigravityAuth, value: ProviderAuthState["phase"], sessionId = owner) =>
52 auth.controller.subscribe(sessionId).pipe(
53 Stream.filter((state) => state.phase === value),
54 Stream.runHead,
55 Effect.map(Option.getOrThrow),
56 );
57
58 const makeHarness = Effect.fn("makeAuthTestHarness")(function* (
59 options: {
60 readonly interactive?: boolean;
61 readonly authorizationUrls?: ReadonlyArray<string>;
62 readonly supportsLogout?: boolean;
63 readonly beforeInitialize?: Effect.Effect<void>;
64 readonly forwardCallback?: Effect.Effect<void, ProviderSetupError>;
65 readonly codeLogin?: boolean;
66 } = {},
67 ) {
68 const loginCodes: string[] = [];
69 const loginCode = yield* Deferred.make<void>();
70 const authenticated = yield* Deferred.make<void, AcpErrors.AcpError>();
71 const discovered = yield* Deferred.make<void, AcpErrors.AcpError>();
72 const closed = yield* Deferred.make<void>();
73 const authenticateCalled = yield* Deferred.make<void>();
74 const events: string[] = [];
75 let receiveAuthorizationUrl:
76 | ((url: string) => Effect.Effect<void, AcpErrors.AcpError>)
77 | undefined;
78 let forwarded = 0;
79 let catalog = ["previous-account-model"];
80 const auth = yield* makeAntigravityAuth({
81 instanceId,
82 makeRuntime: (input) =>
83 Effect.gen(function* () {
84 receiveAuthorizationUrl = input.onAuthorizationUrl;
85 events.push("process-open");
86 yield* Effect.addFinalizer(() =>
87 Effect.gen(function* () {
88 events.push("process-close");
89 yield* Deferred.succeed(closed, undefined);
90 }),
91 );
92 // Like AcpSessionRuntime, `start` reuses one memoized initialize handshake.
93 const initialize = yield* Effect.cached(
94 Effect.gen(function* () {
95 events.push("initialize");
96 yield* options.beforeInitialize ?? Effect.void;
97 return options.supportsLogout === false
98 ? { ...initialized, agentCapabilities: {} }
99 : initialized;
100 }),
101 );
102 return {
103 initialize: () => initialize,
104 start: () =>
105 Effect.gen(function* () {
106 yield* initialize;
107 events.push("authenticate");
108 yield* Deferred.succeed(authenticateCalled, undefined);
109 if (options.interactive !== false && input.onAuthorizationUrl) {
110 for (const url of options.authorizationUrls ?? [authorizationUrl]) {
111 yield* input.onAuthorizationUrl(url);
112 }
113 }
114 yield* Deferred.await(authenticated);
115 events.push("session-new");
116 yield* Deferred.await(discovered);
117 return started;
118 }),
119 request: (method) =>
120 Effect.sync(() => {
121 events.push(method);
122 return {};
123 }),
124 } satisfies AntigravityAuthRuntime;
125 }),
126 onAuthenticated: () =>
127 Effect.sync(() => {
128 catalog = ["gemini-test"];
129 events.push("catalog-published");
130 }),
131 onSignedOut: Effect.sync(() => {
132 catalog = [];
133 events.push("catalog-cleared");
134 }),
135 forwardCallback: () =>
136 options.forwardCallback ??
137 Effect.sync(() => {
138 forwarded += 1;
139 }),
140 codeLogin: ({ onAuthorizationUrl }) =>
141 Effect.gen(function* () {
142 if (!options.codeLogin) return undefined;
143 events.push("login-open");
144 yield* Effect.addFinalizer(() => Effect.sync(() => events.push("login-close")));
145 yield* onAuthorizationUrl(loginUrl);
146 return {
147 submit: (response: string) =>
148 Effect.sync(() => loginCodes.push(response)).pipe(
149 Effect.andThen(Deferred.succeed(loginCode, undefined)),
150 Effect.asVoid,
151 ),
152 completed: Deferred.await(loginCode),
153 };
154 }),
155 });
156 return {
157 auth,
158 authenticated,
159 discovered,
160 closed,
161 authenticateCalled,
162 events,
163 catalog: () => catalog,
164 forwarded: () => forwarded,
165 loginCodes,
166 receiveAuthorizationUrl: (url: string) =>
167 Effect.suspend(() =>
168 receiveAuthorizationUrl
169 ? receiveAuthorizationUrl(url)
170 : Effect.die("Authorization URL receiver is not ready."),
171 ),
172 };
173 });
174
175 it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("AntigravityAuth", (it) => {
176 it.effect("accepts a delayed duplicate after callback completion starts", () =>
177 Effect.gen(function* () {
178 const harness = yield* makeHarness();
179 const state = yield* harness.auth.controller.start(owner);
180 yield* phase(harness.auth, "waiting");
181 yield* harness.auth.controller.complete(owner, {
182 flowId: state.flowId!,
183 callbackUrl,
184 });
185
186 yield* harness.receiveAuthorizationUrl(authorizationUrl);
187
188 yield* Deferred.succeed(harness.authenticated, undefined);
189 yield* Deferred.succeed(harness.discovered, undefined);
190 yield* phase(harness.auth, "succeeded");
191 }),
192 );
193
194 it.effect("signs in through the CLI's code login, then authenticates a fresh process", () =>
195 Effect.gen(function* () {
196 const harness = yield* makeHarness({ codeLogin: true });
197 const state = yield* harness.auth.controller.start(owner);
198 const waiting = yield* phase(harness.auth, "waiting");
199 assert.equal(waiting.authorizationUrl, loginUrl);
200 assert.equal(waiting.interaction?.type, "credentials");
201 const respond = (code: string) =>
202 harness.auth.controller.respond!(owner, {
203 instanceId,
204 flowId: state.flowId!,
205 interactionId: state.flowId!,
206 response: { type: "credentials", values: { code } },
207 });
208 for (const invalid of [callbackUrl, "two words", ""]) {
209 assert.isTrue(Exit.isFailure(yield* respond(invalid).pipe(Effect.exit)), invalid);
210 }
211 assert.equal((yield* respond("4/0Ab-code")).phase, "verifying");
212 assert.deepEqual(harness.loginCodes, ["4/0Ab-code"]);
213
214 yield* Deferred.succeed(harness.authenticated, undefined);
215 yield* Deferred.succeed(harness.discovered, undefined);
216 yield* phase(harness.auth, "succeeded");
217 assert.deepEqual(harness.events, [
218 "login-open",
219 "login-close",
220 "process-open",
221 "initialize",
222 "authenticate",
223 "session-new",
224 "catalog-published",
225 "process-close",
226 ]);
227 }),
228 );
229
230 it.effect("rejects a different second authorization URL", () =>
231 Effect.gen(function* () {
232 const harness = yield* makeHarness({
233 authorizationUrls: [authorizationUrl, `${authorizationUrl}&scope=another-request`],
234 });
235 yield* harness.auth.controller.start(owner);
236
237 const failed = yield* phase(harness.auth, "failed");
238 assert.isNull(failed.authorizationUrl);
239 assert.deepEqual(harness.catalog(), ["previous-account-model"]);
240 }),
241 );
242
243 it.effect("keeps a remote flow private and waits for native auth and catalog discovery", () =>
244 Effect.gen(function* () {
245 const harness = yield* makeHarness();
246 const state = yield* harness.auth.controller.start(owner);
247 assert.isNotNull(state.flowId);
248 const waiting = yield* phase(harness.auth, "waiting");
249 assert.equal(waiting.authorizationUrl, authorizationUrl);
250
251 const other = yield* phase(harness.auth, "waiting", otherOwner);
252 assert.isNull(other.authorizationUrl);
253 assert.isNull(other.flowId);
254 const stolen = yield* harness.auth.controller
255 .complete(otherOwner, { flowId: state.flowId!, callbackUrl })
256 .pipe(Effect.exit);
257 assert.isTrue(Exit.isFailure(stolen));
258 assert.equal(harness.forwarded(), 0);
259
260 const verifying = yield* harness.auth.controller.complete(owner, {
261 flowId: state.flowId!,
262 callbackUrl,
263 });
264 assert.equal(verifying.phase, "verifying");
265 assert.equal(harness.forwarded(), 1);
266 assert.deepEqual(harness.catalog(), ["previous-account-model"]);
267
268 yield* Deferred.succeed(harness.authenticated, undefined);
269 yield* Deferred.succeed(harness.discovered, undefined);
270 const succeeded = yield* phase(harness.auth, "succeeded");
271 assert.deepEqual(harness.catalog(), ["gemini-test"]);
272 assert.isNull(succeeded.authorizationUrl);
273 assert.isNull(succeeded.expiresAt);
274 assert.equal(harness.events.at(-1), "process-close");
275 }),
276 );
277
278 it.effect(
279 "distinguishes a post-authentication session failure without exposing its payload",
280 () =>
281 Effect.gen(function* () {
282 const harness = yield* makeHarness();
283 yield* harness.auth.controller.start(owner);
284 yield* phase(harness.auth, "waiting");
285 yield* Deferred.succeed(harness.authenticated, undefined);
286 yield* Deferred.fail(
287 harness.discovered,
288 new AcpErrors.AcpRequestError({
289 code: -32603,
290 errorMessage: `Internal error ${callbackUrl}`,
291 method: "session/new",
292 }),
293 );
294 const failed = yield* phase(harness.auth, "failed");
295 assert.equal(
296 failed.message,
297 "Antigravity authenticated, but could not initialize a session or load models.",
298 );
299 assert.isNull(failed.authorizationUrl);
300 assert.deepEqual(harness.catalog(), ["previous-account-model"]);
301 yield* Deferred.await(harness.closed);
302 }),
303 );
304
305 it.effect("does not call callback HTTP success a successful Google sign-in", () =>
306 Effect.gen(function* () {
307 const harness = yield* makeHarness();
308 const state = yield* harness.auth.controller.start(owner);
309 yield* phase(harness.auth, "waiting");
310 yield* harness.auth.controller.complete(owner, { flowId: state.flowId!, callbackUrl });
311 yield* Deferred.fail(
312 harness.authenticated,
313 AcpErrors.AcpRequestError.internalError(`access_denied ${callbackUrl}`),
314 );
315 const failed = yield* phase(harness.auth, "failed");
316 assert.include(failed.message ?? "", "not approved");
317 assert.notInclude(failed.message ?? "", "test-code");
318 assert.isNull(failed.authorizationUrl);
319 assert.deepEqual(harness.catalog(), ["previous-account-model"]);
320 yield* Deferred.await(harness.closed);
321 }),
322 );
323
324 it.effect("says Antigravity exited when its process dies during sign-in", () =>
325 Effect.gen(function* () {
326 const harness = yield* makeHarness({ interactive: false });
327 yield* harness.auth.controller.start(owner);
328 yield* Deferred.await(harness.authenticateCalled);
329 yield* Deferred.fail(
330 harness.authenticated,
331 new AcpErrors.AcpProcessExitedError({
332 signal: "SIGILL",
333 stderr: `runtime crashed ${callbackUrl}`,
334 }),
335 );
336 const failed = yield* phase(harness.auth, "failed");
337 assert.include(failed.message ?? "", "exited");
338 assert.include(failed.message ?? "", "SIGILL");
339 assert.notInclude(failed.message ?? "", "Google sign-in failed");
340 assert.notInclude(failed.message ?? "", "runtime crashed");
341 }),
342 );
343
344 it.effect("tells the user when the agent cannot reach Google", () =>
345 Effect.gen(function* () {
346 const harness = yield* makeHarness({ interactive: false });
347 yield* harness.auth.controller.start(owner);
348 yield* Deferred.await(harness.authenticateCalled);
349
350 yield* TestClock.adjust("30 seconds");
351 const stalled = yield* harness.auth.controller.subscribe(owner).pipe(
352 Stream.filter((state) => state.message?.includes("Broken IPv6") === true),
353 Stream.runHead,
354 Effect.map(Option.getOrThrow),
355 );
356 assert.equal(stalled.phase, "starting");
357
358 yield* TestClock.adjust("270 seconds");
359 const failed = yield* phase(harness.auth, "failed");
360 assert.include(failed.message ?? "", "could not reach Google");
361
362 yield* harness.auth.onSignedInElsewhere;
363 const cleared = yield* phase(harness.auth, "idle");
364 assert.isNull(cleared.message);
365 }),
366 );
367
368 it.effect("does not blame the network while the runtime is still starting", () =>
369 Effect.gen(function* () {
370 const initializing = yield* Deferred.make<void>();
371 const ready = yield* Deferred.make<void>();
372 const harness = yield* makeHarness({
373 interactive: false,
374 beforeInitialize: Deferred.succeed(initializing, undefined).pipe(
375 Effect.andThen(Deferred.await(ready)),
376 ),
377 });
378 const hasHint = harness.auth.controller.subscribe(owner).pipe(
379 Stream.runHead,
380 Effect.map((state) => Option.getOrThrow(state).message?.includes("Broken IPv6") === true),
381 );
382 yield* harness.auth.controller.start(owner);
383 yield* Deferred.await(initializing);
384
385 // A one-file runtime can take about a minute to unpack before it answers initialize.
386 yield* TestClock.adjust("60 seconds");
387 assert.isFalse(yield* hasHint);
388
389 yield* Deferred.succeed(ready, undefined);
390 yield* Deferred.await(harness.authenticateCalled);
391 yield* TestClock.adjust("29 seconds");
392 assert.isFalse(yield* hasHint);
393
394 yield* TestClock.adjust("1 second");
395 const stalled = yield* harness.auth.controller.subscribe(owner).pipe(
396 Stream.filter((state) => state.message?.includes("Broken IPv6") === true),
397 Stream.runHead,
398 Effect.map(Option.getOrThrow),
399 );
400 assert.equal(stalled.phase, "starting");
401 }),
402 );
403
404 it.effect("does not blame the network when the runtime never answers initialize", () =>
405 Effect.gen(function* () {
406 const initializing = yield* Deferred.make<void>();
407 const harness = yield* makeHarness({
408 beforeInitialize: Deferred.succeed(initializing, undefined).pipe(
409 Effect.andThen(Effect.never),
410 ),
411 });
412 yield* harness.auth.controller.start(owner);
413 yield* Deferred.await(initializing);
414 const blamesNetwork = /reach(ed)? Google|network|ipv6/i;
415
416 yield* TestClock.adjust("90 seconds");
417 const stalled = yield* harness.auth.controller.subscribe(owner).pipe(
418 Stream.filter((state) => state.message !== "Starting Google sign-in."),
419 Stream.runHead,
420 Effect.map(Option.getOrThrow),
421 );
422 assert.equal(stalled.phase, "starting");
423 assert.notMatch(stalled.message ?? "", blamesNetwork);
424 assert.match(stalled.message ?? "", /not started|stuck/i);
425
426 yield* TestClock.adjust("210 seconds");
427 const failed = yield* phase(harness.auth, "failed");
428 assert.notMatch(failed.message ?? "", blamesNetwork);
429 assert.match(failed.message ?? "", /not respond|may not run/i);
430 }),
431 );
432
433 it.effect("keeps the expired message once the Google link was shown", () =>
434 Effect.gen(function* () {
435 const harness = yield* makeHarness();
436 yield* harness.auth.controller.start(owner);
437 yield* phase(harness.auth, "waiting");
438
439 yield* TestClock.adjust("300 seconds");
440 const failed = yield* phase(harness.auth, "failed");
441 assert.equal(failed.message, "Google sign-in expired. Start sign-in again.");
442 }),
443 );
444
445 it.effect("accepts direct local or cached completion without a callback RPC", () =>
446 Effect.gen(function* () {
447 const harness = yield* makeHarness({ interactive: false });
448 yield* harness.auth.controller.start(owner);
449 yield* Deferred.succeed(harness.authenticated, undefined);
450 yield* Deferred.succeed(harness.discovered, undefined);
451 yield* phase(harness.auth, "succeeded");
452 assert.equal(harness.forwarded(), 0);
453 assert.deepEqual(harness.catalog(), ["gemini-test"]);
454 }),
455 );
456
457 it.effect("rejects mismatched callbacks without sending any HTTP request", () =>
458 Effect.gen(function* () {
459 const harness = yield* makeHarness();
460 const state = yield* harness.auth.controller.start(owner);
461 yield* phase(harness.auth, "waiting");
462 for (const invalidUrl of [
463 callbackUrl.replace("51234", "51235"),
464 callbackUrl.replace("test-state", "wrong-state"),
465 callbackUrl.replace("/?", "/other?"),
466 `${callbackUrl}&state=test-state`,
467 ]) {
468 const result = yield* harness.auth.controller
469 .complete(owner, { flowId: state.flowId!, callbackUrl: invalidUrl })
470 .pipe(Effect.exit);
471 assert.isTrue(Exit.isFailure(result));
472 }
473 assert.equal(harness.forwarded(), 0);
474 assert.equal((yield* phase(harness.auth, "waiting")).authorizationUrl, authorizationUrl);
475 yield* harness.auth.controller.cancel(owner, state.flowId!);
476 }),
477 );
478
479 it.effect("fails the flow when delivery fails after the requesting client disconnects", () =>
480 Effect.gen(function* () {
481 const deliveryGate = yield* Deferred.make<void>();
482 const harness = yield* makeHarness({
483 forwardCallback: Deferred.await(deliveryGate).pipe(
484 Effect.andThen(
485 Effect.fail(
486 new ProviderSetupError({
487 instanceId,
488 operation: "complete",
489 detail: "loopback refused",
490 }),
491 ),
492 ),
493 ),
494 });
495 const state = yield* harness.auth.controller.start(owner);
496 yield* phase(harness.auth, "waiting");
497 const request = yield* harness.auth.controller
498 .complete(owner, { flowId: state.flowId!, callbackUrl })
499 .pipe(Effect.forkScoped);
500 yield* phase(harness.auth, "verifying");
501 yield* Fiber.interrupt(request);
502 yield* Deferred.succeed(deliveryGate, undefined);
503 const failed = yield* phase(harness.auth, "failed");
504 assert.include(failed.message ?? "", "Could not deliver");
505 assert.isTrue(harness.events.includes("process-close"));
506 }),
507 );
508
509 it.effect("cancel closes the owned process without forwarding a denial", () =>
510 Effect.gen(function* () {
511 const harness = yield* makeHarness();
512 const state = yield* harness.auth.controller.start(owner);
513 yield* phase(harness.auth, "waiting");
514 const wrongOwner = yield* harness.auth.controller
515 .cancel(otherOwner, state.flowId!)
516 .pipe(Effect.exit);
517 assert.isTrue(Exit.isFailure(wrongOwner));
518 const cancelled = yield* harness.auth.controller.cancel(owner, state.flowId!);
519 assert.equal(cancelled.phase, "cancelled");
520 assert.isNull(cancelled.authorizationUrl);
521 assert.equal(harness.forwarded(), 0);
522 yield* Deferred.await(harness.closed);
523 assert.deepEqual(harness.catalog(), ["previous-account-model"]);
524 }),
525 );
526
527 it.effect("survives subscriber disconnect and does not replace a competing client's flow", () =>
528 Effect.gen(function* () {
529 const harness = yield* makeHarness();
530 const first = yield* harness.auth.controller.start(owner);
531 yield* phase(harness.auth, "waiting");
532 const second = yield* harness.auth.controller.start(owner);
533 assert.equal(first.flowId, second.flowId);
534 const competing = yield* harness.auth.controller.start(otherOwner).pipe(Effect.exit);
535 assert.isTrue(Exit.isFailure(competing));
536 const resumed = yield* phase(harness.auth, "waiting");
537 assert.equal(resumed.flowId, first.flowId);
538 assert.deepEqual(harness.events, ["process-open", "initialize", "authenticate"]);
539 yield* harness.auth.controller.cancel(owner, first.flowId!);
540 }),
541 );
542
543 it.effect("sign-out closes admission and every process before fresh native logout", () =>
544 Effect.gen(function* () {
545 const harness = yield* makeHarness();
546 const processScope = yield* Scope.make();
547 yield* Effect.addFinalizer(() => Scope.close(processScope, Exit.void));
548 const stop = Effect.gen(function* () {
549 harness.events.push("chat-close");
550 yield* Scope.close(processScope, Exit.void);
551 });
552 yield* harness.auth.withProcess(stop, Effect.void).pipe(Scope.provide(processScope));
553 const stopSessions = Effect.gen(function* () {
554 harness.events.push("sessions-stop");
555 const denied = yield* harness.auth
556 .withProcess(
557 Effect.void,
558 Effect.sync(() => harness.events.push("late-process")),
559 )
560 .pipe(Effect.scoped, Effect.exit);
561 assert.isTrue(Exit.isFailure(denied));
562 });
563 const result = yield* harness.auth.controller.logout(stopSessions);
564 assert.equal(result.phase, "idle");
565 assert.deepEqual(harness.events, [
566 "sessions-stop",
567 "chat-close",
568 "process-open",
569 "initialize",
570 "logout",
571 "catalog-cleared",
572 "process-close",
573 ]);
574 assert.deepEqual(harness.catalog(), []);
575 yield* harness.auth.withProcess(Effect.void, Effect.void).pipe(Effect.scoped);
576 }),
577 );
578
579 it.effect(
580 "sign-out interrupts startup without interrupting its caller after startup returns",
581 () =>
582 Effect.gen(function* () {
583 const harness = yield* makeHarness();
584 const entering = yield* Deferred.make<void>();
585 const continueStartup = yield* Deferred.make<void>();
586 const processScope = yield* Scope.make();
587 yield* Effect.addFinalizer(() => Scope.close(processScope, Exit.void));
588 const task = Effect.gen(function* () {
589 yield* Deferred.succeed(entering, undefined);
590 yield* Deferred.await(continueStartup);
591 harness.events.push("late-spawn");
592 });
593 const startup = yield* harness.auth
594 .withProcess(Scope.close(processScope, Exit.void), task)
595 .pipe(Scope.provide(processScope), Effect.forkScoped);
596 yield* Deferred.await(entering);
597 yield* harness.auth.controller.logout(Effect.void);
598 yield* Deferred.succeed(continueStartup, undefined);
599 assert.isTrue(Exit.isFailure(yield* Fiber.await(startup)));
600 assert.notInclude(harness.events, "late-spawn");
601 assert.include(harness.events, "logout");
602 }),
603 );
604
605 it.effect("failed session stopping still closes owned processes and skips native logout", () =>
606 Effect.gen(function* () {
607 const harness = yield* makeHarness();
608 const processScope = yield* Scope.make();
609 yield* Effect.addFinalizer(() => Scope.close(processScope, Exit.void));
610 const stop = Effect.gen(function* () {
611 harness.events.push("chat-close");
612 yield* Scope.close(processScope, Exit.void);
613 });
614 yield* harness.auth.withProcess(stop, Effect.void).pipe(Scope.provide(processScope));
615 const result = yield* harness.auth.controller
616 .logout(
617 Effect.fail(
618 new ProviderSetupError({
619 instanceId,
620 operation: "stopSessions",
621 detail: "Stop failed.",
622 }),
623 ),
624 )
625 .pipe(Effect.exit);
626 assert.isTrue(Exit.isFailure(result));
627 assert.deepEqual(harness.events, ["chat-close"]);
628 assert.deepEqual(harness.catalog(), ["previous-account-model"]);
629 }),
630 );
631
632 it.effect("finishes sign-out when the requesting client disconnects", () =>
633 Effect.gen(function* () {
634 const harness = yield* makeHarness();
635 const stopping = yield* Deferred.make<void>();
636 const continueStop = yield* Deferred.make<void>();
637 const request = yield* harness.auth.controller
638 .logout(
639 Effect.gen(function* () {
640 yield* Deferred.succeed(stopping, undefined);
641 yield* Deferred.await(continueStop);
642 }),
643 )
644 .pipe(Effect.forkScoped);
645 yield* Deferred.await(stopping);
646 yield* Fiber.interrupt(request);
647 yield* Deferred.succeed(continueStop, undefined);
648 const result = yield* harness.auth.controller.subscribe(owner).pipe(
649 Stream.filter((state) => state.message === "Signed out of Google."),
650 Stream.runHead,
651 Effect.map(Option.getOrThrow),
652 );
653 assert.equal(result.phase, "idle");
654 assert.deepEqual(harness.catalog(), []);
655 assert.include(harness.events, "logout");
656 }),
657 );
658
659 it.effect("does not call logout unless the official process advertises it", () =>
660 Effect.gen(function* () {
661 const harness = yield* makeHarness({ supportsLogout: false });
662 const result = yield* harness.auth.controller.logout(Effect.void).pipe(Effect.exit);
663 assert.isTrue(Exit.isFailure(result));
664 assert.deepEqual(harness.events, ["process-open", "initialize", "process-close"]);
665 assert.deepEqual(harness.catalog(), ["previous-account-model"]);
666 }),
667 );
668 });