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 22, 13:15 UTC
refactor: flatten nested call chains (#26350)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 28, 2026 at 00:56 UTC
9bc4138923481dcada7f90d97ecaf0c42184bd4f
102 files changed
+423
-414
apps/desktop/src/app/DesktopAppActivation.ts
+5
-2
@@ -1,4 +1,5 @@
1
// @effect-diagnostics nodeBuiltinImport:off -- Local socket ownership checks need lstat, an atomic rename, and a directory watch at the Node adapter boundary.
2
+import { pipe } from "effect/Function";
3
import * as NodeCrypto from "node:crypto";
4
import * as NodeFS from "node:fs";
5
import * as NodeFSP from "node:fs/promises";
@@ -151,8 +152,10 @@ export async function startDesktopAppControlServer(input: {
152
}
153
154
if (!isDesktopAppActivationRequest(parsed)) {
154
- finish(
155
- invalidResponse(requestIdFromUnknown(parsed), "The desktop app request is invalid."),
155
+ pipe(
156
+ requestIdFromUnknown(parsed),
157
+ (requestId) => invalidResponse(requestId, "The desktop app request is invalid."),
158
+ finish,
159
);
160
return;
161
}
apps/desktop/src/snapShot/DesktopSnapShot.ts
+5
-4
@@ -1,5 +1,6 @@
1
// @effect-diagnostics globalTimers:off -- Capture timeouts and Electron overlay animation timers run at native callback boundaries outside Effect fibers.
2
3
+import { pipe } from "effect/Function";
4
import {
5
DEFAULT_CLIENT_SETTINGS,
6
DesktopPendingSnapShot,
@@ -1288,10 +1289,10 @@ export const make = Effect.gen(function* () {
1289
if (isModifierPairShortcut(shortcut)) {
1290
registered = yield* Effect.tryPromise(() =>
1291
startPairShortcutProcess(snapShotShortcutModifierPair(shortcut), onCurrentShortcut, () => {
1291
- void runPromise(
1292
- setShortcutFailure(
1293
- snapShotShortcutRegistrationFailureMessage(shortcut, environment.platform),
1294
- ),
1292
+ void pipe(
1293
+ snapShotShortcutRegistrationFailureMessage(shortcut, environment.platform),
1294
+ setShortcutFailure,
1295
+ runPromise,
1296
).catch(() => undefined);
1297
}),
1298
).pipe(
apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsx
+2
-3
@@ -10,7 +10,6 @@ import {
10
} from "@t3tools/client-runtime/connection";
11
import type { EnvironmentId } from "@t3tools/contracts";
12
import Constants from "expo-constants";
13
-import * as Option from "effect/Option";
13
import { AsyncResult } from "effect/reactivity";
14
import { Linking, View } from "react-native";
15
@@ -28,8 +27,8 @@ export function useConnectionDiagnosis(
27
environmentId: EnvironmentId,
28
presentation: EnvironmentPresentation | null,
29
) {
31
- const state = Option.getOrElse(
32
- AsyncResult.value(useAtomValue(environmentCatalog.stateAtom(environmentId))),
30
+ const state = AsyncResult.getOrElse(
31
+ useAtomValue(environmentCatalog.stateAtom(environmentId)),
32
() => AVAILABLE_CONNECTION_STATE,
33
);
34
if (presentation === null || !presentation.entry.enabled) return { diagnosis: null, state };
apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts
+3
-3
@@ -2,7 +2,6 @@ import { usePullRequestConnected } from "./usePullRequestConnected";
2
import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";
3
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4
import type { PullRequestDetail } from "@t3tools/contracts";
5
-import * as Option from "effect/Option";
5
import { AsyncResult } from "effect/reactivity";
6
import { use, useState } from "react";
7
import { composerPullRequests } from "../../state/pull-requests";
@@ -50,8 +49,9 @@ export function usePullRequestFilesViewed(params: PullRequestParams, pr: PullReq
49
input: { ...target.input, files: [{ path, viewed }] },
50
});
51
// The read that is current once the write lands still predates it; a newer one carries it.
53
- const readAtWrite = Option.getOrNull(
54
- AsyncResult.value(registry.get(composerPullRequests.filesViewed(target))),
52
+ const readAtWrite = AsyncResult.getOrElse(
53
+ registry.get(composerPullRequests.filesViewed(target)),
54
+ () => null,
55
);
56
setState((current) => {
57
if (current.key !== scopeKey || current.presses[path]?.version !== version) return current;
apps/mobile/src/features/pull-requests/usePullRequestList.ts
+1
-2
@@ -3,7 +3,6 @@ import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runt
3
import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
4
import * as Cause from "effect/Cause";
5
import * as Effect from "effect/Effect";
6
-import * as Option from "effect/Option";
6
import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
7
import { use, useMemo, useState } from "react";
8
import { environmentCatalog } from "../../connection/catalog";
@@ -32,7 +31,7 @@ type Read = <A>(atom: Atom.Atom<A>) => A;
31
32
/** The head the list query holds now, cached or answered. */
33
function currentHead(read: Read, target: ListTarget) {
35
- return Option.getOrNull(AsyncResult.value(read(composerPullRequests.list(target))));
34
+ return AsyncResult.getOrElse(read(composerPullRequests.list(target)), () => null);
35
}
36
37
function currentPages(read: Read, target: ListTarget): PullRequestListPages | null {
apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx
+1
-1
@@ -56,7 +56,7 @@ export function EnvironmentRoutesSection({
56
const entry = useAtomValue(environmentCatalog.catalogValueAtom).entries.get(environmentId);
57
const prepared = useAtomValue(environmentSession.preparedConnectionValueAtom(environmentId));
58
const sessionResult = useAtomValue(environmentSession.sessionStateAtom(environmentId));
59
- const session = Option.getOrNull(AsyncResult.value(sessionResult));
59
+ const session = AsyncResult.getOrElse(sessionResult, () => null);
60
const [permissionsOpen, setPermissionsOpen] = useState(false);
61
const reorder = useAtomCommand(environmentCatalog.reorderRoutes, "route reorder");
62
const removeRoute = useAtomCommand(environmentCatalog.removeRoute, "route removal");
apps/mobile/src/features/settings/environmentUpdateCheck.ts
+1
-1
@@ -40,7 +40,7 @@ export const environmentReleaseCheckAtom = Atom.family((environmentId: Environme
40
export function releaseCheckValue(
41
result: AsyncResult.AsyncResult<EnvironmentReleaseCheck, Error>,
42
): EnvironmentReleaseCheck | null {
43
- return Option.getOrNull(AsyncResult.value(result));
43
+ return AsyncResult.getOrElse(result, () => null);
44
}
45
46
export function releaseCheckError(
apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
+1
-2
@@ -20,7 +20,6 @@ import { AppText as Text } from "../../components/ui/AppText";
20
import { TerminalContextSheet } from "./TerminalContextSheet";
21
import { hasNativeTerminalSurface, supportsNativeTerminalOutput } from "./nativeTerminalModule";
22
import * as Clipboard from "expo-clipboard";
23
-import * as Option from "effect/Option";
23
import * as Schema from "effect/Schema";
24
import { AsyncResult } from "effect/reactivity";
25
import {
@@ -340,7 +339,7 @@ function readLiveTerminalSessions(
339
): ReadonlyArray<TerminalMenuSession> {
340
if (!readEnvironmentScope(environmentId, AuthTerminalReadScope)) return [];
341
const result = appAtomRegistry.get(terminalEnvironment.metadata({ environmentId, input: null }));
343
- const summaries = Option.getOrElse(AsyncResult.value(result), () => []);
342
+ const summaries = AsyncResult.getOrElse(result, () => []);
343
return summaries
344
.filter((summary) => summary.threadId === threadId)
345
.map((summary) => ({
apps/mobile/src/features/threads/LinkRequestCard.tsx
+3
-2
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import { useAtomValue } from "@effect/atom-react";
3
import {
4
type LinkableMachine,
@@ -125,7 +126,7 @@ function PendingLinkRequest(props: {
126
setDeclining(false),
127
);
128
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
128
- setError(linkRequestFailureMessage(squashAtomCommandFailure(result)));
129
+ pipe(squashAtomCommandFailure(result), linkRequestFailureMessage, setError);
130
}
131
};
132
@@ -311,7 +312,7 @@ function LinkRequestSheet(props: {
312
setPairingCode("");
313
props.onClose();
314
} else if (!isAtomCommandInterrupted(result)) {
314
- setError(linkRequestFailureMessage(squashAtomCommandFailure(result)));
315
+ pipe(squashAtomCommandFailure(result), linkRequestFailureMessage, setError);
316
}
317
};
318
apps/mobile/src/features/threads/SecretRequestCard.tsx
+2
-1
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import {
3
SECRET_REQUEST_DEFAULT_PLACEHOLDER,
4
secretRequestAnswerInput,
@@ -91,7 +92,7 @@ function PendingSecretRequestForm(props: {
92
return;
93
}
94
if (!isAtomCommandInterrupted(result)) {
94
- setError(secretRequestFailureMessage(squashAtomCommandFailure(result)));
95
+ pipe(squashAtomCommandFailure(result), secretRequestFailureMessage, setError);
96
}
97
};
98
apps/mobile/src/features/triage/useStartTriage.ts
+11
-6
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import {
3
isAtomCommandInterrupted,
4
squashAtomCommandFailure,
@@ -67,11 +68,11 @@ export function useStartTriage() {
68
const scratch = await openScratch({ environmentId, input: {} });
69
if (scratch._tag === "Failure") {
70
if (!isAtomCommandInterrupted(scratch)) {
70
- fail(
71
- errorMessage(
72
- squashAtomCommandFailure(scratch),
73
- "This machine cannot start threads without a project.",
74
- ),
71
+ pipe(
72
+ squashAtomCommandFailure(scratch),
73
+ (failure) =>
74
+ errorMessage(failure, "This machine cannot start threads without a project."),
75
+ fail,
76
);
77
}
78
return;
@@ -82,7 +83,11 @@ export function useStartTriage() {
83
});
84
if (prepared._tag === "Failure") {
85
if (!isAtomCommandInterrupted(prepared)) {
85
- fail(errorMessage(squashAtomCommandFailure(prepared), "The server could not prepare it."));
86
+ pipe(
87
+ squashAtomCommandFailure(prepared),
88
+ (failure) => errorMessage(failure, "The server could not prepare it."),
89
+ fail,
90
+ );
91
}
92
return;
93
}
apps/mobile/src/state/entities.ts
+1
-2
@@ -25,7 +25,6 @@ import {
25
threadLinkRefs,
26
type ThreadLink,
27
} from "@t3tools/shared/threadLinks";
28
-import * as Option from "effect/Option";
28
import * as Schema from "effect/Schema";
29
import { AsyncResult, Atom } from "effect/reactivity";
30
@@ -117,7 +116,7 @@ const threadProjectChipIconAtom = Atom.family((key: string) => {
116
);
117
if (!icon) return null;
118
if (icon.kind === "favicon") return icon.uri;
120
- return Option.getOrNull(AsyncResult.value(get(projectGlyphImageAtom(projectGlyphKey(icon)))));
119
+ return AsyncResult.getOrElse(get(projectGlyphImageAtom(projectGlyphKey(icon))), () => null);
120
}).pipe(Atom.withLabel(`mobile-thread-project-chip-icon:${key}`));
121
});
122
apps/mobile/src/state/mediaActions.ts
+1
-2
@@ -13,7 +13,6 @@ import {
13
type SessionGrantInput,
14
} from "@t3tools/contracts";
15
import { normalizeNativeMarkdownUrl } from "../lib/markdownLinks";
16
-import * as Option from "effect/Option";
16
import { AsyncResult } from "effect/reactivity";
17
import { useEffect, useRef, useState } from "react";
18
@@ -32,7 +31,7 @@ function allowsHostMedia(session: SessionGrantInput | null) {
31
function canReadHostMedia(environmentId: EnvironmentId | null): boolean {
32
if (environmentId === null) return true;
33
const result = appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId));
35
- return result._tag !== "Failure" && allowsHostMedia(Option.getOrNull(AsyncResult.value(result)));
34
+ return result._tag !== "Failure" && allowsHostMedia(AsyncResult.getOrElse(result, () => null));
35
}
36
37
export function useMediaActions(source: MediaActionsSource | undefined, onOpenFile?: () => void) {
apps/mobile/src/state/projectClones.ts
+1
-2
@@ -1,7 +1,6 @@
1
import { useAtomValue } from "@effect/atom-react";
2
import { parseScopedProjectKey, scopedProjectKey } from "@t3tools/client-runtime/environment";
3
import type { EnvironmentId, ProjectCloneSnapshot, ScopedProjectRef } from "@t3tools/contracts";
4
-import * as Option from "effect/Option";
4
import { AsyncResult, Atom } from "effect/reactivity";
5
6
import { serverEnvironment } from "./server";
@@ -22,7 +21,7 @@ const environmentProjectClonesAtom = Atom.family((environmentId: EnvironmentId)
21
const result = get(sourceControlEnvironment.projectClones({ environmentId, input: {} }));
22
// On subscription failure, let server dispatch guards decide rather than blocking Start until reconnect.
23
if (result._tag === "Failure") return EMPTY_CLONES;
25
- return Option.getOrElse(AsyncResult.value(result), () => "pending" as const);
24
+ return AsyncResult.getOrElse(result, () => "pending" as const);
25
}).pipe(Atom.withLabel(`mobile-project-clones:${environmentId}`)),
26
);
27
apps/mobile/src/state/queries.ts
+1
-1
@@ -318,7 +318,7 @@ export function usePaginatedBranches(target: VcsRefTarget) {
318
);
319
const results = useAtomValue(pagesAtom);
320
const values = results.flatMap((result) => {
321
- const value = Option.getOrNull(AsyncResult.value(result));
321
+ const value = AsyncResult.getOrElse(result, () => null);
322
return value === null ? [] : [value];
323
});
324
const refs = new Map<string, VcsRef>();
apps/mobile/src/state/query.ts
+1
-2
@@ -1,6 +1,5 @@
1
import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
2
import * as Cause from "effect/Cause";
3
-import * as Option from "effect/Option";
3
import { AsyncResult, Atom } from "effect/reactivity";
4
5
const EMPTY_ASYNC_RESULT_ATOM = Atom.make(AsyncResult.initial<never, never>(false)).pipe(
@@ -31,7 +30,7 @@ export function useEnvironmentQuery<A, E>(
30
const result = useAtomValue(selectedAtom);
31
const refresh = useAtomRefresh(selectedAtom);
32
return {
34
- data: Option.getOrNull(AsyncResult.value(result)),
33
+ data: AsyncResult.getOrElse(result, () => null),
34
// Data may be structurally shared; only a settled success proves a new response.
35
successResult: result._tag === "Success" && !result.waiting ? result : null,
36
failure: result._tag === "Failure" ? Cause.squash(result.cause) : null,
apps/mobile/src/state/session.ts
+1
-1
@@ -21,7 +21,7 @@ export function sessionHasScope(
21
result: AsyncResult.AsyncResult<AuthSessionState, unknown>,
22
scope: AuthEnvironmentScope,
23
): boolean {
24
- const session = Option.getOrNull(AsyncResult.value(result));
24
+ const session = AsyncResult.getOrElse(result, () => null);
25
return result._tag !== "Failure" && session !== null && sessionGrantsScope(session, scope);
26
}
27
apps/mobile/src/state/threads.ts
+2
-3
@@ -10,7 +10,6 @@ import {
10
createThreadFamilyAtoms,
11
} from "@t3tools/client-runtime/state/threads";
12
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
13
-import * as Option from "effect/Option";
13
import { AsyncResult, Atom } from "effect/reactivity";
14
import { useEffect } from "react";
15
@@ -94,8 +93,8 @@ export function useEnvironmentThread(
93
? environmentThreads.stateAtom(environmentId, threadId)
94
: EMPTY_THREAD_STATE_ATOM,
95
);
97
- const state = Option.getOrElse(
98
- AsyncResult.value(result),
96
+ const state = AsyncResult.getOrElse(
97
+ result,
98
() => EMPTY_ENVIRONMENT_THREAD_STATE,
99
) as EnvironmentThreadState;
100
return state;
apps/mobile/src/state/usage.ts
+2
-3
@@ -9,7 +9,6 @@ import {
9
import { needsCursorKeychainAccess, refreshUsage } from "@t3tools/client-runtime/state/usage";
10
import { resolveUsageAccess } from "@t3tools/client-runtime/state/usage-access";
11
import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
12
-import * as Option from "effect/Option";
12
import { AsyncResult, Atom } from "effect/reactivity";
13
import { useCallback, useMemo } from "react";
14
@@ -39,7 +38,7 @@ const usageByWindowAtom = Atom.family((windowKey: string) =>
38
const sessionResult = get(environmentSession.sessionStateAtom(environmentId));
39
const access = resolveUsageAccess({
40
connectionPhase: presentation.connection.phase,
42
- session: Option.getOrNull(AsyncResult.value(sessionResult)),
41
+ session: AsyncResult.getOrElse(sessionResult, () => null),
42
hasSessionError: sessionResult._tag === "Failure",
43
});
44
if (!access.canReadDiagnostics) {
@@ -54,7 +53,7 @@ const usageByWindowAtom = Atom.family((windowKey: string) =>
53
continue;
54
}
55
const result = get(serverEnvironment.usageSummary({ environmentId, input }));
57
- const summary = Option.getOrNull(AsyncResult.value(result));
56
+ const summary = AsyncResult.getOrElse(result, () => null);
57
statuses.push({
58
environmentId,
59
label: presentation.entry.target.label,
apps/mobile/src/state/use-composer-drafts.ts
+1
-3
@@ -1517,9 +1517,7 @@ export function subscribeComposerDraftModelReconciliation(input: {
1517
if (!thread || !draftModelPickMatchesThread(draft.modelSelection, thread.modelSelection))
1518
continue;
1519
// Status and selection must come from the same emission; derived atoms can update apart.
1520
- const shell = Option.getOrNull(
1521
- AsyncResult.value(get(input.shellStateAtom(ref.environmentId))),
1522
- );
1520
+ const shell = AsyncResult.getOrElse(get(input.shellStateAtom(ref.environmentId)), () => null);
1521
if (shell?.status !== "live") continue;
1522
const authoritativeThread = Option.getOrNull(shell.snapshot)?.threads.find(
1523
(candidate) => candidate.id === ref.threadId,
apps/server/scripts/fetch-expo-schema.ts
+5
-2
@@ -4,6 +4,7 @@
4
* without a credential. eas-cli generates its own client from the same
5
* endpoint. Run `vp run generate` afterwards to regenerate the operations.
6
*/
7
+import { pipe } from "effect/Function";
8
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
9
import * as NodeServices from "@effect/platform-node/NodeServices";
10
import * as Effect from "effect/Effect";
@@ -36,8 +37,10 @@ const program = Effect.gen(function* () {
37
Effect.flatMap(HttpClientResponse.schemaBodyJson(IntrospectionResponse)),
38
);
39
// Sorted so a refresh diffs by what Expo changed, not by its declaration order.
39
- const sdl = printSchema(
40
- lexicographicSortSchema(buildClientSchema(response.data as unknown as IntrospectionQuery)),
40
+ const sdl = pipe(
41
+ buildClientSchema(response.data as unknown as IntrospectionQuery),
42
+ lexicographicSortSchema,
43
+ printSchema,
44
);
45
const target = path.join(import.meta.dirname, "..", "schema", "expo.graphql");
46
yield* fs.makeDirectory(path.dirname(target), { recursive: true });
apps/server/scripts/record-pi-rpc-replay-fixture.ts
+7
-2
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import * as NodeServices from "@effect/platform-node/NodeServices";
3
import type { ProviderReplayEntry, ProviderReplayTranscript } from "@t3tools/contracts";
4
import * as Console from "effect/Console";
@@ -99,8 +100,12 @@ function normalizeEntries(input: {
100
.replaceAll(input.workspace, "<workspace>")
101
.replaceAll(home.length > 1 ? home : "\0", "~")
102
.replace(ISO_TIMESTAMP_PATTERN, (iso) =>
102
- DateTime.formatIso(
103
- DateTime.makeUnsafe(shiftTime(DateTime.toEpochMillis(DateTime.makeUnsafe(iso)))),
103
+ pipe(
104
+ DateTime.makeUnsafe(iso),
105
+ DateTime.toEpochMillis,
106
+ shiftTime,
107
+ DateTime.makeUnsafe,
108
+ DateTime.formatIso,
109
),
110
)
111
.replace(UUID_PATTERN, (uuid) => {
apps/server/src/http.ts
+6
-3
@@ -16,7 +16,7 @@ import * as Option from "effect/Option";
16
import * as Path from "effect/Path";
17
import * as Schema from "effect/Schema";
18
import * as Stream from "effect/Stream";
19
-import { cast } from "effect/Function";
19
+import { cast, pipe } from "effect/Function";
20
import {
21
HttpClient,
22
HttpClientResponse,
@@ -181,8 +181,11 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* (
181
if (bytes === null) {
182
return HttpServerResponse.text("MCP app is too large to preview.", { status: 413 });
183
}
184
- const body = new TextEncoder().encode(
185
- injectMcpAppCookieBootstrap(injectMcpAppThemeBootstrap(new TextDecoder().decode(bytes))),
184
+ const body = pipe(
185
+ new TextDecoder().decode(bytes),
186
+ injectMcpAppThemeBootstrap,
187
+ injectMcpAppCookieBootstrap,
188
+ (html) => new TextEncoder().encode(html),
189
);
190
headers["Content-Length"] = String(body.byteLength);
191
return method === "HEAD"
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+6
-2
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import * as DocumentText from "../../provider/DocumentText.ts";
3
import { revertCodexThread } from "../../provider/CodexThreadRevert.ts";
4
import { historyResponseItems } from "@t3tools/provider-core/server/handoffBudget";
@@ -1448,8 +1449,11 @@ function redactCodexProtocolValue(value: unknown): unknown {
1449
return value;
1450
}
1451
try {
1451
- return JSON.stringify(
1452
- redactCodexProtocolValue(boundProviderEventForLogging(JSON.parse(trimmed) as unknown)),
1452
+ return pipe(
1453
+ JSON.parse(trimmed) as unknown,
1454
+ boundProviderEventForLogging,
1455
+ redactCodexProtocolValue,
1456
+ JSON.stringify,
1457
);
1458
} catch {
1459
return value;
apps/server/src/provider/CodexChatGptAuth.ts
+62
-71
@@ -736,78 +736,69 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
736
),
737
)
738
.pipe(Effect.map(Hex.encode), Effect.orDie);
739
- const access = lock.withPermit(
740
- withSessionLock(
741
- Effect.uninterruptible(
742
- Effect.gen(function* () {
743
- const saved = yield* read;
744
- if (Option.isNone(saved))
745
- return yield* failure("access", "Sign in with ChatGPT to use managed Codex.");
746
- let record = saved.value;
747
- if (
748
- options.expectedProfileKey !== undefined &&
749
- (yield* profileKey(record)) !== options.expectedProfileKey
750
- )
751
- return yield* failure("access", "The ChatGPT connection changed. Start a new session.");
752
- if (!record.scopes.includes(REQUIRED_SCOPE))
753
- return yield* failure(
754
- "sharing",
755
- "Token sharing is disabled. Sign in with ChatGPT and enable token sharing.",
756
- );
757
- const now = yield* Clock.currentTimeMillis;
758
- if (record.expiresAt - now > 60_000) return record;
759
- if (record.earliestRefreshAt !== null && record.earliestRefreshAt > now) {
760
- if (record.expiresAt > now) return record;
761
- return yield* failure(
762
- "refresh",
763
- "ChatGPT cannot renew this connection yet. Try again shortly.",
764
- );
765
- }
766
- if (!record.refreshToken) {
767
- yield* remove;
768
- return yield* failure("refresh", "Your ChatGPT connection expired. Sign in again.");
769
- }
770
- const tokens = yield* exchange(
771
- new URLSearchParams({
772
- grant_type: "refresh_token",
773
- client_id: record.clientId,
774
- refresh_token: record.refreshToken,
775
- resource,
776
- }),
777
- ).pipe(
778
- Effect.interruptible,
779
- Effect.timeout("20 seconds"),
780
- Effect.mapError((error) =>
781
- error._tag === "ProviderSetupError" && error.operation === "client"
782
- ? error
783
- : failure(
784
- "refresh",
785
- "Could not renew the ChatGPT connection. Retry, or sign in again.",
786
- ),
787
- ),
788
- );
789
- if (!tokens.refresh_token || tokens.token_type.toLowerCase() !== "bearer") {
790
- return yield* failure("refresh", "ChatGPT returned an invalid renewal. Sign in again.");
791
- }
792
- record = {
793
- ...record,
794
- accessToken: tokens.access_token,
795
- refreshToken: tokens.refresh_token,
796
- expiresAt: (yield* Clock.currentTimeMillis) + tokens.expires_in * 1000,
797
- earliestRefreshAt: earliest(tokens.earliest_refresh_at),
798
- scopes: tokens.scope.split(/\s+/).filter(Boolean),
799
- };
800
- yield* save(record);
801
- if (!record.scopes.includes(REQUIRED_SCOPE))
802
- return yield* failure(
803
- "sharing",
804
- "ChatGPT token sharing is no longer enabled. Sign in again.",
805
- );
806
- return record;
807
- }),
739
+ const access = Effect.gen(function* () {
740
+ const saved = yield* read;
741
+ if (Option.isNone(saved))
742
+ return yield* failure("access", "Sign in with ChatGPT to use managed Codex.");
743
+ let record = saved.value;
744
+ if (
745
+ options.expectedProfileKey !== undefined &&
746
+ (yield* profileKey(record)) !== options.expectedProfileKey
747
+ )
748
+ return yield* failure("access", "The ChatGPT connection changed. Start a new session.");
749
+ if (!record.scopes.includes(REQUIRED_SCOPE))
750
+ return yield* failure(
751
+ "sharing",
752
+ "Token sharing is disabled. Sign in with ChatGPT and enable token sharing.",
753
+ );
754
+ const now = yield* Clock.currentTimeMillis;
755
+ if (record.expiresAt - now > 60_000) return record;
756
+ if (record.earliestRefreshAt !== null && record.earliestRefreshAt > now) {
757
+ if (record.expiresAt > now) return record;
758
+ return yield* failure(
759
+ "refresh",
760
+ "ChatGPT cannot renew this connection yet. Try again shortly.",
761
+ );
762
+ }
763
+ if (!record.refreshToken) {
764
+ yield* remove;
765
+ return yield* failure("refresh", "Your ChatGPT connection expired. Sign in again.");
766
+ }
767
+ const tokens = yield* exchange(
768
+ new URLSearchParams({
769
+ grant_type: "refresh_token",
770
+ client_id: record.clientId,
771
+ refresh_token: record.refreshToken,
772
+ resource,
773
+ }),
774
+ ).pipe(
775
+ Effect.interruptible,
776
+ Effect.timeout("20 seconds"),
777
+ Effect.mapError((error) =>
778
+ error._tag === "ProviderSetupError" && error.operation === "client"
779
+ ? error
780
+ : failure("refresh", "Could not renew the ChatGPT connection. Retry, or sign in again."),
781
),
809
- ),
810
- );
782
+ );
783
+ if (!tokens.refresh_token || tokens.token_type.toLowerCase() !== "bearer") {
784
+ return yield* failure("refresh", "ChatGPT returned an invalid renewal. Sign in again.");
785
+ }
786
+ record = {
787
+ ...record,
788
+ accessToken: tokens.access_token,
789
+ refreshToken: tokens.refresh_token,
790
+ expiresAt: (yield* Clock.currentTimeMillis) + tokens.expires_in * 1000,
791
+ earliestRefreshAt: earliest(tokens.earliest_refresh_at),
792
+ scopes: tokens.scope.split(/\s+/).filter(Boolean),
793
+ };
794
+ yield* save(record);
795
+ if (!record.scopes.includes(REQUIRED_SCOPE))
796
+ return yield* failure(
797
+ "sharing",
798
+ "ChatGPT token sharing is no longer enabled. Sign in again.",
799
+ );
800
+ return record;
801
+ }).pipe(Effect.uninterruptible, withSessionLock, lock.withPermit);
802
const logout = Effect.gen(function* () {
803
const credentials = Option.getOrUndefined(yield* read);
804
let confirmed = !credentials?.refreshToken;
apps/server/src/provider/CodexProvider.ts
+5
-5
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import * as DateTime from "effect/DateTime";
3
import * as Duration from "effect/Duration";
4
import * as Effect from "effect/Effect";
@@ -801,11 +802,10 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
802
presentation: CODEX_PRESENTATION,
803
enabled: codexSettings.enabled,
804
checkedAt,
804
- models: applyConfiguredCodexServiceTier(
805
- applyPreferredCodexDefaultModel(
806
- appendCustomCodexModels(snapshot.models ?? [], codexSettings.customModels),
807
- ),
808
- snapshot.serviceTier,
805
+ models: pipe(
806
+ appendCustomCodexModels(snapshot.models ?? [], codexSettings.customModels),
807
+ applyPreferredCodexDefaultModel,
808
+ (models) => applyConfiguredCodexServiceTier(models, snapshot.serviceTier),
809
),
810
skills: snapshot.skills,
811
slashCommands: [
apps/server/src/provider/Drivers/antigravityUsageReader.ts
+4
-1
@@ -1,5 +1,6 @@
1
// @effect-diagnostics-next-line nodeBuiltinImport:off - Effect's File.Info has no ctime, which the cache fingerprint needs.
2
import * as NodeFSP from "node:fs/promises";
3
+import { pipe } from "effect/Function";
4
5
import type { UsageRecord } from "@t3tools/provider-core/server/usage";
6
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
@@ -244,7 +245,9 @@ const readDatabase = Effect.fn("readDatabase")(function* (
245
for (const row of yield* sql.unsafe<{ readonly data: unknown }>(
246
"SELECT data FROM trajectory_metadata_blob",
247
)) {
247
- trajectoryTimestamp ??= yield* decode(() => timestamp(nested(fields(blob(row.data)), 2)));
248
+ trajectoryTimestamp ??= yield* decode(() =>
249
+ pipe(blob(row.data), fields, (message) => nested(message, 2), timestamp),
250
+ );
251
}
252
}
253
const steps = tables.has("steps")
apps/server/src/secrets/SecretRequests.ts
+3
-2
@@ -1,6 +1,7 @@
1
// Answers stay in the secret store behind one-use refs; orchestration records only request status.
2
// Consuming tools keep values out of transcripts, projections, clients and model context.
3
// A `file` request instead moves its value to an owner-only file for the agent's own shell.
4
+import { pipe } from "effect/Function";
5
import {
6
CommandId,
7
SecretRef,
@@ -143,7 +144,7 @@ const make = Effect.gen(function* () {
144
// Clear failed saves so the pending card can be answered again.
145
Effect.tapError(() =>
146
input.answer.type === "save"
146
- ? removeLogged(storeName(refFor(salt, input.threadId, item.id)))
147
+ ? pipe(refFor(salt, input.threadId, item.id), storeName, removeLogged)
148
: Effect.void,
149
),
150
);
@@ -159,7 +160,7 @@ const make = Effect.gen(function* () {
160
);
161
const card = recorded.turnItems.find((candidate) => candidate.id === item.id);
162
if (card?.type === "secret_request" && card.secretStatus !== "saved") {
162
- yield* removeLogged(storeName(refFor(salt, input.threadId, item.id)));
163
+ yield* pipe(refFor(salt, input.threadId, item.id), storeName, removeLogged);
164
return yield* new SecretRequestError({ reason: "agent_stopped" });
165
}
166
},
apps/server/src/ws.ts
+8
-10
@@ -889,11 +889,10 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs
889
projection: dedupeBodies ? dedupeSnapshotBodies(projection) : projection,
890
};
891
})();
892
- return withLiveDedupe(
893
- Stream.concat(
894
- Stream.concat(rpcInitialItems([snapshotItem]), completionMarker),
895
- eventStreamFrom(snapshotSequence),
896
- ),
892
+ return rpcInitialItems([snapshotItem]).pipe(
893
+ Stream.concat(completionMarker),
894
+ Stream.concat(eventStreamFrom(snapshotSequence)),
895
+ withLiveDedupe,
896
);
897
});
898
@@ -962,11 +961,10 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs
961
if (plan.mode === "snapshot") {
962
return yield* snapshotThenLive();
963
}
965
- return withLiveDedupe(
966
- Stream.concat(
967
- Stream.concat(rpcInitialItems(replay), completionMarker),
968
- eventStreamFrom(highWater),
969
- ),
964
+ return rpcInitialItems(replay).pipe(
965
+ Stream.concat(completionMarker),
966
+ Stream.concat(eventStreamFrom(highWater)),
967
+ withLiveDedupe,
968
);
969
}
970
apps/web/src/browser/previewWebviewConfigState.ts
+1
-2
@@ -5,7 +5,6 @@ import type {
5
EnvironmentId,
6
} from "@t3tools/contracts";
7
import * as Effect from "effect/Effect";
8
-import * as Option from "effect/Option";
8
import * as Schema from "effect/Schema";
9
import { AsyncResult, Atom } from "effect/reactivity";
10
@@ -91,5 +90,5 @@ export function usePreviewWebviewConfig(
90
profileId?: string,
91
): DesktopPreviewWebviewConfig | null {
92
const result = useAtomValue(previewWebviewConfigAtom(configKey(environmentId, profileId)));
94
- return Option.getOrNull(AsyncResult.value(result));
93
+ return AsyncResult.getOrElse(result, () => null);
94
}
apps/web/src/cloud/primaryCloudLinkState.ts
+1
-2
@@ -8,7 +8,6 @@ import * as Cause from "effect/Cause";
8
import * as Context from "effect/Context";
9
import * as Effect from "effect/Effect";
10
import * as Layer from "effect/Layer";
11
-import * as Option from "effect/Option";
11
import { AsyncResult, Atom } from "effect/reactivity";
12
import { HttpClient } from "effect/http";
13
@@ -90,7 +89,7 @@ export function usePrimaryCloudLinkState() {
89
}
90
91
return {
93
- data: result._tag === "Failure" ? null : Option.getOrNull(AsyncResult.value(result)),
92
+ data: result._tag === "Failure" ? null : AsyncResult.getOrElse(result, () => null),
93
error,
94
isPending: result.waiting,
95
refresh,
apps/web/src/components/ChatView.tsx
+5
-9
@@ -185,11 +185,9 @@ import { toastManager } from "./ui/toast";
185
import { projectScriptIdFromCommand } from "~/projectScripts";
186
import { newMessageId } from "~/lib/utils";
187
import {
188
- applyProviderInstanceSettings,
189
- deriveProviderInstanceEntries,
188
NO_PROVIDER_MODEL_SELECTION,
189
+ providerInstanceEntriesFor,
190
shouldShowInstanceBadge,
192
- sortProviderInstanceEntries,
191
} from "../providerInstances";
192
import {
193
useClientSettings,
@@ -1237,12 +1235,10 @@ export default function ChatView(props: ChatViewProps) {
1235
automaticEnvironment,
1236
autoUpdateEnvironments,
1237
});
1240
- const providerInstanceEntries = sortProviderInstanceEntries(
1241
- applyProviderInstanceSettings(
1242
- deriveProviderInstanceEntries(providerStatuses),
1243
- settings,
1244
- activeProject?.id ?? null,
1245
- ),
1238
+ const providerInstanceEntries = providerInstanceEntriesFor(
1239
+ providerStatuses,
1240
+ settings,
1241
+ activeProject?.id ?? null,
1242
);
1243
const activeThreadModelInstanceId = activeThread?.modelSelection.instanceId;
1244
const { selectedProviderEntry, requestedDriverKind } = resolveComposerProviderSelection({
apps/web/src/components/ThreadStatusIndicators.tsx
+5
-2
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import {
3
scopeProjectRef,
4
scopedThreadKey,
@@ -325,8 +326,10 @@ export function ThreadPullRequestsMiniList({
326
pullRequests: ReadonlyArray<ThreadPullRequestLink>;
327
onOpenPullRequest?: (event: MouseEvent<HTMLAnchorElement>, url: string) => void;
328
}) {
328
- const lines = pullRequestListLines(
329
- resolveThreadPullRequestChains(visibleThreadPullRequests(pullRequests)),
329
+ const lines = pipe(
330
+ visibleThreadPullRequests(pullRequests),
331
+ resolveThreadPullRequestChains,
332
+ pullRequestListLines,
333
);
334
if (lines.length === 0) return null;
335
return (
apps/web/src/components/chat/LinkRequestCard.tsx
+3
-2
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import { useAtomValue } from "@effect/atom-react";
3
import {
4
type LinkableMachine,
@@ -106,7 +107,7 @@ function PendingLinkRequest(props: {
107
setDeclining(false),
108
);
109
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
109
- setError(linkRequestFailureMessage(squashAtomCommandFailure(result)));
110
+ pipe(squashAtomCommandFailure(result), linkRequestFailureMessage, setError);
111
}
112
};
113
@@ -311,7 +312,7 @@ function LinkRequestDialog(props: {
312
// The card switches to its answered row once the item updates.
313
close();
314
} else if (!isAtomCommandInterrupted(result)) {
314
- setError(linkRequestFailureMessage(squashAtomCommandFailure(result)));
315
+ pipe(squashAtomCommandFailure(result), linkRequestFailureMessage, setError);
316
}
317
};
318
apps/web/src/components/chat/SecretRequestCard.tsx
+2
-1
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import {
3
SECRET_REQUEST_DEFAULT_PLACEHOLDER,
4
secretRequestAnswerInput,
@@ -86,7 +87,7 @@ function PendingSecretRequestForm(props: {
87
return;
88
}
89
if (!isAtomCommandInterrupted(result)) {
89
- setError(secretRequestFailureMessage(squashAtomCommandFailure(result)));
90
+ pipe(squashAtomCommandFailure(result), secretRequestFailureMessage, setError);
91
}
92
};
93
apps/web/src/components/chat/ThreadDetailsPrRows.tsx
+2
-1
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import { ThreadDetailsControl } from "./ThreadDetailsControl";
3
import type { EnvironmentId, ScopedThreadRef, ThreadPullRequestLink } from "@t3tools/contracts";
4
import {
@@ -94,7 +95,7 @@ export function ThreadDetailsPrRows({
95
const rest =
96
currentLink === null
97
? []
97
- : pullRequestListLines(resolveThreadPullRequestChains(visibleThreadPullRequests(links)))
98
+ : pipe(visibleThreadPullRequests(links), resolveThreadPullRequestChains, pullRequestListLines)
99
.map((line) => line.link)
100
.filter((link) => threadPullRequestKeyOf(link) !== threadPullRequestKeyOf(currentLink));
101
if (rest.length === 0) return currentRow;
apps/web/src/components/chat/useComposerProviderModel.ts
+5
-9
@@ -12,10 +12,8 @@ import {
12
} from "@t3tools/contracts";
13
import {
14
NO_PROVIDER_MODEL_SELECTION,
15
+ providerInstanceEntriesFor,
16
type ProviderInstanceEntry,
16
- applyProviderInstanceSettings,
17
- deriveProviderInstanceEntries,
18
- sortProviderInstanceEntries,
17
} from "../../providerInstances";
18
import { type UnifiedSettings } from "@t3tools/contracts/settings";
19
import { getComposerPromptInjectionState, getComposerProviderState } from "./composerProviderState";
@@ -52,12 +50,10 @@ export function useComposerProviderModel(
50
lockedInstanceId,
51
} = input;
52
const draftModelState = useComposerDraftModelState(threadRef);
55
- const providerInstanceEntries: ReadonlyArray<ProviderInstanceEntry> = sortProviderInstanceEntries(
56
- applyProviderInstanceSettings(
57
- deriveProviderInstanceEntries(providerStatuses),
58
- settings,
59
- activeProjectId,
60
- ),
53
+ const providerInstanceEntries: ReadonlyArray<ProviderInstanceEntry> = providerInstanceEntriesFor(
54
+ providerStatuses,
55
+ settings,
56
+ activeProjectId,
57
);
58
const selection = resolveComposerProviderSelection({
59
entries: providerInstanceEntries,
apps/web/src/components/device/DeviceStreamView.tsx
+1
-2
@@ -1,6 +1,5 @@
1
import type { DevicePlatform, EnvironmentId } from "@t3tools/contracts";
2
import { useAtomValue } from "@effect/atom-react";
3
-import * as Option from "effect/Option";
3
import { AsyncResult, Atom } from "effect/reactivity";
4
import { useId, useRef, useState, type ReactNode } from "react";
5
@@ -197,7 +196,7 @@ export function DeviceStreamView(props: {
196
? deviceAxElementsAtom({ access, platform: props.platform, deviceId: props.deviceId })
197
: NO_AX_ATOM,
198
);
200
- const axElements = Option.getOrElse(AsyncResult.value(axResult), () => NO_AX_ELEMENTS);
199
+ const axElements = AsyncResult.getOrElse(axResult, () => NO_AX_ELEMENTS);
200
201
const pointerActive = useRef(false);
202
const normalizedPoint = (event: React.PointerEvent<HTMLElement>) => {
apps/web/src/components/files/extendedDocumentPreview.ts
+3
-2
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import {
3
IMAGE_DIMENSIONS_HEADER_BYTES,
4
readImageDimensions,
@@ -221,7 +222,7 @@ const HTML_TAGS = new Set([
222
"dd",
223
]);
224
async function epubHtml(node: XmlNode, archive: JSZip, base: string): Promise<string> {
224
- if (node.name === "#text") return boundedMarkup(escape(text(node)));
225
+ if (node.name === "#text") return pipe(text(node), escape, boundedMarkup);
226
const tag =
227
node.name
228
.replace(/^\{[^}]*\}/, "")
@@ -249,7 +250,7 @@ async function epubHtml(node: XmlNode, archive: JSZip, base: string): Promise<st
250
return `<${tag}${spans}>${children}</${tag}>`;
251
}
252
async function odfHtml(node: XmlNode, archive: JSZip): Promise<string> {
252
- if (node.name === "#text") return boundedMarkup(escape(text(node)));
253
+ if (node.name === "#text") return pipe(text(node), escape, boundedMarkup);
254
if (node.name === "text:s" || node.name === "text:tab")
255
return boundedMarkup(
256
`<span data-odf-whitespace>${node.name === "text:tab" ? "	" : " ".repeat(repeat(node.attrs["text:c"], 100))}</span>`,
apps/web/src/components/files/office/fonts.ts
+3
-2
@@ -1,4 +1,5 @@
1
// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+import { pipe } from "effect/Function";
3
import type { BundledFontProvider } from "@betteroffice/docx/layout";
4
import {
5
loadBundledFontBytes,
@@ -23,9 +24,9 @@ export function wordFonts(): BundledFontProvider {
24
25
return {
26
resolve: (family, bold, italic) =>
26
- loader(shippedFace(resolveMetricCompatFace(family, bold, italic))),
27
+ pipe(resolveMetricCompatFace(family, bold, italic), shippedFace, loader),
28
resolveFamily: (family, bold, italic) =>
28
- loader(shippedFace(resolveBundledFamilyFace(family, bold, italic))),
29
+ pipe(resolveBundledFamilyFace(family, bold, italic), shippedFace, loader),
30
resolveScriptFallback: (script, bold, italic) => loader(scriptFace(script, bold, italic)),
31
resolveLastResort: (family, bold, italic) => () =>
32
loadFace(lastResortFace(family, bold, italic, "word")),
apps/web/src/components/files/office/slide-text.ts
+52
-43
@@ -1,4 +1,5 @@
1
// Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode.
2
+import { pipe } from "effect/Function";
3
import * as Option from "effect/Option";
4
import * as Schema from "effect/Schema";
5
import { inspectPresentation, type DeckSnapshot } from "@betteroffice/pptx";
@@ -131,50 +132,58 @@ const scriptRanges: readonly (readonly [FallbackScript, RegExp])[] = [
132
* engine's inspection does not decode, the slides' own runs stand in, without theme fonts or hidden flags.
133
*/
134
export function deckText(bytes: Uint8Array, snapshot: DeckSnapshot): DeckText {
134
- return Option.match(decodeInspected(inspectPresentation(withoutMedia(bytes))), {
135
- onNone: () => fromSnapshot(snapshot),
136
- onSome: (inspected) => {
137
- const schemes =
138
- inspected.themes?.flatMap((theme) =>
139
- theme.theme?.fontScheme ? [theme.theme.fontScheme] : [],
140
- ) ?? [];
141
- const minor = schemes[0]?.minorFont.latin ?? "";
142
-
143
- const drawings = [
144
- ...inspected.slides.flatMap((slide) => slide.drawings),
145
- ...(inspected.layouts ?? []).flatMap((layout) => layout.drawings),
146
- ...(inspected.masters ?? []).flatMap((master) => master.drawings),
147
- ];
148
-
149
- const defaults = (inspected.masters ?? []).flatMap((master) =>
150
- Object.values(master.textStyles ?? {}).flatMap((levels) =>
151
- levels.flatMap((level) =>
152
- level.defaultRun ? [{ text: "", style: level.defaultRun }] : [],
135
+ return pipe(
136
+ withoutMedia(bytes),
137
+ inspectPresentation,
138
+ decodeInspected,
139
+ Option.match({
140
+ onNone: () => fromSnapshot(snapshot),
141
+ onSome: (inspected) => {
142
+ const schemes =
143
+ inspected.themes?.flatMap((theme) =>
144
+ theme.theme?.fontScheme ? [theme.theme.fontScheme] : [],
145
+ ) ?? [];
146
+ const minor = schemes[0]?.minorFont.latin ?? "";
147
+
148
+ const drawings = [
149
+ ...inspected.slides.flatMap((slide) => slide.drawings),
150
+ ...(inspected.layouts ?? []).flatMap((layout) => layout.drawings),
151
+ ...(inspected.masters ?? []).flatMap((master) => master.drawings),
152
+ ];
153
+
154
+ const defaults = (inspected.masters ?? []).flatMap((master) =>
155
+ Object.values(master.textStyles ?? {}).flatMap((levels) =>
156
+ levels.flatMap((level) =>
157
+ level.defaultRun ? [{ text: "", style: level.defaultRun }] : [],
158
+ ),
159
),
154
- ),
155
- );
156
-
157
- return summarize(
158
- [...drawings.flatMap(drawingRuns), ...defaults].flatMap((run) => {
159
- const family = run.style?.fontFamily;
160
- if (!schemes.length || (family && !family.startsWith("+mn") && !family.startsWith("+mj")))
161
- return [run];
162
- return schemes.map((scheme) => ({
163
- ...run,
164
- style: {
165
- ...run.style,
166
- fontFamily: family?.startsWith("+mj")
167
- ? scheme.majorFont.latin
168
- : scheme.minorFont.latin,
169
- },
170
- }));
171
- }),
172
- (family) => (family?.startsWith("+") ? "" : (family ?? "")),
173
- minor,
174
- inspected.slides.map((slide) => slide.hidden ?? false),
175
- );
176
- },
177
- });
160
+ );
161
+
162
+ return summarize(
163
+ [...drawings.flatMap(drawingRuns), ...defaults].flatMap((run) => {
164
+ const family = run.style?.fontFamily;
165
+ if (
166
+ !schemes.length ||
167
+ (family && !family.startsWith("+mn") && !family.startsWith("+mj"))
168
+ )
169
+ return [run];
170
+ return schemes.map((scheme) => ({
171
+ ...run,
172
+ style: {
173
+ ...run.style,
174
+ fontFamily: family?.startsWith("+mj")
175
+ ? scheme.majorFont.latin
176
+ : scheme.minorFont.latin,
177
+ },
178
+ }));
179
+ }),
180
+ (family) => (family?.startsWith("+") ? "" : (family ?? "")),
181
+ minor,
182
+ inspected.slides.map((slide) => slide.hidden ?? false),
183
+ );
184
+ },
185
+ }),
186
+ );
187
}
188
189
/** A file in the deck's zip package: where its central directory record and its local data sit. */
apps/web/src/components/files/projectFilesQueryState.ts
+2
-2
@@ -207,7 +207,7 @@ export function useProjectEntriesQuery(
207
const refreshAtom = useAtomRefresh(atom);
208
const refresh = () => refreshAtom();
209
return {
210
- data: Option.getOrNull(AsyncResult.value(result)),
210
+ data: AsyncResult.getOrElse(result, () => null),
211
error: fileAccess.isPending
212
? null
213
: canReadFiles
@@ -263,7 +263,7 @@ export function useProjectFileQuery(
263
const result = useAtomValue(atom);
264
const refreshAtom = useAtomRefresh(atom);
265
const refresh = () => refreshAtom();
266
- const readData = Option.getOrNull(AsyncResult.value(result));
266
+ const readData = AsyncResult.getOrElse(result, () => null);
267
const isMissing = readData?.exists === false;
268
const optimisticResult = useAtomValue(
269
optimisticFileAtom(environmentId, cwd, relativePath ?? EMPTY_PROJECT_FILE_PATH),
apps/web/src/components/media/MediaActions.tsx
+1
-2
@@ -16,7 +16,6 @@ import {
16
sessionGrantsScope,
17
type SessionGrantInput,
18
} from "@t3tools/contracts";
19
-import * as Option from "effect/Option";
19
import { AsyncResult } from "effect/reactivity";
20
import { useRef, useState, type ReactElement } from "react";
21
@@ -53,7 +52,7 @@ function allowsHostMedia(session: SessionGrantInput | null) {
52
function canReadHostMedia(environmentId: EnvironmentId | null): boolean {
53
if (environmentId === null) return true;
54
const result = appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId));
56
- return result._tag !== "Failure" && allowsHostMedia(Option.getOrNull(AsyncResult.value(result)));
55
+ return result._tag !== "Failure" && allowsHostMedia(AsyncResult.getOrElse(result, () => null));
56
}
57
58
export function useMediaActions(source: MediaActionSource) {
apps/web/src/components/preview/agentOpenedPreviews.ts
+1
-2
@@ -10,7 +10,6 @@ import type {
10
ScopedThreadRef,
11
ThreadId,
12
} from "@t3tools/contracts";
13
-import * as Option from "effect/Option";
13
import { AsyncResult } from "effect/reactivity";
14
15
import { getClientSettings } from "../../hooks/useSettings";
@@ -222,7 +221,7 @@ function watchEnvironmentDevices(environmentId: EnvironmentId): () => void {
221
return appAtomRegistry.subscribe(
222
deviceEnvironment.state({ environmentId, input: {} }),
223
(result) => {
225
- const state = Option.getOrNull(AsyncResult.value(result));
224
+ const state = AsyncResult.getOrElse(result, () => null);
225
if (state === null) return;
226
applyDeviceSnapshot(environmentId, state, {
227
sheetLayout: window.matchMedia(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY).matches,
apps/web/src/components/pullRequest/filesViewedStore.ts
+1
-2
@@ -8,7 +8,6 @@ import type {
8
PullRequestFilesViewedResult,
9
PullRequestRef,
10
} from "@t3tools/contracts";
11
-import * as Option from "effect/Option";
11
import { AsyncResult } from "effect/reactivity";
12
13
import { appAtomRegistry } from "~/rpc/atomRegistry";
@@ -238,7 +237,7 @@ const filesViewedStore = createFilesViewedStore({
237
subscribeAnswers: (target, onAnswer) =>
238
appAtomRegistry.subscribe(
239
filesViewedAtom(target),
241
- (result) => onAnswer(Option.getOrNull(AsyncResult.value(result))),
240
+ (result) => onAnswer(AsyncResult.getOrElse(result, () => null)),
241
{ immediate: true },
242
),
243
send: ({ environmentId, reference }, files) =>
apps/web/src/components/pullRequest/guide/PullRequestGuideRunCoordinator.tsx
+1
-2
@@ -1,7 +1,6 @@
1
import type { AnyRouter } from "@tanstack/react-router";
2
import type { PullRequestReviewGuideResult } from "@t3tools/contracts";
3
import { CircleAlertIcon, CircleCheckIcon } from "lucide-react";
4
-import * as Option from "effect/Option";
4
import { AsyncResult, type AtomRegistry } from "effect/reactivity";
5
6
import { getClientSettings } from "~/hooks/useSettings";
@@ -159,7 +158,7 @@ function watchGuideRun(
158
const unsubscribe = registry.subscribe(
159
atom,
160
(result) => {
162
- const data = Option.getOrNull(AsyncResult.value(result));
161
+ const data = AsyncResult.getOrElse(result, () => null);
162
if (data === null || data === seen) return;
163
seen = data;
164
if (subscribing && watch.answeredRunning === true) return;
apps/web/src/components/settings/AcpRegistryIcon.tsx
+3
-5
@@ -1,6 +1,5 @@
1
import { useAtomValue } from "@effect/atom-react";
2
import * as Effect from "effect/Effect";
3
-import * as Option from "effect/Option";
3
import { AsyncResult, Atom } from "effect/reactivity";
4
import { useId, useState } from "react";
5
import {
@@ -110,10 +109,9 @@ export function AcpRegistryAgentIcon({
109
const iconUrl = resolveOfficialAcpRegistryIconUrl(icon);
110
// Render only after the load pipeline resolves, so the fallback icon does
111
// not flash a broken image.
113
- const source = Option.getOrNull(
114
- AsyncResult.value(
115
- useAtomValue(iconUrl === null ? NO_ICON_SOURCE_ATOM : acpRegistryIconSourceAtom(iconUrl)),
116
- ),
112
+ const source = AsyncResult.getOrElse(
113
+ useAtomValue(iconUrl === null ? NO_ICON_SOURCE_ATOM : acpRegistryIconSourceAtom(iconUrl)),
114
+ () => null,
115
);
116
const [image, setImage] = useState<{
117
readonly source: string;
apps/web/src/components/settings/AcpRegistrySearchStep.tsx
+2
-1
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import { ACP_REGISTRY_MAX_AGENTS, AuthProvidersManageScope } from "@t3tools/contracts";
3
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
4
import {
@@ -111,7 +112,7 @@ export function useAcpRegistrySearch(environmentId: EnvironmentId, enabled: bool
112
return;
113
}
114
if (!isAtomCommandInterrupted(result)) {
114
- setPrepareError(errorMessage(squashAtomCommandFailure(result)));
115
+ pipe(squashAtomCommandFailure(result), errorMessage, setPrepareError);
116
}
117
},
118
};
apps/web/src/components/settings/AddEnvironmentDialog.tsx
+2
-1
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import { ChevronsLeftRightEllipsisIcon, PlusIcon, TerminalIcon } from "lucide-react";
3
import { useAtomValue } from "@effect/atom-react";
4
import { type KeyboardEvent, type ReactNode, useEffect, useRef, useState } from "react";
@@ -155,7 +156,7 @@ export function AddEnvironmentDialog({
156
});
157
if (result._tag === "Failure") {
158
if (!isAtomCommandInterrupted(result)) {
158
- onErrorChange(formatDesktopSshConnectionError(squashAtomCommandFailure(result)));
159
+ pipe(squashAtomCommandFailure(result), formatDesktopSshConnectionError, onErrorChange);
160
}
161
setIsAddingSavedBackend(false);
162
return;
apps/web/src/components/settings/ConnectionDiagnosisDetails.tsx
+2
-2
@@ -28,8 +28,8 @@ import { stackedThreadToast, toastManager } from "../ui/toast";
28
*/
29
export function useConnectionDiagnosis(environment: EnvironmentPresentation) {
30
const environmentId = environment.environmentId;
31
- const state = Option.getOrElse(
32
- AsyncResult.value(useAtomValue(environmentCatalog.stateAtom(environmentId))),
31
+ const state = AsyncResult.getOrElse(
32
+ useAtomValue(environmentCatalog.stateAtom(environmentId)),
33
() => AVAILABLE_CONNECTION_STATE,
34
);
35
const relayStatus = useRelayEnvironmentDiscovery().environments.get(environmentId)?.status;
apps/web/src/components/settings/ProjectDefaultsSettings.tsx
+2
-10
@@ -12,10 +12,8 @@ import {
12
resolveEffectiveDefaultModelSelection,
13
} from "../../modelSelection";
14
import {
15
- applyProviderInstanceSettings,
16
- deriveProviderInstanceEntries,
15
+ providerInstanceEntriesFor,
16
resolveDefaultProviderModelSelection,
18
- sortProviderInstanceEntries,
17
} from "../../providerInstances";
18
import { useEnvironmentProviders, useEnvironments } from "../../state/environments";
19
import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
@@ -70,13 +68,7 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting
68
const selection = storedSelection
69
? resolveEffectiveDefaultModelSelection(settings, providers, storedSelection)
70
: null;
73
- const entries = sortProviderInstanceEntries(
74
- applyProviderInstanceSettings(
75
- deriveProviderInstanceEntries(providers),
76
- settings,
77
- target?.projectId ?? null,
78
- ),
79
- );
71
+ const entries = providerInstanceEntriesFor(providers, settings, target?.projectId ?? null);
72
const modelOptions = getCustomModelOptionsByInstance(
73
settings,
74
providers,
apps/web/src/components/settings/ScheduledTasksSettings.tsx
+6
-13
@@ -1,6 +1,5 @@
1
import { useAtomValue } from "@effect/atom-react";
2
import { connectionStatusTitle } from "@t3tools/client-runtime/connection";
3
-import * as Option from "effect/Option";
3
import { AsyncResult } from "effect/reactivity";
4
import {
5
Clock3Icon,
@@ -48,11 +47,7 @@ import {
47
import { formatRelativeTime } from "../../timestampFormat";
48
import { useEnvironmentSettings } from "../../hooks/useSettings";
49
import { getCustomModelOptionsByInstance } from "../../modelSelection";
51
-import {
52
- applyProviderInstanceSettings,
53
- deriveProviderInstanceEntries,
54
- sortProviderInstanceEntries,
55
-} from "../../providerInstances";
50
+import { providerInstanceEntriesFor } from "../../providerInstances";
51
import { usePrimaryCloudLinkState } from "../../cloud/primaryCloudLinkState";
52
import { requestConfirmDialog } from "../../confirmDialog";
53
import { webhookAddress } from "@t3tools/client-runtime/webhook-address";
@@ -492,7 +487,7 @@ function ScheduledTaskEnvironmentList({
487
const states = environments.map((environment) => {
488
const index = connectedIds.indexOf(environment.environmentId);
489
const query = index < 0 ? null : queries[index]!;
495
- const data = query === null ? null : Option.getOrNull(AsyncResult.value(query));
490
+ const data = query === null ? null : AsyncResult.getOrElse(query, () => null);
491
return {
492
environment,
493
connected: index >= 0,
@@ -1148,12 +1143,10 @@ function ScheduledTaskEditorForm({
1143
: task;
1144
const selectedProjectId = draft.projectId || projects[0]?.id || "";
1145
const selectedProject = projects.find((project) => project.id === selectedProjectId);
1151
- const instanceEntries = sortProviderInstanceEntries(
1152
- applyProviderInstanceSettings(
1153
- deriveProviderInstanceEntries(providers),
1154
- settings,
1155
- selectedProject?.id ?? null,
1156
- ),
1146
+ const instanceEntries = providerInstanceEntriesFor(
1147
+ providers,
1148
+ settings,
1149
+ selectedProject?.id ?? null,
1150
);
1151
1152
const firstInstance = instanceEntries[0];
apps/web/src/components/settings/SettingsPanels.tsx
+5
-11
@@ -61,11 +61,7 @@ import {
61
resolveAppModelSelectionState,
62
selectsPlanAgent,
63
} from "../../modelSelection";
64
-import {
65
- applyProviderInstanceSettings,
66
- deriveProviderInstanceEntries,
67
- sortProviderInstanceEntries,
68
-} from "../../providerInstances";
64
+import { providerInstanceEntriesFor } from "../../providerInstances";
65
import { ensureLocalApi, readLocalApi } from "../../localApi";
66
import { isMacPlatform } from "../../lib/utils";
67
import { useEnvironmentProviders } from "../../state/environments";
@@ -1501,12 +1497,10 @@ export function ThreadsSettingsPanel() {
1497
const textGenInstanceId = textGenerationModelSelection.instanceId;
1498
const textGenModel = textGenerationModelSelection.model;
1499
const textGenModelOptions = textGenerationModelSelection.options;
1504
- const textGenerationModelInstanceEntries = sortProviderInstanceEntries(
1505
- applyProviderInstanceSettings(
1506
- deriveProviderInstanceEntries(textGenerationProviders),
1507
- settings,
1508
- target?.projectId ?? null,
1509
- ),
1500
+ const textGenerationModelInstanceEntries = providerInstanceEntriesFor(
1501
+ textGenerationProviders,
1502
+ settings,
1503
+ target?.projectId ?? null,
1504
);
1505
const hasTextGenerationProvider = textGenerationModelInstanceEntries.some(
1506
(entry) => entry.enabled && entry.isAvailable,
apps/web/src/components/settings/SettingsScopeContext.tsx
+1
-2
@@ -1,7 +1,6 @@
1
import { type EnvironmentId, T3_PROJECT_FILE_NAME, type T3ProjectFile } from "@t3tools/contracts";
2
import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
3
import { useAtomValue } from "@effect/atom-react";
4
-import * as Option from "effect/Option";
4
import { AsyncResult, Atom } from "effect/reactivity";
5
import { createContext, type ReactNode, useContext } from "react";
6
@@ -29,7 +28,7 @@ const memberProjectFilesAtom = Atom.family((membersKey: string) => {
28
if (result.waiting) continue;
29
const data =
30
get(optimisticFileAtom(environmentId, workspaceRoot, T3_PROJECT_FILE_NAME))?.data ??
32
- Option.getOrNull(AsyncResult.value(result));
31
+ AsyncResult.getOrElse(result, () => null);
32
files.set(
33
physicalProjectKey,
34
data === null || data.exists === false || data.truncated
apps/web/src/components/settings/SourceControlWritingSettings.tsx
+5
-11
@@ -19,11 +19,7 @@ import {
19
} from "./useScopedSettings";
20
import { useScopedModelDisabledReason } from "./useScopedModelAvailability";
21
import { useSettingsScope } from "./SettingsScopeContext";
22
-import {
23
- applyProviderInstanceSettings,
24
- deriveProviderInstanceEntries,
25
- sortProviderInstanceEntries,
26
-} from "../../providerInstances";
22
+import { providerInstanceEntriesFor } from "../../providerInstances";
23
import {
24
getCustomModelOptionsByInstance,
25
resolveAppModelSelectionState,
@@ -110,12 +106,10 @@ export function SourceControlWritingSettingsSection() {
106
const textGenerationProviders = serverProviders.filter(
107
(provider) => provider.supportsTextGeneration !== false,
108
);
113
- const instanceEntries = sortProviderInstanceEntries(
114
- applyProviderInstanceSettings(
115
- deriveProviderInstanceEntries(textGenerationProviders),
116
- settings,
117
- target?.projectId ?? null,
118
- ),
109
+ const instanceEntries = providerInstanceEntriesFor(
110
+ textGenerationProviders,
111
+ settings,
112
+ target?.projectId ?? null,
113
);
114
const projectEnabledInstanceIds = new Set(
115
instanceEntries
apps/web/src/components/usage/UsagePriceOverrides.tsx
+1
-2
@@ -1,7 +1,6 @@
1
import { useAtomValue } from "@effect/atom-react";
2
import { AuthSettingsWriteScope, type EnvironmentId, sessionGrantsScope } from "@t3tools/contracts";
3
import { ChevronDownIcon, PlusIcon, RotateCcwIcon, XIcon } from "lucide-react";
4
-import * as Option from "effect/Option";
4
import { AsyncResult, Atom } from "effect/reactivity";
5
import { useRef, useState } from "react";
6
@@ -46,7 +45,7 @@ const priceTargetsAtom = Atom.make((get): readonly UsagePriceTarget[] =>
45
[...get(environmentPresentations.presentationsAtom)].map(([environmentId, environment]) => {
46
const settings = get(serverEnvironment.settingsValueAtom(environmentId));
47
const session = get(environmentSession.sessionStateAtom(environmentId));
49
- const sessionData = Option.getOrNull(AsyncResult.value(session));
48
+ const sessionData = AsyncResult.getOrElse(session, () => null);
49
const access =
50
session._tag === "Failure"
51
? "denied"
apps/web/src/composerDraftStore.ts
+1
-3
@@ -4194,9 +4194,7 @@ export function subscribeComposerDraftModelReconciliation(input: {
4194
const thread = get(input.threadShellAtom(ref));
4195
if (!thread || !draftModelPickMatchesThread(pick, thread.modelSelection)) continue;
4196
// Status and selection must come from the same emission; derived atoms can update apart.
4197
- const shell = Option.getOrNull(
4198
- AsyncResult.value(get(input.shellStateAtom(ref.environmentId))),
4199
- );
4197
+ const shell = AsyncResult.getOrElse(get(input.shellStateAtom(ref.environmentId)), () => null);
4198
if (shell?.status !== "live") continue;
4199
const authoritativeThread = Option.getOrNull(shell.snapshot)?.threads.find(
4200
(candidate) => candidate.id === ref.threadId,
apps/web/src/environments/primary/sessionState.ts
+1
-2
@@ -1,7 +1,6 @@
1
import { useAtomValue } from "@effect/atom-react";
2
import * as Cause from "effect/Cause";
3
import * as Effect from "effect/Effect";
4
-import * as Option from "effect/Option";
4
import { AsyncResult, Atom } from "effect/reactivity";
5
6
import { isLocalEnvironmentDisabled } from "../../localEnvironment";
@@ -30,7 +29,7 @@ export function usePrimarySessionState() {
29
error = cause instanceof Error ? cause.message : "Could not read environment session.";
30
}
31
return {
33
- data: Option.getOrNull(AsyncResult.value(result)),
32
+ data: AsyncResult.getOrElse(result, () => null),
33
error,
34
isPending: result.waiting,
35
refresh: refreshPrimarySessionState,
apps/web/src/filePathDisplay.ts
+5
-2
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import {
3
fileBasename,
4
stripSlashPrefixedWindowsDrive,
@@ -26,8 +27,10 @@ export function formatWorkspaceRelativePath(
27
28
let displayPath = normalizedPath;
29
if (workspaceRoot) {
29
- const normalizedWorkspaceRoot = stripSlashPrefixedWindowsDrive(
30
- normalizePathSeparators(trimTrailingPathSeparators(workspaceRoot)),
30
+ const normalizedWorkspaceRoot = pipe(
31
+ trimTrailingPathSeparators(workspaceRoot),
32
+ normalizePathSeparators,
33
+ stripSlashPrefixedWindowsDrive,
34
);
35
const workspaceLabel = fileBasename(normalizedWorkspaceRoot);
36
const caseInsensitive = isWindowsAbsolutePath(stripSlashPrefixedWindowsDrive(workspaceRoot));
apps/web/src/hooks/useSettings.ts
+1
-1
@@ -574,7 +574,7 @@ function useSharedSettingsSyncTargetIds(includePending = false): ReadonlyArray<E
574
if (includePending && result._tag === "Initial") {
575
return [environmentId];
576
}
577
- const session = result._tag === "Failure" ? null : Option.getOrNull(AsyncResult.value(result));
577
+ const session = result._tag === "Failure" ? null : AsyncResult.getOrElse(result, () => null);
578
return session !== null && sessionGrantsScope(session, AuthSettingsWriteScope)
579
? [environmentId]
580
: [];
apps/web/src/hooks/useTheme.ts
+2
-1
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import type { DesktopBridge } from "@t3tools/contracts";
3
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
4
import * as Schema from "effect/Schema";
@@ -518,7 +519,7 @@ export function setTheme(next: Theme): boolean {
519
if (typeof window === "undefined") return false;
520
try {
521
// Save the current mode first; inferring it from the new theme can switch dark to light.
521
- writeAppearanceModePreference(readAppearanceModePreference(getStored()));
522
+ pipe(getStored(), readAppearanceModePreference, writeAppearanceModePreference);
523
// A whole theme replaces the mix; retain it to restore on a failed preference write.
524
const previousHalvesRaw = window.localStorage.getItem(THEME_HALVES_STORAGE_KEY);
525
window.localStorage.removeItem(THEME_HALVES_STORAGE_KEY);
apps/web/src/lib/assistantCitationNavigation.ts
+6
-2
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import type { AssistantCitation } from "@t3tools/contracts";
3
import {
4
formatAssistantCitationHref,
@@ -27,8 +28,11 @@ export function assistantCitationFromLocation(href: string) {
28
const hash = href.slice(hashIndex + 1);
29
if (!hash.startsWith(CITATION_HASH_PREFIX) || hash.length > 140_000) return null;
30
try {
30
- return parseAssistantCitationHref(
31
- Result.getOrThrow(Base64Url.decodeString(hash.slice(CITATION_HASH_PREFIX.length))),
31
+ return pipe(
32
+ hash.slice(CITATION_HASH_PREFIX.length),
33
+ Base64Url.decodeString,
34
+ Result.getOrThrow,
35
+ parseAssistantCitationHref,
36
);
37
} catch {
38
return null;
apps/web/src/onboarding/useProjectScans.ts
+1
-2
@@ -1,6 +1,5 @@
1
import { RegistryContext, useAtomValue } from "@effect/atom-react";
2
import type { EnvironmentId } from "@t3tools/contracts";
3
-import * as Option from "effect/Option";
3
import { AsyncResult } from "effect/reactivity";
4
import { useContext } from "react";
5
@@ -18,7 +17,7 @@ export function useProjectScans(environmentIds: readonly EnvironmentId[]) {
17
const result = results[index]!;
18
return {
19
environmentId,
21
- data: Option.getOrNull(AsyncResult.value(result)),
20
+ data: AsyncResult.getOrElse(result, () => null),
21
error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null,
22
isPending: result.waiting || result._tag === "Initial",
23
refresh: () => registry.refresh(scanAtom(environmentId)),
apps/web/src/providerInstances.ts
+15
-1
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import {
3
DEFAULT_MODEL_BY_PROVIDER,
4
defaultInstanceIdForDriver,
@@ -147,7 +148,20 @@ function applyProviderInstanceBranding(
148
};
149
}
150
150
-export function sortProviderInstanceEntries(
151
+/** Picker order: each driver's default instance first, then its custom instances. */
152
+export function providerInstanceEntriesFor(
153
+ providers: ReadonlyArray<ServerProvider>,
154
+ settings: Pick<ServerSettings, "providerInstances" | "projectSettingsOverrides">,
155
+ projectId: ProjectId | null,
156
+): ReadonlyArray<ProviderInstanceEntry> {
157
+ return pipe(
158
+ deriveProviderInstanceEntries(providers),
159
+ (entries) => applyProviderInstanceSettings(entries, settings, projectId),
160
+ sortProviderInstanceEntries,
161
+ );
162
+}
163
+
164
+function sortProviderInstanceEntries(
165
entries: ReadonlyArray<ProviderInstanceEntry>,
166
): ReadonlyArray<ProviderInstanceEntry> {
167
const byKind = new Map<ProviderDriverKind, ProviderInstanceEntry[]>();
apps/web/src/state/projectClones.ts
+1
-2
@@ -1,7 +1,6 @@
1
import { useAtomValue } from "@effect/atom-react";
2
import { parseScopedProjectKey, scopedProjectKey } from "@t3tools/client-runtime/environment";
3
import type { EnvironmentId, ProjectCloneSnapshot, ScopedProjectRef } from "@t3tools/contracts";
4
-import * as Option from "effect/Option";
4
import { AsyncResult, Atom } from "effect/reactivity";
5
6
import { environmentServerConfigsAtom } from "./server";
@@ -16,7 +15,7 @@ export const environmentProjectClonesAtom = Atom.family((environmentId: Environm
15
Atom.make((get): ReadonlyArray<ProjectCloneSnapshot> => {
16
if (!get(environmentServerConfigsAtom).has(environmentId)) return EMPTY_CLONES;
17
const result = get(sourceControlEnvironment.projectClones({ environmentId, input: {} }));
19
- return Option.getOrElse(AsyncResult.value(result), () => EMPTY_CLONES);
18
+ return AsyncResult.getOrElse(result, () => EMPTY_CLONES);
19
}).pipe(Atom.withLabel(`web-project-clones:${environmentId}`)),
20
);
21
apps/web/src/state/pullRequests.ts
+2
-2
@@ -547,7 +547,7 @@ function createMergedEnvironmentQuery<Input, A>(
547
if (result._tag === "Failure" && error === null) {
548
error = formatEnvironmentQueryError(result.cause);
549
}
550
- const value = Option.getOrNull(AsyncResult.value(result));
550
+ const value = AsyncResult.getOrElse(result, () => null);
551
if (value !== null) values.push([target.environmentId, value]);
552
}
553
return { values, error, isPending };
@@ -603,7 +603,7 @@ export function usePullRequestTurnRefreshes(
603
604
export function usePullRequestTurnRefresh(environmentId: EnvironmentId): number | null {
605
const result = useAtomValue(pullRequestEnvironment.refreshes({ environmentId, input: {} }));
606
- return Option.getOrNull(AsyncResult.value(result));
606
+ return AsyncResult.getOrElse(result, () => null);
607
}
608
609
export interface MergedPullRequestListView {
apps/web/src/state/queries.ts
+1
-2
@@ -27,7 +27,6 @@ import type {
27
VcsRef,
28
} from "@t3tools/contracts";
29
import * as Cause from "effect/Cause";
30
-import * as Option from "effect/Option";
30
import { AsyncResult, Atom } from "effect/reactivity";
31
import { useEffect, useState } from "react";
32
@@ -208,7 +207,7 @@ export function usePaginatedBranches(target: VcsRefTarget) {
207
pagesKey === null ? EMPTY_VCS_REF_PAGES_ATOM : vcsRefPagesAtom(pagesKey),
208
);
209
const values = results.flatMap((result) => {
211
- const value = Option.getOrNull(AsyncResult.value(result));
210
+ const value = AsyncResult.getOrElse(result, () => null);
211
return value === null ? [] : [value];
212
});
213
const refs = new Map<string, VcsRef>();
apps/web/src/state/query.ts
+1
-1
@@ -40,7 +40,7 @@ export function useEnvironmentQuery<A, E>(
40
const result = useAtomValue(selectedAtom);
41
const refresh = useAtomRefresh(selectedAtom);
42
return {
43
- data: Option.getOrNull(AsyncResult.value(result)),
43
+ data: AsyncResult.getOrElse(result, () => null),
44
dataUpdatedAt: queryUpdatedAt(result),
45
error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null,
46
failure:
apps/web/src/state/server.ts
+9
-7
@@ -68,10 +68,11 @@ const primaryServerStateAtom = Atom.make((get): PrimaryServerState => {
68
}
69
70
const target = { environmentId, input: {} };
71
- const configProjection = Option.getOrNull(
72
- AsyncResult.value(get(serverEnvironment.configProjection(target))),
71
+ const configProjection = AsyncResult.getOrElse(
72
+ get(serverEnvironment.configProjection(target)),
73
+ () => null,
74
);
74
- const welcome = Option.getOrNull(AsyncResult.value(get(serverEnvironment.welcome(target))));
75
+ const welcome = AsyncResult.getOrElse(get(serverEnvironment.welcome(target)), () => null);
76
77
return {
78
config: get(serverEnvironment.configValueAtom(environmentId)),
@@ -98,8 +99,9 @@ export const primaryServerLegacyThreadMigrationAtom = Atom.make(
99
if (environmentId === null) {
100
return null;
101
}
101
- return Option.getOrNull(
102
- AsyncResult.value(get(serverEnvironment.legacyThreadMigration({ environmentId, input: {} }))),
102
+ return AsyncResult.getOrElse(
103
+ get(serverEnvironment.legacyThreadMigration({ environmentId, input: {} })),
104
+ () => null,
105
);
106
},
107
).pipe(Atom.withLabel("web-primary-server-legacy-thread-migration"));
@@ -143,8 +145,8 @@ const environmentConnectionsAtom = Atom.make((get) => {
145
Pick<EnvironmentPresentation, "connection" | "serverConfig">
146
>();
147
for (const [environmentId, entry] of get(environmentCatalog.catalogValueAtom).entries) {
146
- const state = Option.getOrElse(
147
- AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))),
148
+ const state = AsyncResult.getOrElse(
149
+ get(environmentCatalog.stateAtom(environmentId)),
150
() => AVAILABLE_CONNECTION_STATE,
151
);
152
environments.set(environmentId, {
apps/web/src/state/session.ts
+2
-2
@@ -37,7 +37,7 @@ export function sessionHasScope(
37
result: AsyncResult.AsyncResult<AuthSessionState, unknown>,
38
scope: AuthEnvironmentScope,
39
): boolean {
40
- const session = Option.getOrNull(AsyncResult.value(result));
40
+ const session = AsyncResult.getOrElse(result, () => null);
41
return result._tag !== "Failure" && session !== null && sessionGrantsScope(session, scope);
42
}
43
@@ -94,7 +94,7 @@ export function readPreparedConnection(environmentId: EnvironmentId) {
94
export function useEnvironmentSessionState(environmentId: EnvironmentId) {
95
const result = useAtomValue(environmentSession.sessionStateAtom(environmentId));
96
return {
97
- data: Option.getOrNull(AsyncResult.value(result)),
97
+ data: AsyncResult.getOrElse(result, () => null),
98
hasError: result._tag === "Failure",
99
isPending: result.waiting,
100
};
apps/web/src/state/shell.ts
+2
-2
@@ -75,8 +75,8 @@ export const allEnvironmentShellsBootstrappedAtom = Atom.make((get) => {
75
if (Option.isSome(get(environmentShell.stateValueAtom(environmentId)).snapshot)) {
76
continue;
77
}
78
- const connection = Option.getOrElse(
79
- AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))),
78
+ const connection = AsyncResult.getOrElse(
79
+ get(environmentCatalog.stateAtom(environmentId)),
80
() => AVAILABLE_CONNECTION_STATE,
81
);
82
if (connectionProjectionPhase(connection) !== "disconnected") {
apps/web/src/state/sourceControlActions.ts
+7
-9
@@ -21,7 +21,6 @@ import {
21
type ThreadId,
22
} from "@t3tools/contracts";
23
import * as Cause from "effect/Cause";
24
-import * as Option from "effect/Option";
24
import { AsyncResult } from "effect/reactivity";
25
26
import { appAtomRegistry } from "../rpc/atomRegistry";
@@ -373,15 +372,14 @@ export function readCachedPullRequestResolution(
372
if (target.environmentId === null || target.cwd === null || target.reference === null) {
373
return null;
374
}
376
- return Option.getOrNull(
377
- AsyncResult.value(
378
- appAtomRegistry.get(
379
- gitEnvironment.pullRequestResolution({
380
- environmentId: target.environmentId,
381
- input: { cwd: target.cwd, reference: target.reference },
382
- }),
383
- ),
375
+ return AsyncResult.getOrElse(
376
+ appAtomRegistry.get(
377
+ gitEnvironment.pullRequestResolution({
378
+ environmentId: target.environmentId,
379
+ input: { cwd: target.cwd, reference: target.reference },
380
+ }),
381
),
382
+ () => null,
383
);
384
}
385
apps/web/src/state/terminalSessions.ts
+4
-3
@@ -159,8 +159,9 @@ const attachedTerminalSessionFamily = Atom.family((key: string) => {
159
)
160
: null;
161
const metadata = canRead
162
- ? Option.getOrNull(
163
- AsyncResult.value(get(terminalEnvironment.metadata({ environmentId, input: null }))),
162
+ ? AsyncResult.getOrElse(
163
+ get(terminalEnvironment.metadata({ environmentId, input: null })),
164
+ () => null,
165
)
166
: null;
167
const summary =
@@ -172,7 +173,7 @@ const attachedTerminalSessionFamily = Atom.family((key: string) => {
173
const buffer =
174
attach === null
175
? EMPTY_TERMINAL_BUFFER_STATE
175
- : Option.getOrElse(AsyncResult.value(attach), () => EMPTY_TERMINAL_BUFFER_STATE);
176
+ : AsyncResult.getOrElse(attach, () => EMPTY_TERMINAL_BUFFER_STATE);
177
const state = combineTerminalSessionState(summary, buffer);
178
return attach?._tag === "Failure"
179
? { ...state, error: formatEnvironmentQueryError(attach.cause), status: "error" }
apps/web/src/state/threads.ts
+1
-1
@@ -67,7 +67,7 @@ export function useEnvironmentThread(
67
? environmentThreads.stateAtom(environmentId, threadId)
68
: EMPTY_THREAD_STATE_ATOM,
69
);
70
- const state = Option.getOrElse(AsyncResult.value(result), () => EMPTY_ENVIRONMENT_THREAD_STATE);
70
+ const state = AsyncResult.getOrElse(result, () => EMPTY_ENVIRONMENT_THREAD_STATE);
71
return state;
72
}
73
apps/web/src/state/usage.ts
+2
-3
@@ -10,7 +10,6 @@ import {
10
} from "@t3tools/contracts";
11
import { needsCursorKeychainAccess, refreshUsage } from "@t3tools/client-runtime/state/usage";
12
import { resolveUsageAccess } from "@t3tools/client-runtime/state/usage-access";
13
-import * as Option from "effect/Option";
13
import { AsyncResult, Atom } from "effect/reactivity";
14
import { useState } from "react";
15
@@ -42,7 +41,7 @@ const usageByWindowAtom = Atom.family((windowKey: string) =>
41
const sessionResult = get(environmentSession.sessionStateAtom(environmentId));
42
const access = resolveUsageAccess({
43
connectionPhase: presentation.connection.phase,
45
- session: Option.getOrNull(AsyncResult.value(sessionResult)),
44
+ session: AsyncResult.getOrElse(sessionResult, () => null),
45
hasSessionError: sessionResult._tag === "Failure",
46
});
47
if (!access.canReadDiagnostics) {
@@ -57,7 +56,7 @@ const usageByWindowAtom = Atom.family((windowKey: string) =>
56
continue;
57
}
58
const result = get(serverEnvironment.usageSummary({ environmentId, input }));
60
- const summary = Option.getOrNull(AsyncResult.value(result));
59
+ const summary = AsyncResult.getOrElse(result, () => null);
60
statuses.push({
61
environmentId,
62
label: presentation.entry.target.label,
apps/web/src/state/waitForQuerySettled.ts
+1
-2
@@ -1,4 +1,3 @@
1
-import * as Option from "effect/Option";
1
import { AsyncResult, type Atom, type AtomRegistry } from "effect/reactivity";
2
3
/**
@@ -27,7 +26,7 @@ export function waitForQuerySettled<A, E, R>(input: {
26
const onAbort = () => finish(undefined);
27
const check = (result: AsyncResult.AsyncResult<A, E>) => {
28
if (AsyncResult.isFailure(result)) return finish(undefined);
30
- const settled = settle(Option.getOrNull(AsyncResult.value(result)));
29
+ const settled = settle(AsyncResult.getOrElse(result, () => null));
30
if (settled !== undefined) finish(settled);
31
};
32
if (signal.aborted) return finish(undefined);
apps/web/src/themePalette.ts
+7
-7
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import type { EnvironmentTheme } from "@t3tools/contracts";
3
import * as Equal from "effect/Equal";
4
import * as Option from "effect/Option";
@@ -752,13 +753,12 @@ function standardStatusColors(canvas: ThemeRgbColor): {
753
const surfaceOf = (value: string) =>
754
mixThemeRgbColors(canvas, parseThemeRgbColor(value, canvas), surfaceMix);
755
const readableOn = (foreground: string, surface: ThemeRgbColor) =>
755
- themeOklchToThemeColor(
756
- solveOklchLightness(
757
- themeRgbToOklch(parseThemeRgbColor(foreground, canvas)),
758
- [surface],
759
- 4.6,
760
- appearance === "dark" ? "lighter" : "darker",
761
- ),
756
+ pipe(
757
+ parseThemeRgbColor(foreground, canvas),
758
+ themeRgbToOklch,
759
+ (color) =>
760
+ solveOklchLightness(color, [surface], 4.6, appearance === "dark" ? "lighter" : "darker"),
761
+ themeOklchToThemeColor,
762
);
763
const errorSurface = surfaceOf(standard.error);
764
const warningSurface = surfaceOf(standard.warning);
packages/client-runtime/src/relay/managedRelayState.ts
+1
-2
@@ -4,7 +4,6 @@ import * as Cause from "effect/Cause";
4
import * as Clock from "effect/Clock";
5
import * as Data from "effect/Data";
6
import * as Effect from "effect/Effect";
7
-import * as Option from "effect/Option";
7
import * as Schema from "effect/Schema";
8
import * as Stream from "effect/Stream";
9
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
@@ -264,7 +263,7 @@ export function readManagedRelaySnapshotState<A>(
263
): ManagedRelaySnapshotState<A> {
264
const failure = result._tag === "Failure" ? describeManagedRelayFailure(result.cause) : null;
265
return {
267
- data: Option.getOrNull(AsyncResult.value(result)),
266
+ data: AsyncResult.getOrElse(result, () => null),
267
error: failure?.message ?? null,
268
errorTraceId: failure?.traceId ?? null,
269
isPending: result.waiting,
packages/client-runtime/src/state/archivedThreads.ts
+1
-2
@@ -1,7 +1,6 @@
1
import { EnvironmentId, type OrchestrationV2ArchivedShellSnapshot } from "@t3tools/contracts";
2
import * as Arr from "effect/Array";
3
import { pipe } from "effect/Function";
4
-import * as Option from "effect/Option";
4
import * as Order from "effect/Order";
5
import { AsyncResult, Atom } from "effect/reactivity";
6
@@ -53,7 +52,7 @@ export function createArchivedThreadSnapshotsAtomFamily<E>(options: {
52
const result = get(options.getSnapshotAtom(environmentId));
53
isLoading ||= result.waiting;
54
56
- const snapshot = Option.getOrNull(AsyncResult.value(result));
55
+ const snapshot = AsyncResult.getOrElse(result, () => null);
56
if (snapshot !== null) {
57
snapshots.push({ environmentId, snapshot });
58
}
packages/client-runtime/src/state/assets.ts
+1
-1
@@ -257,7 +257,7 @@ export function createProjectFaviconUrlAtomFamily(input: {
257
return Atom.make((get): string | null => {
258
const result = get(image);
259
if (isProjectFaviconFallbackUrl(get(resolvedUrl))) return null;
260
- return Option.getOrElse(AsyncResult.value(result), () => cache.peek(target));
260
+ return AsyncResult.getOrElse(result, () => cache.peek(target));
261
}).pipe(Atom.setIdleTTL(ASSET_URL_IDLE_TTL_MS));
262
});
263
return (target: ProjectFaviconTarget) =>
packages/client-runtime/src/state/commandPermissions.ts
+1
-1
@@ -26,7 +26,7 @@ function makeCommandPermissions<R, E>(
26
const scopes = scopeKey.split(",").filter(Boolean) as AuthEnvironmentScope[];
27
if (scopes.length === 0) return true;
28
const result = get(sessions.sessionStateAtom(environmentId));
29
- const session = Option.getOrNull(AsyncResult.value(result));
29
+ const session = AsyncResult.getOrElse(result, () => null);
30
return (
31
result._tag !== "Failure" &&
32
session !== null &&
packages/client-runtime/src/state/connections.ts
+3
-4
@@ -1,6 +1,5 @@
1
import type { EnvironmentId as EnvironmentIdType } from "@t3tools/contracts";
2
import * as Effect from "effect/Effect";
3
-import * as Option from "effect/Option";
3
import * as Stream from "effect/Stream";
4
import * as SubscriptionRef from "effect/SubscriptionRef";
5
import { AsyncResult, Atom } from "effect/reactivity";
@@ -63,7 +62,7 @@ export function createEnvironmentCatalogAtoms<R, E>(
62
);
63
64
const catalogValueAtom = Atom.make((get) =>
66
- Option.getOrElse(AsyncResult.value(get(catalogAtom)), () => EMPTY_ENVIRONMENT_CATALOG_STATE),
65
+ AsyncResult.getOrElse(get(catalogAtom), () => EMPTY_ENVIRONMENT_CATALOG_STATE),
66
).pipe(Atom.withLabel("environment-catalog-value"));
67
68
const pullRequestRoutingPermissionsAtom = runtime.atom(
@@ -73,7 +72,7 @@ export function createEnvironmentCatalogAtoms<R, E>(
72
{ initialValue: [] as ReadonlyArray<StoredPullRequestRoutingPermission> },
73
);
74
const pullRequestRoutingPermissionsValueAtom = Atom.make((get) =>
76
- Option.getOrElse(AsyncResult.value(get(pullRequestRoutingPermissionsAtom)), () => []),
75
+ AsyncResult.getOrElse(get(pullRequestRoutingPermissionsAtom), () => []),
76
).pipe(Atom.withLabel("environment-pull-request-routing-permissions"));
77
const setPullRequestRoutingPermission = createRuntimeCommand(runtime, {
78
label: "environment-catalog:pull-request-routing-permission",
@@ -104,7 +103,7 @@ export function createEnvironmentCatalogAtoms<R, E>(
103
);
104
105
const networkStatusValueAtom = Atom.make((get) =>
107
- Option.getOrElse(AsyncResult.value(get(networkStatusAtom)), () => "unknown" as const),
106
+ AsyncResult.getOrElse(get(networkStatusAtom), () => "unknown" as const),
107
).pipe(Atom.withLabel("environment-network-status-value"));
108
109
const stateAtom = Atom.family((environmentId: EnvironmentIdType) =>
packages/client-runtime/src/state/olderSettledThreads.test.ts
+1
-1
@@ -520,7 +520,7 @@ describe("createOlderSettledThreadAtoms", () => {
520
yield* Queue.offer(replies, Effect.succeed({ ...found, snapshotSequence: 8 }));
521
yield* until(
522
search,
523
- (result) => Option.getOrNull(AsyncResult.value(result))?.snapshotSequence === 8,
523
+ (result) => AsyncResult.getOrElse(result, () => null)?.snapshotSequence === 8,
524
);
525
expect(requests).toEqual([input, input]);
526
}),
packages/client-runtime/src/state/olderSettledThreads.ts
+1
-1
@@ -213,7 +213,7 @@ export function createOlderSettledThreadAtoms<R, ER, E>(
213
) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, E>>,
214
) {
215
const shellStateValue = (state: AsyncResult.AsyncResult<EnvironmentShellState, E>) =>
216
- Option.getOrNull(AsyncResult.value(state));
216
+ AsyncResult.getOrElse(state, () => null);
217
218
const countReadAtom = createEnvironmentQueryAtomFamily(runtime, {
219
label: "environment-data:orchestration:older-settled-counts",
packages/client-runtime/src/state/presentation.ts
+2
-2
@@ -77,8 +77,8 @@ export function createEnvironmentPresentationAtoms<E>(input: {
77
if (entry === undefined) {
78
return null;
79
}
80
- const state = Option.getOrElse(
81
- AsyncResult.value(get(input.stateAtom(environmentId))),
80
+ const state = AsyncResult.getOrElse(
81
+ get(input.stateAtom(environmentId)),
82
() => AVAILABLE_CONNECTION_STATE,
83
);
84
const previous = Option.getOrNull(get.self<EnvironmentPresentation | null>());
packages/client-runtime/src/state/pullRequests.test.ts
+3
-7
@@ -1430,15 +1430,11 @@ it.effect("updates cached labels after successful edits without rereading the ho
1430
registry.refresh(detail);
1431
yield* detailRefreshStarted.await;
1432
expect(registry.get(detail).waiting).toBe(true);
1433
- expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).labels).toEqual([
1434
- addedLabel,
1435
- ]);
1433
+ expect(AsyncResult.getOrThrow(registry.get(detail)).labels).toEqual([addedLabel]);
1434
yield* releaseDetailRefresh.open;
1435
yield* Effect.exit(AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true }));
1436
expect(AsyncResult.isFailure(registry.get(detail))).toBe(true);
1439
- expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).labels).toEqual([
1440
- addedLabel,
1441
- ]);
1437
+ expect(AsyncResult.getOrThrow(registry.get(detail)).labels).toEqual([addedLabel]);
1438
failDetail = false;
1439
registry.refresh(detail);
1440
expect(
@@ -1562,7 +1558,7 @@ it.effect("publishes the accepted guide run before the follow-up read finishes",
1558
const result = yield* Effect.promise(() => atoms.generateReviewGuide.run(registry, target));
1559
expect(result._tag).toBe("Success");
1560
yield* refreshStarted.await;
1565
- expect(Option.getOrNull(AsyncResult.value(registry.get(query)))).toEqual(accepted);
1561
+ expect(AsyncResult.getOrElse(registry.get(query), () => null)).toEqual(accepted);
1562
}),
1563
),
1564
);
packages/client-runtime/src/state/pullRequests.ts
+2
-2
@@ -520,7 +520,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(
520
Effect.sync(() => {
521
const { reviewers, requested } = target.input;
522
const candidatesAtom = reviewerCandidates(target);
523
- const candidates = Option.getOrNull(AsyncResult.value(registry.get(candidatesAtom)));
523
+ const candidates = AsyncResult.getOrElse(registry.get(candidatesAtom), () => null);
524
const selected =
525
candidates?.candidates.filter((candidate) =>
526
reviewers.some(
@@ -606,7 +606,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(
606
Effect.sync(() => {
607
const { labels, applied } = target.input;
608
const candidatesAtom = labelCandidates(target);
609
- const candidates = Option.getOrNull(AsyncResult.value(registry.get(candidatesAtom)));
609
+ const candidates = AsyncResult.getOrElse(registry.get(candidatesAtom), () => null);
610
const names = new Set(labels);
611
updateCached(registry, candidatesAtom, (value) => ({
612
...value,
packages/client-runtime/src/state/relayDiscovery.ts
+2
-3
@@ -1,5 +1,4 @@
1
import * as Effect from "effect/Effect";
2
-import * as Option from "effect/Option";
2
import * as Stream from "effect/Stream";
3
import * as SubscriptionRef from "effect/SubscriptionRef";
4
import { AsyncResult, Atom } from "effect/reactivity";
@@ -19,8 +18,8 @@ export function createRelayEnvironmentDiscoveryAtoms<R, E>(
18
{ initialValue: RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE },
19
);
20
const stateValueAtom = Atom.make((get) =>
22
- Option.getOrElse(
23
- AsyncResult.value(get(stateAtom)),
21
+ AsyncResult.getOrElse(
22
+ get(stateAtom),
23
() => RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE,
24
),
25
).pipe(Atom.withLabel("relay-environment-discovery-value"));
packages/client-runtime/src/state/runtime.test.ts
+1
-1
@@ -1306,7 +1306,7 @@ describe("persisted environment queries", () => {
1306
);
1307
const registry = yield* mountEnvironmentQuery(harness.atom);
1308
yield* Effect.result(readEnvironmentQuery(registry, harness.atom));
1309
- expect(Option.getOrNull(AsyncResult.value(registry.get(harness.atom)))).toBe("cached");
1309
+ expect(AsyncResult.getOrElse(registry.get(harness.atom), () => null)).toBe("cached");
1310
}),
1311
),
1312
);
packages/client-runtime/src/state/runtime.ts
+5
-4
@@ -558,7 +558,7 @@ const refreshEveryUntilFinal =
558
* reader of only this skips the refetches that changed nothing.
559
*/
560
export const selectEnvironmentQueryData = <A, E>(result: AsyncResult.AsyncResult<A, E>): A | null =>
561
- Option.getOrNull(AsyncResult.value(result));
561
+ AsyncResult.getOrElse(result, () => null);
562
563
type EnvironmentConnection = readonly [
564
SupervisorConnectionState,
@@ -628,7 +628,7 @@ export function environmentSessionGenerationAtom<R, ER>(
628
get.self<{ readonly session: RpcSession.RpcSession | null; readonly count: number }>(),
629
() => ({ session: null, count: 0 }),
630
);
631
- const connection = Option.getOrNull(AsyncResult.value(get(connectionAtom(id))));
631
+ const connection = AsyncResult.getOrElse(get(connectionAtom(id)), () => null);
632
if (connection === null || connection[0].phase !== "connected") return previous;
633
const session = Option.getOrNull(connection[1]);
634
return session === null || session === previous.session
@@ -674,8 +674,9 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
674
| EnvironmentRegistry.EnvironmentNotRegisteredError
675
| EnvironmentRpcUnavailableError
676
>((get) => {
677
- const connection = Option.getOrNull(
678
- AsyncResult.value(get(connectionAtom(target.environmentId))),
677
+ const connection = AsyncResult.getOrElse(
678
+ get(connectionAtom(target.environmentId)),
679
+ () => null,
680
);
681
// A refetch that returns equal content keeps the previous value's
682
// references, so readers of the data skip re-rendering on idle polls.
packages/client-runtime/src/state/server.ts
+3
-2
@@ -792,8 +792,9 @@ export function createServerEnvironmentAtoms<R, E>(
792
}
793
let previousProviders: ServerConfig["providers"] | undefined;
794
return Atom.make((get): ServerConfig | null => {
795
- const projection = Option.getOrNull(
796
- AsyncResult.value(get(configProjection({ environmentId, input: {} }))),
795
+ const projection = AsyncResult.getOrElse(
796
+ get(configProjection({ environmentId, input: {} })),
797
+ () => null,
798
);
799
const config = resolveServerConfigValue(
800
projection,
packages/client-runtime/src/state/session.ts
+8
-6
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import type { AuthSessionState, EnvironmentId, ServerConfig } from "@t3tools/contracts";
3
import * as Data from "effect/Data";
4
import * as Effect from "effect/Effect";
@@ -104,10 +105,11 @@ function makeEnvironmentSessionAtoms<R, E>(
105
// createServerEnvironmentAtoms(...).configValueAtom instead.
106
const initialConfigValueAtom = Atom.family((environmentId: EnvironmentId) =>
107
Atom.make((get): ServerConfig | null =>
107
- Option.getOrNull(
108
- Option.getOrElse(AsyncResult.value(get(initialConfigAtom(environmentId))), () =>
109
- Option.none(),
110
- ),
108
+ pipe(
109
+ get(initialConfigAtom(environmentId)),
110
+ AsyncResult.value,
111
+ Option.flatten,
112
+ Option.getOrNull,
113
),
114
).pipe(Atom.withLabel(`environment-config-value:${environmentId}`)),
115
);
@@ -128,7 +130,7 @@ function makeEnvironmentSessionAtoms<R, E>(
130
131
const preparedConnectionValueAtom = Atom.family((environmentId: EnvironmentId) =>
132
Atom.make((get) =>
131
- Option.getOrElse(AsyncResult.value(get(preparedConnectionAtom(environmentId))), () =>
133
+ AsyncResult.getOrElse(get(preparedConnectionAtom(environmentId)), () =>
134
Option.none<PreparedConnection>(),
135
),
136
).pipe(Atom.withLabel(`environment-prepared-connection:${environmentId}`)),
@@ -165,7 +167,7 @@ function makeEnvironmentSessionAtoms<R, E>(
167
const sessionStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
168
Atom.make(
169
(get): AuthSessionState | null =>
168
- Option.getOrNull(AsyncResult.value(get(sessionStateAtom(environmentId)))) ?? null,
170
+ AsyncResult.getOrElse(get(sessionStateAtom(environmentId)), () => null) ?? null,
171
).pipe(Atom.withLabel(`environment-session-state-value:${environmentId}`)),
172
);
173
packages/client-runtime/src/state/shell.ts
+1
-1
@@ -596,7 +596,7 @@ export function createEnvironmentShellAtoms<R, E>(
596
597
const stateValueAtom = Atom.family((environmentId: EnvironmentId) =>
598
Atom.make((get) =>
599
- Option.getOrElse(AsyncResult.value(get(stateAtom(environmentId))), () => EMPTY_SHELL_STATE),
599
+ AsyncResult.getOrElse(get(stateAtom(environmentId)), () => EMPTY_SHELL_STATE),
600
).pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)),
601
);
602
packages/client-runtime/src/state/terminal.ts
+1
-2
@@ -10,7 +10,6 @@ import {
10
WS_METHODS,
11
} from "@t3tools/contracts";
12
import * as Effect from "effect/Effect";
13
-import * as Option from "effect/Option";
13
import * as Stream from "effect/Stream";
14
import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
15
@@ -323,7 +322,7 @@ export function createTerminalSession(
322
result: AsyncResult.AsyncResult<TerminalBufferState, unknown>,
323
) => {
324
resizeRegistry = registry;
326
- const buffer = Option.getOrElse(AsyncResult.value(result), () => EMPTY_TERMINAL_BUFFER_STATE);
325
+ const buffer = AsyncResult.getOrElse(result, () => EMPTY_TERMINAL_BUFFER_STATE);
326
const status = result._tag === "Failure" ? "error" : buffer.status;
327
if (status !== lastStatus) {
328
lastStatus = status;
packages/client-runtime/src/state/threadDetail.ts
+2
-2
@@ -199,8 +199,8 @@ export function createEnvironmentThreadDetailAtoms<E>(
199
const threadStateValueAtomFamily = Atom.family((key: string) => {
200
const ref = parseThreadKey(key);
201
return Atom.make((get) =>
202
- Option.getOrElse(
203
- AsyncResult.value(get(threadStateAtom(ref.environmentId, ref.threadId))),
202
+ AsyncResult.getOrElse(
203
+ get(threadStateAtom(ref.environmentId, ref.threadId)),
204
() => EMPTY_ENVIRONMENT_THREAD_STATE,
205
),
206
).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-state-value:${key}`));
packages/client-runtime/src/state/threadFamilies.ts
+1
-1
@@ -78,7 +78,7 @@ export function createThreadFamilyAtoms<R, ER, E>(
78
) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, E>>,
79
) {
80
const shellStateValue = (state: AsyncResult.AsyncResult<EnvironmentShellState, E>) =>
81
- Option.getOrNull(AsyncResult.value(state));
81
+ AsyncResult.getOrElse(state, () => null);
82
const generationAtom = Atom.family((environmentId: EnvironmentId) =>
83
Atom.make((get) => shellStateValue(get(shellStateAtom(environmentId)))?.generation ?? 0).pipe(
84
Atom.withLabel(`environment-shell-generation:${environmentId}`),
packages/client-runtime/src/state/threadSearch.ts
+1
-1
@@ -150,7 +150,7 @@ export function createThreadSearchResultsAtomFamily<E>(options: {
150
}),
151
);
152
isLoading ||= result.waiting;
153
- const value = Option.getOrNull(AsyncResult.value(result));
153
+ const value = AsyncResult.getOrElse(result, () => null);
154
if (value !== null) {
155
matches.push(...value.matches.map((match) => ({ ...match, environmentId })));
156
if (value.threads !== undefined && value.threads.length > 0) {
packages/effect-codex-app-server/scripts/generate.ts
+17
-16
@@ -1,5 +1,6 @@
1
#!/usr/bin/env node
2
3
+import { pipe } from "effect/Function";
4
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
5
import * as NodeServices from "@effect/platform-node/NodeServices";
6
import { make as makeJsonSchemaGenerator } from "@effect/openapi-generator/JsonSchemaGenerator";
@@ -636,15 +637,15 @@ const generateFiles = Effect.fn("generateFiles")(function* () {
637
);
638
639
for (const [definitionName, definitionSchema] of Object.entries(parsed.definitions ?? {})) {
639
- aggregateSchemas[localDefinitionNames.get(definitionName)!] = stripNullDefaults(
640
- normalizeNullableTypes(
641
- rewriteExternalRefs(
642
- DefinitionOverrides[definitionName] ?? definitionSchema,
643
- localDefinitionNames,
644
- file.namespace,
645
- exportNameByQualifiedName,
646
- ),
640
+ aggregateSchemas[localDefinitionNames.get(definitionName)!] = pipe(
641
+ rewriteExternalRefs(
642
+ DefinitionOverrides[definitionName] ?? definitionSchema,
643
+ localDefinitionNames,
644
+ file.namespace,
645
+ exportNameByQualifiedName,
646
),
647
+ normalizeNullableTypes,
648
+ stripNullDefaults,
649
);
650
}
651
@@ -655,15 +656,15 @@ const generateFiles = Effect.fn("generateFiles")(function* () {
656
}
657
}
658
658
- aggregateSchemas[file.exportName] = stripNullDefaults(
659
- normalizeNullableTypes(
660
- rewriteExternalRefs(
661
- topLevelSchema,
662
- localDefinitionNames,
663
- file.namespace,
664
- exportNameByQualifiedName,
665
- ),
659
+ aggregateSchemas[file.exportName] = pipe(
660
+ rewriteExternalRefs(
661
+ topLevelSchema,
662
+ localDefinitionNames,
663
+ file.namespace,
664
+ exportNameByQualifiedName,
665
),
666
+ normalizeNullableTypes,
667
+ stripNullDefaults,
668
);
669
}
670
packages/effect-codex-app-server/src/replay.ts
+6
-1
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import * as Cause from "effect/Cause";
3
import * as Duration from "effect/Duration";
4
import * as Effect from "effect/Effect";
@@ -269,7 +270,11 @@ function sameFrame(
270
ignoredConfigKeys: ReadonlySet<string> = new Set(),
271
): boolean {
272
const normalize = (frame: unknown) =>
272
- stableStringify(normalizeThreadRequest(normalizeReplayFrame(frame), ignoredConfigKeys));
273
+ pipe(
274
+ normalizeReplayFrame(frame),
275
+ (request) => normalizeThreadRequest(request, ignoredConfigKeys),
276
+ stableStringify,
277
+ );
278
return normalize(left) === normalize(right);
279
}
280
packages/provider-core/src/server/handoffBudget.ts
+4
-2
@@ -197,14 +197,16 @@ export function renderHistory(
197
return [context, ...messages.map(renderHistoricalMessage)].join("\n\n");
198
}
199
200
+const jsonByteLength = (value: unknown) => Buffer.byteLength(JSON.stringify(value));
201
+
202
export function historyCost(
203
messages: ReadonlyArray<OrchestrationV2HistoricalMessage>,
204
context: string,
205
): number {
206
return (
207
Math.max(
206
- Buffer.byteLength(JSON.stringify(historyResponseItems(messages, context))),
207
- Buffer.byteLength(JSON.stringify(renderHistory(messages, context))),
208
+ jsonByteLength(historyResponseItems(messages, context)),
209
+ jsonByteLength(renderHistory(messages, context)),
210
) + 256
211
);
212
}
packages/shared/src/dpop.ts
+7
-1
@@ -1,3 +1,4 @@
1
+import { pipe } from "effect/Function";
2
import { p256 } from "@noble/curves/nist";
3
import { sha256 } from "@noble/hashes/sha2";
4
import * as Base64Url from "effect/encoding/Base64Url";
@@ -94,7 +95,12 @@ function dpopThumbprintInput(jwk: DpopPublicJwkType): string {
95
}
96
97
export function computeDpopJwkThumbprint(jwk: DpopPublicJwkType): string {
97
- return Base64Url.encode(sha256(new TextEncoder().encode(dpopThumbprintInput(jwk))));
98
+ return pipe(
99
+ dpopThumbprintInput(jwk),
100
+ (input) => new TextEncoder().encode(input),
101
+ sha256,
102
+ Base64Url.encode,
103
+ );
104
}
105
106
export function computeDpopAccessTokenHash(accessToken: string): string {
scripts/lib/public-config.ts
+6
-2
@@ -1,4 +1,5 @@
1
// @effect-diagnostics nodeBuiltinImport:off - Build bootstrap reads optional root env files before an Effect runtime exists.
2
+import { pipe } from "effect/Function";
3
import * as NodeFS from "node:fs";
4
import * as NodePath from "node:path";
5
import * as NodeURL from "node:url";
@@ -19,8 +20,11 @@ export interface T3CodePublicConfig {
20
21
type Environment = Readonly<Record<string, string | undefined>>;
22
22
-const REPO_ROOT = NodePath.dirname(
23
- NodePath.dirname(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url))),
23
+const REPO_ROOT = pipe(
24
+ NodeURL.fileURLToPath(import.meta.url),
25
+ NodePath.dirname,
26
+ NodePath.dirname,
27
+ NodePath.dirname,
28
);
29
30
export function loadRepoEnv({