@devries-cameron20 / t3code Mirror · read-only / commits / 73caab68e3
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

fix(client): commands run as Effects on the caller's fiber, so interrupting a caller stops them (#38912)

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

Julius Marminge committed Nov 19, 2026 at 12:11 UTC 73caab68e33c3a42f71b181b9d852da7badbfcb0
54 files changed +1403 -949
apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+7 -6
@@ -59,6 +59,7 @@ import {
59 } from "@react-navigation/native";
60 import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
61 import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";
62 +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
63 import { pullRequestReviewKey } from "./pullRequestReviewDrafts";
64 import {
65 pullRequestConversationThreads,
@@ -569,12 +570,12 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
570 const refresh = () =>
571 pullRefresh.onRefresh(async (signal) => {
572 const target = requestTarget(params);
572 - await composerPullRequests.invalidate
573 - .run(registry, {
574 - environmentId: target.environmentId,
575 - input: { reference: target.input },
576 - })
577 - .catch(() => undefined);
573 + await runAtomCommand(
574 + registry,
575 + composerPullRequests.invalidate,
576 + { environmentId: target.environmentId, input: { reference: target.input } },
577 + { reportFailure: false },
578 + );
579 if (signal.aborted) return;
580 if (guidesEnabled) refreshGuide();
581 stack.refresh();
apps/mobile/src/features/pull-requests/usePullRequestList.ts
+11 -5
@@ -5,7 +5,11 @@ import {
5 pullRequestPendingEditsFor,
6 } from "@t3tools/client-runtime/state/pull-requests";
7 import { RegistryContext, useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
8 -import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
8 +import {
9 + executeAtomQuery,
10 + runAtomCommand,
11 + squashAtomCommandFailure,
12 +} from "@t3tools/client-runtime/state/runtime";
13 import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
14 import * as Cause from "effect/Cause";
15 import * as Effect from "effect/Effect";
@@ -130,10 +134,12 @@ async function refreshHeads(
134 ) {
135 const responses = await Promise.allSettled(
136 targets.map(async (target) => {
133 - await composerPullRequests.invalidate.run(registry, {
134 - environmentId: target.environmentId,
135 - input: {},
136 - });
137 + await runAtomCommand(
138 + registry,
139 + composerPullRequests.invalidate,
140 + { environmentId: target.environmentId, input: {} },
141 + { reportFailure: false },
142 + );
143 if (signal.aborted) return;
144 const response = await executeAtomQuery(
145 registry,
apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
+8 -6
@@ -15,7 +15,9 @@ import { useAuth } from "@clerk/expo";
15 import { useAtomSet, useAtomValue } from "@effect/atom-react";
16 import * as Notifications from "expo-notifications";
17 import { useNavigation } from "@react-navigation/native";
18 +import * as Cause from "effect/Cause";
19 import * as Effect from "effect/Effect";
20 +import * as Exit from "effect/Exit";
21 import * as Schema from "effect/Schema";
22 import { AsyncResult } from "effect/reactivity";
23 import { useRef, useState, useSyncExternalStore } from "react";
@@ -90,12 +92,12 @@ const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(fun
92 environmentId: EnvironmentId,
93 enabled: boolean,
94 ) {
93 - const result = yield* Effect.promise(() =>
95 + const exit = yield* Effect.exit(
96 updateLiveActivityPreference.run(appAtomRegistry, { environmentId, input: enabled }),
97 );
96 - if (result._tag === "Success") return result.value;
98 + if (Exit.isSuccess(exit)) return exit.value;
99 return yield* toCloudEnvironmentLinkError(
98 - squashAtomCommandFailure(result),
100 + Cause.squash(exit.cause),
101 resolveMessage(msg("Could not update the environment's Live Activity preference.")),
102 );
103 });
@@ -104,12 +106,12 @@ const linkEnvironmentWithPreference = Effect.fn("linkEnvironmentWithPreference")
106 environmentId: EnvironmentId,
107 input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean },
108 ) {
107 - const result = yield* Effect.promise(() =>
109 + const exit = yield* Effect.exit(
110 linkLiveActivityEnvironment.run(appAtomRegistry, { environmentId, input }),
111 );
110 - if (result._tag === "Success") return;
112 + if (Exit.isSuccess(exit)) return;
113 return yield* toCloudEnvironmentLinkError(
112 - squashAtomCommandFailure(result),
114 + Cause.squash(exit.cause),
115 resolveMessage(msg("Could not configure environment relay access.")),
116 );
117 });
apps/mobile/src/features/threads/useFileChipShare.ts
+4 -1
@@ -36,7 +36,10 @@ export function useFileChipShare(
36 requestRef.current = request;
37 void (async () => {
38 if (httpBaseUrl === null) throw new Error(gt("Reconnect to the environment and try again."));
39 - const result = await createUrl({ environmentId, input: { resource: source.resource } });
39 + const result = await createUrl(
40 + { environmentId, input: { resource: source.resource } },
41 + { signal: request.signal },
42 + );
43 if (request.signal.aborted) return;
44 const url =
45 result._tag === "Success" ? resolveAssetUrl(httpBaseUrl, result.value.relativeUrl) : null;
apps/mobile/src/features/usage/usageLimitsRefresh.test.ts
+15 -8
@@ -11,15 +11,22 @@ const state = vi.hoisted(() => ({
11 throw new Error("refresh not set up");
12 },
13 }));
14 -vi.mock("../../state/server", () => ({
15 - serverEnvironment: {
16 - refreshProviders: {
17 - label: "refresh providers",
18 - run: (_registry: unknown, input: { readonly environmentId: string }) =>
19 - state.refresh(input.environmentId),
14 +vi.mock("../../state/server", async () => {
15 + const Effect = await import("effect/Effect");
16 + return {
17 + serverEnvironment: {
18 + refreshProviders: {
19 + label: "refresh providers",
20 + run: (_registry: unknown, input: { readonly environmentId: string }) =>
21 + Effect.promise(() => state.refresh(input.environmentId)).pipe(
22 + Effect.flatMap((result) =>
23 + result._tag === "Failure" ? Effect.failCause(result.cause) : Effect.void,
24 + ),
25 + ),
26 + },
27 },
21 - },
22 -}));
28 + };
29 +});
30
31 import {
32 environmentIdsKey,
apps/mobile/src/lib/attachmentUpload.test.ts
+38 -13
@@ -17,14 +17,32 @@ const mocks = vi.hoisted(() => ({
17 writeFile: vi.fn(),
18 deleteFile: vi.fn(),
19 readBase64: vi.fn(),
20 + // Verification and minting run as Effects; tests steer them with the settled results above.
21 + settledEffect: (
22 + Effect: typeof import("effect/Effect"),
23 + settle: () => Promise<{
24 + readonly _tag: string;
25 + readonly value?: unknown;
26 + readonly error?: object;
27 + }>,
28 + ) =>
29 + Effect.promise(settle).pipe(
30 + Effect.flatMap((result) =>
31 + result._tag === "Success" ? Effect.succeed(result.value) : Effect.fail(result.error),
32 + ),
33 + ),
34 }));
35
22 -vi.mock("@t3tools/client-runtime/state/runtime", () => ({
23 - createEnvironmentRpcCommand: () => Symbol("rpc-command"),
24 - executeAtomQuery: mocks.executeAtomQuery,
25 - runAtomCommand: mocks.runAtomCommand,
26 - squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error,
27 -}));
36 +vi.mock("@t3tools/client-runtime/state/runtime", async () => {
37 + const Effect = await import("effect/Effect");
38 + return {
39 + createEnvironmentRpcCommand: () => Symbol("rpc-command"),
40 + awaitAtomResult: (...args: ReadonlyArray<unknown>) =>
41 + mocks.settledEffect(Effect, () => mocks.executeAtomQuery(...args)),
42 + runAtomCommand: mocks.runAtomCommand,
43 + squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error,
44 + };
45 +});
46
47 vi.mock("../state/atom-registry", () => ({
48 appAtomRegistry: { get: mocks.readAtom },
@@ -38,12 +56,20 @@ vi.mock("../state/assets", () => ({
56 assetEnvironment: { createUrl: mocks.createAssetUrl },
57 }));
58
41 -vi.mock("../state/attachments", () => ({
42 - attachmentEnvironment: {
43 - createUploadUrl: mocks.createUploadUrl,
44 - remove: mocks.removeUpload,
45 - },
46 -}));
59 +vi.mock("../state/attachments", async () => {
60 + const Effect = await import("effect/Effect");
61 + return {
62 + attachmentEnvironment: {
63 + createUploadUrl: {
64 + run: (registry: unknown, input: unknown) =>
65 + mocks.settledEffect(Effect, () =>
66 + mocks.runAtomCommand(registry, mocks.createUploadUrl, input),
67 + ),
68 + },
69 + remove: mocks.removeUpload,
70 + },
71 + };
72 +});
73
74 vi.mock("../state/session", () => ({
75 readEnvironmentScope: () => mocks.canOperate,
@@ -449,7 +475,6 @@ describe("prepareTurnAttachments", () => {
475 sizeBytes: largeImage.sizeBytes,
476 },
477 }),
452 - expect.anything(),
478 );
479 expect(prepared.status).toBe("ready");
480 if (prepared.status !== "ready") return;
apps/mobile/src/persistence/mobile-database.ts
+6 -1
@@ -43,6 +43,7 @@ const ClientCacheSummaryRows = Schema.Array(
43
44 const MobileDatabaseOperation = Schema.Literals([
45 "open",
46 + "close",
47 "migrate",
48 "load-cache",
49 "list-cache",
@@ -127,7 +128,11 @@ const makeAvailable = Effect.gen(function* () {
128 },
129 catch: databaseError("open"),
130 }),
130 - (openDatabase) => Effect.promise(() => openDatabase.closeAsync()).pipe(Effect.ignore),
131 + (openDatabase) =>
132 + Effect.tryPromise({
133 + try: () => openDatabase.closeAsync(),
134 + catch: databaseError("close"),
135 + }).pipe(Effect.ignore),
136 );
137
138 yield* Effect.tryPromise({
apps/mobile/src/state/attachments.test.ts
+37 -31
@@ -5,7 +5,7 @@ import {
5 } from "@t3tools/contracts";
6 import { runAttachmentUploadCycle } from "@t3tools/client-runtime/state/attachments";
7 import * as Cause from "effect/Cause";
8 -import { AsyncResult, AtomRegistry } from "effect/reactivity";
8 +import { AtomRegistry } from "effect/reactivity";
9 import { describe, expect, it } from "@effect/vitest";
10 import * as Effect from "effect/Effect";
11 import * as Fiber from "effect/Fiber";
@@ -35,49 +35,55 @@ const environmentId = EnvironmentId.make("secondary");
35 const registry = AtomRegistry.make();
36 beforeEach(() => {
37 state.grantedEnvironments = new Set(["primary"]);
38 - state.create.mockReset().mockResolvedValue(
39 - AsyncResult.success({
38 + state.create.mockReset().mockReturnValue(
39 + Effect.succeed({
40 attachmentId: "pending",
41 relativeUrl: "/upload",
42 expiresAt: 1,
43 }),
44 );
45 - state.remove.mockReset().mockResolvedValue(AsyncResult.success(undefined));
45 + state.remove.mockReset().mockReturnValue(Effect.void);
46 });
47 afterEach(() => {
48 vi.restoreAllMocks();
49 });
50
51 describe("attachment mutation grants", () => {
52 - it("uses the attachment environment for both mint and deletion", async () => {
53 - const mintResult = await attachmentEnvironment.createUploadUrl.run(registry, {
54 - environmentId,
55 - input: { name: "image.png", mimeType: "image/png", sizeBytes: 1 },
56 - });
57 - const removeResult = await attachmentEnvironment.remove.run(registry, {
58 - environmentId,
59 - input: { attachmentId: "pending" },
60 - });
61 - for (const result of [mintResult, removeResult]) {
62 - expect(result._tag).toBe("Failure");
63 - if (result._tag !== "Failure") throw new Error("Expected permission denial");
64 - const error = Cause.squash<unknown>(result.cause);
65 - expect(error).toBeInstanceOf(EnvironmentAuthorizationError);
66 - expect(error).toMatchObject({ requiredScope: AuthOrchestrationOperateScope });
67 - }
68 - expect(state.create).not.toHaveBeenCalled();
69 - expect(state.remove).not.toHaveBeenCalled();
70 - state.grantedEnvironments.add("secondary");
71 - expect(
72 - (
73 - await attachmentEnvironment.remove.run(registry, {
52 + it.effect("uses the attachment environment for both mint and deletion", () =>
53 + Effect.gen(function* () {
54 + const mintResult = yield* Effect.exit(
55 + attachmentEnvironment.createUploadUrl.run(registry, {
56 + environmentId,
57 + input: { name: "image.png", mimeType: "image/png", sizeBytes: 1 },
58 + }),
59 + );
60 + const removeResult = yield* Effect.exit(
61 + attachmentEnvironment.remove.run(registry, {
62 environmentId,
63 input: { attachmentId: "pending" },
76 - })
77 - )._tag,
78 - ).toBe("Success");
79 - expect(state.remove).toHaveBeenCalledOnce();
80 - });
64 + }),
65 + );
66 + for (const result of [mintResult, removeResult]) {
67 + expect(result._tag).toBe("Failure");
68 + if (result._tag !== "Failure") throw new Error("Expected permission denial");
69 + const error = Cause.squash<unknown>(result.cause);
70 + expect(error).toBeInstanceOf(EnvironmentAuthorizationError);
71 + expect(error).toMatchObject({ requiredScope: AuthOrchestrationOperateScope });
72 + }
73 + expect(state.create).not.toHaveBeenCalled();
74 + expect(state.remove).not.toHaveBeenCalled();
75 + state.grantedEnvironments.add("secondary");
76 + expect(
77 + (yield* Effect.exit(
78 + attachmentEnvironment.remove.run(registry, {
79 + environmentId,
80 + input: { attachmentId: "pending" },
81 + }),
82 + ))._tag,
83 + ).toBe("Success");
84 + expect(state.remove).toHaveBeenCalledOnce();
85 + }),
86 + );
87
88 it.effect("blocks the upload cycle's cleanup after grant revocation", () =>
89 Effect.gen(function* () {
apps/mobile/src/state/attachments.ts
+12 -15
@@ -5,10 +5,9 @@ import {
5 EnvironmentAuthorizationError,
6 type EnvironmentId,
7 } from "@t3tools/contracts";
8 -import * as Cause from "effect/Cause";
8 +import * as Effect from "effect/Effect";
9 import { msg } from "gt-react-native";
10 import { m } from "../i18n/messages";
11 -import { AsyncResult } from "effect/reactivity";
11
12 import { connectionAtomRuntime } from "../connection/runtime";
13 import { readEnvironmentScope } from "./session";
@@ -18,19 +17,17 @@ function requireAttachmentWriteAccess<W extends { readonly environmentId: Enviro
17 ): AtomCommand<W, A, E | EnvironmentAuthorizationError> {
18 return {
19 ...command,
21 - run: async (registry, input) => {
22 - if (!readEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope)) {
23 - return AsyncResult.failure(
24 - Cause.fail(
25 - new EnvironmentAuthorizationError({
26 - message: m(msg("This connection cannot change attachments.")),
27 - requiredScope: AuthOrchestrationOperateScope,
28 - }),
29 - ),
30 - );
31 - }
32 - return command.run(registry, input);
33 - },
20 + run: (registry, input) =>
21 + Effect.suspend((): Effect.Effect<A, E | EnvironmentAuthorizationError> =>
22 + readEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope)
23 + ? command.run(registry, input)
24 + : Effect.fail(
25 + new EnvironmentAuthorizationError({
26 + message: m(msg("This connection cannot change attachments.")),
27 + requiredScope: AuthOrchestrationOperateScope,
28 + }),
29 + ),
30 + ),
31 };
32 }
33
apps/mobile/src/state/composer-attachment-uploads.test.ts
+44 -37
@@ -17,7 +17,6 @@ const native = vi.hoisted(() => ({
17 canOperate: true,
18 nextId: 0,
19 nextUuid: 0,
20 - mint: Symbol("mint"),
20 remove: Symbol("remove"),
21 transfer:
22 vi.fn<(uri: string, url: string, options: UploadOptions) => Promise<{ status: number }>>(),
@@ -130,43 +129,51 @@ vi.mock("./session", async () => {
129 },
130 };
131 });
133 -vi.mock("./attachments", () => ({
134 - attachmentEnvironment: { createUploadUrl: native.mint, remove: native.remove },
135 -}));
132 +vi.mock("./attachments", async () => {
133 + const Effect = await import("effect/Effect");
134 + return {
135 + attachmentEnvironment: {
136 + createUploadUrl: {
137 + run: () =>
138 + Effect.sync(() => {
139 + const id = `pending-${++native.nextId}`;
140 + native.server.set(id, null);
141 + return { attachmentId: id, relativeUrl: `/upload/${id}`, expiresAt: 1 };
142 + }),
143 + },
144 + remove: native.remove,
145 + },
146 + };
147 +});
148 vi.mock("./assets", () => ({ assetEnvironment: { createUrl: (input: unknown) => input } }));
137 -vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
138 - ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
139 - createEnvironmentRpcCommand: () => Symbol("rpc-command"),
140 - executeAtomQuery: async (
141 - _registry: unknown,
142 - query: { input: { resource: { attachmentId: string } } },
143 - ) =>
144 - native.server.get(query.input.resource.attachmentId)
145 - ? { _tag: "Success", value: {} }
146 - : (await import("effect/reactivity")).AsyncResult.failure(
147 - (await import("effect/Cause")).fail({ _tag: "AssetAttachmentNotFoundError" }),
148 - ),
149 - runAtomCommand: async (
150 - _registry: unknown,
151 - command: unknown,
152 - target: { input: { attachmentId?: string } },
153 - ) => {
154 - if (command === native.mint) {
155 - const id = `pending-${++native.nextId}`;
156 - native.server.set(id, null);
157 - return {
158 - _tag: "Success",
159 - value: { attachmentId: id, relativeUrl: `/upload/${id}`, expiresAt: 1 },
160 - };
161 - }
162 - if (command === native.remove && target.input.attachmentId) {
163 - native.deleted.push(target.input.attachmentId);
164 - native.server.delete(target.input.attachmentId);
165 - return { _tag: "Success", value: undefined };
166 - }
167 - throw new Error("Unexpected RPC command");
168 - },
169 -}));
149 +vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => {
150 + const Effect = await import("effect/Effect");
151 + return {
152 + ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
153 + createEnvironmentRpcCommand: () => Symbol("rpc-command"),
154 + awaitAtomResult: (
155 + _registry: unknown,
156 + query: { input: { resource: { attachmentId: string } } },
157 + ) =>
158 + Effect.suspend(() =>
159 + native.server.get(query.input.resource.attachmentId)
160 + ? Effect.succeed({})
161 + : Effect.fail({ _tag: "AssetAttachmentNotFoundError" }),
162 + ),
163 + runAtomCommand: async (
164 + _registry: unknown,
165 + command: unknown,
166 + target: { input: { attachmentId?: string } },
167 + ) => {
168 + if (command === native.remove && target.input.attachmentId) {
169 + native.deleted.push(target.input.attachmentId);
170 + native.server.delete(target.input.attachmentId);
171 + return { _tag: "Success", value: undefined };
172 + }
173 + throw new Error("Unexpected RPC command");
174 + },
175 + };
176 +});
177 vi.mock("./use-thread-outbox", async () => {
178 const { Atom } = await import("effect/reactivity");
179 return {
apps/mobile/src/state/peerPairingCode.ts
+7 -2
@@ -1,5 +1,5 @@
1 import { createPeerPairingCodeCommand } from "@t3tools/client-runtime/state/peerPairingCode";
2 -import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2 +import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3 import type { AuthMcpClientAccess, EnvironmentId } from "@t3tools/contracts";
4 import * as Result from "effect/Result";
5
@@ -17,7 +17,12 @@ export async function mintPairingCodeOn(
17 environmentId: EnvironmentId,
18 access: AuthMcpClientAccess,
19 ): Promise<Result.Result<string, unknown>> {
20 - const result = await mintPairingCode.run(appAtomRegistry, { environmentId, input: access });
20 + const result = await runAtomCommand(
21 + appAtomRegistry,
22 + mintPairingCode,
23 + { environmentId, input: access },
24 + { reportFailure: false },
25 + );
26 return result._tag === "Success"
27 ? Result.succeed(result.value)
28 : Result.fail(squashAtomCommandFailure(result));
apps/mobile/src/state/preferences.test.ts
+11 -5
@@ -1,6 +1,7 @@
1 import { describe, expect, it } from "@effect/vitest";
2 import * as Deferred from "effect/Deferred";
3 import * as Effect from "effect/Effect";
4 +import * as Exit from "effect/Exit";
5 import * as Fiber from "effect/Fiber";
6 import * as Layer from "effect/Layer";
7 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
@@ -76,9 +77,14 @@ describe("mobile preferences state", () => {
77 const registry = AtomRegistry.make();
78 const unmountPreferences = registry.mount(state.preferencesAtom);
79
79 - const save = state.savePreferences.run(registry, {
80 - collapsedProjectGroups: ["project:new"],
81 - });
80 + const save = yield* Effect.forkChild(
81 + Effect.exit(
82 + state.savePreferences.run(registry, {
83 + collapsedProjectGroups: ["project:new"],
84 + }),
85 + ),
86 + { startImmediately: true },
87 + );
88 pendingLoad.resolve({
89 baseFontSize: 18,
90 collapsedProjectGroups: ["project:old"],
@@ -87,7 +93,7 @@ describe("mobile preferences state", () => {
93 const preferences = yield* AtomRegistry.getResult(registry, state.preferencesAtom, {
94 suspendOnWaiting: true,
95 });
90 - const saveResult = yield* Effect.promise(() => save);
96 + const saveResult = yield* Fiber.join(save);
97 expect(preferences).toEqual({
98 baseFontSize: 18,
99 collapsedProjectGroups: ["project:new"],
@@ -95,7 +101,7 @@ describe("mobile preferences state", () => {
101 expect(savePatch).toHaveBeenCalledWith({
102 collapsedProjectGroups: ["project:new"],
103 });
98 - expect(AsyncResult.isFailure(saveResult)).toBe(false);
104 + expect(Exit.isFailure(saveResult)).toBe(false);
105
106 unmountPreferences();
107 registry.dispose();
apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts
+25 -10
@@ -27,6 +27,21 @@ const state = vi.hoisted(() => ({
27 interaction: vi.fn(),
28 prepare: vi.fn(),
29 checkout: vi.fn(),
30 + // Delivery runs commands as Effects; tests steer them with the settled results the mocks return.
31 + command: (Effect: typeof import("effect/Effect"), settle: (input: unknown) => unknown) => ({
32 + label: "command",
33 + run: (_registry: unknown, input: unknown) =>
34 + Effect.promise(
35 + async () =>
36 + (await settle(input)) as
37 + | import("effect/reactivity").AsyncResult.Success<unknown>
38 + | import("effect/reactivity").AsyncResult.Failure<unknown, Error>,
39 + ).pipe(
40 + Effect.flatMap((result) =>
41 + result._tag === "Failure" ? Effect.failCause(result.cause) : Effect.succeed(result.value),
42 + ),
43 + ),
44 + }),
45 modelUnavailable: vi.fn(() => false),
46 familyMount: vi.fn(() => () => {}),
47 threadShells: null as unknown as Atom.Writable<ReadonlyArray<unknown>>,
@@ -48,11 +63,6 @@ const state = vi.hoisted(() => ({
63 },
64 }));
65 vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
51 -vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
52 - ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
53 - runAtomCommand: (_registry: unknown, command: (input: unknown) => unknown, input: unknown) =>
54 - command(input),
55 -}));
66 vi.mock("./session", async () => {
67 const { Atom } = await import("effect/reactivity");
68 const { appAtomRegistry } = await import("./atom-registry");
@@ -88,13 +98,14 @@ vi.mock("./server", async () => {
98 });
99 vi.mock("./threads", async () => {
100 const { Atom, AsyncResult } = await import("effect/reactivity");
101 + const Effect = await import("effect/Effect");
102 state.threadShells = Atom.make<ReadonlyArray<unknown>>([state.thread]).pipe(Atom.keepAlive);
103 return {
104 threadEnvironment: {
94 - startTurn: state.start,
95 - updateMetadata: state.metadata,
96 - setRuntimeMode: state.runtime,
97 - setInteractionMode: state.interaction,
105 + startTurn: state.command(Effect, state.start),
106 + updateMetadata: state.command(Effect, state.metadata),
107 + setRuntimeMode: state.command(Effect, state.runtime),
108 + setInteractionMode: state.command(Effect, state.interaction),
109 },
110 environmentThreadShells: { threadShellsAtom: state.threadShells },
111 threadFamilies: {
@@ -105,7 +116,11 @@ vi.mock("./threads", async () => {
116 environmentThreadDetails: { stateAtom: () => Atom.make(null) },
117 };
118 });
108 -vi.mock("./git", () => ({ gitEnvironment: { preparePullRequestThread: state.checkout } }));
119 +vi.mock("./git", async () => ({
120 + gitEnvironment: {
121 + preparePullRequestThread: state.command(await import("effect/Effect"), state.checkout),
122 + },
123 +}));
124 vi.mock("../lib/modelOptions", () => ({ isModelSelectionUnavailable: state.modelUnavailable }));
125 vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "abcd" }));
126 vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: state.prepare }));
apps/mobile/src/state/threadOutboxDelivery.ts
+9 -2
@@ -9,7 +9,7 @@ import {
9 import {
10 type AtomCommand,
11 type AtomCommandResult,
12 - runAtomCommand,
12 + reportAtomCommandResult,
13 } from "@t3tools/client-runtime/state/runtime";
14 import { threadFamilyRead, type ThreadFamilyRead } from "@t3tools/client-runtime/state/threads";
15 import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
@@ -708,7 +708,14 @@ const deliveryCommand = <W, A, E>(
708 command: AtomCommand<W, A, E>,
709 input: W,
710 ): Effect.Effect<AtomCommandResult<A, E>> =>
711 - Effect.promise(() => runAtomCommand(appAtomRegistry, command, input, { reportFailure: false }));
711 + command.run(appAtomRegistry, input).pipe(
712 + Effect.exit,
713 + Effect.map((exit) => {
714 + const result = AsyncResult.fromExit(exit);
715 + reportAtomCommandResult(result, { label: command.label, reportFailure: false });
716 + return result;
717 + }),
718 + );
719
720 function reportCommandFailure(
721 queuedMessage: QueuedThreadMessage,
apps/mobile/src/state/use-atom-command.ts
+4 -4
@@ -9,13 +9,13 @@ import { useContext } from "react";
9
10 export function useAtomCommand<A, E, W>(
11 command: AtomCommand<W, A, E>,
12 - options?: string | AtomCommandOptions,
13 -): (value: W) => Promise<AtomCommandResult<A, E>> {
12 + options?: string | Omit<AtomCommandOptions, "signal">,
13 +): (value: W, call?: Pick<AtomCommandOptions, "signal">) => Promise<AtomCommandResult<A, E>> {
14 const registry = useContext(RegistryContext);
15 const label = typeof options === "string" ? options : (options?.label ?? command.label);
16 const reportFailure = typeof options === "string" ? true : (options?.reportFailure ?? true);
17 const reportDefect = typeof options === "string" ? true : (options?.reportDefect ?? true);
18
19 - return (value: W) =>
20 - runAtomCommand(registry, command, value, { label, reportFailure, reportDefect });
19 + return (value, call) =>
20 + runAtomCommand(registry, command, value, { label, reportFailure, reportDefect, ...call });
21 }
apps/mobile/src/state/use-atom-query-runner.ts
+4 -3
@@ -9,21 +9,22 @@ import { useContext } from "react";
9
10 export function useAtomQueryRunner<T, A, E>(
11 family: (target: T) => Atom.Atom<AsyncResult.AsyncResult<A, E>>,
12 - options?: string | AtomQueryOptions,
13 -): (target: T) => Promise<AtomCommandResult<A, E>> {
12 + options?: string | Omit<AtomQueryOptions, "signal">,
13 +): (target: T, call?: Pick<AtomQueryOptions, "signal">) => Promise<AtomCommandResult<A, E>> {
14 const registry = useContext(RegistryContext);
15 const explicitLabel = typeof options === "string" ? options : options?.label;
16 const reportFailure = typeof options === "string" ? true : (options?.reportFailure ?? true);
17 const reportDefect = typeof options === "string" ? true : (options?.reportDefect ?? true);
18 const refresh = typeof options === "string" ? false : (options?.refresh ?? false);
19
20 - return (target: T) => {
20 + return (target, call) => {
21 const atom = family(target);
22 return executeAtomQuery(registry, atom, {
23 label: explicitLabel ?? atom.label?.[0] ?? "atom query",
24 reportFailure,
25 reportDefect,
26 refresh,
27 + ...call,
28 });
29 };
30 }
apps/web/src/components/chat/ThreadRelationshipsControl.remote-parent.browser.test.tsx
+18 -7
@@ -25,13 +25,24 @@ const child = {
25 },
26 } as Partial<OrchestrationV2ThreadShell> as OrchestrationV2ThreadShell;
27
28 -vi.mock(import("../../state/orchestration"), async (original) => ({
29 - ...(await original()),
30 - threadTitlesRead: {
31 - label: "thread-titles-read",
32 - run: (_registry: unknown, input: unknown) => read(input),
33 - } as never,
34 -}));
28 +vi.mock(import("../../state/orchestration"), async (original) => {
29 + const Effect = await import("effect/Effect");
30 + type Reply =
31 + | { readonly _tag: "Success"; readonly value: unknown }
32 + | { readonly _tag: "Failure"; readonly cause: Cause.Cause<Error> };
33 + return {
34 + ...(await original()),
35 + threadTitlesRead: {
36 + label: "thread-titles-read",
37 + run: (_registry: unknown, input: unknown) =>
38 + Effect.promise(() => read(input) as Promise<Reply>).pipe(
39 + Effect.flatMap((reply) =>
40 + reply._tag === "Success" ? Effect.succeed(reply.value) : Effect.failCause(reply.cause),
41 + ),
42 + ),
43 + } as never,
44 + };
45 +});
46 vi.mock(import("../../state/entities"), async (original) => ({
47 ...(await original()),
48 useThreadProjection: () => null,
apps/web/src/components/chat/ThreadVisitWatermark.browser.test.tsx
+3 -2
@@ -1,6 +1,7 @@
1 import { claimThreadOpen } from "@t3tools/client-runtime/state/thread-search";
2 import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
3 -import { AsyncResult, Atom } from "effect/reactivity";
3 +import * as Effect from "effect/Effect";
4 +import { Atom } from "effect/reactivity";
5 import { expect, it, vi } from "vite-plus/test";
6
7 import { fakeTimers, render } from "../../../test/render";
@@ -55,7 +56,7 @@ function visitedThreadIds() {
56
57 it("records the visit of the next thread at once after switching threads", async () => {
58 mocks.visitRun.mockReset();
58 - mocks.visitRun.mockResolvedValue(AsyncResult.success(undefined));
59 + mocks.visitRun.mockReturnValue(Effect.void);
60 setShell(threadA, "2026-01-02T00:00:00.000Z");
61 setShell(threadB, "2026-01-03T00:00:00.000Z");
62 using _timers = fakeTimers();
apps/web/src/components/chat/citationProcedure.ts
+4 -3
@@ -1,6 +1,7 @@
1 import { useAtomValue } from "@effect/atom-react";
2 -import { type AtomCommandSuccess, runAtomCommand } from "@t3tools/client-runtime/state/runtime";
2 +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
3 import { sentMessageFromToolItem } from "@t3tools/shared/toolOutput";
4 +import type * as Effect from "effect/Effect";
5 import { Atom, type AtomRegistry } from "effect/reactivity";
6 import { msg } from "gt-react";
7 import { m } from "../../i18n/messages";
@@ -33,8 +34,8 @@ export type CitedHistoryOutcome =
34 | { readonly _tag: "failed"; readonly title: string; readonly description: string }
35 | { readonly _tag: "aborted" };
36
36 -type HistoryPageResult = AtomCommandSuccess<
37 - Awaited<ReturnType<typeof threadEnvironment.loadEarlierHistory.run>>
37 +type HistoryPageResult = Effect.Success<
38 + ReturnType<typeof threadEnvironment.loadEarlierHistory.run>
39 >;
40
41 const MAX_CITATION_PAGES = 20;
apps/web/src/components/device/useDeviceControls.browser.test.tsx
+14 -5
@@ -3,13 +3,16 @@ import type { DeviceHubAccess } from "@t3tools/client-runtime/device/hub-access"
3 import type { AtomCommandConcurrency } from "@t3tools/client-runtime/state/runtime";
4 import { RegistryContext } from "@effect/atom-react";
5 import * as Cause from "effect/Cause";
6 +import type { Effect } from "effect/Effect";
7 import { AtomRegistry } from "effect/reactivity";
8 import { useEffect } from "react";
9 import { expect, it, vi } from "vite-plus/test";
10
11 import { act, render } from "../../../test/render";
12
12 -type Result = { _tag: "Success"; value: DeviceDetail } | { _tag: "Failure"; cause: unknown };
13 +type Result =
14 + | { _tag: "Success"; value: DeviceDetail }
15 + | { _tag: "Failure"; cause: Cause.Cause<Error> };
16 const { read, action, subscribe } = vi.hoisted(() => ({
17 read: vi.fn<() => Promise<Result>>(),
18 action: vi.fn<() => Promise<Result>>(),
@@ -19,6 +22,7 @@ const { read, action, subscribe } = vi.hoisted(() => ({
22 // Stubs only the transport; the device atoms' real scheduler and lanes decide ordering.
23 vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => {
24 const runtime = await original();
25 + const Effects = await import("effect/Effect");
26 const createEnvironmentRpcCommand = (
27 _runtime: unknown,
28 options: {
@@ -28,19 +32,24 @@ vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => {
32 registry: AtomRegistry.AtomRegistry,
33 concurrency: AtomCommandConcurrency<unknown>,
34 input: unknown,
31 - execute: () => Promise<Result>,
32 - ) => Promise<Result>;
35 + effect: Effect<DeviceDetail, Error>,
36 + ) => Effect<DeviceDetail, Error>;
37 };
38 readonly concurrency?: AtomCommandConcurrency<unknown>;
39 },
40 ) => {
41 const send = options.label === "environment-data:device:detail" ? read : action;
42 + const sent = Effects.promise(() => send()).pipe(
43 + Effects.flatMap((result) =>
44 + result._tag === "Success" ? Effects.succeed(result.value) : Effects.failCause(result.cause),
45 + ),
46 + );
47 return {
48 label: options.label,
49 run: (registry: AtomRegistry.AtomRegistry, input: unknown) =>
50 options.scheduler && options.concurrency
42 - ? options.scheduler.schedule(registry, options.concurrency, input, () => send())
43 - : send(),
51 + ? options.scheduler.schedule(registry, options.concurrency, input, sent)
52 + : sent,
53 };
54 };
55 return { ...runtime, createEnvironmentRpcCommand: createEnvironmentRpcCommand as never };
apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx
+2 -1
@@ -1,4 +1,5 @@
1 import { RegistryContext } from "@effect/atom-react";
2 +import * as Effect from "effect/Effect";
3 import { Atom, AtomRegistry } from "effect/reactivity";
4 import {
5 DEFAULT_UNIFIED_SETTINGS,
@@ -66,7 +67,7 @@ const permissions = new Map<string, Atom.Writable<boolean>>();
67 function setup() {
68 state.connected = true;
69 state.tasksLoaded = true;
69 - state.remove.mockReset().mockResolvedValue({ _tag: "Success", value: { id: task.id } });
70 + state.remove.mockReset().mockReturnValue(Effect.succeed({ id: task.id }));
71 state.secondary = false;
72 permissions.clear();
73 permissions.set(environmentId, Atom.make(true));
apps/web/src/components/sidebar/updateEverythingRun.test.ts
+2 -3
@@ -1,5 +1,6 @@
1 import { AVAILABLE_CONNECTION_STATE } from "@t3tools/client-runtime/connection";
2 import { EnvironmentId, type ServerConfig } from "@t3tools/contracts";
3 +import * as Effect from "effect/Effect";
4 import { AsyncResult, Atom } from "effect/reactivity";
5 import { afterEach, describe, expect, it, vi } from "vite-plus/test";
6
@@ -71,9 +72,7 @@ describe("startDesktopUpdateLaunchNotice", () => {
72 AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE, phase: "backoff" as const }),
73 ) as unknown as ReturnType<typeof environmentCatalog.stateAtom>,
74 );
74 - using retryNow = vi
75 - .spyOn(environmentCatalog.retryNow, "run")
76 - .mockResolvedValue(AsyncResult.success(undefined));
75 + using retryNow = vi.spyOn(environmentCatalog.retryNow, "run").mockReturnValue(Effect.void);
76 const stop = relaunchWhileRestarting(environmentId);
77 try {
78 await vi.advanceTimersByTimeAsync(1_000);
apps/web/src/components/sidebar/updateEverythingRun.tsx
+3 -3
@@ -350,9 +350,9 @@ function followHandedOffServers(servers: ReadonlyArray<HandedOffServer>): void {
350 ).pipe(
351 Stream.map((state) => AsyncResult.getOrElse(state, () => AVAILABLE_CONNECTION_STATE)),
352 ),
353 - retryNow: Effect.promise(() =>
354 - environmentCatalog.retryNow.run(appAtomRegistry, server.environmentId),
355 - ).pipe(Effect.asVoid),
353 + retryNow: environmentCatalog.retryNow
354 + .run(appAtomRegistry, server.environmentId)
355 + .pipe(Effect.ignoreCause),
356 }),
357 );
358 const unsubscribe = appAtomRegistry.subscribe(
apps/web/src/environments/primary/httpLayer.ts
+8 -2
@@ -1,7 +1,7 @@
1 import { layerRemoteHttpClient } from "@t3tools/client-runtime/rpc";
2 import * as Effect from "effect/Effect";
3 import * as Layer from "effect/Layer";
4 -import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
4 +import { FetchHttpClient, HttpClient, HttpClientError, HttpClientRequest } from "effect/http";
5
6 import { readDesktopPrimaryBearerToken } from "./desktopAuth";
7 import { resolvePrimaryEnvironmentHttpUrl } from "./target";
@@ -21,7 +21,13 @@ function isSameOriginBrowserPrimary(): boolean {
21 function withPrimaryBearerToken(client: HttpClient.HttpClient): HttpClient.HttpClient {
22 return client.pipe(
23 HttpClient.mapRequestEffect((request) =>
24 - Effect.promise(readDesktopPrimaryBearerToken).pipe(
24 + Effect.tryPromise({
25 + try: readDesktopPrimaryBearerToken,
26 + catch: (cause) =>
27 + new HttpClientError.HttpClientError({
28 + reason: new HttpClientError.TransportError({ request, cause }),
29 + }),
30 + }).pipe(
31 Effect.map((bearerToken) =>
32 bearerToken ? HttpClientRequest.bearerToken(request, bearerToken) : request,
33 ),
apps/web/src/hooks/useSettings.favorites.browser.test.tsx
+14 -1
@@ -59,6 +59,7 @@ vi.mock("~/localApi", () => ({
59
60 vi.mock(import("~/state/server"), async (original) => {
61 const actual = await original();
62 + const Effect = await import("effect/Effect");
63 return {
64 ...actual,
65 serverEnvironment: {
@@ -66,7 +67,19 @@ vi.mock(import("~/state/server"), async (original) => {
67 settingsValueAtom: ((id: EnvironmentId) => state.settings.get(id)) as never,
68 updateSettings: {
69 ...actual.serverEnvironment.updateSettings,
69 - run: (_registry: unknown, input: unknown) => state.persist(input),
70 + run: (_registry: unknown, input: unknown) =>
71 + Effect.promise(
72 + () =>
73 + state.persist(input) as Promise<
74 + AsyncResult.Success<ServerSettings> | AsyncResult.Failure<ServerSettings, Error>
75 + >,
76 + ).pipe(
77 + Effect.flatMap((result) =>
78 + result._tag === "Failure"
79 + ? Effect.failCause(result.cause)
80 + : Effect.succeed(result.value),
81 + ),
82 + ),
83 } as never,
84 },
85 };
apps/web/src/lib/attachmentUploadQueue.test.ts
+37 -11
@@ -20,13 +20,31 @@ const mocks = vi.hoisted(() => ({
20 runAtomCommand: vi.fn(),
21 readEnvironmentScope: vi.fn(),
22 readPreparedConnection: vi.fn(),
23 + // Verification and minting run as Effects; tests steer them with the settled results above.
24 + settledEffect: (
25 + Effect: typeof import("effect/Effect"),
26 + settle: () => Promise<{
27 + readonly _tag: string;
28 + readonly value?: unknown;
29 + readonly error?: object;
30 + }>,
31 + ) =>
32 + Effect.promise(settle).pipe(
33 + Effect.flatMap((result) =>
34 + result._tag === "Success" ? Effect.succeed(result.value) : Effect.fail(result.error),
35 + ),
36 + ),
37 }));
38
25 -vi.mock("@t3tools/client-runtime/state/runtime", () => ({
26 - executeAtomQuery: mocks.executeAtomQuery,
27 - runAtomCommand: mocks.runAtomCommand,
28 - squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error,
29 -}));
39 +vi.mock("@t3tools/client-runtime/state/runtime", async () => {
40 + const Effect = await import("effect/Effect");
41 + return {
42 + awaitAtomResult: (...args: ReadonlyArray<unknown>) =>
43 + mocks.settledEffect(Effect, () => mocks.executeAtomQuery(...args)),
44 + runAtomCommand: mocks.runAtomCommand,
45 + squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error,
46 + };
47 +});
48
49 vi.mock("../rpc/atomRegistry", async () => {
50 const { AtomRegistry } = await import("effect/reactivity");
@@ -41,12 +59,20 @@ vi.mock("../state/assets", () => ({
59 assetEnvironment: { createUrl: mocks.createAssetUrl },
60 }));
61
44 -vi.mock("../state/attachments", () => ({
45 - attachmentEnvironment: {
46 - createUploadUrl: mocks.createUploadUrl,
47 - remove: mocks.removeUpload,
48 - },
49 -}));
62 +vi.mock("../state/attachments", async () => {
63 + const Effect = await import("effect/Effect");
64 + return {
65 + attachmentEnvironment: {
66 + createUploadUrl: {
67 + run: (registry: unknown, input: unknown) =>
68 + mocks.settledEffect(Effect, () =>
69 + mocks.runAtomCommand(registry, mocks.createUploadUrl, input),
70 + ),
71 + },
72 + remove: mocks.removeUpload,
73 + },
74 + };
75 +});
76
77 vi.mock("../state/session", () => ({
78 readEnvironmentScope: mocks.readEnvironmentScope,
apps/web/src/state/connectMcpApproval.ts
+7 -2
@@ -2,7 +2,7 @@ import {
2 type ConnectMcpApprovalCall,
3 createConnectMcpApprovalCommand,
4 } from "@t3tools/client-runtime/state/connectMcpApproval";
5 -import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
5 +import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
6 import type { EnvironmentId } from "@t3tools/contracts";
7 import * as Result from "effect/Result";
8
@@ -16,7 +16,12 @@ export async function runConnectMcpApproval(
16 environmentId: EnvironmentId,
17 call: ConnectMcpApprovalCall,
18 ) {
19 - const result = await connectMcpApproval.run(appAtomRegistry, { environmentId, call });
19 + const result = await runAtomCommand(
20 + appAtomRegistry,
21 + connectMcpApproval,
22 + { environmentId, call },
23 + { reportFailure: false },
24 + );
25 return result._tag === "Success"
26 ? Result.succeed(result.value)
27 : Result.fail(squashAtomCommandFailure(result));
apps/web/src/state/device.ts
+16 -28
@@ -4,10 +4,7 @@ import {
4 type DeviceHubAccess,
5 resolveDeviceHubAccess,
6 } from "@t3tools/client-runtime/state/deviceHubAccess";
7 -import {
8 - createEnvironmentRpcQueryAtomFamily,
9 - runAtomCommand,
10 -} from "@t3tools/client-runtime/state/runtime";
7 +import { createEnvironmentRpcQueryAtomFamily } from "@t3tools/client-runtime/state/runtime";
8 import {
9 type DeviceDetail,
10 type DeviceServiceState,
@@ -130,23 +127,21 @@ export const deviceDetailAtom = Atom.family((key: DeviceDetailKey) =>
127 */
128 export const deviceDetailReadAtom = Atom.family((key: DeviceDetailKey) =>
129 Atom.make((get) =>
133 - Effect.promise(() =>
134 - runAtomCommand(
135 - get.registry,
136 - deviceEnvironment.detail,
137 - { environmentId: key.environmentId, input: { hostId: key.hostId, deviceId: key.deviceId } },
138 - { reportFailure: false },
139 - ),
140 - ).pipe(
141 - Effect.map((result) =>
142 - get.set(
143 - deviceDetailAtom(key),
144 - result._tag === "Success"
145 - ? { detail: result.value, error: null }
146 - : { detail: null, error: formatEnvironmentQueryError(result.cause) },
147 - ),
130 + deviceEnvironment.detail
131 + .run(get.registry, {
132 + environmentId: key.environmentId,
133 + input: { hostId: key.hostId, deviceId: key.deviceId },
134 + })
135 + .pipe(
136 + Effect.matchCause({
137 + onSuccess: (detail) => get.set(deviceDetailAtom(key), { detail, error: null }),
138 + onFailure: (cause) =>
139 + get.set(deviceDetailAtom(key), {
140 + detail: null,
141 + error: formatEnvironmentQueryError(cause),
142 + }),
143 + }),
144 ),
149 - ),
145 ).pipe(Atom.withLabel(`device-detail-read:${key.hostId}:${key.deviceId}`)),
146 );
147
@@ -156,14 +151,7 @@ export const deviceDetailReadAtom = Atom.family((key: DeviceDetailKey) =>
151 */
152 export const deviceHostProbeAtom = Atom.family((environmentId: EnvironmentId) =>
153 Atom.make((get) =>
159 - Effect.promise(() =>
160 - runAtomCommand(
161 - get.registry,
162 - deviceEnvironment.list,
163 - { environmentId, input: {} },
164 - { reportFailure: false },
165 - ),
166 - ).pipe(Effect.asVoid),
154 + deviceEnvironment.list.run(get.registry, { environmentId, input: {} }).pipe(Effect.ignore),
155 ).pipe(Atom.withLabel(`device-host-probe:${environmentId}`)),
156 );
157
apps/web/src/state/peerPairingCode.ts
+13 -3
@@ -2,7 +2,7 @@ import {
2 createMcpApprovalCodeCommand,
3 createPeerPairingCodeCommand,
4 } from "@t3tools/client-runtime/state/peerPairingCode";
5 -import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
5 +import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
6 import type {
7 AuthMcpClientAccess,
8 AuthPairingCredentialResult,
@@ -25,7 +25,12 @@ export async function mintPairingCodeOn(
25 environmentId: EnvironmentId,
26 access: AuthMcpClientAccess,
27 ): Promise<Result.Result<string, unknown>> {
28 - const result = await mintPairingCode.run(appAtomRegistry, { environmentId, input: access });
28 + const result = await runAtomCommand(
29 + appAtomRegistry,
30 + mintPairingCode,
31 + { environmentId, input: access },
32 + { reportFailure: false },
33 + );
34 return result._tag === "Success"
35 ? Result.succeed(result.value)
36 : Result.fail(squashAtomCommandFailure(result));
@@ -36,7 +41,12 @@ export async function mintMcpApprovalCodeOn(
41 environmentId: EnvironmentId,
42 access: AuthMcpClientAccess,
43 ): Promise<Result.Result<AuthPairingCredentialResult, unknown>> {
39 - const result = await mintMcpApprovalCode.run(appAtomRegistry, { environmentId, input: access });
44 + const result = await runAtomCommand(
45 + appAtomRegistry,
46 + mintMcpApprovalCode,
47 + { environmentId, input: access },
48 + { reportFailure: false },
49 + );
50 return result._tag === "Success"
51 ? Result.succeed(result.value)
52 : Result.fail(squashAtomCommandFailure(result));
apps/web/src/state/use-atom-command.ts
+4 -4
@@ -9,13 +9,13 @@ import { useContext } from "react";
9
10 export function useAtomCommand<A, E, W>(
11 command: AtomCommand<W, A, E>,
12 - options?: string | AtomCommandOptions,
13 -): (value: W) => Promise<AtomCommandResult<A, E>> {
12 + options?: string | Omit<AtomCommandOptions, "signal">,
13 +): (value: W, call?: Pick<AtomCommandOptions, "signal">) => Promise<AtomCommandResult<A, E>> {
14 const registry = useContext(RegistryContext);
15 const label = typeof options === "string" ? options : (options?.label ?? command.label);
16 const reportFailure = typeof options === "string" ? true : (options?.reportFailure ?? true);
17 const reportDefect = typeof options === "string" ? true : (options?.reportDefect ?? true);
18
19 - return (value: W) =>
20 - runAtomCommand(registry, command, value, { label, reportFailure, reportDefect });
19 + return (value, call) =>
20 + runAtomCommand(registry, command, value, { label, reportFailure, reportDefect, ...call });
21 }
apps/web/src/state/use-atom-query-runner.ts
+4 -3
@@ -9,21 +9,22 @@ import { useContext } from "react";
9
10 export function useAtomQueryRunner<T, A, E>(
11 family: (target: T) => Atom.Atom<AsyncResult.AsyncResult<A, E>>,
12 - options?: string | AtomQueryOptions,
13 -): (target: T) => Promise<AtomCommandResult<A, E>> {
12 + options?: string | Omit<AtomQueryOptions, "signal">,
13 +): (target: T, call?: Pick<AtomQueryOptions, "signal">) => Promise<AtomCommandResult<A, E>> {
14 const registry = useContext(RegistryContext);
15 const explicitLabel = typeof options === "string" ? options : options?.label;
16 const reportFailure = typeof options === "string" ? true : (options?.reportFailure ?? true);
17 const reportDefect = typeof options === "string" ? true : (options?.reportDefect ?? true);
18 const refresh = typeof options === "string" ? false : (options?.refresh ?? false);
19
20 - return (target: T) => {
20 + return (target, call) => {
21 const atom = family(target);
22 return executeAtomQuery(registry, atom, {
23 label: explicitLabel ?? atom.label?.[0] ?? "atom query",
24 reportFailure,
25 reportDefect,
26 refresh,
27 + ...call,
28 });
29 };
30 }
apps/web/src/textGenerators.ts
+7 -15
@@ -1,6 +1,6 @@
1 +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
2 import { useAtomValue } from "@effect/atom-react";
3 import { providerClients } from "@t3tools/client-runtime/provider-clients";
3 -import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
4 import {
5 type EnvironmentId,
6 type ModelSelection,
@@ -135,20 +135,12 @@ const textGeneratorModelsAtom = Atom.family((key: string) => {
135 return Atom.make((get) => {
136 // Read again after a refresh; the server's cache already holds the new list by then.
137 get(refreshCountAtom(`${environmentId}:${id}`));
138 - return Effect.promise(() =>
139 - runAtomCommand(
140 - get.registry,
141 - serverEnvironment.listTextGeneratorModels,
142 - { environmentId, input: { id } },
143 - { reportFailure: false },
144 - ),
145 - ).pipe(
146 - Effect.flatMap((result) =>
147 - result._tag === "Success"
148 - ? Effect.succeed(result.value.models)
149 - : Effect.fail(formatEnvironmentQueryError(result.cause)),
150 - ),
151 - );
138 + return serverEnvironment.listTextGeneratorModels
139 + .run(get.registry, { environmentId, input: { id } })
140 + .pipe(
141 + Effect.map((result) => result.models),
142 + Effect.catchCause((cause) => Effect.fail(formatEnvironmentQueryError(cause))),
143 + );
144 }).pipe(Atom.setIdleTTL(5 * 60_000), Atom.withLabel(`text-generator-models:${key}`));
145 });
146
packages/client-runtime/src/providerSkills.test.ts
+12 -13
@@ -4,8 +4,8 @@ import {
4 ProviderInstanceId,
5 type ServerProvider,
6 } from "@t3tools/contracts";
7 -import * as Cause from "effect/Cause";
8 -import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
7 +import * as Effect from "effect/Effect";
8 +import { Atom, AtomRegistry } from "effect/reactivity";
9 import { afterEach, describe, expect, it, vi } from "vite-plus/test";
10
11 import {
@@ -185,17 +185,16 @@ describe("provider workspace snapshot refresh atom", () => {
185 let droppedReplies = options?.droppedReplies ?? 0;
186 const providersAtom = Atom.make<ReadonlyArray<ServerProvider> | null>(initialProviders);
187 const responses: Response[] = [...(initialResponses ?? [])];
188 - const run = vi.fn(async () => {
189 - const providers = await (responses.shift() ?? (() => null))();
190 - if (providers === null) {
191 - return AsyncResult.failure<{ providers: ReadonlyArray<ServerProvider> }, string>(
192 - Cause.fail("offline"),
193 - );
194 - }
195 - if (droppedReplies > 0) droppedReplies -= 1;
196 - else registry.set(providersAtom, providers);
197 - return AsyncResult.success({ providers });
198 - });
188 + const run = vi.fn(() =>
189 + Effect.promise(async () => (responses.shift() ?? (() => null))()).pipe(
190 + Effect.flatMap((providers) => {
191 + if (providers === null) return Effect.fail("offline");
192 + if (droppedReplies > 0) droppedReplies -= 1;
193 + else registry.set(providersAtom, providers);
194 + return Effect.succeed({ providers });
195 + }),
196 + ),
197 + );
198 const family = createProviderWorkspaceSnapshotRefreshAtomFamily({
199 providers: () => providersAtom,
200 refreshProviders: { label: "refresh", run },
packages/client-runtime/src/relay/discovery.test.ts
+13 -6
@@ -200,14 +200,23 @@ describe("RelayEnvironmentDiscovery", () => {
200 const registry = AtomRegistry.make();
201 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
202
203 - const refresh = atoms.refresh.run(registry, undefined);
203 + const refresh = yield* Effect.forkChild(
204 + Effect.exit(atoms.refresh.run(registry, undefined)),
205 + { startImmediately: true },
206 + );
207 yield* SubscriptionRef.changes(discovery.state).pipe(
208 Stream.filter((state) => state.environments.size === environments.length),
209 Stream.runHead,
210 );
208 - const coalescedRefresh = atoms.refresh.run(registry, undefined);
211 + const coalescedRefresh = yield* Effect.forkChild(
212 + Effect.exit(atoms.refresh.run(registry, undefined)),
213 + { startImmediately: true },
214 + );
215 yield* Ref.set(harness.listedEnvironments, [environments[1]!]);
210 - const mutationRefresh = atoms.refreshAfterMutation.run(registry, undefined);
216 + const mutationRefresh = yield* Effect.forkChild(
217 + Effect.exit(atoms.refreshAfterMutation.run(registry, undefined)),
218 + { startImmediately: true },
219 + );
220
221 const requests = yield* Ref.get(harness.statusRequests);
222 for (const environment of environments) {
@@ -216,9 +225,7 @@ describe("RelayEnvironmentDiscovery", () => {
225 status(environment, "online"),
226 );
227 }
219 - const results = yield* Effect.promise(() =>
220 - Promise.all([refresh, coalescedRefresh, mutationRefresh]),
221 - );
228 + const results = yield* Fiber.joinAll([refresh, coalescedRefresh, mutationRefresh]);
229 for (const result of results) {
230 expect(result._tag).toBe("Success");
231 }
packages/client-runtime/src/state/attachments.test.ts
+7 -7
@@ -7,7 +7,7 @@ import {
7 } from "@t3tools/contracts";
8 import * as Effect from "effect/Effect";
9 import * as Fiber from "effect/Fiber";
10 -import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
10 +import { Atom, AtomRegistry } from "effect/reactivity";
11
12 import type { AtomCommand } from "./runtime.ts";
13 import {
@@ -34,8 +34,8 @@ type RemoveCommand = AtomCommand<
34 function makeCreateUploadUrl(attachmentId: string): CreateUploadUrlCommand {
35 return {
36 label: "test:create-upload-url",
37 - run: async () =>
38 - AsyncResult.success<AttachmentCreateUploadUrlResult, never>({
37 + run: () =>
38 + Effect.succeed({
39 attachmentId,
40 relativeUrl: `/api/attachments/upload/${attachmentId}`,
41 expiresAt: 1,
@@ -46,10 +46,10 @@ function makeCreateUploadUrl(attachmentId: string): CreateUploadUrlCommand {
46 const removeCalls: string[] = [];
47 const remove: RemoveCommand = {
48 label: "test:remove",
49 - run: async (_registry, input) => {
50 - removeCalls.push(input.input.attachmentId);
51 - return AsyncResult.success(undefined);
52 - },
49 + run: (_registry, input) =>
50 + Effect.sync(() => {
51 + removeCalls.push(input.input.attachmentId);
52 + }),
53 };
54
55 const uploadInput: AttachmentCreateUploadUrlInput = {
packages/client-runtime/src/state/attachments.ts
+28 -29
@@ -6,7 +6,9 @@ import {
6 type AttachmentDeleteInput,
7 type EnvironmentId,
8 } from "@t3tools/contracts";
9 +import * as Cause from "effect/Cause";
10 import * as Effect from "effect/Effect";
11 +import * as Exit from "effect/Exit";
12 import { mFallback, msg } from "gt-i18n";
13 import type { MFunctionType } from "gt-i18n/types";
14 import type { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
@@ -14,9 +16,8 @@ import type { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
16 import type { EnvironmentRegistry } from "../connection/registry.ts";
17 import {
18 createEnvironmentRpcCommand,
17 - executeAtomQuery,
19 + awaitAtomResult,
20 runAtomCommand,
19 - squashAtomCommandFailure,
21 type AtomCommand,
22 } from "./runtime.ts";
23
@@ -65,25 +66,25 @@ export function verifyPersistedAttachmentUpload<A, E>(input: {
66 readonly environmentId: EnvironmentId;
67 readonly attachmentId: string;
68 }): Effect.Effect<PersistedAttachmentVerification> {
68 - return Effect.promise(() =>
69 - executeAtomQuery(
70 - input.registry,
71 - input.createAssetUrl({
72 - environmentId: input.environmentId,
73 - input: { resource: { _tag: "attachment", attachmentId: input.attachmentId } },
74 - }),
75 - // `refresh` forces a server round trip: the asset URL query atom caches
76 - // results (SWR), so a retry right after a transient failure would
77 - // otherwise re-observe the cached failure and never ask the server.
78 - { reportFailure: false, reportDefect: false, refresh: true },
79 - ),
69 + return awaitAtomResult(
70 + input.registry,
71 + input.createAssetUrl({
72 + environmentId: input.environmentId,
73 + input: { resource: { _tag: "attachment", attachmentId: input.attachmentId } },
74 + }),
75 + // `refresh` forces a server round trip: the asset URL query atom caches
76 + // results (SWR), so a retry right after a transient failure would
77 + // otherwise re-observe the cached failure and never ask the server.
78 + { refresh: true },
79 ).pipe(
81 - Effect.map((result): PersistedAttachmentVerification => {
82 - if (result._tag === "Success") return { status: "verified" };
83 - const error = squashAtomCommandFailure(result);
84 - return isAssetAttachmentNotFoundFailure(error)
85 - ? { status: "missing" }
86 - : { status: "failed", error };
80 + Effect.matchCause({
81 + onSuccess: (): PersistedAttachmentVerification => ({ status: "verified" }),
82 + onFailure: (cause): PersistedAttachmentVerification => {
83 + const error = Cause.squash(cause);
84 + return isAssetAttachmentNotFoundFailure(error)
85 + ? { status: "missing" }
86 + : { status: "failed", error };
87 + },
88 }),
89 Effect.withSpan("Attachments.verifyPersistedUpload"),
90 );
@@ -141,20 +142,18 @@ export function runAttachmentUploadCycle<E, RE, TE>(input: {
142 }): Effect.Effect<AttachmentUploadCycleResult> {
143 return Effect.uninterruptibleMask((restore) =>
144 Effect.gen(function* () {
144 - const minted = yield* Effect.promise(() =>
145 - runAtomCommand(
146 - input.registry,
147 - input.createUploadUrl,
148 - { environmentId: input.environmentId, input: input.upload },
149 - { reportFailure: false },
150 - ),
145 + const minted = yield* Effect.exit(
146 + input.createUploadUrl.run(input.registry, {
147 + environmentId: input.environmentId,
148 + input: input.upload,
149 + }),
150 );
152 - if (minted._tag !== "Success") {
151 + if (Exit.isFailure(minted)) {
152 return {
153 status: "failed",
154 step: "mint",
155 attachmentId: null,
157 - error: squashAtomCommandFailure(minted),
156 + error: Cause.squash(minted.cause),
157 } as const;
158 }
159 const attachmentId = minted.value.attachmentId;
packages/client-runtime/src/state/commandPermissions.test.ts
+6 -5
@@ -32,7 +32,7 @@ import * as Layer from "effect/Layer";
32 import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity";
33 import { EnvironmentRegistry } from "../connection/registry.ts";
34 import { createCommandPermissions } from "./commandPermissions.ts";
35 -import { createEnvironmentRpcCommand } from "./runtime.ts";
35 +import { createEnvironmentRpcCommand, runAtomCommand } from "./runtime.ts";
36 import { AVAILABLE_CONNECTION_STATE, BearerConnectionTarget } from "../connection/model.ts";
37 import { createPeerLinkEnvironmentAtoms } from "./peerLinks.ts";
38
@@ -290,9 +290,10 @@ describe("command permissions", () => {
290 });
291 const target = { environmentId: env, input: { id: ScheduledTaskId.make("task") } };
292 try {
293 - const first = command.run(registry, target);
293 + const quiet = { reportFailure: false, reportDefect: false };
294 + const first = runAtomCommand(registry, command, target, quiet);
295 await entered;
295 - const second = command.run(registry, target);
296 + const second = runAtomCommand(registry, command, target, quiet);
297 registry.set(sessions(env), AsyncResult.success(grant(false)));
298 release();
299 expect((await first)._tag).toBe("Success");
@@ -468,10 +469,10 @@ it.effect(
469 setAccess(false);
470 expect(yield* readLinks).toEqual({ links: [] });
471 const linkInput = { url: peer.urls[0]!, pairingCode: "test-code", access: peer.access };
471 - const link = Effect.promise(() =>
472 + const link = Effect.exit(
473 peerLinks.link.run(registry, { environmentId: env, input: linkInput }),
474 );
474 - const unlink = Effect.promise(() =>
475 + const unlink = Effect.exit(
476 peerLinks.unlink.run(registry, {
477 environmentId: env,
478 input: { environmentId: peer.environmentId },
packages/client-runtime/src/state/projectCommands.test.ts
+3 -3
@@ -140,7 +140,7 @@ const makeHarness = Effect.fn("TestProjectCommands.makeHarness")(function* () {
140 permissions: [AuthFilesystemWriteScope],
141 }),
142 );
143 - const openScratch = Effect.promise(() =>
143 + const openScratch = Effect.exit(
144 commands.openScratch.run(registry, { environmentId: ENVIRONMENT_ID, input: {} }),
145 );
146 return { registry, storedProject, openScratch, commands, metadataRequests, readResponse };
@@ -307,7 +307,7 @@ describe("writeFile metadata", () => {
307 { suspendOnWaiting: true },
308 ).pipe(Effect.forkChild);
309 yield* Deferred.await(started);
310 - const write = yield* Effect.promise(() =>
310 + const write = yield* Effect.exit(
311 h.commands.writeFile.run(h.registry, {
312 environmentId: ENVIRONMENT_ID,
313 input: { cwd: "/repo", relativePath: "foo", contents: "new" },
@@ -342,7 +342,7 @@ describe("writeFile metadata", () => {
342 { kind: "file", byteLength: 5 },
343 { kind: "file", byteLength: 5 },
344 ]);
345 - const result = yield* Effect.promise(() =>
345 + const result = yield* Effect.exit(
346 h.commands.writeFile.run(h.registry, {
347 environmentId: ENVIRONMENT_ID,
348 input: { cwd: "/repo", relativePath: "./foo", contents: "new" },
packages/client-runtime/src/state/pullRequests.test.ts
+111 -75
@@ -16,6 +16,7 @@ import {
16 import { expect, it } from "@effect/vitest";
17 import * as Schema from "effect/Schema";
18 import * as Deferred from "effect/Deferred";
19 +import * as Exit from "effect/Exit";
20 import * as Fiber from "effect/Fiber";
21 import * as TestClock from "effect/testing/TestClock";
22 import * as Effect from "effect/Effect";
@@ -980,18 +981,28 @@ it.effect("keeps concurrent diff file reads on different hosts separate", () =>
981 oldPath: "src/app.ts",
982 newPath: "src/app.ts",
983 } as const;
983 - const first = atoms.diffFileContents.run(registry, {
984 - environmentId: TARGET.environmentId,
985 - input: { ...input, host: "github.com" },
986 - });
984 + const first = yield* Effect.forkChild(
985 + Effect.exit(
986 + atoms.diffFileContents.run(registry, {
987 + environmentId: TARGET.environmentId,
988 + input: { ...input, host: "github.com" },
989 + }),
990 + ),
991 + { startImmediately: true },
992 + );
993 yield* started.await;
988 - const second = atoms.diffFileContents.run(registry, {
989 - environmentId: TARGET.environmentId,
990 - input: { ...input, host: "github.example.com" },
991 - });
994 + const second = yield* Effect.forkChild(
995 + Effect.exit(
996 + atoms.diffFileContents.run(registry, {
997 + environmentId: TARGET.environmentId,
998 + input: { ...input, host: "github.example.com" },
999 + }),
1000 + ),
1001 + { startImmediately: true },
1002 + );
1003 yield* release.open;
1004
994 - const results = yield* Effect.promise(() => Promise.all([first, second]));
1005 + const results = yield* Fiber.joinAll([first, second]);
1006 expect(results).toMatchObject([
1007 { _tag: "Success", value: { newContents: "github.com" } },
1008 { _tag: "Success", value: { newContents: "github.example.com" } },
@@ -1022,22 +1033,32 @@ it.effect.each(["closed", "draft", "permission", "stack", "method"] as const)(
1033 environmentId: TARGET.environmentId,
1034 input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 },
1035 };
1025 - const merge = atoms.runAction.run(registry, {
1026 - ...target,
1027 - input: {
1028 - ...target.input,
1029 - action: "merge",
1030 - resolveMergeMethod: () => {
1031 - if (reason === "method") throw new Error("No merge method is available.");
1032 - return "squash";
1033 - },
1034 - },
1035 - });
1036 - const close = atoms.runAction.run(registry, {
1037 - ...target,
1038 - input: { ...target.input, action: "close" },
1039 - });
1040 - const results = yield* Effect.promise(() => Promise.all([merge, close]));
1036 + const merge = yield* Effect.forkChild(
1037 + Effect.exit(
1038 + atoms.runAction.run(registry, {
1039 + ...target,
1040 + input: {
1041 + ...target.input,
1042 + action: "merge",
1043 + resolveMergeMethod: () => {
1044 + if (reason === "method") throw new Error("No merge method is available.");
1045 + return "squash";
1046 + },
1047 + },
1048 + }),
1049 + ),
1050 + { startImmediately: true },
1051 + );
1052 + const close = yield* Effect.forkChild(
1053 + Effect.exit(
1054 + atoms.runAction.run(registry, {
1055 + ...target,
1056 + input: { ...target.input, action: "close" },
1057 + }),
1058 + ),
1059 + { startImmediately: true },
1060 + );
1061 + const results = yield* Fiber.joinAll([merge, close]);
1062 expect(results.map((result) => result._tag)).toEqual(["Failure", "Success"]);
1063 expect(calls).toEqual(["close"]);
1064 }),
@@ -1065,21 +1086,26 @@ it.effect("keeps a close batch ordered and continues after a refused close", ()
1086 }),
1087 } as unknown as WsRpcProtocolClient;
1088 const { atoms, registry } = yield* makeTestRuntime(client);
1068 - const batch = [6, 5, 4].map((number) =>
1069 - atoms.runAction.run(registry, {
1070 - environmentId: TARGET.environmentId,
1071 - input: {
1072 - projectId: ProjectId.make("project-1"),
1073 - repository: "acme/web",
1074 - number,
1075 - action: "close",
1076 - },
1077 - }),
1089 + const batch = yield* Effect.forEach([6, 5, 4], (number) =>
1090 + Effect.forkChild(
1091 + Effect.exit(
1092 + atoms.runAction.run(registry, {
1093 + environmentId: TARGET.environmentId,
1094 + input: {
1095 + projectId: ProjectId.make("project-1"),
1096 + repository: "acme/web",
1097 + number,
1098 + action: "close",
1099 + },
1100 + }),
1101 + ),
1102 + { startImmediately: true },
1103 + ),
1104 );
1105 yield* Deferred.await(started);
1106 expect(calls).toEqual([6]);
1107 yield* Deferred.succeed(release, undefined);
1082 - const results = yield* Effect.promise(() => Promise.all(batch));
1108 + const results = yield* Fiber.joinAll(batch);
1109 expect(results.map((result) => result._tag)).toEqual(["Success", "Failure", "Success"]);
1110 expect(calls).toEqual([6, 5, 4]);
1111 }),
@@ -1185,7 +1211,7 @@ it.effect("shows an action's reply in loaded readers and moves list rows without
1211 }
1212 reads.length = 0;
1213
1188 - const answer = yield* Effect.promise(() =>
1214 + const answer = yield* Effect.exit(
1215 atoms.runAction.run(registry, { ...target, input: { ...target.input, action: "merge" } }),
1216 );
1217
@@ -1251,7 +1277,7 @@ it.effect("keeps an action's reply when a refresh started before the action answ
1277 registry.refresh(detail);
1278 yield* Deferred.await(started);
1279
1254 - yield* Effect.promise(() =>
1280 + yield* Effect.exit(
1281 atoms.runAction.run(registry, {
1282 ...target,
1283 input: { ...actionReference, action: "merge" },
@@ -1314,7 +1340,7 @@ it.effect("keeps a list read the server's refresh started before the action repl
1340 });
1341 yield* Effect.addFinalizer(() => Effect.sync(stop));
1342
1317 - yield* Effect.promise(() =>
1343 + yield* Effect.exit(
1344 atoms.runAction.run(registry, {
1345 ...target,
1346 input: { ...actionReference, action: "merge" },
@@ -1386,7 +1412,7 @@ it.effect("restarts a list page read sent while the action was in flight", () =>
1412 yield* Effect.promise(() => executeAtomQuery(registry, atom));
1413 }
1414
1389 - const action = yield* Effect.promise(() =>
1415 + const action = yield* Effect.exit(
1416 atoms.runAction.run(registry, {
1417 ...target,
1418 input: { ...actionReference, action: "close" },
@@ -1425,7 +1451,7 @@ it.effect("shows a reopen reply at once and re-reads the fields it lacks", () =>
1451 registry.mount(detail);
1452 yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
1453
1428 - yield* Effect.promise(() =>
1454 + yield* Effect.exit(
1455 atoms.runAction.run(registry, {
1456 ...target,
1457 input: { ...actionReference, action: "reopen" },
@@ -1482,7 +1508,7 @@ it.effect("keeps each reader's read time when a reply leaves its checks as they
1508 yield* Effect.promise(() => executeAtomQuery(registry, atom));
1509 }
1510
1485 - yield* Effect.promise(() =>
1511 + yield* Effect.exit(
1512 atoms.runAction.run(registry, {
1513 ...target,
1514 input: { ...actionReference, action: "ready" },
@@ -1529,7 +1555,7 @@ it.effect("re-reads an unstamped preview rather than order a reply against it",
1555 registry.mount(preview);
1556 yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true });
1557
1532 - yield* Effect.promise(() =>
1558 + yield* Effect.exit(
1559 atoms.runAction.run(registry, {
1560 ...target,
1561 input: { ...actionReference, action: "close" },
@@ -1580,7 +1606,7 @@ it.effect("leaves a loaded list page alone when the reply concerns none of its r
1606 yield* Effect.addFinalizer(() => Effect.sync(unmount));
1607 yield* Effect.promise(() => executeAtomQuery(registry, page));
1608
1583 - yield* Effect.promise(() =>
1609 + yield* Effect.exit(
1610 atoms.runAction.run(registry, {
1611 ...target,
1612 input: { ...actionReference, action: "ready" },
@@ -1626,7 +1652,7 @@ it.effect("keeps the server's post-commit read when a reopen reply lacks fields"
1652 });
1653 yield* Effect.addFinalizer(() => Effect.sync(stop));
1654
1629 - yield* Effect.promise(() =>
1655 + yield* Effect.exit(
1656 atoms.runAction.run(registry, {
1657 ...target,
1658 input: { ...actionReference, action: "reopen" },
@@ -1670,7 +1696,7 @@ it.effect.each([
1696 yield* AtomRegistry.getResult(registry, reader, { suspendOnWaiting: true });
1697 }
1698
1673 - yield* Effect.promise(() =>
1699 + yield* Effect.exit(
1700 atoms.runAction.run(registry, {
1701 ...target,
1702 input: { ...actionReference, action: "ready" },
@@ -1726,21 +1752,21 @@ it.effect("keeps hover previews fresh after edits and turns", () =>
1752 ).toBe(title);
1753 yield* Effect.promise(() => executeAtomQuery(registry, preview));
1754 expect(reads).toBe(1);
1729 - const edited = yield* Effect.promise(() =>
1755 + const edited = yield* Effect.exit(
1756 atoms.update.run(registry, { ...target, input: { ...reference, title: "Edited" } }),
1757 );
1732 - expect(AsyncResult.isSuccess(edited)).toBe(true);
1758 + expect(Exit.isSuccess(edited)).toBe(true);
1759 expect(
1760 (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title,
1761 ).toBe("Edited");
1736 - yield* Effect.promise(() =>
1762 + yield* Effect.exit(
1763 atoms.runAction.run(registry, { ...target, input: { ...reference, action: "close" } }),
1764 );
1765 expect(
1766 (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title,
1767 ).toBe("Closed");
1768 title = "Refreshed";
1743 - yield* Effect.promise(() =>
1769 + yield* Effect.exit(
1770 atoms.invalidate.run(registry, {
1771 environmentId: target.environmentId,
1772 input: { reference },
@@ -1933,13 +1959,13 @@ it.effect("shares close, reopen, and merge with an untouched client's mounted PR
1959 }),
1960 ];
1961 yield* Effect.addFinalizer(() => Effect.sync(() => stops.forEach((stop) => stop())));
1936 - const result = yield* Effect.promise(() =>
1962 + const result = yield* Effect.exit(
1963 writer.atoms.runAction.run(writer.registry, {
1964 ...target,
1965 input: { ...target.input, action },
1966 }),
1967 );
1942 - expect(AsyncResult.isSuccess(result)).toBe(true);
1968 + expect(Exit.isSuccess(result)).toBe(true);
1969 yield* detailChanged.await;
1970 yield* summaryChanged.await;
1971 yield* listChanged.await;
@@ -2110,7 +2136,7 @@ it.effect("updates cached labels after successful edits without rereading the ho
2136 yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
2137 yield* AtomRegistry.getResult(registry, candidates, { suspendOnWaiting: true });
2138
2113 - const added = yield* Effect.promise(() =>
2139 + const added = yield* Effect.exit(
2140 atoms.setLabels.run(registry, {
2141 ...target,
2142 input: {
@@ -2123,7 +2149,7 @@ it.effect("updates cached labels after successful edits without rereading the ho
2149 },
2150 }),
2151 );
2126 - expect(AsyncResult.isSuccess(added)).toBe(true);
2152 + expect(Exit.isSuccess(added)).toBe(true);
2153 expect(yield* AtomRegistry.getResult(registry, detail)).toEqual({
2154 title: "keep this title",
2155 labels: [existing, addedLabel],
@@ -2138,7 +2164,7 @@ it.effect("updates cached labels after successful edits without rereading the ho
2164
2165 for (const name of ["existing", "new"]) {
2166 refuse = name === "new";
2141 - const result = yield* Effect.promise(() =>
2167 + const result = yield* Effect.exit(
2168 atoms.setLabels.run(registry, {
2169 ...target,
2170 input: { ...target.input, labels: [name], applied: false },
@@ -2279,7 +2305,7 @@ it.effect("publishes the accepted guide run before the follow-up read finishes",
2305 const query = atoms.reviewGuide(target);
2306 registry.mount(query);
2307 yield* AtomRegistry.getResult(registry, query, { suspendOnWaiting: true });
2282 - const result = yield* Effect.promise(() => atoms.generateReviewGuide.run(registry, target));
2308 + const result = yield* Effect.exit(atoms.generateReviewGuide.run(registry, target));
2309 expect(result._tag).toBe("Success");
2310 yield* refreshStarted.await;
2311 expect(AsyncResult.getOrElse(registry.get(query), () => null)).toEqual(accepted);
@@ -2358,7 +2384,7 @@ it.effect.each([
2384 }
2385 reads = 0;
2386
2361 - const acting = yield* Effect.promise(() =>
2387 + const acting = yield* Effect.exit(
2388 atoms.runAction.run(registry, { ...target, input: { ...actionReference, action } }),
2389 ).pipe(Effect.forkScoped);
2390 yield* Deferred.await(sent);
@@ -2424,7 +2450,7 @@ it.effect("puts readers back when the host refuses an action, and saves nothing
2450 yield* Effect.promise(() => executeAtomQuery(registry, atom));
2451 }
2452
2427 - const acting = yield* Effect.promise(() =>
2453 + const acting = yield* Effect.exit(
2454 atoms.runAction.run(registry, {
2455 ...target,
2456 input: { ...actionReference, action: "close" },
@@ -2497,7 +2523,7 @@ it.effect(
2523 registry.mount(detail);
2524 yield* Effect.promise(() => executeAtomQuery(registry, detail));
2525
2500 - yield* Effect.promise(() =>
2526 + yield* Effect.exit(
2527 atoms.runAction.run(registry, {
2528 ...target,
2529 input: { ...actionReference, action: "close" },
@@ -2561,30 +2587,40 @@ it.effect.each([
2587 registry.mount(list);
2588 yield* Effect.promise(() => executeAtomQuery(registry, list));
2589
2564 - const closes = [1, 2].map((number) =>
2565 - atoms.runAction.run(registry, {
2566 - environmentId: TARGET.environmentId,
2567 - input: { ...actionReference, number, action: "close" },
2568 - }),
2590 + const closes = yield* Effect.forEach([1, 2], (number) =>
2591 + Effect.forkChild(
2592 + Effect.exit(
2593 + atoms.runAction.run(registry, {
2594 + environmentId: TARGET.environmentId,
2595 + input: { ...actionReference, number, action: "close" },
2596 + }),
2597 + ),
2598 + { startImmediately: true },
2599 + ),
2600 );
2601 yield* Deferred.await(firstSent);
2602
2603 expect(Option.getOrThrow(AsyncResult.value(registry.get(list))).entries).toEqual([]);
2604
2574 - const reopen = atoms.runAction.run(registry, {
2575 - environmentId: TARGET.environmentId,
2576 - input: { ...actionReference, number: 1, action: "reopen" },
2577 - });
2605 + const reopen = yield* Effect.forkChild(
2606 + Effect.exit(
2607 + atoms.runAction.run(registry, {
2608 + environmentId: TARGET.environmentId,
2609 + input: { ...actionReference, number: 1, action: "reopen" },
2610 + }),
2611 + ),
2612 + { startImmediately: true },
2613 + );
2614 expect(
2615 Option.getOrThrow(AsyncResult.value(registry.get(list))).entries.map((row) => row.number),
2616 ).toEqual([1]);
2617 yield* Deferred.succeed(release, undefined);
2582 - yield* Effect.promise(() => Promise.all(closes));
2618 + yield* Fiber.joinAll(closes);
2619 expect(
2620 Option.getOrThrow(AsyncResult.value(registry.get(list))).entries.map((row) => row.number),
2621 ).toEqual([1]);
2622 yield* Deferred.succeed(releaseReopen, undefined);
2587 - expect((yield* Effect.promise(() => reopen))._tag).toBe("Failure");
2623 + expect((yield* Fiber.join(reopen))._tag).toBe("Failure");
2624 expect(Option.getOrThrow(AsyncResult.value(registry.get(list))).entries).toEqual([]);
2625 }),
2626 ),
@@ -2612,7 +2648,7 @@ it.effect("leaves a merge as it is until the host says what it did", () =>
2648 registry.mount(detail);
2649 yield* Effect.promise(() => executeAtomQuery(registry, detail));
2650
2615 - const acting = yield* Effect.promise(() =>
2651 + const acting = yield* Effect.exit(
2652 atoms.runAction.run(registry, {
2653 ...target,
2654 input: { ...actionReference, action: "merge" },
@@ -2716,7 +2752,7 @@ it.effect.each(["accepted", "refused"] as const)(
2752 )?.title,
2753 ];
2754
2719 - const editing = yield* Effect.promise(() =>
2755 + const editing = yield* Effect.exit(
2756 atoms.update.run(registry, { ...target, input: { ...actionReference, title: "Edited" } }),
2757 ).pipe(Effect.forkScoped);
2758 yield* Deferred.await(sent);
@@ -2794,7 +2830,7 @@ it.effect.each(["accepted", "refused"] as const)(
2830 yield* Effect.promise(() => executeAtomQuery(registry, atom));
2831 }
2832
2797 - const labelling = yield* Effect.promise(() =>
2833 + const labelling = yield* Effect.exit(
2834 atoms.setLabels.run(registry, {
2835 ...target,
2836 input: { ...actionReference, labels: ["new"], applied: true },
@@ -2869,7 +2905,7 @@ it.effect.each(["loaded", "loading"] as const)(
2905 }
2906 yield* Deferred.await(readStarted);
2907
2872 - yield* Effect.promise(() =>
2908 + yield* Effect.exit(
2909 atoms.setLabels.run(registry, {
2910 ...target,
2911 input: { ...actionReference, labels: ["new"], applied: true },
@@ -2916,7 +2952,7 @@ it.effect.each(["accepted", "refused"] as const)(
2952 yield* Effect.promise(() => executeAtomQuery(registry, checks));
2953 const state = () => Option.getOrThrow(AsyncResult.value(registry.get(checks)))?.state;
2954
2919 - const acting = yield* Effect.promise(() =>
2955 + const acting = yield* Effect.exit(
2956 atoms.runAction.run(registry, {
2957 ...target,
2958 input: { ...actionReference, action: "close" },
packages/client-runtime/src/state/pullRequests.ts
+14 -11
@@ -316,17 +316,20 @@ function showWhileInFlight<Target extends { readonly environmentId: EnvironmentI
316 ): C {
317 return {
318 ...command,
319 - run: async (registry, target) => {
320 - const edit = editOf(registry, target);
321 - if (edit === null) return command.run(registry, target);
322 - const edits = pullRequestPendingEditsAtom(target.environmentId);
323 - registry.update(edits, (current) => [...current, edit]);
324 - try {
325 - return await command.run(registry, target);
326 - } finally {
327 - registry.update(edits, (current) => current.filter((entry) => entry !== edit));
328 - }
329 - },
319 + run: (registry, target) =>
320 + Effect.suspend(() => {
321 + const edit = editOf(registry, target);
322 + if (edit === null) return command.run(registry, target);
323 + const edits = pullRequestPendingEditsAtom(target.environmentId);
324 + return Effect.acquireUseRelease(
325 + Effect.sync(() => registry.update(edits, (current) => [...current, edit])),
326 + () => command.run(registry, target),
327 + () =>
328 + Effect.sync(() =>
329 + registry.update(edits, (current) => current.filter((entry) => entry !== edit)),
330 + ),
331 + );
332 + }),
333 } satisfies AtomCommand<Target, A, E>;
334 }
335
packages/client-runtime/src/state/runtime.test.ts
+197 -125
@@ -26,6 +26,7 @@ import * as DateTime from "effect/DateTime";
26 import * as Deferred from "effect/Deferred";
27 import * as Effect from "effect/Effect";
28 import * as Exit from "effect/Exit";
29 +import * as Fiber from "effect/Fiber";
30 import * as Latch from "effect/Latch";
31 import * as Layer from "effect/Layer";
32 import * as Option from "effect/Option";
@@ -67,7 +68,6 @@ import {
68 createEnvironmentSubscriptionAtomFamily,
69 createRuntimeCommand,
70 environmentSessionGenerationAtom,
70 - scheduleAtomCommandEffect,
71 executeAtomQuery,
72 type QueryAnswerHandler,
73 } from "./runtime.ts";
@@ -1559,64 +1559,100 @@ describe("executeAtomQuery", () => {
1559 });
1560
1561 describe("runtime command runner", () => {
1562 - it("settles generated command scheduler defects from direct callers", async () => {
1563 - const defect = new Error("invalid command key");
1564 - const runtime = Atom.runtime(Layer.empty);
1565 - const command = createRuntimeCommand(runtime, {
1566 - label: "test.invalid-key",
1567 - concurrency: {
1568 - mode: "serial",
1569 - key: () => {
1570 - throw defect;
1562 + const start = <A, E>(effect: Effect.Effect<A, E>) =>
1563 + Effect.forkChild(Effect.exit(effect), { startImmediately: true });
1564 +
1565 + it.effect("fails the run with a defect when its lane key throws", () =>
1566 + Effect.gen(function* () {
1567 + const defect = new Error("invalid command key");
1568 + const command = createRuntimeCommand(Atom.runtime(Layer.empty), {
1569 + label: "test.invalid-key",
1570 + concurrency: {
1571 + mode: "serial",
1572 + key: () => {
1573 + throw defect;
1574 + },
1575 },
1572 - },
1573 - execute: () => Effect.void,
1574 - });
1575 - const registry = AtomRegistry.make();
1576 + execute: () => Effect.void,
1577 + });
1578 + const registry = AtomRegistry.make();
1579
1577 - const result = await command.run(registry, undefined);
1578 - expect(result._tag).toBe("Failure");
1579 - if (result._tag === "Failure") {
1580 - expect(Cause.hasDies(result.cause)).toBe(true);
1581 - expect(Cause.squash(result.cause)).toBe(defect);
1582 - }
1583 - registry.dispose();
1584 - });
1580 + const exit = yield* Effect.exit(command.run(registry, undefined));
1581 + expect(Exit.isFailure(exit) && Cause.squash(exit.cause)).toBe(defect);
1582 + registry.dispose();
1583 + }),
1584 + );
1585
1586 - it("serializes commands that share a scheduler and lane", async () => {
1587 - const firstLatch = Latch.makeUnsafe();
1588 - const events: string[] = [];
1589 - const runtime = Atom.runtime(Layer.empty);
1590 - const scheduler = createAtomCommandScheduler();
1591 - const concurrency = { mode: "serial" as const, key: () => "shared" };
1592 - const firstCommand = createRuntimeCommand(runtime, {
1593 - label: "test.first",
1594 - scheduler,
1595 - concurrency,
1596 - execute: () =>
1597 - Effect.sync(() => events.push("first:start")).pipe(
1598 - Effect.andThen(firstLatch.await),
1599 - Effect.tap(() => Effect.sync(() => events.push("first:end"))),
1600 - ),
1601 - });
1602 - const secondCommand = createRuntimeCommand(runtime, {
1603 - label: "test.second",
1604 - scheduler,
1605 - concurrency,
1606 - execute: () => Effect.sync(() => events.push("second:start")),
1607 - });
1608 - const registry = AtomRegistry.make();
1586 + it.effect("stops a command when its caller is interrupted", () =>
1587 + Effect.gen(function* () {
1588 + const started = Latch.makeUnsafe();
1589 + let stopped = false;
1590 + const command = createRuntimeCommand(Atom.runtime(Layer.empty), {
1591 + label: "test.interrupt",
1592 + execute: () =>
1593 + Effect.sync(() => started.openUnsafe()).pipe(
1594 + Effect.andThen(Effect.never),
1595 + Effect.onInterrupt(() =>
1596 + Effect.sync(() => {
1597 + stopped = true;
1598 + }),
1599 + ),
1600 + ),
1601 + });
1602 + const registry = AtomRegistry.make();
1603
1610 - const first = firstCommand.run(registry, undefined);
1611 - const second = secondCommand.run(registry, undefined);
1612 - await Promise.resolve();
1613 - expect(events).toEqual(["first:start"]);
1604 + const run = yield* start(command.run(registry, undefined));
1605 + yield* started.await;
1606 + yield* Fiber.interrupt(run);
1607
1615 - firstLatch.openUnsafe();
1616 - await Promise.all([first, second]);
1617 - expect(events).toEqual(["first:start", "first:end", "second:start"]);
1618 - registry.dispose();
1619 - });
1608 + expect(stopped).toBe(true);
1609 + registry.dispose();
1610 + }),
1611 + );
1612 +
1613 + it.effect("serializes a lane, and skips a queued command its caller stopped waiting for", () =>
1614 + Effect.gen(function* () {
1615 + const firstStarted = Latch.makeUnsafe();
1616 + const firstLatch = Latch.makeUnsafe();
1617 + const events: string[] = [];
1618 + const runtime = Atom.runtime(Layer.empty);
1619 + const scheduler = createAtomCommandScheduler();
1620 + const concurrency = { mode: "serial" as const, key: () => "shared" };
1621 + const firstCommand = createRuntimeCommand(runtime, {
1622 + label: "test.first",
1623 + scheduler,
1624 + concurrency,
1625 + execute: () =>
1626 + Effect.sync(() => {
1627 + events.push("first:start");
1628 + firstStarted.openUnsafe();
1629 + }).pipe(
1630 + Effect.andThen(firstLatch.await),
1631 + Effect.tap(() => Effect.sync(() => events.push("first:end"))),
1632 + ),
1633 + });
1634 + const queuedCommand = createRuntimeCommand(runtime, {
1635 + label: "test.queued",
1636 + scheduler,
1637 + concurrency,
1638 + execute: (name: string) => Effect.sync(() => events.push(`${name}:start`)),
1639 + });
1640 + const registry = AtomRegistry.make();
1641 +
1642 + const first = yield* start(firstCommand.run(registry, undefined));
1643 + yield* firstStarted.await;
1644 + const abandoned = yield* start(queuedCommand.run(registry, "abandoned"));
1645 + const third = yield* start(queuedCommand.run(registry, "third"));
1646 + yield* Fiber.interrupt(abandoned);
1647 + expect(events).toEqual(["first:start"]);
1648 +
1649 + firstLatch.openUnsafe();
1650 + yield* Fiber.join(first);
1651 + yield* Fiber.join(third);
1652 + expect(events).toEqual(["first:start", "first:end", "third:start"]);
1653 + registry.dispose();
1654 + }),
1655 + );
1656
1657 it.effect("releases a shared scheduler lane before the outer command finishes", () =>
1658 Effect.gen(function* () {
@@ -1629,15 +1665,16 @@ describe("runtime command runner", () => {
1665 const updateCommand = createRuntimeCommand(runtime, {
1666 label: "test.update",
1667 execute: (_input: void, registry) =>
1632 - scheduleAtomCommandEffect(
1633 - registry,
1634 - scheduler,
1635 - concurrency,
1636 - undefined,
1637 - Effect.sync(() => handoffStarted.openUnsafe()).pipe(
1638 - Effect.andThen(handoffComplete.await),
1639 - ),
1640 - ).pipe(Effect.andThen(resumeComplete.await)),
1668 + scheduler
1669 + .schedule(
1670 + registry,
1671 + concurrency,
1672 + undefined,
1673 + Effect.sync(() => handoffStarted.openUnsafe()).pipe(
1674 + Effect.andThen(handoffComplete.await),
1675 + ),
1676 + )
1677 + .pipe(Effect.andThen(resumeComplete.await)),
1678 });
1679 const configCommand = createRuntimeCommand(runtime, {
1680 label: "test.config",
@@ -1647,21 +1684,14 @@ describe("runtime command runner", () => {
1684 });
1685 const registry = AtomRegistry.make();
1686
1650 - const update = updateCommand.run(registry, undefined);
1687 + const update = yield* start(updateCommand.run(registry, undefined));
1688 yield* handoffStarted.await;
1652 - const config = configCommand.run(registry, undefined);
1689 + const config = yield* start(configCommand.run(registry, undefined));
1690 handoffComplete.openUnsafe();
1691
1655 - expect(yield* Effect.promise(() => config)).toMatchObject({
1656 - _tag: "Success",
1657 - value: "configured",
1658 - waiting: false,
1659 - });
1692 + expect(yield* Fiber.join(config)).toEqual(Exit.succeed("configured"));
1693 resumeComplete.openUnsafe();
1661 - expect(yield* Effect.promise(() => update)).toMatchObject({
1662 - _tag: "Success",
1663 - waiting: false,
1664 - });
1694 + expect(Exit.isSuccess(yield* Fiber.join(update))).toBe(true);
1695 registry.dispose();
1696 }),
1697 );
@@ -1673,10 +1703,9 @@ describe("runtime command runner", () => {
1703 const reconnected = yield* Deferred.make<void>();
1704 const states = yield* Queue.unbounded<{ readonly phase: string }>();
1705 yield* Queue.offer(states, { phase: "connected" });
1676 - const runtime = Atom.runtime(Layer.empty);
1706 const scheduler = createAtomCommandScheduler();
1707 const concurrency = { mode: "serial" as const, key: () => "shared" };
1679 - const command = createRuntimeCommand(runtime, {
1708 + const command = createRuntimeCommand(Atom.runtime(Layer.empty), {
1709 label: "test.desktop-update-handoff",
1710 execute: (_input: void, registry) =>
1711 Effect.gen(function* () {
@@ -1692,9 +1721,8 @@ describe("runtime command runner", () => {
1721 Effect.andThen(Deferred.succeed(reconnected, undefined)),
1722 Effect.forkChild,
1723 );
1695 - yield* scheduleAtomCommandEffect(
1724 + yield* scheduler.schedule(
1725 registry,
1697 - scheduler,
1726 concurrency,
1727 undefined,
1728 Deferred.succeed(commitStarting, undefined).pipe(
@@ -1708,62 +1736,106 @@ describe("runtime command runner", () => {
1736 });
1737 const registry = AtomRegistry.make();
1738
1711 - expect(yield* Effect.promise(() => command.run(registry, undefined))).toMatchObject({
1712 - _tag: "Success",
1713 - });
1739 + yield* command.run(registry, undefined);
1740 registry.dispose();
1741 }),
1742 );
1743
1718 - it("deduplicates single-flight commands by key", async () => {
1719 - const latch = Latch.makeUnsafe();
1720 - let executions = 0;
1721 - const runtime = Atom.runtime(Layer.empty);
1722 - const command = createRuntimeCommand(runtime, {
1723 - label: "test.single-flight",
1724 - concurrency: { mode: "singleFlight", key: (key: string) => key },
1725 - execute: () =>
1726 - Effect.sync(() => executions++).pipe(Effect.andThen(latch.await), Effect.as("done")),
1727 - });
1728 - const registry = AtomRegistry.make();
1744 + it.effect("shares a single-flight run, which stops once its last caller stops waiting", () =>
1745 + Effect.gen(function* () {
1746 + const started = Latch.makeUnsafe();
1747 + let executions = 0;
1748 + let stopped = false;
1749 + const command = createRuntimeCommand(Atom.runtime(Layer.empty), {
1750 + label: "test.single-flight",
1751 + concurrency: { mode: "singleFlight", key: (key: string) => key },
1752 + execute: () =>
1753 + Effect.sync(() => {
1754 + executions++;
1755 + started.openUnsafe();
1756 + }).pipe(
1757 + Effect.andThen(Effect.never),
1758 + Effect.onInterrupt(() =>
1759 + Effect.sync(() => {
1760 + stopped = true;
1761 + }),
1762 + ),
1763 + ),
1764 + });
1765 + const registry = AtomRegistry.make();
1766
1730 - const first = command.run(registry, "same");
1731 - const second = command.run(registry, "same");
1732 - latch.openUnsafe();
1767 + const first = yield* start(command.run(registry, "same"));
1768 + const second = yield* start(command.run(registry, "same"));
1769 + yield* started.await;
1770 + yield* Fiber.interrupt(first);
1771 + expect({ executions, stopped }).toEqual({ executions: 1, stopped: false });
1772
1734 - expect(await first).toMatchObject({ _tag: "Success", value: "done", waiting: false });
1735 - expect(await second).toMatchObject({ _tag: "Success", value: "done", waiting: false });
1736 - expect(executions).toBe(1);
1737 - registry.dispose();
1738 - });
1773 + yield* Fiber.interrupt(second);
1774 + expect(stopped).toBe(true);
1775 + registry.dispose();
1776 + }),
1777 + );
1778
1740 - it("coalesces pending latest-value commands without interrupting the active call", async () => {
1741 - const firstLatch = Latch.makeUnsafe();
1742 - const executed: number[] = [];
1743 - const runtime = Atom.runtime(Layer.empty);
1744 - const command = createRuntimeCommand(runtime, {
1745 - label: "test.latest",
1746 - concurrency: { mode: "latest", key: () => "shared" },
1747 - execute: (value: number) =>
1748 - Effect.sync(() => executed.push(value)).pipe(
1749 - Effect.andThen(value === 1 ? firstLatch.await : Effect.void),
1750 - Effect.as(value),
1751 - ),
1752 - });
1753 - const registry = AtomRegistry.make();
1779 + it.effect("gives every single-flight caller the shared result", () =>
1780 + Effect.gen(function* () {
1781 + const latch = Latch.makeUnsafe();
1782 + let executions = 0;
1783 + const command = createRuntimeCommand(Atom.runtime(Layer.empty), {
1784 + label: "test.single-flight",
1785 + concurrency: { mode: "singleFlight", key: (key: string) => key },
1786 + execute: () =>
1787 + Effect.sync(() => executions++).pipe(Effect.andThen(latch.await), Effect.as("done")),
1788 + });
1789 + const registry = AtomRegistry.make();
1790
1755 - const first = command.run(registry, 1);
1756 - await Promise.resolve();
1757 - const second = command.run(registry, 2);
1758 - const third = command.run(registry, 3);
1759 - firstLatch.openUnsafe();
1791 + const first = yield* start(command.run(registry, "same"));
1792 + const second = yield* start(command.run(registry, "same"));
1793 + latch.openUnsafe();
1794
1761 - expect(await first).toMatchObject({ _tag: "Success", value: 1, waiting: false });
1762 - expect(await second).toMatchObject({ _tag: "Success", value: 3, waiting: false });
1763 - expect(await third).toMatchObject({ _tag: "Success", value: 3, waiting: false });
1764 - expect(executed).toEqual([1, 3]);
1765 - registry.dispose();
1766 - });
1795 + expect(yield* Fiber.join(first)).toEqual(Exit.succeed("done"));
1796 + expect(yield* Fiber.join(second)).toEqual(Exit.succeed("done"));
1797 + expect(executions).toBe(1);
1798 + registry.dispose();
1799 + }),
1800 + );
1801 +
1802 + it.effect("coalesces queued latest-value commands, and drops one nobody waits for", () =>
1803 + Effect.gen(function* () {
1804 + const firstStarted = Latch.makeUnsafe();
1805 + const firstLatch = Latch.makeUnsafe();
1806 + const executed: number[] = [];
1807 + const command = createRuntimeCommand(Atom.runtime(Layer.empty), {
1808 + label: "test.latest",
1809 + concurrency: { mode: "latest", key: () => "shared" },
1810 + execute: (value: number) =>
1811 + Effect.sync(() => {
1812 + executed.push(value);
1813 + firstStarted.openUnsafe();
1814 + }).pipe(Effect.andThen(value === 1 ? firstLatch.await : Effect.void), Effect.as(value)),
1815 + });
1816 + const registry = AtomRegistry.make();
1817 +
1818 + const first = yield* start(command.run(registry, 1));
1819 + yield* firstStarted.await;
1820 + const second = yield* start(command.run(registry, 2));
1821 + const third = yield* start(command.run(registry, 3));
1822 + firstLatch.openUnsafe();
1823 +
1824 + expect(yield* Fiber.join(first)).toEqual(Exit.succeed(1));
1825 + expect(yield* Fiber.join(second)).toEqual(Exit.succeed(3));
1826 + expect(yield* Fiber.join(third)).toEqual(Exit.succeed(3));
1827 + expect(executed).toEqual([1, 3]);
1828 +
1829 + firstLatch.closeUnsafe();
1830 + const running = yield* start(command.run(registry, 1));
1831 + const abandoned = yield* start(command.run(registry, 4));
1832 + yield* Fiber.interrupt(abandoned);
1833 + firstLatch.openUnsafe();
1834 + yield* Fiber.join(running);
1835 + expect(executed).toEqual([1, 3, 1]);
1836 + registry.dispose();
1837 + }),
1838 + );
1839 });
1840
1841 describe("persisted environment queries", () => {
packages/client-runtime/src/state/runtime.ts
+221 -179
@@ -11,10 +11,13 @@ import {
11 type EnvironmentId as EnvironmentIdType,
12 } from "@t3tools/contracts";
13 import * as Cause from "effect/Cause";
14 +import * as Deferred from "effect/Deferred";
15 import * as Effect from "effect/Effect";
15 -import * as Exit from "effect/Exit";
16 +import type * as Exit from "effect/Exit";
17 +import * as Fiber from "effect/Fiber";
18 import * as Option from "effect/Option";
19 import * as Schema from "effect/Schema";
20 +import * as Semaphore from "effect/Semaphore";
21 import * as Stream from "effect/Stream";
22 import * as SubscriptionRef from "effect/SubscriptionRef";
23 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
@@ -140,6 +143,8 @@ export interface AtomCommandOptions {
143 readonly label?: string;
144 readonly reportFailure?: boolean;
145 readonly reportDefect?: boolean;
146 + /** Aborting interrupts the run. */
147 + readonly signal?: AbortSignal | undefined;
148 }
149
150 export interface AtomCommandReporter {
@@ -149,7 +154,11 @@ export interface AtomCommandReporter {
154
155 export interface AtomCommand<W, A, E> {
156 readonly label: string;
152 - readonly run: (registry: AtomRegistry.AtomRegistry, input: W) => Promise<AtomCommandResult<A, E>>;
157 + /**
158 + * Runs on the calling fiber, so interrupting the caller stops the command. Code outside
159 + * Effect starts it with `runAtomCommand`.
160 + */
161 + readonly run: (registry: AtomRegistry.AtomRegistry, input: W) => Effect.Effect<A, E>;
162 }
163
164 export type AtomCommandConcurrency<W> =
@@ -159,194 +168,220 @@ export type AtomCommandConcurrency<W> =
168 readonly key: (input: W) => string;
169 };
170
162 -interface AtomCommandSchedulerState {
163 - readonly serial: Map<string, Promise<unknown>>;
164 - readonly singleFlight: Map<string, Promise<unknown>>;
165 - readonly latest: Map<string, AtomCommandLatestLane>;
171 +/** One run that several callers wait on. It is interrupted once the last of them stops waiting. */
172 +interface SharedRun {
173 + readonly result: Deferred.Deferred<unknown, unknown>;
174 + waiters: number;
175 + fiber: Fiber.Fiber<unknown, unknown> | undefined;
176 }
177
168 -interface AtomCommandLatestBatch {
169 - execute: () => Promise<AtomCommandResult<unknown, unknown>>;
170 - readonly resolve: Array<(result: AtomCommandResult<unknown, unknown>) => void>;
178 +interface AtomCommandLatestLane {
179 + pending: (SharedRun & { start: Effect.Effect<void> }) | undefined;
180 }
181
173 -interface AtomCommandLatestLane {
174 - running: boolean;
175 - pending: AtomCommandLatestBatch | undefined;
182 +interface AtomCommandSchedulerState {
183 + readonly serial: Map<string, { readonly semaphore: Semaphore.Semaphore; users: number }>;
184 + readonly singleFlight: Map<string, SharedRun>;
185 + readonly latest: Map<string, AtomCommandLatestLane>;
186 }
187
188 export interface AtomCommandScheduler {
179 - readonly schedule: <W, A, E>(
189 + readonly schedule: <W, A, E, R>(
190 registry: AtomRegistry.AtomRegistry,
191 concurrency: AtomCommandConcurrency<W>,
192 input: W,
183 - execute: () => Promise<AtomCommandResult<A, E>>,
184 - ) => Promise<AtomCommandResult<A, E>>;
193 + effect: Effect.Effect<A, E, R>,
194 + ) => Effect.Effect<A, E, R>;
195 }
196
187 -async function settleAtomCommandResult<A, E>(
188 - execute: () => Promise<AtomCommandResult<A, E>>,
189 -): Promise<AtomCommandResult<A, E>> {
190 - try {
191 - return await execute();
192 - } catch (defect) {
193 - return AsyncResult.failure(Cause.die(defect));
194 - }
195 -}
197 +const startSharedRun = <A, E>(run: SharedRun, effect: Effect.Effect<A, E>) =>
198 + effect.pipe(
199 + Effect.interruptible,
200 + Effect.onExit((exit) => Deferred.done(run.result, exit)),
201 + Effect.ignoreCause,
202 + Effect.forkDetach({ startImmediately: true }),
203 + Effect.map((fiber) => {
204 + run.fiber = fiber;
205 + }),
206 + );
207 +
208 +const awaitSharedRun = <A, E>(
209 + run: SharedRun,
210 + restore: <X, XE, XR>(effect: Effect.Effect<X, XE, XR>) => Effect.Effect<X, XE, XR>,
211 + abandon: Effect.Effect<void>,
212 +): Effect.Effect<A, E> => {
213 + run.waiters++;
214 + return restore(Deferred.await(run.result as Deferred.Deferred<A, E>)).pipe(
215 + Effect.onInterrupt(() => (--run.waiters === 0 ? abandon : Effect.void)),
216 + );
217 +};
218 +
219 +const interruptSharedRun = (run: SharedRun) =>
220 + run.fiber === undefined ? Effect.void : Fiber.interrupt(run.fiber);
221
222 export function createAtomCommandScheduler(): AtomCommandScheduler {
223 const registryStates = new WeakMap<AtomRegistry.AtomRegistry, AtomCommandSchedulerState>();
199 -
200 - const stateFor = (registry: AtomRegistry.AtomRegistry): AtomCommandSchedulerState => {
201 - const existing = registryStates.get(registry);
202 - if (existing !== undefined) {
203 - return existing;
224 + const stateFor = (registry: AtomRegistry.AtomRegistry) => {
225 + let state = registryStates.get(registry);
226 + if (state === undefined) {
227 + state = { serial: new Map(), singleFlight: new Map(), latest: new Map() };
228 + registryStates.set(registry, state);
229 }
205 - const state: AtomCommandSchedulerState = {
206 - serial: new Map(),
207 - singleFlight: new Map(),
208 - latest: new Map(),
209 - };
210 - registryStates.set(registry, state);
230 return state;
231 };
232
214 - return {
215 - schedule: <W, A, E>(
216 - registry: AtomRegistry.AtomRegistry,
217 - concurrency: AtomCommandConcurrency<W>,
218 - input: W,
219 - execute: () => Promise<AtomCommandResult<A, E>>,
220 - ): Promise<AtomCommandResult<A, E>> => {
221 - if (concurrency.mode === "parallel") {
222 - return execute();
223 - }
233 + const serial = <A, E, R>(
234 + lanes: AtomCommandSchedulerState["serial"],
235 + key: string,
236 + effect: Effect.Effect<A, E, R>,
237 + ) =>
238 + Effect.acquireUseRelease(
239 + Effect.sync(() => {
240 + const lane = lanes.get(key) ?? { semaphore: Semaphore.makeUnsafe(1), users: 0 };
241 + lanes.set(key, lane);
242 + lane.users++;
243 + return lane;
244 + }),
245 + (lane) => lane.semaphore.withPermit(effect),
246 + (lane) =>
247 + Effect.sync(() => {
248 + if (--lane.users === 0) lanes.delete(key);
249 + }),
250 + );
251
225 - const key = concurrency.key(input);
226 - const state = stateFor(registry);
227 - if (concurrency.mode === "singleFlight") {
228 - const existing = state.singleFlight.get(key) as
229 - | Promise<AtomCommandResult<A, E>>
230 - | undefined;
231 - if (existing !== undefined) {
232 - return existing;
252 + const singleFlight = <A, E, R>(
253 + flights: AtomCommandSchedulerState["singleFlight"],
254 + key: string,
255 + effect: Effect.Effect<A, E, R>,
256 + ) =>
257 + Effect.uninterruptibleMask((restore) =>
258 + Effect.gen(function* () {
259 + let flight = flights.get(key);
260 + if (flight === undefined) {
261 + const started: SharedRun = {
262 + result: Deferred.makeUnsafe(),
263 + waiters: 0,
264 + fiber: undefined,
265 + };
266 + flight = started;
267 + flights.set(key, started);
268 + const context = yield* Effect.context<R>();
269 + yield* startSharedRun(
270 + started,
271 + effect.pipe(
272 + Effect.provide(context),
273 + Effect.ensuring(
274 + Effect.sync(() => {
275 + if (flights.get(key) === started) flights.delete(key);
276 + }),
277 + ),
278 + ),
279 + );
280 }
234 - const current = execute();
235 - state.singleFlight.set(key, current);
236 - void current.then(
237 - () => {
238 - if (state.singleFlight.get(key) === current) {
239 - state.singleFlight.delete(key);
240 - }
241 - },
242 - () => {
243 - if (state.singleFlight.get(key) === current) {
244 - state.singleFlight.delete(key);
245 - }
246 - },
281 + const joined = flight;
282 + return yield* awaitSharedRun<A, E>(
283 + joined,
284 + restore,
285 + Effect.suspend(() => {
286 + // Left the map first, so a caller arriving during the interrupt starts a fresh run.
287 + if (flights.get(key) === joined) flights.delete(key);
288 + return interruptSharedRun(joined);
289 + }),
290 );
248 - return current;
249 - }
291 + }),
292 + );
293
251 - if (concurrency.mode === "serial") {
252 - const previous = state.serial.get(key);
253 - const current = previous === undefined ? execute() : previous.then(execute, execute);
254 - state.serial.set(key, current);
255 - void current.then(
256 - () => {
257 - if (state.serial.get(key) === current) {
258 - state.serial.delete(key);
259 - }
260 - },
261 - () => {
262 - if (state.serial.get(key) === current) {
263 - state.serial.delete(key);
294 + const latest = <A, E, R>(
295 + lanes: AtomCommandSchedulerState["latest"],
296 + key: string,
297 + effect: Effect.Effect<A, E, R>,
298 + ) =>
299 + Effect.uninterruptibleMask((restore) =>
300 + Effect.gen(function* () {
301 + const context = yield* Effect.context<R>();
302 + const existing = lanes.get(key);
303 + const lane = existing ?? { pending: undefined };
304 + lanes.set(key, lane);
305 + // Callers that queue behind a run share the next one, which runs the newest of them.
306 + const batch = lane.pending ?? {
307 + result: Deferred.makeUnsafe(),
308 + waiters: 0,
309 + fiber: undefined,
310 + start: Effect.void,
311 + };
312 + batch.start = startSharedRun(batch, Effect.provide(effect, context));
313 + lane.pending = batch;
314 +
315 + if (existing === undefined) {
316 + const drain: Effect.Effect<void> = Effect.suspend(() => {
317 + const next = lane.pending;
318 + if (next === undefined) {
319 + lanes.delete(key);
320 + return Effect.void;
321 }
265 - },
266 - );
267 - return current;
268 - }
269 -
270 - let lane = state.latest.get(key);
271 - if (lane === undefined) {
272 - lane = { running: false, pending: undefined };
273 - state.latest.set(key, lane);
274 - }
275 - const activeLane = lane;
276 -
277 - const result = new Promise<AtomCommandResult<A, E>>((resolve) => {
278 - if (activeLane.pending === undefined) {
279 - activeLane.pending = {
280 - execute: execute as () => Promise<AtomCommandResult<unknown, unknown>>,
281 - resolve: [resolve as (result: AtomCommandResult<unknown, unknown>) => void],
282 - };
283 - return;
322 + lane.pending = undefined;
323 + return next.start.pipe(
324 + Effect.andThen(Deferred.await(next.result)),
325 + Effect.exit,
326 + Effect.andThen(drain),
327 + );
328 + });
329 + yield* drain.pipe(Effect.forkDetach({ startImmediately: true }));
330 }
285 - activeLane.pending.execute = execute as () => Promise<AtomCommandResult<unknown, unknown>>;
286 - activeLane.pending.resolve.push(
287 - resolve as (result: AtomCommandResult<unknown, unknown>) => void,
331 + return yield* awaitSharedRun<A, E>(
332 + batch,
333 + restore,
334 + Effect.suspend(() => {
335 + if (lane.pending === batch) lane.pending = undefined;
336 + return interruptSharedRun(batch);
337 + }),
338 );
289 - });
339 + }),
340 + );
341
291 - if (!activeLane.running) {
292 - activeLane.running = true;
293 - void (async () => {
294 - while (activeLane.pending !== undefined) {
295 - const batch = activeLane.pending;
296 - activeLane.pending = undefined;
297 - let batchResult: AtomCommandResult<unknown, unknown>;
298 - try {
299 - batchResult = await batch.execute();
300 - } catch (defect) {
301 - batchResult = AsyncResult.failure(Cause.die(defect));
302 - }
303 - for (const resolve of batch.resolve) {
304 - resolve(batchResult);
342 + return {
343 + schedule: (registry, concurrency, input, effect) =>
344 + concurrency.mode === "parallel"
345 + ? effect
346 + : Effect.suspend(() => {
347 + const key = concurrency.key(input);
348 + const state = stateFor(registry);
349 + switch (concurrency.mode) {
350 + case "serial":
351 + return serial(state.serial, key, effect);
352 + case "singleFlight":
353 + return singleFlight(state.singleFlight, key, effect);
354 + case "latest":
355 + return latest(state.latest, key, effect);
356 }
306 - }
307 - activeLane.running = false;
308 - if (state.latest.get(key) === activeLane) {
309 - state.latest.delete(key);
310 - }
311 - })();
312 - }
313 -
314 - return result;
315 - },
357 + }),
358 };
359 }
360
319 -export const scheduleAtomCommandEffect =
320 - /* Every atom command passes through this scheduler; the command owns its tracing boundary. */
321 - Effect.fnUntraced(function* <W, A, E, R>(
322 - registry: AtomRegistry.AtomRegistry,
323 - scheduler: AtomCommandScheduler,
324 - concurrency: AtomCommandConcurrency<W>,
325 - input: W,
326 - effect: Effect.Effect<A, E, R>,
327 - ): Effect.fn.Return<A, E, R> {
328 - const context = yield* Effect.context<R>();
329 - const result = yield* Effect.promise((signal) =>
330 - scheduler.schedule<W, A, E>(registry, concurrency, input, async () => {
331 - const exit = await Effect.runPromiseExitWith(context)(effect, { signal });
332 - return Exit.isSuccess(exit)
333 - ? AsyncResult.success(exit.value)
334 - : AsyncResult.failure(exit.cause);
335 - }),
336 - );
337 - return result._tag === "Success" ? result.value : yield* Effect.failCause(result.cause);
361 +const settleAtEdge = <A, E>(
362 + effect: Effect.Effect<A, E>,
363 + options: AtomCommandOptions,
364 + reporter: AtomCommandReporter,
365 +): Promise<AtomCommandResult<A, E>> =>
366 + Effect.runPromiseExit(effect, { signal: options.signal }).then((exit) => {
367 + const result = AsyncResult.fromExit(exit);
368 + reportAtomCommandResult(result, options, reporter);
369 + return result;
370 });
371
340 -export async function runAtomCommand<W, A, E>(
372 +/** Starts a command from outside Effect. Effect callers yield `command.run` instead. */
373 +export function runAtomCommand<W, A, E>(
374 registry: AtomRegistry.AtomRegistry,
375 command: AtomCommand<W, A, E>,
376 input: W,
377 options: AtomCommandOptions = {},
378 reporter: AtomCommandReporter = console,
379 ): Promise<AtomCommandResult<A, E>> {
347 - const result = await settleAtomCommandResult(() => command.run(registry, input));
348 - reportAtomCommandResult(result, { ...options, label: options.label ?? command.label }, reporter);
349 - return result;
380 + return settleAtEdge(
381 + Effect.suspend(() => command.run(registry, input)),
382 + { ...options, label: options.label ?? command.label },
383 + reporter,
384 + );
385 }
386
387 export function mapAtomCommandResult<A, E, B>(
@@ -378,16 +413,6 @@ export async function settleAsyncResult<A, E>(
413 }
414 }
415
381 -async function executeAtomCommand<A, E>(
382 - execute: () => Promise<Exit.Exit<A, E>>,
383 - options: AtomCommandOptions = {},
384 - reporter: AtomCommandReporter = console,
385 -): Promise<AtomCommandResult<A, E>> {
386 - const result = await settleAsyncResult(execute);
387 - reportAtomCommandResult(result, options, reporter);
388 - return result;
389 -}
390 -
416 export interface AtomQueryOptions extends AtomCommandOptions {
417 /**
418 * Force a fresh execution instead of accepting a value the atom already
@@ -395,16 +420,18 @@ export interface AtomQueryOptions extends AtomCommandOptions {
420 * verification flows where a cached failure must not satisfy a retry.
421 */
422 readonly refresh?: boolean;
398 - readonly signal?: AbortSignal;
423 }
424
401 -export async function executeAtomQuery<A, E>(
425 +/**
426 + * A query atom's settled value. The atom stays mounted while the caller waits, and
427 + * interrupting the caller releases it.
428 + */
429 +export const awaitAtomResult = <A, E>(
430 registry: AtomRegistry.AtomRegistry,
431 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
404 - options: AtomQueryOptions = {},
405 - reporter: AtomCommandReporter = console,
406 -): Promise<AtomCommandResult<A, E>> {
407 - const query = Effect.scoped(
432 + options: Pick<AtomQueryOptions, "refresh"> = {},
433 +): Effect.Effect<A, E> =>
434 + Effect.scoped(
435 Effect.gen(function* () {
436 yield* AtomRegistry.mount(registry, atom);
437 if (options.refresh) {
@@ -420,13 +447,28 @@ export async function executeAtomQuery<A, E>(
447 });
448 }),
449 );
423 - return executeAtomCommand(
424 - () => Effect.runPromiseExit(query, { signal: options.signal }),
425 - options,
426 - reporter,
427 - );
450 +
451 +/** Reads a query atom from outside Effect. Effect callers yield `awaitAtomResult` instead. */
452 +export function executeAtomQuery<A, E>(
453 + registry: AtomRegistry.AtomRegistry,
454 + atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
455 + options: AtomQueryOptions = {},
456 + reporter: AtomCommandReporter = console,
457 +): Promise<AtomCommandResult<A, E>> {
458 + return settleAtEdge(awaitAtomResult(registry, atom, options), options, reporter);
459 }
460
461 +/** Runs an effect on the calling fiber with the services of an atom runtime. */
462 +export const provideAtomRuntime =
463 + <R, ER>(registry: AtomRegistry.AtomRegistry, runtime: Atom.AtomRuntime<R, ER>) =>
464 + <A, E>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E | ER> =>
465 + Effect.scoped(
466 + AtomRegistry.mount(registry, runtime).pipe(
467 + Effect.andThen(AtomRegistry.getResult(registry, runtime)),
468 + Effect.flatMap((context) => Effect.provide(effect, context)),
469 + ),
470 + );
471 +
472 export function createRuntimeCommand<R, ER, W, A, E>(
473 runtime: Atom.AtomRuntime<R, ER>,
474 options: {
@@ -441,13 +483,13 @@ export function createRuntimeCommand<R, ER, W, A, E>(
483 return {
484 label: options.label,
485 run: (registry, input) =>
444 - settleAtomCommandResult(() =>
445 - scheduler.schedule(registry, concurrency, input, () => {
446 - const atom = runtime
447 - .atom(options.execute(input, registry))
448 - .pipe(Atom.withLabel(options.label));
449 - return executeAtomQuery(registry, atom, { reportDefect: false, reportFailure: false });
450 - }),
486 + scheduler.schedule(
487 + registry,
488 + concurrency,
489 + input,
490 + Effect.suspend(() => options.execute(input, registry)).pipe(
491 + provideAtomRuntime(registry, runtime),
492 + ),
493 ),
494 };
495 }
packages/client-runtime/src/state/server.test.ts
+51 -35
@@ -72,6 +72,7 @@ import {
72 waitForDesktopUpdateTarget,
73 runDesktopCommitWithReconnectObserver,
74 } from "./server.ts";
75 +import { runAtomCommand } from "./runtime.ts";
76 import { applyServerConfigProjection } from "./serverConfigProjection.ts";
77
78 const CONFIG = {
@@ -350,10 +351,14 @@ describe("accepted server update recovery", () => {
351 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (value) =>
352 Effect.sync(() => value.dispose()),
353 );
353 - const pending = atoms.updateServer.run(registry, {
354 - environmentId: TARGET.environmentId,
355 - input: { targetVersion: "0.0.31" },
356 - });
354 + // The registry drops an unmounted atom's value while the update is still running.
355 + yield* AtomRegistry.mount(registry, serverUpdateStateAtom(TARGET.environmentId));
356 + const pending = runAtomCommand(
357 + registry,
358 + atoms.updateServer,
359 + { environmentId: TARGET.environmentId, input: { targetVersion: "0.0.31" } },
360 + { reportFailure: false, reportDefect: false },
361 + );
362 if (loss === "cancel") {
363 yield* Fiber.interrupt(yield* Deferred.await(cancelFiber));
364 const cancelled = yield* Effect.promise(() => pending);
@@ -1584,11 +1589,13 @@ describe("launcher update resume", () => {
1589 const updateStateAtom = serverUpdateStateAtom(TARGET.environmentId);
1590 yield* AtomRegistry.mount(registry, updateStateAtom);
1591
1587 - yield* Effect.promise(() =>
1588 - atoms.updateServer.run(registry, {
1589 - environmentId: TARGET.environmentId,
1590 - input: { targetVersion: "0.0.31" },
1591 - }),
1592 + yield* Effect.promise((signal) =>
1593 + runAtomCommand(
1594 + registry,
1595 + atoms.updateServer,
1596 + { environmentId: TARGET.environmentId, input: { targetVersion: "0.0.31" } },
1597 + { reportFailure: false, reportDefect: false, signal },
1598 + ),
1599 ).pipe(Effect.forkScoped);
1600 return {
1601 // The host saw its first call: the update request or a lifecycle subscription.
@@ -1743,25 +1750,28 @@ describe("provider setup commands", () => {
1750 Effect.sync(() => registry.dispose()),
1751 );
1752 const install = (instanceId: string) =>
1746 - atoms.startProviderInstall.run(registry, {
1747 - environmentId: TARGET.environmentId,
1748 - input: { instanceId: ProviderInstanceId.make(instanceId) },
1749 - });
1753 + Effect.forkChild(
1754 + Effect.exit(
1755 + atoms.startProviderInstall.run(registry, {
1756 + environmentId: TARGET.environmentId,
1757 + input: { instanceId: ProviderInstanceId.make(instanceId) },
1758 + }),
1759 + ),
1760 + { startImmediately: true },
1761 + );
1762
1751 - const codex = install("codex");
1763 + const codex = yield* install("codex");
1764 expect(yield* Queue.take(requested)).toBe("codex");
1753 - const duplicateCodex = install("codex");
1754 - const antigravity = install("antigravity");
1765 + const duplicateCodex = yield* install("codex");
1766 + const antigravity = yield* install("antigravity");
1767 yield* Deferred.succeed(release, undefined);
1768
1757 - expect(yield* Effect.promise(() => codex)).toMatchObject({
1769 + expect(yield* Fiber.join(codex)).toMatchObject({
1770 _tag: "Success",
1771 value: { driver: "codex" },
1772 });
1761 - expect(yield* Effect.promise(() => duplicateCodex)).toEqual(
1762 - yield* Effect.promise(() => codex),
1763 - );
1764 - expect(yield* Effect.promise(() => antigravity)).toMatchObject({
1773 + expect(yield* Fiber.join(duplicateCodex)).toEqual(yield* Fiber.join(codex));
1774 + expect(yield* Fiber.join(antigravity)).toMatchObject({
1775 _tag: "Success",
1776 value: { driver: "antigravity" },
1777 });
@@ -1811,22 +1821,28 @@ describe("provider setup commands", () => {
1821 Effect.sync(() => registry.dispose()),
1822 );
1823
1814 - void atoms.updateProvider.run(registry, {
1815 - environmentId: TARGET.environmentId,
1816 - input: { provider: ProviderDriverKind.make("opencode") },
1817 - });
1824 + yield* Effect.forkChild(
1825 + atoms.updateProvider.run(registry, {
1826 + environmentId: TARGET.environmentId,
1827 + input: { provider: ProviderDriverKind.make("opencode") },
1828 + }),
1829 + { startImmediately: true },
1830 + );
1831 yield* Deferred.await(updateStarted);
1819 - void atoms.mutateProviderInstance.run(registry, {
1820 - environmentId: TARGET.environmentId,
1821 - input: {
1822 - patch: {},
1823 - providerInstanceMutation: {
1824 - operation: "upsert",
1825 - instanceId: ProviderInstanceId.make("codex"),
1826 - instance: { driver: ProviderDriverKind.make("codex"), enabled: false },
1832 + yield* Effect.forkChild(
1833 + atoms.mutateProviderInstance.run(registry, {
1834 + environmentId: TARGET.environmentId,
1835 + input: {
1836 + patch: {},
1837 + providerInstanceMutation: {
1838 + operation: "upsert",
1839 + instanceId: ProviderInstanceId.make("codex"),
1840 + instance: { driver: ProviderDriverKind.make("codex"), enabled: false },
1841 + },
1842 },
1828 - },
1829 - });
1843 + }),
1844 + { startImmediately: true },
1845 + );
1846
1847 const saved = yield* Deferred.await(settingsSaved).pipe(
1848 Effect.as(true),
packages/client-runtime/src/state/server.ts
+1 -3
@@ -43,7 +43,6 @@ import {
43 createEnvironmentRpcSubscriptionAtomFamily,
44 createEnvironmentSubscriptionAtomFamily,
45 createRuntimeCommand,
46 - scheduleAtomCommandEffect,
46 } from "./runtime.ts";
47 import * as EnvironmentRegistry from "../connection/registry.ts";
48 import * as EnvironmentSupervisor from "../connection/supervisor.ts";
@@ -1068,9 +1067,8 @@ export function createServerEnvironmentAtoms<R, E>(
1067 Effect.andThen(Deferred.succeed(desktopReconnected, undefined)),
1068 Effect.forkChild,
1069 );
1071 - const result = yield* scheduleAtomCommandEffect(
1070 + const result = yield* configScheduler.schedule(
1071 atomRegistry,
1073 - configScheduler,
1072 configConcurrency,
1073 target,
1074 Effect.gen(function* () {
packages/client-runtime/src/state/terminal.test.ts
+12 -8
@@ -6,7 +6,7 @@ import {
6 type TerminalWriteInput,
7 type TerminalCloseInput,
8 } from "@t3tools/contracts";
9 -import * as Cause from "effect/Cause";
9 +import * as Effect from "effect/Effect";
10 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
11 import { expect, it } from "vite-plus/test";
12
@@ -104,15 +104,19 @@ function setup(
104 const command = (name: string) => ({
105 label: name,
106 run: (_registry: AtomRegistry.AtomRegistry, value: { readonly input: CommandInput }) => {
107 - const result = (async () => {
107 + const settled = Promise.withResolvers<void>();
108 + pending.push(settled.promise);
109 + return Effect.promise(async () => {
110 calls.push({ command: name, input: value.input });
111 if (options.beforeCommand) await options.beforeCommand(name, value.input);
110 - return name === "resize" && options.resizeFailure?.()
111 - ? AsyncResult.failure(Cause.fail("resize rejected"))
112 - : AsyncResult.success(undefined);
113 - })();
114 - pending.push(result);
115 - return result;
112 + }).pipe(
113 + Effect.flatMap(() =>
114 + name === "resize" && options.resizeFailure?.()
115 + ? Effect.fail("resize rejected")
116 + : Effect.void,
117 + ),
118 + Effect.ensuring(Effect.sync(settled.resolve)),
119 + );
120 },
121 });
122 const write = command("write");
packages/client-runtime/src/state/threadCommands.test.ts
+198 -107
@@ -188,38 +188,53 @@ describe("history loading", () => {
188 ),
189 });
190 yield* Effect.addFinalizer(() => Deferred.succeed(historyReply, { _tag: "loaded" }));
191 - const history = h.commands.loadEarlierHistory.run(h.registry, {
192 - environmentId: ENVIRONMENT_ID,
193 - input: { threadId: THREAD_ID },
194 - });
191 + const history = yield* Effect.forkChild(
192 + Effect.exit(
193 + h.commands.loadEarlierHistory.run(h.registry, {
194 + environmentId: ENVIRONMENT_ID,
195 + input: { threadId: THREAD_ID },
196 + }),
197 + ),
198 + { startImmediately: true },
199 + );
200 yield* Deferred.await(historyStarted);
196 - const send = h.commands.startTurn.run(h.registry, {
197 - environmentId: ENVIRONMENT_ID,
198 - input: {
199 - threadId: THREAD_ID,
200 - message: {
201 - messageId: MessageId.make("message"),
202 - role: "user",
203 - text: "Send while history loads",
204 - attachments: [],
205 - },
206 - runtimeMode: "full-access",
207 - interactionMode: "default",
208 - dispatchMode: "start",
209 - },
210 - });
201 + const send = yield* Effect.forkChild(
202 + Effect.exit(
203 + h.commands.startTurn.run(h.registry, {
204 + environmentId: ENVIRONMENT_ID,
205 + input: {
206 + threadId: THREAD_ID,
207 + message: {
208 + messageId: MessageId.make("message"),
209 + role: "user",
210 + text: "Send while history loads",
211 + attachments: [],
212 + },
213 + runtimeMode: "full-access",
214 + interactionMode: "default",
215 + dispatchMode: "start",
216 + },
217 + }),
218 + ),
219 + { startImmediately: true },
220 + );
221 // Dispatched after Send on another thread, so it arrives first only if Send is queued.
222 const controlThreadId = ThreadId.make("control-thread");
213 - const control = h.commands.interruptTurn.run(h.registry, {
214 - environmentId: ENVIRONMENT_ID,
215 - input: { threadId: controlThreadId, runId: RunId.make("control-run") },
216 - });
223 + const control = yield* Effect.forkChild(
224 + Effect.exit(
225 + h.commands.interruptTurn.run(h.registry, {
226 + environmentId: ENVIRONMENT_ID,
227 + input: { threadId: controlThreadId, runId: RunId.make("control-run") },
228 + }),
229 + ),
230 + { startImmediately: true },
231 + );
232 const first = yield* Queue.take(h.requests);
233 yield* Deferred.succeed(first.reply, { sequence: 1 });
234 yield* Deferred.succeed(historyReply, { _tag: "loaded" });
235 const second = yield* Queue.take(h.requests);
236 yield* Deferred.succeed(second.reply, { sequence: 2 });
222 - const results = yield* Effect.promise(() => Promise.all([history, send, control]));
237 + const results = yield* Fiber.joinAll([history, send, control]);
238
239 expect(first.command).toMatchObject({ type: "message.dispatch", threadId: THREAD_ID });
240 expect(second.command).toMatchObject({ type: "run.interrupt", threadId: controlThreadId });
@@ -233,14 +248,19 @@ describe("interrupt turn", () => {
248 it.effect("reconciles pending work when the server rejects the interrupt", () =>
249 Effect.gen(function* () {
250 const h = yield* makeHarness();
236 - const result = h.commands.interruptTurn.run(h.registry, {
237 - environmentId: ENVIRONMENT_ID,
238 - input: { threadId: THREAD_ID, runId: RunId.make("finished-run") },
239 - });
251 + const result = yield* Effect.forkChild(
252 + Effect.exit(
253 + h.commands.interruptTurn.run(h.registry, {
254 + environmentId: ENVIRONMENT_ID,
255 + input: { threadId: THREAD_ID, runId: RunId.make("finished-run") },
256 + }),
257 + ),
258 + { startImmediately: true },
259 + );
260 const request = yield* Queue.take(h.requests);
261 expect(request.command.type).toBe("run.interrupt");
262 yield* Deferred.fail(request.reply, new Error("Run is not interruptible"));
243 - expect((yield* Effect.promise(() => result))._tag).toBe("Failure");
263 + expect((yield* Fiber.join(result))._tag).toBe("Failure");
264 expect(yield* Queue.take(h.reconciled)).toBe(THREAD_ID);
265 }),
266 );
@@ -257,10 +277,15 @@ describe("interrupt turn", () => {
277 Effect.flatMap(Fiber.join),
278 ),
279 });
260 - const result = h.commands.interruptTurn.run(h.registry, {
261 - environmentId: ENVIRONMENT_ID,
262 - input: { threadId: THREAD_ID, runId: RunId.make("running-run") },
263 - });
280 + const result = yield* Effect.forkChild(
281 + Effect.exit(
282 + h.commands.interruptTurn.run(h.registry, {
283 + environmentId: ENVIRONMENT_ID,
284 + input: { threadId: THREAD_ID, runId: RunId.make("running-run") },
285 + }),
286 + ),
287 + { startImmediately: true },
288 + );
289 const request = yield* Queue.take(h.requests);
290 yield* Deferred.succeed(request.reply, { sequence: 1 });
291 yield* Deferred.await(asked);
@@ -270,7 +295,7 @@ describe("interrupt turn", () => {
295 it.effect("resolves Stop without waiting for the pending work lookup", () =>
296 Effect.gen(function* () {
297 const { threadScope, result } = yield* stopWithBlockedLookup();
273 - expect((yield* Effect.promise(() => result))._tag).toBe("Success");
298 + expect((yield* Fiber.join(result))._tag).toBe("Success");
299 yield* Scope.close(threadScope, Exit.void);
300 }),
301 );
@@ -279,7 +304,7 @@ describe("interrupt turn", () => {
304 Effect.gen(function* () {
305 const { threadScope, result } = yield* stopWithBlockedLookup();
306 yield* Scope.close(threadScope, Exit.void);
282 - expect((yield* Effect.promise(() => result))._tag).toBe("Success");
307 + expect((yield* Fiber.join(result))._tag).toBe("Success");
308 }),
309 );
310 });
@@ -298,7 +323,10 @@ describe("title regeneration", () => {
323 };
324
325 h.registry.set(source, null);
301 - const result = h.commands.regenerateTitle.run(h.registry, target);
326 + const result = yield* Effect.forkChild(
327 + Effect.exit(h.commands.regenerateTitle.run(h.registry, target)),
328 + { startImmediately: true },
329 + );
330 const request = yield* Queue.take(h.requests);
331 const requestId = request.command.commandId;
332 yield* Deferred.succeed(request.reply, { sequence: 2 });
@@ -332,13 +360,16 @@ describe("title regeneration", () => {
360 },
361 ],
362 });
335 - const outcome = yield* Effect.promise(() => result);
363 + const outcome = yield* Fiber.join(result);
364 expect(outcome).toMatchObject({
365 _tag: "Success",
366 value: { status: "failed", message: "model unavailable" },
367 });
368
341 - const superseded = h.commands.regenerateTitle.run(h.registry, target);
369 + const superseded = yield* Effect.forkChild(
370 + Effect.exit(h.commands.regenerateTitle.run(h.registry, target)),
371 + { startImmediately: true },
372 + );
373 const second = yield* Queue.take(h.requests);
374 h.registry.set(source, {
375 ...SNAPSHOT,
@@ -346,7 +377,7 @@ describe("title regeneration", () => {
377 threads: [{ ...thread, titleRegeneration: null, lastTitleRegeneration: earlier }],
378 });
379 yield* Deferred.succeed(second.reply, { sequence: 4 });
349 - expect(yield* Effect.promise(() => superseded)).toMatchObject({
380 + expect(yield* Fiber.join(superseded)).toMatchObject({
381 _tag: "Success",
382 value: null,
383 });
@@ -356,17 +387,22 @@ describe("title regeneration", () => {
387 it.effect("settles without an outcome when the environment disconnects while waiting", () =>
388 Effect.gen(function* () {
389 const h = yield* makeHarness();
359 - const result = h.commands.regenerateTitle.run(h.registry, {
360 - environmentId: ENVIRONMENT_ID,
361 - input: { threadId: THREAD_ID },
362 - });
390 + const result = yield* Effect.forkChild(
391 + Effect.exit(
392 + h.commands.regenerateTitle.run(h.registry, {
393 + environmentId: ENVIRONMENT_ID,
394 + input: { threadId: THREAD_ID },
395 + }),
396 + ),
397 + { startImmediately: true },
398 + );
399 const request = yield* Queue.take(h.requests);
400 yield* Deferred.succeed(request.reply, { sequence: 2 });
401 yield* SubscriptionRef.update(h.connection, (state) => ({
402 ...state,
403 phase: "backoff" as const,
404 }));
369 - expect(yield* Effect.promise(() => result)).toMatchObject({ _tag: "Success", value: null });
405 + expect(yield* Fiber.join(result)).toMatchObject({ _tag: "Success", value: null });
406 }),
407 );
408 });
@@ -408,23 +444,28 @@ describe("remote thread lifecycle commands", () => {
444 ],
445 };
446 h.registry.set(source, initial);
411 - const result = h.commands[action].run(h.registry, {
412 - environmentId: ENVIRONMENT_ID,
413 - input: {
414 - threadId: THREAD_ID,
415 - commandId: CommandId.make(action),
416 - reason: "user",
417 - enabled: false,
418 - orderKey: "a",
419 - snoozedUntil: "2099-01-01T00:00:00.000Z",
420 - ...input,
421 - },
422 - });
447 + const result = yield* Effect.forkChild(
448 + Effect.exit(
449 + h.commands[action].run(h.registry, {
450 + environmentId: ENVIRONMENT_ID,
451 + input: {
452 + threadId: THREAD_ID,
453 + commandId: CommandId.make(action),
454 + reason: "user",
455 + enabled: false,
456 + orderKey: "a",
457 + snoozedUntil: "2099-01-01T00:00:00.000Z",
458 + ...input,
459 + },
460 + }),
461 + ),
462 + { startImmediately: true },
463 + );
464 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(expected);
465 const request = yield* Queue.take(h.requests);
466 expect(h.registry.get(source)).toBe(initial);
467 yield* Deferred.fail(request.reply, new Error("Remote rejected the action"));
427 - expect((yield* Effect.promise(() => result))._tag).toBe("Failure");
468 + expect((yield* Fiber.join(result))._tag).toBe("Failure");
469 expect(h.registry.get(h.visibleAtom)).toBe(initial);
470 }),
471 );
@@ -437,30 +478,40 @@ describe("remote thread lifecycle commands", () => {
478 ...SNAPSHOT,
479 threads: [{ ...SNAPSHOT.threads[0]!, snoozedUntil: FUTURE, snoozedAt: earlierSnoozedAt }],
480 });
440 - const result = h.commands.snooze.run(h.registry, {
441 - environmentId: ENVIRONMENT_ID,
442 - input: { threadId: THREAD_ID, snoozedUntil: DateTime.formatIso(FUTURE) },
443 - });
481 + const result = yield* Effect.forkChild(
482 + Effect.exit(
483 + h.commands.snooze.run(h.registry, {
484 + environmentId: ENVIRONMENT_ID,
485 + input: { threadId: THREAD_ID, snoozedUntil: DateTime.formatIso(FUTURE) },
486 + }),
487 + ),
488 + { startImmediately: true },
489 + );
490 const snoozedAt = h.registry.get(h.visibleAtom)?.threads[0]?.snoozedAt;
491 expect(DateTime.toEpochMillis(snoozedAt!)).toBeGreaterThan(
492 DateTime.toEpochMillis(earlierSnoozedAt),
493 );
494 const request = yield* Queue.take(h.requests);
495 yield* Deferred.succeed(request.reply, { sequence: 2 });
450 - expect((yield* Effect.promise(() => result))._tag).toBe("Success");
496 + expect((yield* Fiber.join(result))._tag).toBe("Success");
497 }),
498 );
499
500 it.effect("keeps the preview after acknowledgement until the matching shell update arrives", () =>
501 Effect.gen(function* () {
502 const h = yield* makeHarness();
457 - const result = h.commands.settle.run(h.registry, {
458 - environmentId: ENVIRONMENT_ID,
459 - input: { threadId: THREAD_ID },
460 - });
503 + const result = yield* Effect.forkChild(
504 + Effect.exit(
505 + h.commands.settle.run(h.registry, {
506 + environmentId: ENVIRONMENT_ID,
507 + input: { threadId: THREAD_ID },
508 + }),
509 + ),
510 + { startImmediately: true },
511 + );
512 const request = yield* Queue.take(h.requests);
513 yield* Deferred.succeed(request.reply, { sequence: 3 });
463 - expect((yield* Effect.promise(() => result))._tag).toBe("Success");
514 + expect((yield* Fiber.join(result))._tag).toBe("Success");
515 const changed = {
516 ...SNAPSHOT,
517 snapshotSequence: 2,
@@ -494,18 +545,28 @@ describe("remote thread lifecycle commands", () => {
545 () =>
546 Effect.gen(function* () {
547 const h = yield* makeHarness();
497 - const settle = h.commands.settle.run(h.registry, {
498 - environmentId: ENVIRONMENT_ID,
499 - input: { threadId: THREAD_ID },
500 - });
548 + const settle = yield* Effect.forkChild(
549 + Effect.exit(
550 + h.commands.settle.run(h.registry, {
551 + environmentId: ENVIRONMENT_ID,
552 + input: { threadId: THREAD_ID },
553 + }),
554 + ),
555 + { startImmediately: true },
556 + );
557 const first = yield* Queue.take(h.requests);
502 - const unsettle = h.commands.unsettle.run(h.registry, {
503 - environmentId: ENVIRONMENT_ID,
504 - input: { threadId: THREAD_ID, reason: "user" },
505 - });
558 + const unsettle = yield* Effect.forkChild(
559 + Effect.exit(
560 + h.commands.unsettle.run(h.registry, {
561 + environmentId: ENVIRONMENT_ID,
562 + input: { threadId: THREAD_ID, reason: "user" },
563 + }),
564 + ),
565 + { startImmediately: true },
566 + );
567 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("active");
568 yield* Deferred.fail(first.reply, new Error("Settle rejected"));
508 - yield* Effect.promise(() => settle);
569 + yield* Fiber.join(settle);
570 expect(h.registry.get(h.visibleAtom)?.threads[0]?.settledOverride).toBe("active");
571 const second = yield* Queue.take(h.requests);
572 expect(second.command.type).toBe("thread.unsettle");
@@ -516,7 +577,7 @@ describe("remote thread lifecycle commands", () => {
577 };
578 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
579 yield* Deferred.succeed(second.reply, { sequence: 2 });
519 - yield* Effect.promise(() => unsettle);
580 + yield* Fiber.join(unsettle);
581 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
582 }),
583 );
@@ -525,10 +586,15 @@ describe("remote thread lifecycle commands", () => {
586 Effect.gen(function* () {
587 const h = yield* makeHarness();
588 const otherEnvironment = EnvironmentId.make("other-remote");
528 - const result = h.commands.settle.run(h.registry, {
529 - environmentId: ENVIRONMENT_ID,
530 - input: { threadId: THREAD_ID },
531 - });
589 + const result = yield* Effect.forkChild(
590 + Effect.exit(
591 + h.commands.settle.run(h.registry, {
592 + environmentId: ENVIRONMENT_ID,
593 + input: { threadId: THREAD_ID },
594 + }),
595 + ),
596 + { startImmediately: true },
597 + );
598 const request = yield* Queue.take(h.requests);
599 expect(h.registry.get(h.commands.snapshotAtom(otherEnvironment))).toBe(SNAPSHOT);
600 expect(h.registry.get(h.commands.rowActionsAtom(ENVIRONMENT_ID))).toBe(1);
@@ -537,7 +603,7 @@ describe("remote thread lifecycle commands", () => {
603 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), removed);
604 expect(h.registry.get(h.visibleAtom)?.threads).toEqual([]);
605 yield* Deferred.fail(request.reply, new Error("Thread removed"));
540 - yield* Effect.promise(() => result);
606 + yield* Fiber.join(result);
607 expect(h.registry.get(h.visibleAtom)).toBe(removed);
608 }),
609 );
@@ -550,18 +616,28 @@ describe("remote thread lifecycle commands", () => {
616 const parked =
617 action === "settle" ? { settledOverride: "settled" as const } : { snoozedUntil: FUTURE };
618 const awake = action === "settle" ? { settledOverride: "active" } : { snoozedUntil: null };
553 - const result = h.commands[action].run(h.registry, {
554 - environmentId: ENVIRONMENT_ID,
555 - input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
556 - });
619 + const result = yield* Effect.forkChild(
620 + Effect.exit(
621 + h.commands[action].run(h.registry, {
622 + environmentId: ENVIRONMENT_ID,
623 + input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
624 + }),
625 + ),
626 + { startImmediately: true },
627 + );
628 const first = yield* Queue.take(h.requests);
558 - const undo = h.commands[action === "settle" ? "unsettle" : "unsnooze"].run(h.registry, {
559 - environmentId: ENVIRONMENT_ID,
560 - input: { threadId: THREAD_ID, reason: "user" },
561 - });
629 + const undo = yield* Effect.forkChild(
630 + Effect.exit(
631 + h.commands[action === "settle" ? "unsettle" : "unsnooze"].run(h.registry, {
632 + environmentId: ENVIRONMENT_ID,
633 + input: { threadId: THREAD_ID, reason: "user" },
634 + }),
635 + ),
636 + { startImmediately: true },
637 + );
638 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
639 yield* Deferred.succeed(first.reply, { sequence: 2 });
564 - expect((yield* Effect.promise(() => result))._tag).toBe("Success");
640 + expect((yield* Fiber.join(result))._tag).toBe("Success");
641 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
642 const confirmed = {
643 ...SNAPSHOT,
@@ -573,7 +649,7 @@ describe("remote thread lifecycle commands", () => {
649 const second = yield* Queue.take(h.requests);
650 expect(second.command.type).toBe(action === "settle" ? "thread.unsettle" : "thread.unsnooze");
651 yield* Deferred.fail(second.reply, new Error("Undo rejected"));
576 - expect((yield* Effect.promise(() => undo))._tag).toBe("Failure");
652 + expect((yield* Fiber.join(undo))._tag).toBe("Failure");
653 expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
654 }),
655 );
@@ -583,10 +659,15 @@ describe("remote thread lifecycle commands", () => {
659 (action) =>
660 Effect.gen(function* () {
661 const h = yield* makeHarness();
586 - const result = h.commands[action].run(h.registry, {
587 - environmentId: ENVIRONMENT_ID,
588 - input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
589 - });
662 + const result = yield* Effect.forkChild(
663 + Effect.exit(
664 + h.commands[action].run(h.registry, {
665 + environmentId: ENVIRONMENT_ID,
666 + input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
667 + }),
668 + ),
669 + { startImmediately: true },
670 + );
671 const request = yield* Queue.take(h.requests);
672 const newer = {
673 ...SNAPSHOT,
@@ -596,7 +677,7 @@ describe("remote thread lifecycle commands", () => {
677 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), newer);
678 expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(newer.threads[0]);
679 yield* Deferred.succeed(request.reply, { sequence: 2 });
599 - expect((yield* Effect.promise(() => result))._tag).toBe("Success");
680 + expect((yield* Fiber.join(result))._tag).toBe("Success");
681 expect(h.registry.get(h.visibleAtom)).toBe(newer);
682 }),
683 );
@@ -611,10 +692,15 @@ describe("remote thread lifecycle commands", () => {
692 threads: [{ ...SNAPSHOT.threads[0]!, pendingRuntimeRequest: USER_INPUT }],
693 };
694 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), stale);
614 - const result = h.commands[action].run(h.registry, {
615 - environmentId: ENVIRONMENT_ID,
616 - input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
617 - });
695 + const result = yield* Effect.forkChild(
696 + Effect.exit(
697 + h.commands[action].run(h.registry, {
698 + environmentId: ENVIRONMENT_ID,
699 + input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
700 + }),
701 + ),
702 + { startImmediately: true },
703 + );
704 const request = yield* Queue.take(h.requests);
705 if (action === "settle") {
706 expect(h.registry.get(h.visibleAtom)?.threads[0]).toBe(stale.threads[0]);
@@ -625,7 +711,7 @@ describe("remote thread lifecycle commands", () => {
711 });
712 }
713 yield* Deferred.succeed(request.reply, { sequence: 2 });
628 - expect((yield* Effect.promise(() => result))._tag).toBe("Success");
714 + expect((yield* Fiber.join(result))._tag).toBe("Success");
715 expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(
716 action === "settle" ? { settledOverride: "settled" } : { snoozedUntil: FUTURE },
717 );
@@ -650,10 +736,15 @@ describe("remote thread lifecycle commands", () => {
736 ],
737 };
738 h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), initial);
653 - const result = h.commands.snooze.run(h.registry, {
654 - environmentId: ENVIRONMENT_ID,
655 - input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
656 - });
739 + const result = yield* Effect.forkChild(
740 + Effect.exit(
741 + h.commands.snooze.run(h.registry, {
742 + environmentId: ENVIRONMENT_ID,
743 + input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
744 + }),
745 + ),
746 + { startImmediately: true },
747 + );
748 const request = yield* Queue.take(h.requests);
749 const snoozed = h.registry.get(h.visibleAtom)?.threads[0];
750 expect(DateTime.toEpochMillis(snoozed!.snoozedAt!)).toBeGreaterThanOrEqual(
@@ -661,7 +752,7 @@ describe("remote thread lifecycle commands", () => {
752 );
753 expect(snoozed?.pendingRuntimeRequest).toEqual(USER_INPUT);
754 yield* Deferred.succeed(request.reply, { sequence: 2 });
664 - expect((yield* Effect.promise(() => result))._tag).toBe("Success");
755 + expect((yield* Fiber.join(result))._tag).toBe("Success");
756 }),
757 );
758 });
packages/client-runtime/src/state/threadCommands.ts
+19 -21
@@ -18,7 +18,6 @@ import {
18 createEnvironmentCommand,
19 createEnvironmentRpcCommand,
20 environmentConnectionAtom,
21 - mapAtomCommandResult,
21 } from "./runtime.ts";
22 import { waitForTitleRegenerationOutcome } from "./threadTitleRegeneration.ts";
23 import {
@@ -148,10 +147,11 @@ export function createThreadEnvironmentAtoms<R, E>(
147 command: AtomCommand<W, A, E>,
148 ): AtomCommand<W, A, E> => ({
149 label: command.label,
151 - run: (registry, target) => {
152 - registry.update(rowActionsAtom(target.environmentId), (count) => count + 1);
153 - return command.run(registry, target);
154 - },
150 + run: (registry, target) =>
151 + Effect.suspend(() => {
152 + registry.update(rowActionsAtom(target.environmentId), (count) => count + 1);
153 + return command.run(registry, target);
154 + }),
155 });
156
157 const sent = {
@@ -460,24 +460,22 @@ export function createThreadEnvironmentAtoms<R, E>(
460 );
461 const regenerateTitle = {
462 label: commands.armTitleRegeneration.label,
463 - run: async (
463 + run: (
464 registry: AtomRegistry.AtomRegistry,
465 target: { readonly environmentId: EnvironmentId; readonly input: { threadId: ThreadId } },
466 - ) => {
467 - const armed = await commands.armTitleRegeneration.run(registry, target);
468 - const outcome =
469 - armed._tag === "Success"
470 - ? await waitForTitleRegenerationOutcome(
471 - registry,
472 - {
473 - snapshot: snapshotAtom(target.environmentId),
474 - disconnected: disconnectedAtom(target.environmentId),
475 - },
476 - { threadId: target.input.threadId, ...armed.value },
477 - )
478 - : null;
479 - return mapAtomCommandResult(armed, () => outcome);
480 - },
466 + ) =>
467 + commands.armTitleRegeneration.run(registry, target).pipe(
468 + Effect.flatMap((armed) =>
469 + waitForTitleRegenerationOutcome(
470 + registry,
471 + {
472 + snapshot: snapshotAtom(target.environmentId),
473 + disconnected: disconnectedAtom(target.environmentId),
474 + },
475 + { threadId: target.input.threadId, ...armed },
476 + ),
477 + ),
478 + ),
479 };
480 return {
481 ...commands,
packages/client-runtime/src/state/threadLifecycle.ts
+27 -24
@@ -5,6 +5,8 @@ import type {
5 ThreadId,
6 } from "@t3tools/contracts";
7 import * as DateTime from "effect/DateTime";
8 +import * as Effect from "effect/Effect";
9 +import * as Exit from "effect/Exit";
10 import { Atom } from "effect/reactivity";
11
12 import type { AtomCommand } from "./runtime.ts";
@@ -71,38 +73,39 @@ export function createOptimisticThreadLifecycle(
73 ): typeof command {
74 return {
75 label: command.label,
74 - run: async (registry, target) => {
75 - const now = DateTime.nowUnsafe();
76 - const pending = pendingAtom(target.environmentId);
77 - const source = sourceSnapshotAtom(target.environmentId);
78 - const update: PendingThreadUpdate = {
79 - threadId: target.input.threadId,
80 - apply: (thread) => apply(thread, target.input, now, update.sequence !== undefined),
81 - };
82 - const remove = () =>
83 - registry.update(pending, (current) => current.filter((item) => item !== update));
84 - registry.update(pending, (current) => [...current, update]);
85 - let confirmed = false;
86 - try {
87 - const result = await command.run(registry, target);
88 - if (result._tag === "Success") {
89 - update.sequence = result.value.sequence;
76 + run: (registry, target) =>
77 + Effect.suspend(() => {
78 + const now = DateTime.nowUnsafe();
79 + const pending = pendingAtom(target.environmentId);
80 + const source = sourceSnapshotAtom(target.environmentId);
81 + const update: PendingThreadUpdate = {
82 + threadId: target.input.threadId,
83 + apply: (thread) => apply(thread, target.input, now, update.sequence !== undefined),
84 + };
85 + const remove = () =>
86 + registry.update(pending, (current) => current.filter((item) => item !== update));
87 + // Stays applied after the reply until a snapshot at or past its sequence replaces it.
88 + const confirm = (sequence: number) => {
89 + update.sequence = sequence;
90 registry.update(pending, (current) => [...current]);
91 const reconcile = (snapshot: OrchestrationV2ShellSnapshot | null) => {
92 - if (snapshot === null || snapshot.snapshotSequence >= result.value.sequence) {
92 + if (snapshot === null || snapshot.snapshotSequence >= sequence) {
93 remove();
94 unsubscribe();
95 }
96 };
97 const unsubscribe = registry.subscribe(source, reconcile);
98 reconcile(registry.get(source));
99 - confirmed = true;
100 - }
101 - return result;
102 - } finally {
103 - if (!confirmed) remove();
104 - }
105 - },
99 + };
100 + registry.update(pending, (current) => [...current, update]);
101 + return command
102 + .run(registry, target)
103 + .pipe(
104 + Effect.onExit((exit) =>
105 + Effect.sync(() => (Exit.isSuccess(exit) ? confirm(exit.value.sequence) : remove())),
106 + ),
107 + );
108 + }),
109 };
110 }
111
packages/client-runtime/src/state/threadTitleRegeneration.ts
+7 -8
@@ -4,6 +4,7 @@ import type {
4 ThreadId,
5 ThreadTitleRegenerationOutcome,
6 } from "@t3tools/contracts";
7 +import * as Effect from "effect/Effect";
8 import type { Atom, AtomRegistry } from "effect/reactivity";
9
10 export interface TitleRegenerationRequest {
@@ -40,27 +41,25 @@ export function waitForTitleRegenerationOutcome(
41 registry: AtomRegistry.AtomRegistry,
42 sources: TitleRegenerationSources,
43 request: TitleRegenerationRequest,
43 -): Promise<ThreadTitleRegenerationOutcome | null> {
44 - return new Promise((resolve) => {
45 - let settled = false;
44 +): Effect.Effect<ThreadTitleRegenerationOutcome | null> {
45 + return Effect.callback((resume) => {
46 let unsubscribes: ReadonlyArray<() => void> = [];
47 const release = () => {
48 for (const unsubscribe of unsubscribes) unsubscribe();
49 + unsubscribes = [];
50 };
51 const check = () => {
51 - if (settled) return;
52 let outcome = settledOutcome(registry.get(sources.snapshot), request);
53 if (outcome === undefined && registry.get(sources.disconnected)) outcome = null;
54 if (outcome === undefined) return;
55 - settled = true;
55 release();
57 - resolve(outcome);
56 + resume(Effect.succeed(outcome));
57 };
58 unsubscribes = [
59 registry.subscribe(sources.snapshot, check),
60 registry.subscribe(sources.disconnected, check),
61 ];
63 - if (settled) release();
64 - else check();
62 + check();
63 + return Effect.sync(release);
64 });
65 }
packages/client-runtime/src/state/threadVisits.test.ts
+17 -16
@@ -1,10 +1,10 @@
1 import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2 -import * as Cause from "effect/Cause";
3 -import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
2 +import * as Deferred from "effect/Deferred";
3 +import * as Effect from "effect/Effect";
4 +import { Atom, AtomRegistry } from "effect/reactivity";
5 import { expect, it, vi } from "vite-plus/test";
6
7 import type { VisitThreadInput } from "../operations/commands.ts";
7 -import type { AtomCommandResult } from "./runtime.ts";
8 import { claimThreadOpen } from "./threadSearch.ts";
9 import { createThreadVisitTracker, VISIT_DISPATCH_THROTTLE_MS } from "./threadVisits.ts";
10
@@ -35,7 +35,7 @@ function setup(threadName: string, initial: Omit<Shell, "environmentId" | "id">
35 const visits: Array<VisitThreadInput> = [];
36 const localVisits: Array<string> = [];
37 let online = true;
38 - let pendingResult: Promise<AtomCommandResult<void, string>> | undefined;
38 + let pendingResult: Effect.Effect<void, string> | undefined;
39 const attempts: Array<VisitThreadInput> = [];
40 const sessionGenerationAtom = Atom.make(1);
41 const tracker = createThreadVisitTracker({
@@ -43,15 +43,16 @@ function setup(threadName: string, initial: Omit<Shell, "environmentId" | "id">
43 sessionGenerationAtom: () => sessionGenerationAtom,
44 visit: {
45 label: "test-visit",
46 - run: async (_registry, value) => {
47 - attempts.push(value.input);
48 - const pending = pendingResult;
49 - pendingResult = undefined;
50 - if (online) visits.push(value.input);
51 - if (pending) return pending;
52 - if (!online) return AsyncResult.failure(Cause.fail("disconnected"));
53 - return AsyncResult.success(undefined);
54 - },
46 + run: (_registry, value) =>
47 + Effect.suspend(() => {
48 + attempts.push(value.input);
49 + const pending = pendingResult;
50 + pendingResult = undefined;
51 + if (online) visits.push(value.input);
52 + if (pending) return pending;
53 + if (!online) return Effect.fail("disconnected");
54 + return Effect.void;
55 + }),
56 },
57 markLocalVisit: (_ref, visitedAt) => localVisits.push(visitedAt),
58 });
@@ -62,9 +63,9 @@ function setup(threadName: string, initial: Omit<Shell, "environmentId" | "id">
63 localVisits,
64 attempts,
65 deferNextVisit: () => {
65 - const deferred = Promise.withResolvers<AtomCommandResult<void, string>>();
66 - pendingResult = deferred.promise;
67 - return () => deferred.resolve(AsyncResult.failure(Cause.fail("disconnected")));
66 + const deferred = Deferred.makeUnsafe<void, string>();
67 + pendingResult = Deferred.await(deferred);
68 + return () => Deferred.doneUnsafe(deferred, Effect.fail("disconnected"));
69 },
70 reconnect: () => registry.set(sessionGenerationAtom, registry.get(sessionGenerationAtom) + 1),
71 mount: () => registry.mount(tracker(ref)),
packages/client-runtime/src/state/usage.test.ts
+9 -2
@@ -39,7 +39,7 @@ function harness(ids = ["a"], modelFilters: Record<string, UsageModelFilter> = {
39 const environments = ids.map((id) => {
40 const environmentId = EnvironmentId.make(id);
41 const rates = Promise.withResolvers<
42 - AsyncResult.Success<typeof pricing> | AsyncResult.Failure<never, unknown>
42 + AsyncResult.Success<typeof pricing> | AsyncResult.Failure<never, Error>
43 >();
44 const scan = Promise.withResolvers<UsageSummary>();
45 const scanStarted = Promise.withResolvers<void>();
@@ -78,7 +78,14 @@ function harness(ids = ["a"], modelFilters: Record<string, UsageModelFilter> = {
78 run: (
79 _registry: AtomRegistry.AtomRegistry,
80 { environmentId }: { environmentId: EnvironmentId },
81 - ) => get(environmentId).rates.promise,
81 + ) =>
82 + Effect.promise(() => get(environmentId).rates.promise).pipe(
83 + Effect.flatMap((result) =>
84 + AsyncResult.isSuccess(result)
85 + ? Effect.succeed(result.value)
86 + : Effect.failCause(result.cause),
87 + ),
88 + ),
89 },
90 },
91 presentations: {
packages/client-runtime/src/state/vcs.test.ts
+19 -13
@@ -12,6 +12,7 @@ import {
12 import { describe, expect, it } from "@effect/vitest";
13 import * as Deferred from "effect/Deferred";
14 import * as Effect from "effect/Effect";
15 +import * as Exit from "effect/Exit";
16 import * as Fiber from "effect/Fiber";
17 import * as Layer from "effect/Layer";
18 import * as Logger from "effect/Logger";
@@ -426,36 +427,36 @@ describe("cached VCS refs", () => {
427 Effect.sync(() => registry.dispose()),
428 );
429
429 - const result = yield* Effect.promise(() =>
430 + const result = yield* Effect.exit(
431 atoms.pull.run(registry, {
432 environmentId: TARGET.environmentId,
433 input: { cwd: "/repo" },
434 }),
435 );
436
436 - expect(AsyncResult.isFailure(result)).toBe(true);
437 + expect(Exit.isFailure(result)).toBe(true);
438 expect(yield* Ref.get(clears)).toBe(1);
439 expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(1);
440
440 - const refreshResult = yield* Effect.promise(() =>
441 + const refreshResult = yield* Effect.exit(
442 atoms.refreshStatus.run(registry, {
443 environmentId: TARGET.environmentId,
444 input: { cwd: "/repo" },
445 }),
446 );
447
447 - expect(AsyncResult.isSuccess(refreshResult)).toBe(true);
448 + expect(Exit.isSuccess(refreshResult)).toBe(true);
449 expect(yield* Ref.get(clears)).toBe(2);
450 expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(2);
451
451 - const prepareResult = yield* Effect.promise(() =>
452 + const prepareResult = yield* Effect.exit(
453 createGitEnvironmentAtoms(runtime).preparePullRequestThread.run(registry, {
454 environmentId: TARGET.environmentId,
455 input: { cwd: "/repo", reference: "42", mode: "local" },
456 }),
457 );
458
458 - expect(AsyncResult.isSuccess(prepareResult)).toBe(true);
459 + expect(Exit.isSuccess(prepareResult)).toBe(true);
460 expect(yield* Ref.get(clears)).toBe(3);
461 expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(3);
462 }),
@@ -502,21 +503,26 @@ describe("cached VCS refs", () => {
503 );
504 const target = { environmentId: TARGET.environmentId, input: { cwd: "/repo" } };
505
505 - const refresh = atoms.refreshLocalStatusForPicker.run(registry, {
506 - ...target,
507 - input: { cwd: "/repo", localOnly: true },
508 - });
506 + const refresh = yield* Effect.forkChild(
507 + Effect.exit(
508 + atoms.refreshLocalStatusForPicker.run(registry, {
509 + ...target,
510 + input: { cwd: "/repo", localOnly: true },
511 + }),
512 + ),
513 + { startImmediately: true },
514 + );
515 yield* Deferred.await(refreshStarted);
510 - const checkout = yield* Effect.promise(() =>
516 + const checkout = yield* Effect.exit(
517 atoms.switchRef.run(registry, {
518 ...target,
519 input: { cwd: "/repo", refName: "feature" },
520 }),
521 );
522
517 - expect(AsyncResult.isSuccess(checkout)).toBe(true);
523 + expect(Exit.isSuccess(checkout)).toBe(true);
524 yield* Deferred.succeed(releaseRefresh, undefined);
519 - expect(AsyncResult.isSuccess(yield* Effect.promise(() => refresh))).toBe(true);
525 + expect(Exit.isSuccess(yield* Fiber.join(refresh))).toBe(true);
526 }),
527 );
528
packages/client-runtime/src/state/vcsAction.test.ts
+30 -15
@@ -30,7 +30,7 @@ import * as EnvironmentSupervisor from "../connection/supervisor.ts";
30 import * as Persistence from "../platform/persistence.ts";
31 import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
32 import type { RpcSession } from "../rpc/session.ts";
33 -import type { AtomCommandResult } from "./runtime.ts";
33 +import { runAtomCommand, type AtomCommandResult } from "./runtime.ts";
34 import {
35 applyVcsActionProgressEvent,
36 beginVcsActionState,
@@ -521,12 +521,17 @@ describe("vcsActionState", () => {
521 const threadId = ThreadId.make("thread-stacked-action");
522 const projectId = ProjectId.make("project-stacked-action");
523 const successfulResult = yield* Effect.promise(() =>
524 - manager.runStackedAction(targetKey).run(registry, {
525 - actionId: successfulActionId,
526 - action,
527 - threadId,
528 - projectId,
529 - }),
524 + runAtomCommand(
525 + registry,
526 + manager.runStackedAction(targetKey),
527 + {
528 + actionId: successfulActionId,
529 + action,
530 + threadId,
531 + projectId,
532 + },
533 + { reportFailure: false, reportDefect: false },
534 + ),
535 );
536
537 expect(AsyncResult.isSuccess(successfulResult)).toBe(true);
@@ -538,10 +543,15 @@ describe("vcsActionState", () => {
543 ]);
544
545 const failedResult = yield* Effect.promise(() =>
541 - manager.runStackedAction(targetKey).run(registry, {
542 - actionId: failedActionId,
543 - action,
544 - }),
546 + runAtomCommand(
547 + registry,
548 + manager.runStackedAction(targetKey),
549 + {
550 + actionId: failedActionId,
551 + action,
552 + },
553 + { reportFailure: false, reportDefect: false },
554 + ),
555 );
556
557 expect(AsyncResult.isFailure(failedResult)).toBe(true);
@@ -555,10 +565,15 @@ describe("vcsActionState", () => {
565 expect(removed).toEqual([`${environmentId}:*`, `${environmentId}:*`]);
566
567 const interruptedResult = yield* Effect.promise(() =>
558 - manager.runStackedAction(targetKey).run(registry, {
559 - actionId: interruptedActionId,
560 - action,
561 - }),
568 + runAtomCommand(
569 + registry,
570 + manager.runStackedAction(targetKey),
571 + {
572 + actionId: interruptedActionId,
573 + action,
574 + },
575 + { reportFailure: false, reportDefect: false },
576 + ),
577 );
578
579 expect(AsyncResult.isFailure(interruptedResult)).toBe(true);
packages/client-runtime/src/state/vcsStatusRevalidation.test.ts
+3 -2
@@ -1,5 +1,6 @@
1 import { EnvironmentId } from "@t3tools/contracts";
2 -import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
2 +import * as Effect from "effect/Effect";
3 +import { Atom, AtomRegistry } from "effect/reactivity";
4 import { describe, expect, it, vi } from "vite-plus/test";
5
6 import { createVcsStatusRevalidationAtomFamily } from "./vcsStatusRevalidation.ts";
@@ -9,7 +10,7 @@ const environmentId = EnvironmentId.make("environment-1");
10 function setup(options: { readonly connected?: boolean; readonly wake?: boolean }) {
11 const connectedAtom = Atom.make(options.connected ?? false);
12 const wakes = new Set<() => void>();
12 - const run = vi.fn(async () => AsyncResult.success(null));
13 + const run = vi.fn(() => Effect.succeed(null));
14 const family = createVcsStatusRevalidationAtomFamily({
15 refreshStatus: { label: "refresh-status", run },
16 ...(options.connected === undefined ? {} : { connected: () => connectedAtom }),