@devries-cameron20 / t3code Mirror · read-only / commits / 4b87a45770
Fork 0

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

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

Synced Nov 22, 04:30 UTC

build: run Effect rules on mobile and lock in clean suggestion rules (#31111)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 4, 2026 at 15:54 UTC 4b87a45770d24a47f7e6bc40e3f19011e41c7724
43 files changed +473 -292
apps/desktop/src/preview/BrowserImport/BrowserImport.ts
+4 -3
@@ -96,12 +96,12 @@ export class BrowserCookieWriteError extends Schema.TaggedError<BrowserCookieWri
96 "BrowserCookieWriteError",
97 {
98 url: Schema.String,
99 - name: Schema.String,
99 + cookieName: Schema.String,
100 cause: Schema.Defect(),
101 },
102 ) {
103 override get message(): string {
104 - return `Could not write imported cookie ${this.name} for ${this.url}.`;
104 + return `Could not write imported cookie ${this.cookieName} for ${this.url}.`;
105 }
106 }
107
@@ -167,7 +167,8 @@ export const writeCookies = Effect.fn("BrowserImport.writeCookies")(function* (
167 sameSite: cookie.sameSite,
168 ...(cookie.expirationDate === undefined ? {} : { expirationDate: cookie.expirationDate }),
169 }),
170 - catch: (cause) => new BrowserCookieWriteError({ url: cookie.url, name: cookie.name, cause }),
170 + catch: (cause) =>
171 + new BrowserCookieWriteError({ url: cookie.url, cookieName: cookie.name, cause }),
172 }).pipe(
173 Effect.as(true),
174 Effect.tapError((error) => Effect.logDebug(error.message, { cause: error.cause })),
apps/mobile/src/components/PdfPreview.android.tsx
+4 -1
@@ -31,7 +31,10 @@ const preparedPdfAtom = Atom.family((uri: string) =>
31 },
32 catch: (cause) => (cause instanceof Error ? cause.message : "The PDF could not be loaded."),
33 }).pipe(
34 - Effect.flatMap((file) => (file === null ? Effect.interrupt : Effect.succeed(file))),
34 + Effect.filterOrElse(
35 + (file) => file !== null,
36 + () => Effect.interrupt,
37 + ),
38 Effect.interruptible,
39 ),
40 (file) => Effect.sync(file.dispose),
apps/mobile/src/connection/environment-cache-store.test.ts
+1 -1
@@ -252,7 +252,7 @@ function makeDatabase() {
252 }),
253 clearAllCaches: Effect.sync(() => values.clear()),
254 inspectCaches: Effect.succeed([]),
255 - loadPreferencesJson: Effect.succeed(Option.none()),
255 + loadPreferencesJson: Effect.succeedNone,
256 savePreferencesJson: () => Effect.void,
257 });
258 return { database, removed, schemaVersions, values };
apps/mobile/src/connection/environment-cache-store.ts
+3 -3
@@ -54,13 +54,13 @@ function mapDatabaseError(operation: CacheOperation) {
54 return (error: MobileDatabase.MobileDatabaseError) => persistenceError(operation, error);
55 }
56
57 -function loadDecodedCache<A, B>(input: {
57 +function loadDecodedCache<A, B, E>(input: {
58 readonly database: MobileDatabase.MobileDatabase["Service"];
59 readonly environmentId: EnvironmentId;
60 readonly kind: MobileDatabase.ClientCacheKind;
61 readonly cacheKey: string;
62 readonly operation: CacheOperation;
63 - readonly decode: (raw: string) => Effect.Effect<A, unknown>;
63 + readonly decode: (raw: string) => Effect.Effect<A, E>;
64 readonly select: (value: A) => Option.Option<B>;
65 }): Effect.Effect<Option.Option<B>, Persistence.ConnectionPersistenceError> {
66 return input.database.loadCache(input.environmentId, input.kind, input.cacheKey).pipe(
@@ -81,7 +81,7 @@ function loadDecodedCache<A, B>(input: {
81 Effect.andThen(
82 input.database
83 .removeCache(input.environmentId, input.kind, input.cacheKey)
84 - .pipe(Effect.catch(() => Effect.void)),
84 + .pipe(Effect.ignore),
85 ),
86 Effect.as(Option.none<B>()),
87 ),
apps/mobile/src/connection/migration.ts
+10 -7
@@ -87,16 +87,19 @@ function migrateConnection(
87 );
88 }
89
90 +const decodeLegacyCatalogJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
91 +
92 export const migrateLegacyConnectionCatalog = Effect.fn(
93 "mobile.connectionMigration.migrateCatalog",
94 )(function* (raw: string) {
93 - const parsed = yield* Effect.try({
94 - try: () => JSON.parse(raw) as unknown,
95 - catch: (cause) =>
96 - new LegacyConnectionMigrationError({
97 - message: `Could not parse the legacy mobile connection catalog: ${String(cause)}`,
98 - }),
99 - });
95 + const parsed = yield* decodeLegacyCatalogJson(raw).pipe(
96 + Effect.mapError(
97 + (cause) =>
98 + new LegacyConnectionMigrationError({
99 + message: `Could not parse the legacy mobile connection catalog: ${String(cause)}`,
100 + }),
101 + ),
102 + );
103 const legacy = yield* decodeLegacyConnectionDocument(parsed).pipe(
104 Effect.mapError(
105 (cause) =>
apps/mobile/src/connection/platform.ts
+15 -15
@@ -10,6 +10,7 @@ import {
10 Wakeups,
11 } from "@t3tools/client-runtime/connection";
12 import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
13 +import * as Clock from "effect/Clock";
14 import * as Context from "effect/Context";
15 import * as Effect from "effect/Effect";
16 import * as Layer from "effect/Layer";
@@ -120,8 +121,9 @@ const layerWakeups = Wakeups.layer({
121 [
122 Stream.callback<"application-active-probe" | "application-active-long">((queue) =>
123 Effect.acquireRelease(
123 - Effect.sync(() => {
124 - let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;
124 + Effect.gen(function* () {
125 + const nowMs = yield* Clock.currentTimeMillis;
126 + let backgroundedAtMs = AppState.currentState === "background" ? nowMs : null;
127 return AppState.addEventListener("change", (state) => {
128 if (state === "background") {
129 backgroundedAtMs = Date.now();
@@ -187,7 +189,7 @@ const layerCapabilities = Layer.effectContext(
189 Context.add(
190 ClientCapabilities.PrimaryEnvironmentAuth,
191 ClientCapabilities.PrimaryEnvironmentAuth.of({
190 - bearerToken: Effect.succeed(Option.none()),
192 + bearerToken: Effect.succeedNone,
193 }),
194 ),
195 // The relay device id already persists in secure storage; analytics only sends its hash.
@@ -205,7 +207,7 @@ const layerCapabilities = Layer.effectContext(
207 detail: `Could not load the mobile device identity: ${String(cause)}`,
208 }),
209 ),
208 - Effect.map(Option.some),
210 + Effect.asSome,
211 ),
212 }),
213 ),
@@ -218,21 +220,25 @@ const layerCapabilities = Layer.effectContext(
220 Context.add(
221 ClientCapabilities.SshEnvironmentGateway,
222 ClientCapabilities.SshEnvironmentGateway.of({
221 - provision: () =>
223 + provision: Effect.fn("ClientCapabilities.SshEnvironmentGateway.provision")(() =>
224 Effect.fail(
225 new ConnectionBlockedError({
226 reason: "unsupported",
227 detail: "SSH environments are only available in the desktop app.",
228 }),
229 ),
228 - prepare: () =>
230 + ),
231 + prepare: Effect.fn("ClientCapabilities.SshEnvironmentGateway.prepare")(() =>
232 Effect.fail(
233 new ConnectionBlockedError({
234 reason: "unsupported",
235 detail: "SSH environments are only available in the desktop app.",
236 }),
237 ),
235 - disconnect: () => Effect.void,
238 + ),
239 + disconnect: Effect.fn("ClientCapabilities.SshEnvironmentGateway.disconnect")(
240 + () => Effect.void,
241 + ),
242 }),
243 ),
244 );
@@ -252,7 +258,7 @@ const layerProvidedCapabilities = layerCapabilities.pipe(Layer.provide(Runtime.l
258 const layerEnvironmentOwnedDataCleanup = Layer.succeed(
259 Persistence.EnvironmentOwnedDataCleanup,
260 Persistence.EnvironmentOwnedDataCleanup.of({
255 - clear: (environmentId) =>
261 + clear: Effect.fn("Persistence.EnvironmentOwnedDataCleanup.clear")((environmentId) =>
262 Effect.all(
263 [
264 Effect.promise(() => clearThreadOutboxEnvironment(environmentId)),
@@ -260,14 +266,8 @@ const layerEnvironmentOwnedDataCleanup = Layer.succeed(
266 Effect.sync(() => clearThreadComposerErrorsForEnvironment(environmentId)),
267 ],
268 { concurrency: "unbounded", discard: true },
263 - ).pipe(
264 - Effect.catch((cause) =>
265 - Effect.logWarning("Could not clear mobile environment-owned data.", {
266 - environmentId,
267 - cause,
268 - }),
269 - ),
269 ),
270 + ),
271 }),
272 );
273
apps/mobile/src/connection/storage.ts
+24 -15
@@ -59,24 +59,33 @@ export const layer = Layer.effectContext(
59 ),
60 });
61 const registrationStore = Persistence.ConnectionRegistrationStore.of({
62 - register: (registration, routes) =>
63 - catalog
64 - .update((document) => registerConnectionInCatalog(document, registration, routes))
65 - .pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
66 - setRoutes: (environmentId, routes) =>
67 - catalog
68 - .update((document) => setRoutesInCatalog(document, environmentId, routes))
69 - .pipe(Effect.mapError((error) => targetPersistenceError("set-connection-routes", error))),
70 - remove: (environmentId) =>
62 + register: Effect.fn("Persistence.ConnectionRegistrationStore.register")(
63 + (registration, routes) =>
64 + catalog
65 + .update((document) => registerConnectionInCatalog(document, registration, routes))
66 + .pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
67 + ),
68 + setRoutes: Effect.fn("Persistence.ConnectionRegistrationStore.setRoutes")(
69 + (environmentId, routes) =>
70 + catalog
71 + .update((document) => setRoutesInCatalog(document, environmentId, routes))
72 + .pipe(
73 + Effect.mapError((error) => targetPersistenceError("set-connection-routes", error)),
74 + ),
75 + ),
76 + remove: Effect.fn("Persistence.ConnectionRegistrationStore.remove")((environmentId) =>
77 catalog
78 .update((document) => removeConnectionFromCatalog(document, environmentId))
79 .pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
74 - setEnabled: (environmentId, enabled) =>
75 - catalog
76 - .update((document) => setConnectionEnabledInCatalog(document, environmentId, enabled))
77 - .pipe(
78 - Effect.mapError((error) => targetPersistenceError("set-connection-enabled", error)),
79 - ),
80 + ),
81 + setEnabled: Effect.fn("Persistence.ConnectionRegistrationStore.setEnabled")(
82 + (environmentId, enabled) =>
83 + catalog
84 + .update((document) => setConnectionEnabledInCatalog(document, environmentId, enabled))
85 + .pipe(
86 + Effect.mapError((error) => targetPersistenceError("set-connection-enabled", error)),
87 + ),
88 + ),
89 });
90 const profileStore = ProfileStore.make({
91 get: (connectionId) =>
apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts
+11 -2
@@ -31,6 +31,7 @@ import {
31 releaseAgentAwarenessRelayTokenProvider,
32 setAgentAwarenessRelayTokenProvider,
33 updateAgentAwarenessRegistrationPreferences,
34 + type AgentAwarenessRegistrationError,
35 } from "./remoteRegistration";
36 import * as Notifications from "expo-notifications";
37 import { Platform } from "react-native";
@@ -216,7 +217,11 @@ const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundO
217 }
218 idlePasses = 0;
219 const exit = yield* Effect.exit(
219 - pending.operation as Effect.Effect<unknown, unknown, ManagedRelay.ManagedRelayClient>,
220 + pending.operation as Effect.Effect<
221 + unknown,
222 + AgentAwarenessRegistrationError,
223 + ManagedRelay.ManagedRelayClient
224 + >,
225 );
226 yield* Effect.sync(() => {
227 pending.resolve(exit);
@@ -394,7 +399,11 @@ describe("makeRelayDeviceRegistrationRequest", () => {
399 // activity lock, or, without one, at its device-id lookup.
400 const rotatedRegistration = yield* Effect.forkChild(
401 Effect.exit(
397 - rotated.operation as Effect.Effect<unknown, unknown, ManagedRelay.ManagedRelayClient>,
402 + rotated.operation as Effect.Effect<
403 + unknown,
404 + AgentAwarenessRegistrationError,
405 + ManagedRelay.ManagedRelayClient
406 + >,
407 ),
408 { startImmediately: true },
409 );
apps/mobile/src/features/agent-awareness/remoteRegistration.ts
+26 -18
@@ -5,6 +5,7 @@ import {
5 } from "./androidNotifications";
6 import Constants from "expo-constants";
7 import * as Notifications from "expo-notifications";
8 +import * as Clock from "effect/Clock";
9 import * as Effect from "effect/Effect";
10 import * as Schema from "effect/Schema";
11 import * as Semaphore from "effect/Semaphore";
@@ -75,6 +76,10 @@ export class AgentAwarenessOperationError extends Schema.TaggedError<AgentAwaren
76 }
77 }
78
79 +export type AgentAwarenessRegistrationError =
80 + | AgentAwarenessOperationError
81 + | ManagedRelay.ManagedRelayClientError;
82 +
83 // ActivityKit returns new wrappers per id; serialize by id to prevent stale-token registration.
84 const activityPushTokenLocks = new Map<string, Semaphore.Semaphore>();
85 // Each accepted registration replays the relay aggregate, repairing drifted or orphaned activities.
@@ -321,7 +326,7 @@ function registrationSignature(body: RelayDeviceRegistrationRequest): string {
326 const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWithRelay")(function* (
327 body: RelayDeviceRegistrationRequest,
328 expectedGeneration: number,
324 -): Effect.fn.Return<void, unknown, ManagedRelay.ManagedRelayClient> {
329 +): Effect.fn.Return<void, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
330 if (expectedGeneration !== deviceRegistrationGeneration) {
331 return;
332 }
@@ -340,10 +345,9 @@ const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWith
345 }
346
347 const identity = relayTokenProviderIdentity ?? "";
343 - const persisted = yield* Effect.tryPromise({
344 - try: () => loadAgentAwarenessRegistrationRecord(),
345 - catch: (cause) => cause,
346 - }).pipe(Effect.orElseSucceed(() => null));
348 + const persisted = yield* Effect.tryPromise(() => loadAgentAwarenessRegistrationRecord()).pipe(
349 + Effect.orElseSucceed(() => null),
350 + );
351 if (expectedGeneration !== deviceRegistrationGeneration) {
352 // Signed out while the record loaded — do not resurrect the cleared
353 // record or report the previous account's registration as current.
@@ -354,10 +358,11 @@ const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWith
358 // Android registration also silently replays the current card. Collapse
359 // foreground bursts, but repair missed pushes on cold start or a return
360 // after time away, just like re-registering an iOS activity token.
361 + const now = yield* Clock.currentTimeMillis;
362 const needsAndroidReplay =
363 body.platform === "android" &&
364 (androidDeviceReplayedAt === null ||
360 - Date.now() - androidDeviceReplayedAt >= ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS);
365 + now - androidDeviceReplayedAt >= ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS);
366 if (
367 persisted &&
368 persisted.identity === identity &&
@@ -379,7 +384,7 @@ const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWith
384 // stale success must not overwrite either.
385 return;
386 }
382 - if (body.platform === "android") androidDeviceReplayedAt = Date.now();
387 + if (body.platform === "android") androidDeviceReplayedAt = yield* Clock.currentTimeMillis;
388 setRegistrationStatus("registered");
389 yield* Effect.promise(() =>
390 saveAgentAwarenessRegistrationRecord({
@@ -395,7 +400,7 @@ const unregisterDeviceWithRelay = Effect.fn("remoteRegistration.unregisterDevice
400 function* (input: {
401 readonly deviceId: string;
402 readonly tokenProvider: () => Promise<string | null>;
398 - }): Effect.fn.Return<void, unknown, ManagedRelay.ManagedRelayClient> {
403 + }): Effect.fn.Return<void, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
404 if (!readRelayConfig()) return;
405 const token = yield* Effect.tryPromise({
406 try: input.tokenProvider,
@@ -513,7 +518,7 @@ const readAgentActivitySnapshot: () => Effect.Effect<
518 const registerLiveActivityWithRelay = Effect.fn("remoteRegistration.registerLiveActivityWithRelay")(
519 function* (
520 body: RelayLiveActivityRegistrationRequest,
516 - ): Effect.fn.Return<boolean, unknown, ManagedRelay.ManagedRelayClient> {
521 + ): Effect.fn.Return<boolean, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
522 if (!readRelayConfig()) return false;
523 const token = yield* relayToken("read-live-activity-registration-relay-token");
524 if (!token) {
@@ -540,8 +545,8 @@ function logRegistrationError(context: string, error: unknown): void {
545 });
546 }
547
543 -function runRegistrationInBackground(
544 - operation: Effect.Effect<unknown, unknown, ManagedRelay.ManagedRelayClient>,
548 +function runRegistrationInBackground<E>(
549 + operation: Effect.Effect<unknown, E, ManagedRelay.ManagedRelayClient>,
550 context: string,
551 ): void {
552 void (async () => {
@@ -623,7 +628,7 @@ function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: stri
628 const registerDevice = Effect.fn("remoteRegistration.registerDevice")(function* (
629 input: RegisterDeviceInput = {},
630 expectedGeneration = deviceRegistrationGeneration,
626 -): Effect.fn.Return<void, unknown, ManagedRelay.ManagedRelayClient> {
631 +): Effect.fn.Return<void, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
632 if (!canRegisterPushNotifications()) {
633 return;
634 }
@@ -687,7 +692,7 @@ const registerDevice = Effect.fn("remoteRegistration.registerDevice")(function*
692
693 function registerDeviceForCurrentUser(): Effect.Effect<
694 void,
690 - unknown,
695 + AgentAwarenessRegistrationError,
696 ManagedRelay.ManagedRelayClient
697 > {
698 return registerDevice(undefined);
@@ -773,7 +778,7 @@ export function refreshAgentAwarenessRegistration(): Effect.Effect<
778
779 export function updateAgentAwarenessRegistrationPreferences(
780 preferencesOverride: Partial<Preferences>,
776 -): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
781 +): Effect.Effect<void, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
782 return registerDevice({ preferencesOverride }).pipe(
783 Effect.tapError((error) =>
784 Effect.sync(() => {
@@ -837,7 +842,7 @@ export const registerLiveActivityPushToken = Effect.fn(
842 "remoteRegistration.registerLiveActivityPushToken",
843 )(function* (input: {
844 readonly activity: LiveActivity<AgentActivityProps>;
840 -}): Effect.fn.Return<boolean, unknown, ManagedRelay.ManagedRelayClient> {
845 +}): Effect.fn.Return<boolean, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
846 if (!canRegisterRemoteLiveActivities()) {
847 return false;
848 }
@@ -885,9 +890,12 @@ const registerLiveActivityPushTokenValue = Effect.fn(
890 "remoteRegistration.registerLiveActivityPushTokenValue",
891 )(function* (input: {
892 readonly activityPushToken: string;
888 -}): Effect.fn.Return<boolean, unknown, ManagedRelay.ManagedRelayClient> {
893 +}): Effect.fn.Return<boolean, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
894 const acceptedAt = registeredActivityPushTokens.get(input.activityPushToken);
890 - if (acceptedAt !== undefined && Date.now() - acceptedAt < ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS) {
895 + if (
896 + acceptedAt !== undefined &&
897 + (yield* Clock.currentTimeMillis) - acceptedAt < ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS
898 + ) {
899 return true;
900 }
901 const deviceId = yield* Effect.tryPromise({
@@ -903,7 +911,7 @@ const registerLiveActivityPushTokenValue = Effect.fn(
911 activityPushToken: input.activityPushToken,
912 });
913 if (registered) {
906 - registeredActivityPushTokens.set(input.activityPushToken, Date.now());
914 + registeredActivityPushTokens.set(input.activityPushToken, yield* Clock.currentTimeMillis);
915 }
916 return registered;
917 });
apps/mobile/src/features/cloud/dpop.ts
+3 -1
@@ -60,7 +60,9 @@ export const layer = Layer.mergeAll(
60 Digest.Digest,
61 Digest.Digest.of({
62 digest,
63 - digestHex: (algorithm, data) => Effect.map(digest(algorithm, data), Hex.encode),
63 + digestHex: Effect.fn("Digest.Digest.digestHex")((algorithm, data) =>
64 + Effect.map(digest(algorithm, data), Hex.encode),
65 + ),
66 }),
67 ),
68 );
apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
+3 -4
@@ -42,10 +42,9 @@ const crashLogAtom = Atom.make(
42 records: parseStartupCrashRecords(entries),
43 })),
44 Effect.catch((error) =>
45 - Effect.sync((): CrashLogState => {
46 - console.warn("[diagnostics] could not read the expo-updates log", error);
47 - return { status: "unavailable" };
48 - }),
45 + Effect.logWarning("[diagnostics] could not read the expo-updates log", error).pipe(
46 + Effect.as<CrashLogState>({ status: "unavailable" }),
47 + ),
48 ),
49 ),
50 ).pipe(Atom.withLabel("mobile:diagnostics-crash-log"));
apps/mobile/src/features/files/useFileTreeEntries.ts
+4 -2
@@ -2,6 +2,7 @@ import { useAtomMount, useAtomSubscribe } from "@effect/atom-react";
2 import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
3 import { ProjectListEntriesError, type EnvironmentId, type ProjectEntry } from "@t3tools/contracts";
4 import * as Cause from "effect/Cause";
5 +import * as Schema from "effect/Schema";
6 import { useLayoutEffect, useRef, useState } from "react";
7 import { Atom } from "effect/reactivity";
8
@@ -11,6 +12,8 @@ import { projectEnvironment } from "../../state/projects";
12 import { useDebouncedValue } from "../../state/queries";
13 import { useEnvironmentQuery } from "../../state/query";
14
15 +const isProjectListEntriesError = Schema.is(ProjectListEntriesError);
16 +
17 function createDirectories() {
18 return {
19 target: {},
@@ -273,8 +276,7 @@ export function useFileTreeEntries(input: {
276 });
277 };
278 const missingRoot =
276 - root.failure instanceof ProjectListEntriesError &&
277 - root.failure.failure === "workspace_root_not_found";
279 + isProjectListEntriesError(root.failure) && root.failure.failure === "workspace_root_not_found";
280 const rootData = missingRoot ? null : root.data;
281 const rootListing = root.successResult ?? directories.rootListing;
282 if (
apps/mobile/src/features/pull-requests/usePullRequestList.test.tsx
+10 -2
@@ -23,6 +23,11 @@ vi.mock("../../connection/catalog", async () => {
23 vi.mock("../../state/pull-requests", async () => {
24 const { AsyncResult, Atom } = await import("effect/reactivity");
25 const Effect = await import("effect/Effect");
26 + const Schema = await import("effect/Schema");
27 + class PullRequestListTestError extends Schema.TaggedError<PullRequestListTestError>()(
28 + "PullRequestListTestError",
29 + { message: Schema.String },
30 + ) {}
31 const page = (nextCursors: PullRequestListResult["nextCursors"]): PullRequestListResult => ({
32 entries: [],
33 nextCursors,
@@ -37,8 +42,11 @@ vi.mock("../../state/pull-requests", async () => {
42 return Atom.make(
43 Effect.suspend(() => {
44 if (target.environmentId === "offline")
40 - return Effect.fail(new Error("Environment is not connected."));
41 - if (target.input.cursors && mocks.failPage) return Effect.fail(new Error("Page failed."));
45 + return Effect.fail(
46 + new PullRequestListTestError({ message: "Environment is not connected." }),
47 + );
48 + if (target.input.cursors && mocks.failPage)
49 + return Effect.fail(new PullRequestListTestError({ message: "Page failed." }));
50 return Effect.succeed(response);
51 }),
52 );
apps/mobile/src/features/pull-requests/usePullRequestList.ts
+12 -10
@@ -131,16 +131,18 @@ async function refreshHeads(
131
132 // One load of each kind per list scope. The atoms are not kept alive, so leaving a scope (a
133 // filter change, unmount) interrupts its load and aborts the requests.
134 -const pageLoadFamily = Atom.family((scopeKey: string) =>
135 - Atom.fn((retry: boolean, get) =>
136 - Effect.promise((signal) => loadNextPages(get.registry, JSON.parse(scopeKey), retry, signal)),
137 - ),
138 -);
139 -const refreshLoadFamily = Atom.family((scopeKey: string) =>
140 - Atom.fn((_: void, get) =>
141 - Effect.promise((signal) => refreshHeads(get.registry, JSON.parse(scopeKey), signal)),
142 - ),
143 -);
134 +const pageLoadFamily = Atom.family((scopeKey: string) => {
135 + const targets: readonly ListTarget[] = JSON.parse(scopeKey);
136 + return Atom.fn((retry: boolean, get) =>
137 + Effect.promise((signal) => loadNextPages(get.registry, targets, retry, signal)),
138 + );
139 +});
140 +const refreshLoadFamily = Atom.family((scopeKey: string) => {
141 + const targets: readonly ListTarget[] = JSON.parse(scopeKey);
142 + return Atom.fn((_: void, get) =>
143 + Effect.promise((signal) => refreshHeads(get.registry, targets, signal)),
144 + );
145 +});
146
147 // Changes when any of the scope's environments brings up a new session.
148 const sessionsFamily = Atom.family((scopeKey: string) =>
apps/mobile/src/features/settings/environmentUpdateCheck.ts
+19 -2
@@ -1,6 +1,7 @@
1 import type { EnvironmentId } from "@t3tools/contracts";
2 import * as Effect from "effect/Effect";
3 import * as Option from "effect/Option";
4 +import * as Schema from "effect/Schema";
5 import { AsyncResult, Atom } from "effect/reactivity";
6
7 import { findEnvironmentUpdate } from "./environment-maintenance";
@@ -10,8 +11,19 @@ export interface EnvironmentReleaseCheck {
11 readonly targetVersion: string | null;
12 }
13
14 +export class EnvironmentUpdateCheckError extends Schema.TaggedError<EnvironmentUpdateCheckError>()(
15 + "EnvironmentUpdateCheckError",
16 + {
17 + message: Schema.String,
18 + cause: Schema.optional(Schema.Defect()),
19 + },
20 +) {}
21 +
22 const asError = (cause: unknown) =>
14 - cause instanceof Error ? cause : new Error("Could not check for updates.");
23 + new EnvironmentUpdateCheckError({
24 + message: cause instanceof Error ? cause.message : "Could not check for updates.",
25 + cause,
26 + });
27
28 /**
29 * Looks up the newest T3 Code release for one environment. The atom is not
@@ -29,7 +41,12 @@ export const environmentReleaseCheckAtom = Atom.family((environmentId: Environme
41 }).pipe(
42 Effect.timeoutOrElse({
43 duration: "20 seconds",
32 - orElse: () => Effect.fail(new Error("Checking for updates timed out. Try again.")),
44 + orElse: () =>
45 + Effect.fail(
46 + new EnvironmentUpdateCheckError({
47 + message: "Checking for updates timed out. Try again.",
48 + }),
49 + ),
50 }),
51 );
52 return { fromVersion, targetVersion } satisfies EnvironmentReleaseCheck;
apps/mobile/src/features/sharing/incoming-share-storage.ts
+3 -1
@@ -18,6 +18,8 @@ export class IncomingShareStorageError extends Schema.TaggedError<IncomingShareS
18 }
19 }
20
21 +const isIncomingShareStorageError = Schema.is(IncomingShareStorageError);
22 +
23 function fileName(shareId: string): string {
24 return `${encodeURIComponent(shareId)}.json`;
25 }
@@ -73,7 +75,7 @@ export async function loadIncomingShareDrafts(options?: {
75 }
76 return drafts.sort((left, right) => right.createdAt.localeCompare(left.createdAt));
77 } catch (cause) {
76 - if (cause instanceof IncomingShareStorageError) {
78 + if (isIncomingShareStorageError(cause)) {
79 throw cause;
80 }
81 throw new IncomingShareStorageError({ operation: "load", shareId: null, cause });
apps/mobile/src/lib/attachmentDocument.ts
+15 -2
@@ -10,6 +10,7 @@ import { fetch } from "expo/fetch";
10 import { File } from "expo-file-system";
11 import * as Effect from "effect/Effect";
12 import * as Option from "effect/Option";
13 +import * as Schema from "effect/Schema";
14 import { useEffect, useRef, useState } from "react";
15
16 import type { FileBackedComposerAttachment } from "./composerImages";
@@ -57,19 +58,31 @@ async function readAttachmentText(key: AttachmentTextKey, signal: AbortSignal) {
58 return readFilePreviewResponse(response, signal);
59 }
60
61 +class AttachmentTextReadError extends Schema.TaggedError<AttachmentTextReadError>()(
62 + "AttachmentTextReadError",
63 + {
64 + message: Schema.String,
65 + cause: Schema.Defect(),
66 + },
67 +) {}
68 +
69 // Plain-object keys compare structurally (Effect `Equal`/`Hash`). Unmounting the
70 // last reader interrupts the read, which aborts the fetch.
71 const attachmentTextAtom = Atom.family((key: AttachmentTextKey) =>
72 Atom.make(
73 Effect.tryPromise({
74 try: (signal) => readAttachmentText(key, signal),
66 - catch: (cause) => (cause instanceof Error ? cause : new Error("Could not read this file.")),
75 + catch: (cause) =>
76 + new AttachmentTextReadError({
77 + message: cause instanceof Error ? cause.message : "Could not read this file.",
78 + cause,
79 + }),
80 }),
81 ).pipe(Atom.withLabel("attachment-text")),
82 );
83
84 const noAttachmentText = Atom.make(
72 - AsyncResult.initial<{ text: string; truncated: boolean }, Error>(),
85 + AsyncResult.initial<{ text: string; truncated: boolean }, AttachmentTextReadError>(),
86 ).pipe(Atom.withLabel("attachment-text:none"));
87
88 /** Captured bytes never resolve against the workspace. */
apps/mobile/src/lib/composerImagePreview.ts
+3 -4
@@ -50,10 +50,9 @@ export const materializedPreviewAtom = Atom.family(({ attachment }: Materialized
50 Atom.make(
51 Effect.tryPromise(() => materializeDataUrlPreview(attachment.id, attachment.previewUri)).pipe(
52 Effect.catch((error) =>
53 - Effect.sync(() => {
54 - console.warn("[composer-attachments] could not cache an image preview", error);
55 - return null;
56 - }),
53 + Effect.logWarning("[composer-attachments] could not cache an image preview", error).pipe(
54 + Effect.as(null),
55 + ),
56 ),
57 ),
58 ).pipe(Atom.withLabel(`composer-image-preview:${attachment.id}`)),
apps/mobile/src/lib/hot-swappable-atom-runtime.ts
+1
@@ -48,6 +48,7 @@ export function hotSwappableAtomRuntime<R, E>(options: {
48 entry = existing;
49 options.registry.set(
50 entry.layerAtom,
51 + // @effect-diagnostics-next-line anyUnknownInErrorContext:off - the HMR registry erases each runtime's R and E
52 options.layer as Layer.Layer<
53 unknown,
54 unknown,
apps/mobile/src/lib/localAttachmentPreview.ts
+19 -2
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
4 import * as Equal from "effect/Equal";
5 import * as Hash from "effect/Hash";
6 import * as Option from "effect/Option";
7 +import * as Schema from "effect/Schema";
8 import { Atom, AsyncResult } from "effect/reactivity";
9
10 import type { FileBackedComposerAttachment } from "./composerImages";
@@ -84,6 +85,14 @@ class LocalAttachmentPreviewKey implements Equal.Equal {
85 }
86 }
87
88 +class LocalAttachmentPreviewLoadError extends Schema.TaggedError<LocalAttachmentPreviewLoadError>()(
89 + "LocalAttachmentPreviewLoadError",
90 + {
91 + message: Schema.String,
92 + cause: Schema.Defect(),
93 + },
94 +) {}
95 +
96 const localAttachmentPreviewFamily = Atom.family((key: LocalAttachmentPreviewKey) =>
97 Atom.make(
98 // The lease lives as long as the atom: unmounting the last reader (or a
@@ -92,8 +101,16 @@ const localAttachmentPreviewFamily = Atom.family((key: LocalAttachmentPreviewKey
101 Effect.tryPromise({
102 try: (signal) => loadLocalAttachmentPreview(key.attachment, signal),
103 catch: (cause) =>
95 - cause instanceof Error ? cause : new Error("The local file is unavailable."),
96 - }).pipe(Effect.flatMap((file) => (file === null ? Effect.interrupt : Effect.succeed(file)))),
104 + new LocalAttachmentPreviewLoadError({
105 + message: cause instanceof Error ? cause.message : "The local file is unavailable.",
106 + cause,
107 + }),
108 + }).pipe(
109 + Effect.filterOrElse(
110 + (file) => file !== null,
111 + () => Effect.interrupt,
112 + ),
113 + ),
114 (file) => Effect.sync(file.dispose),
115 ),
116 ).pipe(Atom.withLabel(`local-attachment-preview:${key.attachment.id}`)),
apps/mobile/src/persistence/mobile-database.ts
+16 -13
@@ -1,4 +1,5 @@
1 import type { EnvironmentId } from "@t3tools/contracts";
2 +import * as Clock from "effect/Clock";
3 import * as Context from "effect/Context";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
@@ -115,7 +116,7 @@ export class MobileDatabase extends Context.Service<
116 updatedAt: number,
117 ) => Effect.Effect<void, MobileDatabaseError>;
118 }
118 ->()("@t3tools/mobile/persistence/MobileDatabase") {}
119 +>()("@t3tools/mobile/persistence/mobile-database/MobileDatabase") {}
120
121 const makeAvailable = Effect.gen(function* () {
122 const database = yield* Effect.acquireRelease(
@@ -165,8 +166,9 @@ const makeAvailable = Effect.gen(function* () {
166 });
167
168 return MobileDatabase.of({
168 - loadCache: Effect.fn("MobileDatabase.loadCache")((environmentId, kind, cacheKey) =>
169 - Effect.tryPromise({
169 + loadCache: Effect.fn("MobileDatabase.loadCache")(function* (environmentId, kind, cacheKey) {
170 + const now = yield* Clock.currentTimeMillis;
171 + const row = yield* Effect.tryPromise({
172 try: () =>
173 database.getFirstAsync<{ readonly payload: string }>(
174 `SELECT payload
@@ -176,11 +178,12 @@ const makeAvailable = Effect.gen(function* () {
178 environmentId,
179 kind,
180 cacheKey,
179 - Date.now() - 30 * 24 * 60 * 60_000,
181 + now - 30 * 24 * 60 * 60_000,
182 ),
183 catch: databaseError("load-cache"),
182 - }).pipe(Effect.map((row) => Option.fromNullishOr(row?.payload))),
183 - ),
184 + });
185 + return Option.fromNullishOr(row?.payload);
186 + }),
187 listCache: Effect.fn("MobileDatabase.listCache")((kind) =>
188 Effect.tryPromise({
189 try: () =>
@@ -331,16 +334,16 @@ const makeAvailable = Effect.gen(function* () {
334 function makeUnavailable(error: MobileDatabaseError): MobileDatabase["Service"] {
335 const fail = Effect.fail(error);
336 return MobileDatabase.of({
334 - loadCache: () => fail,
335 - listCache: () => fail,
336 - saveCache: () => fail,
337 - removeCache: () => fail,
338 - clearCacheKind: () => fail,
339 - clearEnvironmentCache: () => fail,
337 + loadCache: Effect.fn("MobileDatabase.loadCache")(() => fail),
338 + listCache: Effect.fn("MobileDatabase.listCache")(() => fail),
339 + saveCache: Effect.fn("MobileDatabase.saveCache")(() => fail),
340 + removeCache: Effect.fn("MobileDatabase.removeCache")(() => fail),
341 + clearCacheKind: Effect.fn("MobileDatabase.clearCacheKind")(() => fail),
342 + clearEnvironmentCache: Effect.fn("MobileDatabase.clearEnvironmentCache")(() => fail),
343 clearAllCaches: fail,
344 inspectCaches: fail,
345 loadPreferencesJson: fail,
343 - savePreferencesJson: () => fail,
346 + savePreferencesJson: Effect.fn("MobileDatabase.savePreferencesJson")(() => fail),
347 });
348 }
349
apps/mobile/src/persistence/mobile-preferences.ts
+28 -27
@@ -25,6 +25,7 @@ import { MobileStorageDecodeError, MobileStorageEncodeError } from "./mobile-sto
25
26 const PREFERENCES_KEY = "t3code.preferences";
27 const PREFERENCES_FALLBACK_KEY = "t3code.preferences.fallback";
28 +const encodeJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
29
30 export const PullRequestListControls = Schema.Struct({
31 state: PullRequestListState,
@@ -148,6 +149,8 @@ export class MobilePreferencesSaveError extends Schema.TaggedError<MobilePrefere
149 }
150 }
151
152 +const isMobilePreferencesSaveError = Schema.is(MobilePreferencesSaveError);
153 +
154 interface PreferencesFallback {
155 readonly payload: string;
156 readonly updatedAt: number;
@@ -165,7 +168,7 @@ export class MobilePreferencesStore extends Context.Service<
168 transform: (current: Preferences) => Partial<Preferences>,
169 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
170 }
168 ->()("@t3tools/mobile/persistence/MobilePreferencesStore") {}
171 +>()("@t3tools/mobile/persistence/mobile-preferences/MobilePreferencesStore") {}
172
173 function sanitizePreferences(parsed: Preferences): Preferences {
174 const preferences: {
@@ -417,10 +420,9 @@ const make = Effect.fn("MobilePreferencesStore.make")(function* () {
420 key: string,
421 value: unknown,
422 ) {
420 - return yield* Effect.try({
421 - try: () => JSON.stringify(value),
422 - catch: (cause) => new MobileStorageEncodeError({ key, cause }),
423 - });
423 + return yield* encodeJson(value).pipe(
424 + Effect.mapError((cause) => new MobileStorageEncodeError({ key, cause })),
425 + );
426 });
427
428 const nextUpdatedAt = Ref.modify(lastUpdatedAt, (last) => {
@@ -533,34 +535,33 @@ const make = Effect.fn("MobilePreferencesStore.make")(function* () {
535 .withPermits(1)(loadUnlocked)
536 .pipe(Effect.mapError((cause) => new MobilePreferencesLoadError({ cause })));
537
536 - const update = Effect.fn("MobilePreferencesStore.update")((transform) =>
537 - lock
538 - .withPermits(1)(
539 - Effect.gen(function* () {
540 - const current = yield* loadUnlocked;
541 - const patch = yield* Effect.try({
542 - try: () => transform(current),
543 - catch: (cause) => new MobilePreferencesSaveError({ cause }),
544 - });
545 - const next: Preferences = { ...current, ...patch };
546 - const payload = yield* encode(PREFERENCES_KEY, next);
547 - yield* saveJson(payload);
548 - return next;
549 - }),
550 - )
551 - .pipe(
552 - Effect.mapError((cause) =>
553 - cause instanceof MobilePreferencesSaveError
554 - ? cause
555 - : new MobilePreferencesSaveError({ cause }),
538 + const update = Effect.fn("MobilePreferencesStore.update")(
539 + (transform: (current: Preferences) => Partial<Preferences>) =>
540 + lock
541 + .withPermits(1)(
542 + Effect.gen(function* () {
543 + const current = yield* loadUnlocked;
544 + const patch = yield* Effect.try({
545 + try: () => transform(current),
546 + catch: (cause) => new MobilePreferencesSaveError({ cause }),
547 + });
548 + const next: Preferences = { ...current, ...patch };
549 + const payload = yield* encode(PREFERENCES_KEY, next);
550 + yield* saveJson(payload);
551 + return next;
552 + }),
553 + )
554 + .pipe(
555 + Effect.mapError((cause) =>
556 + isMobilePreferencesSaveError(cause) ? cause : new MobilePreferencesSaveError({ cause }),
557 + ),
558 ),
557 - ),
559 );
560
561 return MobilePreferencesStore.of({
562 load,
563 update,
563 - savePatch: (patch) => update(() => patch),
564 + savePatch: Effect.fn("MobilePreferencesStore.savePatch")((patch) => update(() => patch)),
565 });
566 });
567
apps/mobile/src/persistence/mobile-secure-storage.ts
+1 -1
@@ -26,7 +26,7 @@ export class MobileSecureStorage extends Context.Service<
26 readonly setItem: (key: string, value: string) => Effect.Effect<void, MobileSecureStorageError>;
27 readonly removeItem: (key: string) => Effect.Effect<void, MobileSecureStorageError>;
28 }
29 ->()("@t3tools/mobile/persistence/MobileSecureStorage") {}
29 +>()("@t3tools/mobile/persistence/mobile-secure-storage/MobileSecureStorage") {}
30
31 const make = MobileSecureStorage.of({
32 getItem: Effect.fn("MobileSecureStorage.getItem")((key) =>
apps/mobile/src/persistence/mobile-storage.ts
+11 -8
@@ -11,6 +11,7 @@ import * as MobileSecureStorage from "./mobile-secure-storage";
11 const AGENT_AWARENESS_DEVICE_ID_KEY = "t3code.agent-awareness.device-id";
12 const AGENT_AWARENESS_REGISTRATION_KEY = "t3code.agent-awareness.registration";
13 const RECENT_THREAD_SHORTCUTS_KEY = "t3code.recent-thread-shortcuts";
14 +const encodeJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
15
16 export class MobileStorageDecodeError extends Schema.TaggedError<MobileStorageDecodeError>()(
17 "MobileStorageDecodeError",
@@ -93,7 +94,7 @@ export class MobileStorage extends Context.Service<
94 MobileSecureStorage.MobileSecureStorageError | MobileStorageEncodeError
95 >;
96 }
96 ->()("@t3tools/mobile/persistence/MobileStorage") {}
97 +>()("@t3tools/mobile/persistence/mobile-storage/MobileStorage") {}
98
99 export const make = Effect.fn("MobileStorage.make")(function* () {
100 const secureStorage = yield* MobileSecureStorage.MobileSecureStorage;
@@ -118,10 +119,9 @@ export const make = Effect.fn("MobileStorage.make")(function* () {
119 });
120
121 const writeJson = Effect.fn("MobileStorage.writeJson")(function* (key: string, value: unknown) {
121 - const encoded = yield* Effect.try({
122 - try: () => JSON.stringify(value),
123 - catch: (cause) => new MobileStorageEncodeError({ key, cause }),
124 - });
122 + const encoded = yield* encodeJson(value).pipe(
123 + Effect.mapError((cause) => new MobileStorageEncodeError({ key, cause })),
124 + );
125 yield* secureStorage.setItem(key, encoded);
126 });
127
@@ -184,14 +184,17 @@ export const make = Effect.fn("MobileStorage.make")(function* () {
184 loadOrCreateAgentAwarenessDeviceId,
185 loadAgentAwarenessDeviceId,
186 loadAgentAwarenessRegistrationRecord,
187 - saveAgentAwarenessRegistrationRecord: (record) =>
188 - writeJson(AGENT_AWARENESS_REGISTRATION_KEY, record),
187 + saveAgentAwarenessRegistrationRecord: Effect.fn(
188 + "MobileStorage.saveAgentAwarenessRegistrationRecord",
189 + )((record) => writeJson(AGENT_AWARENESS_REGISTRATION_KEY, record)),
190 clearAgentAwarenessRegistrationRecord: secureStorage.setItem(
191 AGENT_AWARENESS_REGISTRATION_KEY,
192 "",
193 ),
194 loadRecentThreadShortcuts,
194 - saveRecentThreadShortcuts: (threads) => writeJson(RECENT_THREAD_SHORTCUTS_KEY, { threads }),
195 + saveRecentThreadShortcuts: Effect.fn("MobileStorage.saveRecentThreadShortcuts")((threads) =>
196 + writeJson(RECENT_THREAD_SHORTCUTS_KEY, { threads }),
197 + ),
198 });
199 });
200
apps/mobile/src/state/assets.ts
+35 -13
@@ -10,7 +10,9 @@ import {
10 } from "@t3tools/client-runtime/state/assets";
11 import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
12 import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
13 +import * as Clock from "effect/Clock";
14 import * as Effect from "effect/Effect";
15 +import * as Schema from "effect/Schema";
16 import { Atom, AsyncResult } from "effect/reactivity";
17
18 import { environmentCatalog } from "../connection/catalog";
@@ -143,27 +145,47 @@ interface FreshAssetUrlKey {
145 readonly revision: number;
146 }
147
148 +class AssetUrlUnavailableError extends Schema.TaggedError<AssetUrlUnavailableError>()(
149 + "AssetUrlUnavailableError",
150 + {
151 + message: Schema.String,
152 + cause: Schema.optional(Schema.Defect()),
153 + },
154 +) {}
155 +
156 // Plain-object keys compare structurally (Effect `Equal`/`Hash`).
157 const freshAssetUrlFamily = Atom.family((key: FreshAssetUrlKey) =>
158 Atom.make(
159 Effect.tryPromise({
150 - try: async (signal): Promise<AuthorizedAssetUrl> => {
151 - const url =
152 - key.environmentId === null
153 - ? null
154 - : await refreshAssetUrl(key.environmentId, key.resource, signal);
155 - if (!url) throw new Error("Reconnect to this environment and try again.");
156 - return { url, authorizedAt: Date.now() };
157 - },
160 + try: async (signal) =>
161 + key.environmentId === null
162 + ? null
163 + : await refreshAssetUrl(key.environmentId, key.resource, signal),
164 catch: (cause) =>
159 - cause instanceof Error ? cause : new Error("The attachment is unavailable."),
160 - }),
165 + new AssetUrlUnavailableError({
166 + message: cause instanceof Error ? cause.message : "The attachment is unavailable.",
167 + cause,
168 + }),
169 + }).pipe(
170 + Effect.flatMap((url) =>
171 + url
172 + ? Effect.map(Clock.currentTimeMillis, (authorizedAt): AuthorizedAssetUrl => ({
173 + url,
174 + authorizedAt,
175 + }))
176 + : Effect.fail(
177 + new AssetUrlUnavailableError({
178 + message: "Reconnect to this environment and try again.",
179 + }),
180 + ),
181 + ),
182 + ),
183 ).pipe(Atom.withLabel("fresh-asset-url")),
184 );
185
164 -const noFreshAssetUrl = Atom.make(AsyncResult.initial<AuthorizedAssetUrl, Error>()).pipe(
165 - Atom.withLabel("fresh-asset-url:none"),
166 -);
186 +const noFreshAssetUrl = Atom.make(
187 + AsyncResult.initial<AuthorizedAssetUrl, AssetUrlUnavailableError>(),
188 +).pipe(Atom.withLabel("fresh-asset-url:none"));
189 const noSessionGeneration = Atom.make(0);
190
191 /**
apps/mobile/src/state/composer-attachment-uploads.ts
+4 -1
@@ -1,6 +1,7 @@
1 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2 import { useAtomValue } from "@effect/atom-react";
3 import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts";
4 +import * as Schema from "effect/Schema";
5 import { Atom, AsyncResult } from "effect/reactivity";
6
7 import { prepareTurnAttachments } from "../lib/attachmentUpload";
@@ -31,6 +32,8 @@ import {
32 import { environmentSession, readEnvironmentScope, sessionHasScope } from "./session";
33 import { workspaceConnections } from "./workspace";
34
35 +const isComposerDraftPersistenceError = Schema.is(ComposerDraftPersistenceError);
36 +
37 export {
38 composerAttachmentUploadBlockReason,
39 composerAttachmentsStillUploading,
@@ -164,7 +167,7 @@ export function createComposerAttachmentUploadWorker(
167 if (!retained) return "abandon";
168 // Draft-save failure only costs re-upload after restart; the outbox saves references independently, so preserve accepted uploads.
169 await flushComposerDrafts().catch((error: unknown) => {
167 - if (!(error instanceof ComposerDraftPersistenceError)) throw error;
170 + if (!isComposerDraftPersistenceError(error)) throw error;
171 console.warn("[composer-attachments] could not save the uploaded reference", error);
172 });
173 return "persisted";
apps/mobile/src/state/use-composer-drafts.ts
+3 -1
@@ -358,6 +358,8 @@ export class ComposerDraftPersistenceError extends Schema.TaggedError<ComposerDr
358 }
359 }
360
361 +const isComposerDraftPersistenceError = Schema.is(ComposerDraftPersistenceError);
362 +
363 export interface ComposerDraft {
364 readonly text: string;
365 readonly context?: OrchestrationMessageContext;
@@ -1061,7 +1063,7 @@ export function ensureComposerDraftsLoaded(): void {
1063 if (loadPromise === loading) loadPromise = null;
1064 console.warn(
1065 "[composer-drafts] failed to hydrate drafts",
1064 - cause instanceof ComposerDraftPersistenceError
1066 + isComposerDraftPersistenceError(cause)
1067 ? cause
1068 : new ComposerDraftPersistenceError({
1069 operation: "hydrate",
apps/mobile/tsconfig.json
+27 -1
@@ -1,6 +1,32 @@
1 {
2 - "extends": "expo/tsconfig.base.json",
2 + "extends": ["expo/tsconfig.base.json", "../../tsconfig.effect.json"],
3 "compilerOptions": {
4 + "plugins": [
5 + {
6 + "name": "@effect/language-service",
7 + // Severities deep-merge with tsconfig.effect.json; React Native has no Effect platform layer.
8 + "diagnosticSeverity": {
9 + "globalDate": "off",
10 + "globalConsole": "off",
11 + "globalRandom": "off",
12 + "globalTimers": "off",
13 + "globalFetch": "off"
14 + },
15 + "overrides": [
16 + {
17 + "include": [
18 + "scripts/*.ts",
19 + "scripts/*.mts",
20 + "fingerprint.config.js",
21 + "**/*.test.ts",
22 + "**/*.test.tsx",
23 + "**/*.test-support.ts"
24 + ],
25 + "options": { "diagnosticSeverity": { "nodeBuiltinImport": "off" } }
26 + }
27 + ]
28 + }
29 + ],
30 "allowImportingTsExtensions": true,
31 "strict": true,
32 "noUncheckedIndexedAccess": true,
apps/server/src/assets/AttachmentUpload.ts
+1 -1
@@ -203,7 +203,7 @@ export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(functio
203 }
204 // Publishing without replacement keeps an upload and its cached text immutable.
205 const published = yield* fileSystem.link(partPath, finalPath).pipe(
206 - Effect.map(() => true),
206 + Effect.as(true),
207 Effect.catch((error) => {
208 if (error.reason._tag === "AlreadyExists") return Effect.succeed(false);
209 return Effect.tryPromise({
apps/server/src/auth/ServerSecretStore.test.ts
+7 -12
@@ -1,7 +1,6 @@
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { assert, it } from "@effect/vitest";
4 -import * as Cause from "effect/Cause";
4 import * as Deferred from "effect/Deferred";
5 import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
@@ -93,17 +92,13 @@ const layerConcurrentReadMissFileSystem = Layer.effect(
92 yield* Deferred.succeed(readBarrier, void 0);
93 }
94 yield* Deferred.await(readBarrier);
96 - return yield* Effect.failCause(
97 - Cause.fail(
98 - PlatformError.systemError({
99 - _tag: "NotFound",
100 - module: "FileSystem",
101 - method: "readFile",
102 - pathOrDescriptor: String(path),
103 - description: "Secret file does not exist yet.",
104 - }),
105 - ),
106 - );
95 + return yield* PlatformError.systemError({
96 + _tag: "NotFound",
97 + module: "FileSystem",
98 + method: "readFile",
99 + pathOrDescriptor: String(path),
100 + description: "Secret file does not exist yet.",
101 + });
102 });
103 }),
104 )
apps/server/src/cloud/bootService.test.ts
+1 -3
@@ -624,9 +624,7 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
624 const { service, commands, control, makeService } = yield* makeHarness();
625 yield* service.install();
626 const failure = yield* service
627 - .withStopped(
628 - Effect.suspend(() => Effect.fail(control.active ? "running" : "repair failed")),
629 - )
627 + .withStopped(Effect.failSync(() => (control.active ? "running" : "repair failed")))
628 .pipe(Effect.flip);
629 expect(failure).toBe("repair failed");
630 expect(control.active).toBe(true);
apps/server/src/provider/AntigravityAuth.ts
+2 -2
@@ -212,7 +212,7 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* <
212 );
213 // Propagate interruption after the exit wait so concurrent stop waiters stay attached.
214 return yield* restore(Fiber.await(fiber)).pipe(
215 - Effect.flatMap((result) => result),
215 + Effect.flatten,
216 Effect.ensuring(Fiber.interrupt(fiber)),
217 Effect.ensuring(
218 Effect.sync(() => {
@@ -544,7 +544,7 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* <
544 }),
545 );
546 const worker = yield* task.pipe(Effect.forkIn(instanceScope));
547 - return yield* Fiber.await(worker).pipe(Effect.flatMap((result) => result));
547 + return yield* Fiber.await(worker).pipe(Effect.flatten);
548 }),
549 subscribe: (ownerSessionId) =>
550 SubscriptionRef.changes(snapshot).pipe(
apps/server/src/sourceControl/SourceControlRepositoryService.ts
+1 -1
@@ -488,7 +488,7 @@ export const make = Effect.gen(function* () {
488 args: ["rev-parse", "--verify", "HEAD"],
489 })
490 .pipe(
491 - Effect.map(() => true),
491 + Effect.as(true),
492 Effect.orElseSucceed(() => false),
493 );
494 if (!hasCommits) {
apps/server/src/textGeneration/AntigravityTextGeneration.test.ts
+1 -1
@@ -115,7 +115,7 @@ const makeFixture = Effect.fn("makeAntigravityTextGenerationFixture")(function*
115 }),
116 );
117 return yield* Fiber.await(child).pipe(
118 - Effect.flatMap((exit) => exit),
118 + Effect.flatten,
119 Effect.ensuring(Fiber.interrupt(child)),
120 );
121 });
infra/relay/src/clientConfig.ts
+3 -3
@@ -45,10 +45,10 @@ const relayClientConfigEnv = (config: RelayClientConfig & { readonly url: string
45
46 export class EnvValueNotSingleLineError extends Schema.TaggedError<EnvValueNotSingleLineError>()(
47 "EnvValueNotSingleLineError",
48 - { name: Schema.String },
48 + { key: Schema.String },
49 ) {
50 override get message(): string {
51 - return `${this.name} contains a line break and cannot be written as one .env assignment.`;
51 + return `${this.key} contains a line break and cannot be written as one .env assignment.`;
52 }
53 }
54
@@ -106,7 +106,7 @@ export const PublishClientConfig = Alchemy.Action(
106 const entries = relayClientConfigEnv({ ...input, url });
107 // Reject line breaks in provider values to prevent injected assignments.
108 for (const [name, value] of Object.entries(entries)) {
109 - if (/[\r\n]/u.test(value)) return yield* new EnvValueNotSingleLineError({ name });
109 + if (/[\r\n]/u.test(value)) return yield* new EnvValueNotSingleLineError({ key: name });
110 }
111 const existing = (yield* fs.exists(target)) ? yield* fs.readFileString(target) : "";
112 yield* fs.writeFileString(target, reconcileEnvFile(existing, entries));
packages/client-runtime/src/connection/registry.test.ts
+1 -4
@@ -525,10 +525,7 @@ function registrySpanNames<A, E, R>(effect: Effect.Effect<A, E, R>) {
525 return new Tracer.NativeSpan(options);
526 },
527 });
528 - return effect.pipe(
529 - Effect.withTracer(tracer),
530 - Effect.map(() => names),
531 - );
528 + return effect.pipe(Effect.withTracer(tracer), Effect.as(names));
529 }
530
531 function awaitConnectionState(
packages/effect-acp/src/agent.test.ts
+1 -6
@@ -256,12 +256,7 @@ it.effect("effect-acp agent keeps RPC ids within int32 and apart from extension
256 Schema.fromJsonString(RequestPermissionRequest),
257 );
258 const decodedExt = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
259 - const firstIsPermission = yield* decodedPermission(firstOutbound).pipe(
260 - Effect.match({
261 - onFailure: () => false,
262 - onSuccess: () => true,
263 - }),
264 - );
259 + const firstIsPermission = yield* decodedPermission(firstOutbound).pipe(Effect.isSuccess);
260
261 const permissionRequest = firstIsPermission
262 ? yield* decodedPermission(firstOutbound)
packages/effect-acp/src/client.test.ts
+1 -6
@@ -718,12 +718,7 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
718
719 const decodedInitialize = Schema.decodeEffect(Schema.fromJsonString(InitializeRequest));
720 const decodedExt = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
721 - const firstIsInitialize = yield* decodedInitialize(firstOutbound).pipe(
722 - Effect.match({
723 - onFailure: () => false,
724 - onSuccess: () => true,
725 - }),
726 - );
721 + const firstIsInitialize = yield* decodedInitialize(firstOutbound).pipe(Effect.isSuccess);
722
723 const initializeRequest = firstIsInitialize
724 ? yield* decodedInitialize(firstOutbound)
packages/provider-core/src/server/providerAuthFlow.ts
+1 -1
@@ -221,7 +221,7 @@ export const make = Effect.fn("ProviderAuthFlow.make")(function* (options: {
221 Effect.forkIn(child),
222 );
223 return yield* restore(Fiber.await(fiber)).pipe(
224 - Effect.flatMap((result) => result),
224 + Effect.flatten,
225 Effect.onExit((result) =>
226 Exit.isFailure(result) ? Scope.close(child, Exit.void) : Effect.void,
227 ),
packages/provider-cursor/src/server/adapter.test.ts
+3 -3
@@ -116,7 +116,7 @@ describe("CursorAdapterV2", () => {
116 : {}),
117 },
118 },
119 - }).pipe(Effect.orDie);
119 + });
120 }
121 const readUpdates: ReadonlyArray<InteractionUpdate> = [
122 {
@@ -144,7 +144,7 @@ describe("CursorAdapterV2", () => {
144 })),
145 ];
146 for (const update of readUpdates) {
147 - yield* input.onDelta!(update).pipe(Effect.orDie);
147 + yield* input.onDelta!(update);
148 }
149 return {
150 agentId: "native-cursor-lifecycle",
@@ -158,7 +158,7 @@ describe("CursorAdapterV2", () => {
158 }),
159 cancel: Effect.void,
160 };
161 - }),
161 + }).pipe(Effect.orDie),
162 }),
163 }),
164 Effect.provide(TestProviderHost.layer({ cwd: workspace })),
packages/provider-cursor/src/server/auth.ts
+1 -1
@@ -142,7 +142,7 @@ export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: Cu
142 Effect.forkIn(child),
143 );
144 return yield* restore(Fiber.await(fiber)).pipe(
145 - Effect.flatMap((result) => result),
145 + Effect.flatten,
146 Effect.onExit((result) =>
147 Exit.isFailure(result) ? Scope.close(child, Exit.void) : Effect.void,
148 ),
tsconfig.base.json
+3 -88
@@ -1,4 +1,6 @@
1 {
2 + // The Effect language service config lives apart so apps/mobile can extend it with Expo's base.
3 + "extends": "./tsconfig.effect.json",
4 "compilerOptions": {
5 "target": "ESNext",
6 "module": "NodeNext",
@@ -17,93 +19,6 @@
19 "skipLibCheck": true,
20 "allowSyntheticDefaultImports": true,
21 "esModuleInterop": true,
20 - "resolveJsonModule": true,
21 - "plugins": [
22 - {
23 - "name": "@effect/language-service",
24 - "namespaceImportPackages": ["@effect/platform-node", "effect"],
25 - "effectFn": ["span", "inferred-span", "suggested-span"],
26 - "diagnosticSeverity": {
27 - "abortControllerInEffect": "error",
28 - "runEffectInsideEffect": "error",
29 - "flatMapConditionalToFilterOrFail": "error",
30 - "catchConditionalRefailToCatchIf": "error",
31 - "tryCatchInEffectGen": "error",
32 - "schemaStructWithTag": "error",
33 - "preferTypedSchemaDecoder": "error",
34 - "catchUnfailableEffect": "error",
35 - "raceFirstWithSleepToTimeout": "error",
36 - "redundantMapError": "error",
37 - "optionMatchToFromOption": "error",
38 - "catchToIgnore": "error",
39 - "unnecessaryEffectGen": "error",
40 - "allOfMapToForEach": "error",
41 - "catchToOrElseSucceed": "error",
42 - "unnecessaryFailYieldableError": "error",
43 - "preferSucceedSomeOrNone": "error",
44 - "effectSucceedWithVoid": "error",
45 - "provideLayerSucceedToProvideService": "error",
46 - "flatMapIgnoredParamToAndThen": "error",
47 - "mapSomeToAsSome": "error",
48 - "unnecessaryPipeChain": "error",
49 - "returnEffectInGen": "off",
50 - "effectFnOpportunity": "error",
51 - "anyUnknownInErrorContext": "error",
52 - "unsafeEffectTypeAssertion": "error",
53 - "instanceOfSchema": "error",
54 - "deterministicKeys": "error",
55 - "strictEffectProvide": "off",
56 - // We use Effect's unstable modules (http, sql) on purpose. These rules
57 - // also make effect-tsgo 0.47+ report false TS2790 errors on `delete`.
58 - "unstableApiUsage": "off",
59 - "experimentalApiUsage": "off",
60 - "missingEffectServiceDependency": "error",
61 - "leakingRequirements": "error",
62 - "globalErrorInEffectCatch": "error",
63 - "globalErrorInEffectFailure": "error",
64 - "unknownInEffectCatch": "error",
65 - "strictBooleanExpressions": "off",
66 - "lazyEffect": "off",
67 - "globalJsonInEffect": "error",
68 - "schemaSyncInEffect": "error",
69 - "cryptoRandomUUID": "error",
70 - "cryptoRandomUUIDInEffect": "error",
71 - "nodeBuiltinImport": "error",
72 - "globalDate": "error",
73 - "globalDateInEffect": "error",
74 - "globalConsole": "error",
75 - "globalConsoleInEffect": "error",
76 - "globalRandom": "error",
77 - "globalRandomInEffect": "error",
78 - "globalTimers": "error",
79 - "globalTimersInEffect": "error",
80 - "globalFetch": "error",
81 - "globalFetchInEffect": "error",
82 - "schemaNumber": "off"
83 - },
84 - "overrides": [
85 - {
86 - "include": ["**/*.test.ts", "**/*.test.tsx"],
87 - "options": {
88 - "diagnosticSeverity": {
89 - "globalJsonInEffect": "off",
90 - "effectFnOpportunity": "off"
91 - }
92 - }
93 - },
94 - {
95 - "include": [
96 - "**/*.spec.ts",
97 - "**/*.spec.tsx",
98 - "**/*.testkit.ts",
99 - "**/*.testkit.tsx",
100 - "**/{test,tests,testkit,testing,fixtures,integration}/**",
101 - "packages/provider-testing/**"
102 - ],
103 - "options": { "diagnosticSeverity": { "effectFnOpportunity": "off" } }
104 - }
105 - ]
106 - }
107 - ]
22 + "resolveJsonModule": true
23 }
24 }
tsconfig.effect.json new
+131
@@ -0,0 +1,131 @@
1 +{
2 + "compilerOptions": {
3 + "plugins": [
4 + {
5 + "name": "@effect/language-service",
6 + "namespaceImportPackages": ["@effect/platform-node", "effect"],
7 + "effectFn": ["span", "inferred-span", "suggested-span"],
8 + "diagnosticSeverity": {
9 + "abortControllerInEffect": "error",
10 + "runEffectInsideEffect": "error",
11 + "flatMapConditionalToFilterOrFail": "error",
12 + "catchConditionalRefailToCatchIf": "error",
13 + "tryCatchInEffectGen": "error",
14 + "schemaStructWithTag": "error",
15 + "preferTypedSchemaDecoder": "error",
16 + "catchUnfailableEffect": "error",
17 + "raceFirstWithSleepToTimeout": "error",
18 + "redundantMapError": "error",
19 + "optionMatchToFromOption": "error",
20 + "catchToIgnore": "error",
21 + "unnecessaryEffectGen": "error",
22 + "allOfMapToForEach": "error",
23 + "catchToOrElseSucceed": "error",
24 + "unnecessaryFailYieldableError": "error",
25 + "preferSucceedSomeOrNone": "error",
26 + "effectSucceedWithVoid": "error",
27 + "provideLayerSucceedToProvideService": "error",
28 + "flatMapIgnoredParamToAndThen": "error",
29 + "mapSomeToAsSome": "error",
30 + "unnecessaryPipeChain": "error",
31 + "returnEffectInGen": "off",
32 + "effectFnOpportunity": "error",
33 + "anyUnknownInErrorContext": "error",
34 + "unsafeEffectTypeAssertion": "error",
35 + "instanceOfSchema": "error",
36 + "deterministicKeys": "error",
37 + "strictEffectProvide": "off",
38 + // We use Effect's unstable modules (http, sql) on purpose. These rules
39 + // also make effect-tsgo 0.47+ report false TS2790 errors on `delete`.
40 + "unstableApiUsage": "off",
41 + "experimentalApiUsage": "off",
42 + "missingEffectServiceDependency": "error",
43 + "leakingRequirements": "error",
44 + "globalErrorInEffectCatch": "error",
45 + "globalErrorInEffectFailure": "error",
46 + "unknownInEffectCatch": "error",
47 + "strictBooleanExpressions": "off",
48 + "lazyEffect": "off",
49 + "globalJsonInEffect": "error",
50 + "schemaSyncInEffect": "error",
51 + "cryptoRandomUUID": "error",
52 + "cryptoRandomUUIDInEffect": "error",
53 + "nodeBuiltinImport": "error",
54 + "globalDate": "error",
55 + "globalDateInEffect": "error",
56 + "globalConsole": "error",
57 + "globalConsoleInEffect": "error",
58 + "globalRandom": "error",
59 + "globalRandomInEffect": "error",
60 + "globalTimers": "error",
61 + "globalTimersInEffect": "error",
62 + "globalFetch": "error",
63 + "globalFetchInEffect": "error",
64 + "acquireReleaseDisposable": "error",
65 + "catchAllTagDispatchToCatchTag": "error",
66 + "catchAllToMapError": "error",
67 + "catchChainToFirstSuccessOf": "error",
68 + "catchDieToOrDie": "error",
69 + "catchIfTagToCatchTag": "error",
70 + "catchRefailToTapError": "error",
71 + "catchTagToCatchReason": "error",
72 + "effectMapFlatten": "error",
73 + "effectMapVoid": "error",
74 + "effectSleepZeroToYieldNow": "error",
75 + "effectSucceedWithUndefined": "error",
76 + "errorPayloadShadowsName": "error",
77 + "failCauseToConstructor": "error",
78 + "flatMapIdentityToFlatten": "error",
79 + "flatMapToMap": "error",
80 + "flatMapToTap": "error",
81 + "manualMetricTapToTrack": "error",
82 + "mapConstToAs": "error",
83 + "mapSomeCatchNoSuchElement": "error",
84 + "matchBooleanToIsSuccess": "error",
85 + "matchEffectToMapBoth": "error",
86 + "matchEffectToMatch": "error",
87 + "matchToResultOrOption": "error",
88 + "multipleCatchTag": "error",
89 + "preferUnsafeConstructor": "error",
90 + "redundantOrDie": "error",
91 + "redundantSchemaTagIdentifier": "error",
92 + "resultMatchToFromResult": "error",
93 + "runOfExitToRunExit": "error",
94 + "suspendFailToFailSync": "error",
95 + "syncToSucceed": "error",
96 + "timeoutCatchTagToTimeoutOrElse": "error",
97 + "unnecessaryPipe": "error",
98 + "unnecessaryTypeofType": "error",
99 + "schemaNumber": "off"
100 + },
101 + "overrides": [
102 + {
103 + "include": ["**/*.test.ts", "**/*.test.tsx"],
104 + "options": {
105 + "diagnosticSeverity": {
106 + "globalJsonInEffect": "off",
107 + "effectFnOpportunity": "off"
108 + }
109 + }
110 + },
111 + {
112 + "include": [
113 + "**/*.spec.ts",
114 + "**/*.spec.tsx",
115 + "**/*.testkit.ts",
116 + "**/*.testkit.tsx",
117 + "**/test/**/*",
118 + "**/tests/**/*",
119 + "**/testkit/**/*",
120 + "**/testing/**/*",
121 + "**/fixtures/**/*",
122 + "**/integration/**/*",
123 + "packages/provider-testing/**/*"
124 + ],
125 + "options": { "diagnosticSeverity": { "effectFnOpportunity": "off" } }
126 + }
127 + ]
128 + }
129 + ]
130 + }
131 +}