@devries-cameron20 / t3code-1 / commits / 669445a770
Fork 0

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

refactor(client): use Effect functions across web desktop and mobile (#21998)

Julius Marminge committed Oct 19, 2026 at 18:31 UTC 669445a7705c36be7eb7a5f4f02af0db41ccc264
28 files changed +1310 -1299
apps/desktop/src/app/DesktopCliCommand.ts
+5 -3
@@ -83,15 +83,17 @@ export const make = Effect.gen(function* () {
83 Effect.orElseSucceed(() => false),
84 );
85
86 - const isOurLink = (link: string) =>
87 - Effect.gen(function* () {
86 + const isOurLink = Effect.fn("DesktopCliCommand.isOurLink")(
87 + function* (link: string) {
88 yield* fs.readLink(link);
89 // The launcher is a few KB; never read a large binary another `t3` links to.
90 const info = yield* fs.stat(link);
91 if (info.type !== "File" || Number(info.size) > 16_384) return false;
92 const content = yield* fs.readFileString(link);
93 return content.includes(DesktopCliShim.MARKER);
94 - }).pipe(Effect.orElseSucceed(() => false));
94 + },
95 + Effect.orElseSucceed(() => false),
96 + );
97
98 const powershell = (env: Record<string, string>) =>
99 Effect.scoped(
apps/desktop/src/app/DesktopLegacyLocalStorage.ts
+5 -3
@@ -34,8 +34,8 @@ const make = Effect.gen(function* () {
34 const markerPath = yield* Ref.make(Option.none<string>());
35
36 /** Newest file mtime in a directory; appending to a log leaves the directory's own mtime alone. */
37 - const newestFileMtime = (directory: string) =>
38 - Effect.gen(function* () {
37 + const newestFileMtime = Effect.fn("DesktopLegacyLocalStorage.newestFileMtime")(
38 + function* (directory: string) {
39 let newest = 0;
40 for (const name of yield* fs.readDirectory(directory)) {
41 const info = yield* fs.stat(path.join(directory, name)).pipe(Effect.option);
@@ -47,7 +47,9 @@ const make = Effect.gen(function* () {
47 newest = Math.max(newest, mtime);
48 }
49 return newest;
50 - }).pipe(Effect.option);
50 + },
51 + (effect, _directory) => effect.pipe(Effect.option),
52 + );
53
54 const findV1LocalStorage = Effect.gen(function* () {
55 let newest: { readonly directory: string; readonly mtime: number } | null = null;
apps/desktop/src/backend/DesktopBackendConfiguration.ts
+11 -7
@@ -875,8 +875,9 @@ export const make = Effect.gen(function* () {
875 }
876 return distro ? `WSL (${distro})` : "WSL";
877 }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),
878 - resolveWsl: (input) =>
879 - Effect.gen(function* () {
878 + // The span options depend on each request's port and distro.
879 + resolveWsl: Effect.fnUntraced(
880 + function* (input) {
881 const shared = yield* sharedInputs;
882 return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
883 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
@@ -884,11 +885,14 @@ export const make = Effect.gen(function* () {
885 Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
886 Effect.provideService(FileSystem.FileSystem, fileSystem),
887 );
887 - }).pipe(
888 - Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
889 - attributes: { port: input.port, distro: input.distro ?? null },
890 - }),
891 - ),
888 + },
889 + (effect, input) =>
890 + effect.pipe(
891 + Effect.withSpan("desktop.backendConfiguration.resolveWsl", {
892 + attributes: { port: input.port, distro: input.distro ?? null },
893 + }),
894 + ),
895 + ),
896 });
897 });
898
apps/desktop/src/backend/DesktopBackendManager.ts
+16 -11
@@ -1114,20 +1114,25 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
1114 });
1115 });
1116
1117 - const waitForReady = (timeout: Duration.Duration): Effect.Effect<boolean> =>
1118 - Effect.gen(function* () {
1117 + const waitForReady: (timeout: Duration.Duration) => Effect.Effect<boolean> = Effect.fn(
1118 + "DesktopBackendManager.waitForReady",
1119 + )(
1120 + function* (_timeout: Duration.Duration) {
1121 const current = yield* Ref.get(state);
1122 if (!current.desiredRunning) return { done: true, ready: false };
1123 return current.ready ? { done: true, ready: true } : { done: false, ready: false };
1122 - }).pipe(
1123 - Effect.repeat({
1124 - until: (status) => status.done,
1125 - schedule: Schedule.spaced(Duration.millis(100)),
1126 - }),
1127 - Effect.map((status) => status.ready),
1128 - Effect.timeoutOption(timeout),
1129 - Effect.map(Option.getOrElse(() => false)),
1130 - );
1124 + },
1125 + (effect, timeout) =>
1126 + effect.pipe(
1127 + Effect.repeat({
1128 + until: (status) => status.done,
1129 + schedule: Schedule.spaced(Duration.millis(100)),
1130 + }),
1131 + Effect.map((status) => status.ready),
1132 + Effect.timeoutOption(timeout),
1133 + Effect.map(Option.getOrElse(() => false)),
1134 + ),
1135 + );
1136
1137 yield* Effect.addFinalizer(() => stop());
1138
apps/desktop/src/backend/DesktopBackendPool.ts
+48 -50
@@ -249,61 +249,59 @@ export const layer = Layer.effect(
249 ),
250 );
251
252 - const unregister: DesktopBackendPool["Service"]["unregister"] = (id) =>
253 - Effect.gen(function* () {
254 - if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {
255 - return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();
256 - }
257 - const done = yield* Deferred.make<void>();
258 - const action = yield* SynchronizedRef.modifyEffect(
259 - instancesRef,
260 - (
261 - current,
262 - ): Effect.Effect<
263 - readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]
264 - > => {
265 - const entry = current.get(id);
266 - if (entry === undefined) {
267 - return Effect.succeed([{ _tag: "Absent" } as const, current] as const);
268 - }
269 - if (entry._tag === "Closing") {
270 - return Effect.succeed([
271 - { _tag: "Wait", done: entry.done } as const,
272 - current,
273 - ] as const);
274 - }
275 - const next = new Map(current);
276 - next.set(id, { _tag: "Closing", done });
277 - return Effect.succeed([
278 - { _tag: "Close", entry } as const,
279 - next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
280 - ] as const);
281 - },
282 - );
283 -
284 - if (action._tag === "Absent") return;
285 - if (action._tag === "Wait") {
286 - yield* Deferred.await(action.done);
287 - return;
288 - }
289 -
290 - const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {
291 - const closing = current.get(id);
292 - if (closing?._tag !== "Closing" || closing.done !== done) {
293 - return Effect.succeed([undefined, current] as const);
252 + const unregister: DesktopBackendPool["Service"]["unregister"] = Effect.fn(
253 + "DesktopBackendPool.unregister",
254 + )(function* (id) {
255 + if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {
256 + return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();
257 + }
258 + const done = yield* Deferred.make<void>();
259 + const action = yield* SynchronizedRef.modifyEffect(
260 + instancesRef,
261 + (
262 + current,
263 + ): Effect.Effect<
264 + readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]
265 + > => {
266 + const entry = current.get(id);
267 + if (entry === undefined) {
268 + return Effect.succeed([{ _tag: "Absent" } as const, current] as const);
269 + }
270 + if (entry._tag === "Closing") {
271 + return Effect.succeed([{ _tag: "Wait", done: entry.done } as const, current] as const);
272 }
273 const next = new Map(current);
296 - next.delete(id);
274 + next.set(id, { _tag: "Closing", done });
275 return Effect.succeed([
298 - undefined,
276 + { _tag: "Close", entry } as const,
277 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
278 ] as const);
301 - }).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);
302 - yield* Option.match(action.entry.scope, {
303 - onNone: () => Effect.void,
304 - onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),
305 - }).pipe(Effect.ensuring(finish));
306 - });
279 + },
280 + );
281 +
282 + if (action._tag === "Absent") return;
283 + if (action._tag === "Wait") {
284 + yield* Deferred.await(action.done);
285 + return;
286 + }
287 +
288 + const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {
289 + const closing = current.get(id);
290 + if (closing?._tag !== "Closing" || closing.done !== done) {
291 + return Effect.succeed([undefined, current] as const);
292 + }
293 + const next = new Map(current);
294 + next.delete(id);
295 + return Effect.succeed([
296 + undefined,
297 + next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
298 + ] as const);
299 + }).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);
300 + yield* Option.match(action.entry.scope, {
301 + onNone: () => Effect.void,
302 + onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),
303 + }).pipe(Effect.ensuring(finish));
304 + });
305
306 return DesktopBackendPool.of({
307 get: (id) =>
apps/desktop/src/electron/ElectronWindow.ts
+3 -2
@@ -324,8 +324,9 @@ export const make = Effect.gen(function* () {
324 cause,
325 }),
326 }).pipe(Effect.orDie),
327 - sendAll: (channel, ...args) =>
328 - Effect.gen(function* () {
327 + sendAll:
328 + /* Window broadcasts run for streamed updates; avoid a span per broadcast. */
329 + Effect.fnUntraced(function* (channel, ...args) {
330 for (const window of yield* listWindows) {
331 if (yield* isWindowDestroyed(window)) {
332 continue;
apps/desktop/src/preview/Manager.ts
+5 -3
@@ -2375,8 +2375,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
2375
2376 // The scheme is read after the session attaches so a concurrent setColorScheme is not
2377 // overwritten with a stale snapshot.
2378 - const restoreControlSession = (tabId: string, wc: Electron.WebContents) =>
2379 - Effect.gen(function* () {
2378 + const restoreControlSession = Effect.fn("PreviewManager.restoreControlSession")(
2379 + function* (tabId: string, wc: Electron.WebContents) {
2380 const beforeAttach = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
2381 if (beforeAttach?.webContentsId !== wc.id) return;
2382 const control = yield* ensureControlSession(wc);
@@ -2401,7 +2401,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
2401 }),
2402 );
2403 }
2404 - }).pipe(Effect.ignore);
2404 + },
2405 + (effect, _tabId, _wc) => effect.pipe(Effect.ignore),
2406 + );
2407
2408 // Only the session that saw the detach is replaced: by the time the event is
2409 // handled the guest may already hold a newer one, which must stay.
apps/desktop/src/snapShot/DesktopSnapShot.ts
+9 -6
@@ -1708,8 +1708,8 @@ export const make = Effect.gen(function* () {
1708 ),
1709 Effect.mapError((cause) => new DesktopSnapShotError({ operation: "list-pending", cause })),
1710 ),
1711 - read: (id) =>
1712 - Effect.gen(function* () {
1711 + read: Effect.fn("DesktopSnapShot.read")(
1712 + function* (id) {
1713 const metadata = yield* fileSystem
1714 .readFileString(path.join(captureDirectory, `${id}.json`))
1715 .pipe(Effect.flatMap(decodePendingCaptureJson));
@@ -1718,11 +1718,14 @@ export const make = Effect.gen(function* () {
1718 ...metadata,
1719 dataUrl: `data:image/png;base64,${Base64.encode(png)}`,
1720 };
1721 - }).pipe(
1722 - Effect.mapError(
1723 - (cause) => new DesktopSnapShotError({ operation: "read", captureId: id, cause }),
1721 + },
1722 + (effect, id) =>
1723 + effect.pipe(
1724 + Effect.mapError(
1725 + (cause) => new DesktopSnapShotError({ operation: "read", captureId: id, cause }),
1726 + ),
1727 ),
1725 - ),
1728 + ),
1729 setAnimationDestination: (id, destination) =>
1730 Effect.promise(async () => {
1731 if (linuxFeedback?.id === id && destination.relativeFrame) {
apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts
+90 -88
@@ -199,96 +199,98 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
199 ),
200 ).pipe(Effect.forkScoped);
201
202 - const sampleOnce = (allowSuspendRecovery: boolean) =>
203 - Effect.gen(function* () {
204 - const sampledAt = yield* DateTime.now;
205 - const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);
206 - const demand = (yield* Ref.get(diagnosticsDemandSources)).size > 0;
207 - const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(
208 - [
209 - Ref.get(powerState),
210 - powerMonitor.getSystemIdleTime,
211 - powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),
212 - powerMonitor.isOnBatteryPower,
213 - electronApp.getAppMetrics,
214 - ],
215 - { concurrency: "unbounded" },
216 - );
217 - // One Electron sampler preserves the shared CPU measurement interval.
218 - yield* rendererHistory.recordMetrics(metrics);
219 - const polledLocked =
220 - systemIdleState === "unknown"
221 - ? currentPower.locked
222 - : booleanState(systemIdleState === "locked");
223 - const polledOnBattery = booleanState(onBattery);
224 - const observedPower = yield* Ref.modify(powerState, (latestPower) => {
225 - const preserveEventLocked =
226 - latestPower.lockedEventPending ||
227 - latestPower.locked !== currentPower.locked ||
228 - latestPower.lockedEventPending !== currentPower.lockedEventPending;
229 - const preserveEventOnBattery =
230 - latestPower.onBatteryEventPending ||
231 - latestPower.onBattery !== currentPower.onBattery ||
232 - latestPower.onBatteryEventPending !== currentPower.onBatteryEventPending;
233 - const preserveEventSuspended =
234 - latestPower.suspendedEventPending ||
235 - latestPower.suspended !== currentPower.suspended ||
236 - latestPower.suspendedEventPending !== currentPower.suspendedEventPending;
237 - const next: PowerState = {
238 - ...latestPower,
239 - idle: idleState(systemIdleState),
240 - locked: preserveEventLocked ? latestPower.locked : polledLocked,
241 - lockedEventPending:
242 - latestPower.lockedEventPending &&
243 - (systemIdleState === "unknown" || polledLocked !== latestPower.locked),
244 - suspended:
245 - allowSuspendRecovery && !preserveEventSuspended ? false : latestPower.suspended,
246 - suspendedEventPending: false,
247 - onBattery: preserveEventOnBattery ? latestPower.onBattery : polledOnBattery,
248 - onBatteryEventPending:
249 - latestPower.onBatteryEventPending && polledOnBattery !== latestPower.onBattery,
202 + const sampleOnce =
203 + /* Periodic telemetry sampling should not generate its own tracing traffic. */
204 + Effect.fnUntraced(
205 + function* (allowSuspendRecovery: boolean) {
206 + const sampledAt = yield* DateTime.now;
207 + const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);
208 + const demand = (yield* Ref.get(diagnosticsDemandSources)).size > 0;
209 + const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(
210 + [
211 + Ref.get(powerState),
212 + powerMonitor.getSystemIdleTime,
213 + powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),
214 + powerMonitor.isOnBatteryPower,
215 + electronApp.getAppMetrics,
216 + ],
217 + { concurrency: "unbounded" },
218 + );
219 + // One Electron sampler preserves the shared CPU measurement interval.
220 + yield* rendererHistory.recordMetrics(metrics);
221 + const polledLocked =
222 + systemIdleState === "unknown"
223 + ? currentPower.locked
224 + : booleanState(systemIdleState === "locked");
225 + const polledOnBattery = booleanState(onBattery);
226 + const observedPower = yield* Ref.modify(powerState, (latestPower) => {
227 + const preserveEventLocked =
228 + latestPower.lockedEventPending ||
229 + latestPower.locked !== currentPower.locked ||
230 + latestPower.lockedEventPending !== currentPower.lockedEventPending;
231 + const preserveEventOnBattery =
232 + latestPower.onBatteryEventPending ||
233 + latestPower.onBattery !== currentPower.onBattery ||
234 + latestPower.onBatteryEventPending !== currentPower.onBatteryEventPending;
235 + const preserveEventSuspended =
236 + latestPower.suspendedEventPending ||
237 + latestPower.suspended !== currentPower.suspended ||
238 + latestPower.suspendedEventPending !== currentPower.suspendedEventPending;
239 + const next: PowerState = {
240 + ...latestPower,
241 + idle: idleState(systemIdleState),
242 + locked: preserveEventLocked ? latestPower.locked : polledLocked,
243 + lockedEventPending:
244 + latestPower.lockedEventPending &&
245 + (systemIdleState === "unknown" || polledLocked !== latestPower.locked),
246 + suspended:
247 + allowSuspendRecovery && !preserveEventSuspended ? false : latestPower.suspended,
248 + suspendedEventPending: false,
249 + onBattery: preserveEventOnBattery ? latestPower.onBattery : polledOnBattery,
250 + onBatteryEventPending:
251 + latestPower.onBatteryEventPending && polledOnBattery !== latestPower.onBattery,
252 + };
253 + return [next, next] as const;
254 + });
255 + const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);
256 + const snapshot: DesktopHostTelemetrySnapshot = {
257 + version: 1,
258 + type: "desktopTelemetry",
259 + sequence: nextSequence,
260 + sampledAtUnixMs,
261 + electronPid: process.pid,
262 + power: {
263 + source: "electron-main",
264 + idle: observedPower.idle,
265 + idleSeconds,
266 + locked: observedPower.locked,
267 + suspended: observedPower.suspended,
268 + onBattery: observedPower.onBattery,
269 + lowPowerMode: "unknown",
270 + thermalState: observedPower.thermalState,
271 + stale: false,
272 + updatedAt: sampledAt,
273 + },
274 + speedLimitPercent: observedPower.speedLimitPercent,
275 + electronProcesses: (demand ? metrics : []).map((metric) => ({
276 + pid: metric.pid,
277 + creationTimeMs: Math.max(0, Math.round(metric.creationTime)),
278 + type: metric.type,
279 + ...(metric.name === undefined ? {} : { name: metric.name }),
280 + ...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }),
281 + cpuPercent: metric.cpu.percentCPUUsage,
282 + ...(metric.cpu.cumulativeCPUUsage === undefined
283 + ? {}
284 + : { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }),
285 + idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond,
286 + workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)),
287 + peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)),
288 + })),
289 };
251 - return [next, next] as const;
252 - });
253 - const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);
254 - const snapshot: DesktopHostTelemetrySnapshot = {
255 - version: 1,
256 - type: "desktopTelemetry",
257 - sequence: nextSequence,
258 - sampledAtUnixMs,
259 - electronPid: process.pid,
260 - power: {
261 - source: "electron-main",
262 - idle: observedPower.idle,
263 - idleSeconds,
264 - locked: observedPower.locked,
265 - suspended: observedPower.suspended,
266 - onBattery: observedPower.onBattery,
267 - lowPowerMode: "unknown",
268 - thermalState: observedPower.thermalState,
269 - stale: false,
270 - updatedAt: sampledAt,
271 - },
272 - speedLimitPercent: observedPower.speedLimitPercent,
273 - electronProcesses: (demand ? metrics : []).map((metric) => ({
274 - pid: metric.pid,
275 - creationTimeMs: Math.max(0, Math.round(metric.creationTime)),
276 - type: metric.type,
277 - ...(metric.name === undefined ? {} : { name: metric.name }),
278 - ...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }),
279 - cpuPercent: metric.cpu.percentCPUUsage,
280 - ...(metric.cpu.cumulativeCPUUsage === undefined
281 - ? {}
282 - : { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }),
283 - idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond,
284 - workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)),
285 - peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)),
286 - })),
287 - };
290
289 - yield* Ref.set(latest, Option.some(snapshot));
290 - yield* PubSub.publish(changes, snapshot);
291 - }).pipe(
291 + yield* Ref.set(latest, Option.some(snapshot));
292 + yield* PubSub.publish(changes, snapshot);
293 + },
294 Effect.catchCauseIf(
295 (cause) => !Cause.hasInterrupts(cause),
296 (cause) =>
apps/desktop/src/updates/DesktopRemoteUpdates.ts
+69 -68
@@ -188,84 +188,85 @@ export const listen: Effect.Effect<
188 Effect.forkScoped,
189 );
190
191 - const step = (state: DesktopUpdateState): Effect.Effect<boolean, never, Scope.Scope> =>
192 - Effect.gen(function* () {
193 - const next = nextRemoteDesktopUpdateStep(state, attempts, disabledReason);
194 - switch (next.action) {
195 - case "wait":
196 - return false;
197 - case "check":
198 - attempts = { ...attempts, checks: attempts.checks + 1 };
199 - yield* updates.check("remote-update").pipe(
200 - Effect.flatMap((result) => {
201 - if (result.checked) return Effect.void;
202 - attempts = { ...attempts, checks: attempts.checks - 1 };
203 - return retryLater(state);
204 - }),
205 - Effect.forkScoped,
206 - );
191 + const step = Effect.fn("DesktopRemoteUpdates.step")(function* (
192 + state: DesktopUpdateState,
193 + ): Effect.fn.Return<boolean, never, Scope.Scope> {
194 + const next = nextRemoteDesktopUpdateStep(state, attempts, disabledReason);
195 + switch (next.action) {
196 + case "wait":
197 + return false;
198 + case "check":
199 + attempts = { ...attempts, checks: attempts.checks + 1 };
200 + yield* updates.check("remote-update").pipe(
201 + Effect.flatMap((result) => {
202 + if (result.checked) return Effect.void;
203 + attempts = { ...attempts, checks: attempts.checks - 1 };
204 + return retryLater(state);
205 + }),
206 + Effect.forkScoped,
207 + );
208 + return false;
209 + case "download":
210 + attempts = { ...attempts, downloads: attempts.downloads + 1 };
211 + yield* updates.download.pipe(
212 + Effect.flatMap((result) => {
213 + if (result.accepted) return Effect.void;
214 + attempts = { ...attempts, downloads: attempts.downloads - 1 };
215 + return retryLater(state);
216 + }),
217 + Effect.forkScoped,
218 + );
219 + return false;
220 + case "install": {
221 + // The download event fires before its action releases the
222 + // updater reservation. Wait until the prepared install can
223 + // be committed by the client in a separate RPC.
224 + if (yield* updates.isActionActive) {
225 + yield* retryLater(state);
226 return false;
208 - case "download":
209 - attempts = { ...attempts, downloads: attempts.downloads + 1 };
210 - yield* updates.download.pipe(
211 - Effect.flatMap((result) => {
212 - if (result.accepted) return Effect.void;
213 - attempts = { ...attempts, downloads: attempts.downloads - 1 };
214 - return retryLater(state);
215 - }),
216 - Effect.forkScoped,
217 - );
218 - return false;
219 - case "install": {
220 - // The download event fires before its action releases the
221 - // updater reservation. Wait until the prepared install can
222 - // be committed by the client in a separate RPC.
223 - if (yield* updates.isActionActive) {
224 - yield* retryLater(state);
225 - return false;
226 - }
227 - if (state.downloadedVersion === null) {
228 - yield* publishReport(
229 - state,
230 - {
231 - outcome: "failed",
232 - reason: "The desktop app lost the downloaded update.",
233 - },
234 - request.requestId,
235 - );
236 - return true;
237 - }
238 - yield* Ref.set(
239 - preparedUpdateRef,
240 - Option.some({
241 - requestId: request.requestId,
242 - downloadedVersion: state.downloadedVersion,
243 - status: "prepared",
244 - expiresAt:
245 - (yield* Clock.currentTimeMillis) + Duration.toMillis(PREPARED_UPDATE_TTL),
246 - }),
247 - );
248 - yield* publishReport(state, { outcome: "ready-to-install" }, request.requestId);
249 - yield* logInfo("remote update prepared", { requestId: request.requestId });
250 - return true;
227 }
252 - case "done":
228 + if (state.downloadedVersion === null) {
229 yield* publishReport(
230 state,
231 {
256 - outcome: next.outcome,
257 - ...(next.reason === undefined ? {} : { reason: next.reason }),
232 + outcome: "failed",
233 + reason: "The desktop app lost the downloaded update.",
234 },
235 request.requestId,
236 );
261 - yield* logInfo("remote update finished", {
262 - requestId: request.requestId,
263 - outcome: next.outcome,
264 - reason: next.reason ?? null,
265 - });
237 return true;
238 + }
239 + yield* Ref.set(
240 + preparedUpdateRef,
241 + Option.some({
242 + requestId: request.requestId,
243 + downloadedVersion: state.downloadedVersion,
244 + status: "prepared",
245 + expiresAt:
246 + (yield* Clock.currentTimeMillis) + Duration.toMillis(PREPARED_UPDATE_TTL),
247 + }),
248 + );
249 + yield* publishReport(state, { outcome: "ready-to-install" }, request.requestId);
250 + yield* logInfo("remote update prepared", { requestId: request.requestId });
251 + return true;
252 }
268 - });
253 + case "done":
254 + yield* publishReport(
255 + state,
256 + {
257 + outcome: next.outcome,
258 + ...(next.reason === undefined ? {} : { reason: next.reason }),
259 + },
260 + request.requestId,
261 + );
262 + yield* logInfo("remote update finished", {
263 + requestId: request.requestId,
264 + outcome: next.outcome,
265 + reason: next.reason ?? null,
266 + });
267 + return true;
268 + }
269 + });
270
271 yield* Effect.raceFirst(
272 Effect.gen(function* () {
apps/desktop/src/wsl/DesktopWslEnvironment.ts
+166 -169
@@ -599,141 +599,70 @@ export const formatMissingToolsReason = (
599 return `WSL distro is missing required tools: ${issues.join(", ")}. Install ${remediations.join(" and ")}, then retry.`;
600 };
601
602 -const probeWslRuntimeImpl = (
602 +const probeWslRuntimeImpl = Effect.fn("DesktopWslEnvironment.probeWslRuntimeImpl")(function* (
603 distro: string | null,
604 linuxAppRoot: string,
605 -): Effect.Effect<ProbeWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> =>
606 - Effect.gen(function* () {
607 - const probe = yield* runWslShell(
608 - distro,
609 - buildWslRuntimeProbeScript(linuxAppRoot),
610 - PROBE_TIMEOUT,
611 - {
612 - resolveNode: false,
613 - },
614 - );
615 - const transportFailureReason = formatWslShellTransportFailureReason(
616 - probe.transportFailure,
617 - "the staged runtime",
618 - );
619 - if (transportFailureReason !== null) {
620 - return { ok: false, reason: transportFailureReason } as const;
621 - }
622 - if (probe.exitCode !== 0) {
623 - const trimmedTail = probe.stderr.trim().slice(-500);
624 - return {
625 - ok: false,
626 - reason: `${linuxAppRoot}/t3 --version failed (exit ${probe.exitCode})${trimmedTail ? `: ${trimmedTail}` : ""}`,
627 - } as const;
628 - }
629 - const resolvedPath = parseResolvedPath(probe.stdout);
630 - if (resolvedPath === null) {
631 - return {
632 - ok: false,
633 - reason: "WSL login-shell PATH could not be resolved during backend preflight.",
634 - } as const;
635 - }
636 - return { ok: true, resolvedPath } as const;
637 - });
605 +): Effect.fn.Return<ProbeWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> {
606 + const probe = yield* runWslShell(
607 + distro,
608 + buildWslRuntimeProbeScript(linuxAppRoot),
609 + PROBE_TIMEOUT,
610 + {
611 + resolveNode: false,
612 + },
613 + );
614 + const transportFailureReason = formatWslShellTransportFailureReason(
615 + probe.transportFailure,
616 + "the staged runtime",
617 + );
618 + if (transportFailureReason !== null) {
619 + return { ok: false, reason: transportFailureReason } as const;
620 + }
621 + if (probe.exitCode !== 0) {
622 + const trimmedTail = probe.stderr.trim().slice(-500);
623 + return {
624 + ok: false,
625 + reason: `${linuxAppRoot}/t3 --version failed (exit ${probe.exitCode})${trimmedTail ? `: ${trimmedTail}` : ""}`,
626 + } as const;
627 + }
628 + const resolvedPath = parseResolvedPath(probe.stdout);
629 + if (resolvedPath === null) {
630 + return {
631 + ok: false,
632 + reason: "WSL login-shell PATH could not be resolved during backend preflight.",
633 + } as const;
634 + }
635 + return { ok: true, resolvedPath } as const;
636 +});
637
639 -const ensureNodePtyImpl = (
638 +const ensureNodePtyImpl = Effect.fn("DesktopWslEnvironment.ensureNodePtyImpl")(function* (
639 distro: string | null,
640 linuxRepoRoot: string,
641 options: EnsureWslNodePtyOptions = {},
643 -): Effect.Effect<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> =>
644 - Effect.gen(function* () {
645 - // node-pty lives in the apps/server workspace's node_modules; resolve from
646 - // there rather than the monorepo root, where Bun's hoist layout omits it.
647 - const linuxServerDir = `${linuxRepoRoot}/apps/server`;
642 +): Effect.fn.Return<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> {
643 + // node-pty lives in the apps/server workspace's node_modules; resolve from
644 + // there rather than the monorepo root, where Bun's hoist layout omits it.
645 + const linuxServerDir = `${linuxRepoRoot}/apps/server`;
646
649 - const probe = yield* runWslShell(
650 - distro,
651 - NODE_PTY_PROBE_SCRIPT(linuxServerDir),
652 - PROBE_TIMEOUT,
653 - options,
654 - );
655 - const nodePath = parseNodePath(probe.stdout);
656 - const resolvedPath = parseResolvedPath(probe.stdout);
657 -
658 - const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
659 - if (transportFailureReason !== null) {
660 - return {
661 - ok: false,
662 - reason: transportFailureReason,
663 - fatal: false,
664 - } as const;
665 - }
666 -
667 - if (nodePath === null) {
668 - const toolchainCheck = yield* runWslShell(
669 - distro,
670 - TOOLCHAIN_CHECK_SCRIPT,
671 - TOOLCHAIN_TIMEOUT,
672 - options,
673 - );
674 - const toolchainTransportFailure = formatWslShellTransportFailureReason(
675 - toolchainCheck.transportFailure,
676 - );
677 - if (toolchainTransportFailure !== null) {
678 - return {
679 - ok: false,
680 - reason: toolchainTransportFailure,
681 - fatal: false,
682 - retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
683 - } as const;
684 - }
685 - const report = parseToolchainReport(toolchainCheck.stdout);
686 - const reason =
687 - formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null) ??
688 - "Node.js was not found in the WSL distro. Install it (e.g. via nvm) and restart the desktop app.";
689 - return { ok: false, reason, fatal: true } as const;
690 - }
691 -
692 - if (resolvedPath === null) {
693 - return {
694 - ok: false,
695 - reason: "WSL login-shell PATH could not be resolved during backend preflight.",
696 - fatal: true,
697 - } as const;
698 - }
699 -
700 - if (probe.exitCode === 3) {
701 - return {
702 - ok: false,
703 - reason:
704 - 'WSL server dependencies could not be loaded (for example "node-pty"). The native packages the server needs are not unpacked where the WSL distro\'s Node can read them — this is a packaging problem with this build. Please report it.',
705 - fatal: true,
706 - } as const;
707 - }
708 -
709 - if (probe.exitCode === 0) {
710 - const rawVersion = parseNodeVersion(probe.stdout);
711 - if (
712 - rawVersion !== null &&
713 - options.nodeEngineRange &&
714 - !satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())
715 - ) {
716 - const range = options.nodeEngineRange.trim();
717 - return {
718 - ok: false,
719 - reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,
720 - fatal: true,
721 - } as const;
722 - }
723 - return { ok: true, nodePath, resolvedPath } as const;
724 - }
647 + const probe = yield* runWslShell(
648 + distro,
649 + NODE_PTY_PROBE_SCRIPT(linuxServerDir),
650 + PROBE_TIMEOUT,
651 + options,
652 + );
653 + const nodePath = parseNodePath(probe.stdout);
654 + const resolvedPath = parseResolvedPath(probe.stdout);
655
726 - if (options.allowBuild !== true) {
727 - const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
728 - if (packagedProbeFailure !== null) {
729 - return {
730 - ok: false,
731 - reason: packagedProbeFailure,
732 - fatal: true,
733 - } as const;
734 - }
735 - }
656 + const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
657 + if (transportFailureReason !== null) {
658 + return {
659 + ok: false,
660 + reason: transportFailureReason,
661 + fatal: false,
662 + } as const;
663 + }
664
665 + if (nodePath === null) {
666 const toolchainCheck = yield* runWslShell(
667 distro,
668 TOOLCHAIN_CHECK_SCRIPT,
@@ -752,55 +681,124 @@ const ensureNodePtyImpl = (
681 } as const;
682 }
683 const report = parseToolchainReport(toolchainCheck.stdout);
684 + const reason =
685 + formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null) ??
686 + "Node.js was not found in the WSL distro. Install it (e.g. via nvm) and restart the desktop app.";
687 + return { ok: false, reason, fatal: true } as const;
688 + }
689
756 - if (options.allowBuild !== true) {
757 - // Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp,
758 - // or network is needed — and we must not nag the user to install build
759 - // tools they don't need.
760 - const nodeOnlyReason = formatMissingToolsReason(
761 - {
762 - missingTools: report.missingTools.filter((tool) => tool === "node"),
763 - nodeVersion: report.nodeVersion,
764 - },
765 - options.nodeEngineRange?.trim() || null,
766 - );
690 + if (resolvedPath === null) {
691 + return {
692 + ok: false,
693 + reason: "WSL login-shell PATH could not be resolved during backend preflight.",
694 + fatal: true,
695 + } as const;
696 + }
697 +
698 + if (probe.exitCode === 3) {
699 + return {
700 + ok: false,
701 + reason:
702 + 'WSL server dependencies could not be loaded (for example "node-pty"). The native packages the server needs are not unpacked where the WSL distro\'s Node can read them — this is a packaging problem with this build. Please report it.',
703 + fatal: true,
704 + } as const;
705 + }
706 +
707 + if (probe.exitCode === 0) {
708 + const rawVersion = parseNodeVersion(probe.stdout);
709 + if (
710 + rawVersion !== null &&
711 + options.nodeEngineRange &&
712 + !satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())
713 + ) {
714 + const range = options.nodeEngineRange.trim();
715 return {
716 ok: false,
769 - reason:
770 - nodeOnlyReason ??
771 - "The bundled WSL backend binary (node-pty) could not be loaded in this distro. This usually means an unsupported CPU architecture or incompatible system libraries (glibc). Use a glibc-based x64/arm64 WSL distro such as Ubuntu; if you already are, please report this with your distro and the output of `uname -m`.",
717 + reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,
718 fatal: true,
719 } as const;
720 }
721 + return { ok: true, nodePath, resolvedPath } as const;
722 + }
723
776 - const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);
777 - if (missingReason !== null) {
778 - return { ok: false, reason: missingReason, fatal: true } as const;
779 - }
780 -
781 - const build = yield* runWslShell(
782 - distro,
783 - NODE_PTY_BUILD_SCRIPT(linuxServerDir),
784 - BUILD_TIMEOUT,
785 - options,
786 - );
787 - const buildTransportFailure = formatWslShellTransportFailureReason(build.transportFailure);
788 - if (buildTransportFailure !== null) {
724 + if (options.allowBuild !== true) {
725 + const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
726 + if (packagedProbeFailure !== null) {
727 return {
728 ok: false,
791 - reason: buildTransportFailure,
792 - fatal: false,
793 - retryLimit: BUILD_TRANSPORT_RETRY_LIMIT,
729 + reason: packagedProbeFailure,
730 + fatal: true,
731 } as const;
732 }
796 - if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
797 - const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500);
733 + }
734 +
735 + const toolchainCheck = yield* runWslShell(
736 + distro,
737 + TOOLCHAIN_CHECK_SCRIPT,
738 + TOOLCHAIN_TIMEOUT,
739 + options,
740 + );
741 + const toolchainTransportFailure = formatWslShellTransportFailureReason(
742 + toolchainCheck.transportFailure,
743 + );
744 + if (toolchainTransportFailure !== null) {
745 + return {
746 + ok: false,
747 + reason: toolchainTransportFailure,
748 + fatal: false,
749 + retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,
750 + } as const;
751 + }
752 + const report = parseToolchainReport(toolchainCheck.stdout);
753 +
754 + if (options.allowBuild !== true) {
755 + // Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp,
756 + // or network is needed — and we must not nag the user to install build
757 + // tools they don't need.
758 + const nodeOnlyReason = formatMissingToolsReason(
759 + {
760 + missingTools: report.missingTools.filter((tool) => tool === "node"),
761 + nodeVersion: report.nodeVersion,
762 + },
763 + options.nodeEngineRange?.trim() || null,
764 + );
765 return {
766 ok: false,
800 - reason: `node-pty Linux build failed (exit ${build.exitCode}): ${trimmedTail || "no stderr captured"}`,
767 + reason:
768 + nodeOnlyReason ??
769 + "The bundled WSL backend binary (node-pty) could not be loaded in this distro. This usually means an unsupported CPU architecture or incompatible system libraries (glibc). Use a glibc-based x64/arm64 WSL distro such as Ubuntu; if you already are, please report this with your distro and the output of `uname -m`.",
770 fatal: true,
771 } as const;
803 - });
772 + }
773 +
774 + const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);
775 + if (missingReason !== null) {
776 + return { ok: false, reason: missingReason, fatal: true } as const;
777 + }
778 +
779 + const build = yield* runWslShell(
780 + distro,
781 + NODE_PTY_BUILD_SCRIPT(linuxServerDir),
782 + BUILD_TIMEOUT,
783 + options,
784 + );
785 + const buildTransportFailure = formatWslShellTransportFailureReason(build.transportFailure);
786 + if (buildTransportFailure !== null) {
787 + return {
788 + ok: false,
789 + reason: buildTransportFailure,
790 + fatal: false,
791 + retryLimit: BUILD_TRANSPORT_RETRY_LIMIT,
792 + } as const;
793 + }
794 + if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
795 + const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500);
796 + return {
797 + ok: false,
798 + reason: `node-pty Linux build failed (exit ${build.exitCode}): ${trimmedTail || "no stderr captured"}`,
799 + fatal: true,
800 + } as const;
801 +});
802
803 const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(function* (
804 distro: string | null,
@@ -1059,17 +1057,16 @@ const getUserHomeImpl = (
1057 Effect.orElseSucceed(() => Option.none<string>()),
1058 );
1059
1062 -const makeIsAvailable = (
1060 +const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable")(function* (
1061 platform: NodeJS.Platform,
1062 windir: string,
1065 -): Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path> =>
1066 - Effect.gen(function* () {
1067 - if (platform !== "win32") return false;
1068 - const path = yield* Path.Path;
1069 - const fileSystem = yield* FileSystem.FileSystem;
1070 - const wslExePath = path.join(windir, "System32", "wsl.exe");
1071 - return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));
1072 - });
1063 +): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
1064 + if (platform !== "win32") return false;
1065 + const path = yield* Path.Path;
1066 + const fileSystem = yield* FileSystem.FileSystem;
1067 + const wslExePath = path.join(windir, "System32", "wsl.exe");
1068 + return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));
1069 +});
1070
1071 export interface DesktopWslEnvironmentTestStub {
1072 readonly isAvailable?: boolean;
apps/desktop/src/wsl/DesktopWslServerTree.ts
+16 -13
@@ -48,22 +48,25 @@ export class DesktopWslServerTree extends Context.Service<
48 }
49 >()("@t3tools/desktop/wsl/DesktopWslServerTree") {}
50
51 -export const forEachBoundedTree = <Node, E, R>(
51 +export const forEachBoundedTree = Effect.fn("DesktopWslServerTree.forEachBoundedTree")(function* <
52 + Node,
53 + E,
54 + R,
55 +>(
56 roots: ReadonlyArray<Node>,
57 visit: (node: Node) => Effect.Effect<ReadonlyArray<Node>, E, R>,
54 -): Effect.Effect<void, E, R> =>
55 - Effect.gen(function* () {
56 - const pending = [...roots];
57 - while (pending.length > 0) {
58 - const batch = pending.splice(-COPY_CONCURRENCY);
59 - const children = yield* Effect.forEach(batch, visit, {
60 - concurrency: COPY_CONCURRENCY,
61 - });
62 - for (const entries of children) {
63 - pending.push(...entries);
64 - }
58 +): Effect.fn.Return<void, E, R> {
59 + const pending = [...roots];
60 + while (pending.length > 0) {
61 + const batch = pending.splice(-COPY_CONCURRENCY);
62 + const children = yield* Effect.forEach(batch, visit, {
63 + concurrency: COPY_CONCURRENCY,
64 + });
65 + for (const entries of children) {
66 + pending.push(...entries);
67 }
66 - });
68 + }
69 +});
70
71 interface CopyTreeEntry {
72 readonly sourcePath: string;
apps/mobile/src/features/agent-awareness/remoteRegistration.ts
+359 -371
@@ -255,8 +255,8 @@ function iosMajorVersion(): number {
255 return Number.isFinite(major) ? major : 18;
256 }
257
258 -function nativePushTokenRegistration(observedPushToken?: string) {
259 - return Effect.gen(function* () {
258 +const nativePushTokenRegistration = Effect.fn("remoteRegistration.nativePushTokenRegistration")(
259 + function* (observedPushToken?: string) {
260 if (!canRegisterPushNotifications() || !supportsAgentAwarenessPush()) {
261 return { notificationsEnabled: false, pushToken: null };
262 }
@@ -294,22 +294,21 @@ function nativePushTokenRegistration(observedPushToken?: string) {
294 ? token.data.trim()
295 : null;
296 return { notificationsEnabled: pushToken !== null, pushToken };
297 - });
298 -}
297 + },
298 +);
299
300 -const relayToken = (
300 +const relayToken = Effect.fn("remoteRegistration.relayToken")(function* (
301 operation: "read-device-registration-relay-token" | "read-live-activity-registration-relay-token",
302 -) =>
303 - Effect.gen(function* () {
304 - const provider = relayTokenProvider;
305 - if (!provider) {
306 - return null;
307 - }
308 - return yield* Effect.tryPromise({
309 - try: provider,
310 - catch: (cause) => new AgentAwarenessOperationError({ operation, cause }),
311 - });
302 +) {
303 + const provider = relayTokenProvider;
304 + if (!provider) {
305 + return null;
306 + }
307 + return yield* Effect.tryPromise({
308 + try: provider,
309 + catch: (cause) => new AgentAwarenessOperationError({ operation, cause }),
310 });
311 +});
312
313 function registrationSignature(body: RelayDeviceRegistrationRequest): string {
314 return [
@@ -331,112 +330,110 @@ function registrationSignature(body: RelayDeviceRegistrationRequest): string {
330 ].join("|");
331 }
332
334 -function registerDeviceWithRelay(
333 +const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWithRelay")(function* (
334 body: RelayDeviceRegistrationRequest,
335 expectedGeneration: number,
337 -): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
338 - return Effect.gen(function* () {
339 - if (expectedGeneration !== deviceRegistrationGeneration) {
340 - logRegistrationDebug("device registration cancelled before relay request", {
341 - expectedGeneration,
342 - currentGeneration: deviceRegistrationGeneration,
343 - });
344 - return;
345 - }
346 - const relayConfig = readRelayConfig();
347 - if (!relayConfig) {
348 - setRegistrationStatus("unknown");
349 - return;
350 - }
351 - const token = yield* relayToken("read-device-registration-relay-token");
352 - if (expectedGeneration !== deviceRegistrationGeneration) {
353 - logRegistrationDebug("device registration cancelled after auth lookup", {
354 - expectedGeneration,
355 - currentGeneration: deviceRegistrationGeneration,
356 - });
357 - return;
358 - }
359 - if (!token) {
360 - logRegistrationDebug("relay device registration skipped; user is not signed in");
361 - setRegistrationStatus("unknown");
362 - return;
363 - }
364 -
365 - const identity = relayTokenProviderIdentity ?? "";
366 - const persisted = yield* Effect.tryPromise({
367 - try: () => loadAgentAwarenessRegistrationRecord(),
368 - catch: (cause) => cause,
369 - }).pipe(Effect.orElseSucceed(() => null));
370 - if (expectedGeneration !== deviceRegistrationGeneration) {
371 - // Signed out while the record loaded — do not resurrect the cleared
372 - // record or report the previous account's registration as current.
373 - logRegistrationDebug("device registration cancelled after record lookup", {
374 - expectedGeneration,
375 - currentGeneration: deviceRegistrationGeneration,
376 - });
377 - return;
378 - }
379 - const payload = body;
380 - const signature = `${relayConfig.url}|${registrationSignature(payload)}`;
381 - // Android registration also silently replays the current card. Collapse
382 - // foreground bursts, but repair missed pushes on cold start or a return
383 - // after time away, just like re-registering an iOS activity token.
384 - const needsAndroidReplay =
385 - body.platform === "android" &&
386 - (androidDeviceReplayedAt === null ||
387 - Date.now() - androidDeviceReplayedAt >= ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS);
388 - if (
389 - persisted &&
390 - persisted.identity === identity &&
391 - persisted.signature === signature &&
392 - !needsAndroidReplay
393 - ) {
394 - setRegistrationStatus("registered");
395 - logRegistrationDebug("relay device registration skipped; already registered for account", {
396 - expectedGeneration,
397 - });
398 - return;
399 - }
400 -
401 - const client = yield* ManagedRelay.ManagedRelayClient;
402 - logRegistrationDebug("relay device registration request started", {
336 +): Effect.fn.Return<void, unknown, ManagedRelay.ManagedRelayClient> {
337 + if (expectedGeneration !== deviceRegistrationGeneration) {
338 + logRegistrationDebug("device registration cancelled before relay request", {
339 expectedGeneration,
340 + currentGeneration: deviceRegistrationGeneration,
341 });
405 - yield* client.registerDevice({
406 - clerkToken: token,
407 - payload,
342 + return;
343 + }
344 + const relayConfig = readRelayConfig();
345 + if (!relayConfig) {
346 + setRegistrationStatus("unknown");
347 + return;
348 + }
349 + const token = yield* relayToken("read-device-registration-relay-token");
350 + if (expectedGeneration !== deviceRegistrationGeneration) {
351 + logRegistrationDebug("device registration cancelled after auth lookup", {
352 + expectedGeneration,
353 + currentGeneration: deviceRegistrationGeneration,
354 });
409 - if (expectedGeneration !== deviceRegistrationGeneration) {
410 - // Signed out while the request was in flight: the sign-out path already
411 - // reset the status and cleared the record for the next account, so a
412 - // stale success must not overwrite either.
413 - logRegistrationDebug("device registration completed after sign-out; result discarded", {
414 - expectedGeneration,
415 - currentGeneration: deviceRegistrationGeneration,
416 - });
417 - return;
418 - }
419 - if (body.platform === "android") androidDeviceReplayedAt = Date.now();
355 + return;
356 + }
357 + if (!token) {
358 + logRegistrationDebug("relay device registration skipped; user is not signed in");
359 + setRegistrationStatus("unknown");
360 + return;
361 + }
362 +
363 + const identity = relayTokenProviderIdentity ?? "";
364 + const persisted = yield* Effect.tryPromise({
365 + try: () => loadAgentAwarenessRegistrationRecord(),
366 + catch: (cause) => cause,
367 + }).pipe(Effect.orElseSucceed(() => null));
368 + if (expectedGeneration !== deviceRegistrationGeneration) {
369 + // Signed out while the record loaded — do not resurrect the cleared
370 + // record or report the previous account's registration as current.
371 + logRegistrationDebug("device registration cancelled after record lookup", {
372 + expectedGeneration,
373 + currentGeneration: deviceRegistrationGeneration,
374 + });
375 + return;
376 + }
377 + const payload = body;
378 + const signature = `${relayConfig.url}|${registrationSignature(payload)}`;
379 + // Android registration also silently replays the current card. Collapse
380 + // foreground bursts, but repair missed pushes on cold start or a return
381 + // after time away, just like re-registering an iOS activity token.
382 + const needsAndroidReplay =
383 + body.platform === "android" &&
384 + (androidDeviceReplayedAt === null ||
385 + Date.now() - androidDeviceReplayedAt >= ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS);
386 + if (
387 + persisted &&
388 + persisted.identity === identity &&
389 + persisted.signature === signature &&
390 + !needsAndroidReplay
391 + ) {
392 setRegistrationStatus("registered");
421 - yield* Effect.promise(() =>
422 - saveAgentAwarenessRegistrationRecord({
423 - identity,
424 - signature,
425 - }).catch((error: unknown) => {
426 - logRegistrationError("persist registration record failed", error);
427 - }),
428 - );
429 - logRegistrationDebug("relay device registration request completed", {
393 + logRegistrationDebug("relay device registration skipped; already registered for account", {
394 expectedGeneration,
395 });
396 + return;
397 + }
398 +
399 + const client = yield* ManagedRelay.ManagedRelayClient;
400 + logRegistrationDebug("relay device registration request started", {
401 + expectedGeneration,
402 });
433 -}
403 + yield* client.registerDevice({
404 + clerkToken: token,
405 + payload,
406 + });
407 + if (expectedGeneration !== deviceRegistrationGeneration) {
408 + // Signed out while the request was in flight: the sign-out path already
409 + // reset the status and cleared the record for the next account, so a
410 + // stale success must not overwrite either.
411 + logRegistrationDebug("device registration completed after sign-out; result discarded", {
412 + expectedGeneration,
413 + currentGeneration: deviceRegistrationGeneration,
414 + });
415 + return;
416 + }
417 + if (body.platform === "android") androidDeviceReplayedAt = Date.now();
418 + setRegistrationStatus("registered");
419 + yield* Effect.promise(() =>
420 + saveAgentAwarenessRegistrationRecord({
421 + identity,
422 + signature,
423 + }).catch((error: unknown) => {
424 + logRegistrationError("persist registration record failed", error);
425 + }),
426 + );
427 + logRegistrationDebug("relay device registration request completed", {
428 + expectedGeneration,
429 + });
430 +});
431
435 -function unregisterDeviceWithRelay(input: {
436 - readonly deviceId: string;
437 - readonly tokenProvider: () => Promise<string | null>;
438 -}): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
439 - return Effect.gen(function* () {
432 +const unregisterDeviceWithRelay = Effect.fn("remoteRegistration.unregisterDeviceWithRelay")(
433 + function* (input: {
434 + readonly deviceId: string;
435 + readonly tokenProvider: () => Promise<string | null>;
436 + }): Effect.fn.Return<void, unknown, ManagedRelay.ManagedRelayClient> {
437 if (!readRelayConfig()) return;
438 const token = yield* Effect.tryPromise({
439 try: input.tokenProvider,
@@ -456,8 +453,8 @@ function unregisterDeviceWithRelay(input: {
453 clerkToken: token,
454 deviceId: input.deviceId,
455 });
459 - });
460 -}
456 + },
457 +);
458
459 function environmentPublishesAgentActivity(environmentId: EnvironmentId): boolean {
460 return (
@@ -536,12 +533,12 @@ function armAgentAwarenessLiveActivityForLocalWorkNow(input: {
533 }
534 }
535
539 -function readAgentActivitySnapshot(): Effect.Effect<
536 +const readAgentActivitySnapshot: () => Effect.Effect<
537 RelayAgentActivitySnapshotResponse | null,
538 never,
539 ManagedRelay.ManagedRelayClient
543 -> {
544 - return Effect.gen(function* () {
540 +> = Effect.fn("remoteRegistration.readAgentActivitySnapshot")(
541 + function* () {
542 if (!readRelayConfig()) return null;
543 const token = yield* relayToken("read-live-activity-registration-relay-token");
544 if (!token) {
@@ -549,20 +546,19 @@ function readAgentActivitySnapshot(): Effect.Effect<
546 }
547 const client = yield* ManagedRelay.ManagedRelayClient;
548 return yield* client.getAgentActivitySnapshot({ clerkToken: token });
552 - }).pipe(
553 - Effect.catch((error) =>
554 - Effect.sync(() => {
555 - logRegistrationError("agent activity snapshot read failed", error);
556 - return null;
557 - }),
558 - ),
559 - );
560 -}
561 -
562 -function registerLiveActivityWithRelay(
563 - body: RelayLiveActivityRegistrationRequest,
564 -): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
565 - return Effect.gen(function* () {
549 + },
550 + Effect.catch((error) =>
551 + Effect.sync(() => {
552 + logRegistrationError("agent activity snapshot read failed", error);
553 + return null;
554 + }),
555 + ),
556 +);
557 +
558 +const registerLiveActivityWithRelay = Effect.fn("remoteRegistration.registerLiveActivityWithRelay")(
559 + function* (
560 + body: RelayLiveActivityRegistrationRequest,
561 + ): Effect.fn.Return<boolean, unknown, ManagedRelay.ManagedRelayClient> {
562 if (!readRelayConfig()) return false;
563 const token = yield* relayToken("read-live-activity-registration-relay-token");
564 if (!token) {
@@ -576,8 +572,8 @@ function registerLiveActivityWithRelay(
572 payload: body,
573 });
574 return true;
579 - });
580 -}
575 + },
576 +);
577
578 function logRegistrationError(context: string, error: unknown): void {
579 if (!__DEV__) {
@@ -693,78 +689,76 @@ function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: stri
689 startPendingDeviceRegistration();
690 }
691
696 -function registerDevice(
692 +const registerDevice = Effect.fn("remoteRegistration.registerDevice")(function* (
693 input: RegisterDeviceInput = {},
694 expectedGeneration = deviceRegistrationGeneration,
699 -): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
700 - return Effect.gen(function* () {
701 - if (!canRegisterPushNotifications()) {
702 - logRegistrationDebug("device registration skipped; platform does not support it");
703 - return;
704 - }
695 +): Effect.fn.Return<void, unknown, ManagedRelay.ManagedRelayClient> {
696 + if (!canRegisterPushNotifications()) {
697 + logRegistrationDebug("device registration skipped; platform does not support it");
698 + return;
699 + }
700
706 - logRegistrationDebug("device registration loading local state", { expectedGeneration });
707 - const [deviceId, storedPreferences] = yield* Effect.all([
708 - Effect.tryPromise({
709 - try: () => loadOrCreateAgentAwarenessDeviceId(),
710 - catch: (cause) =>
711 - new AgentAwarenessOperationError({
712 - operation: "load-device-registration-identifier",
713 - cause,
714 - }),
715 - }),
716 - Effect.tryPromise({
717 - try: () => loadPreferences(),
718 - catch: (cause) =>
719 - new AgentAwarenessOperationError({
720 - operation: "load-device-registration-preferences",
721 - cause,
722 - }),
723 - }),
724 - ]);
725 - const preferences = mergeAgentAwarenessRegistrationPreferences(
726 - storedPreferences,
727 - input.preferencesOverride,
728 - );
729 - if (expectedGeneration !== deviceRegistrationGeneration) return;
730 - if (relayTokenProvider && relayTokenProviderIdentity) {
731 - configureAndroidAgentNotifications(
732 - deviceId,
733 - relayTokenProviderIdentity,
734 - preferences.liveActivitiesEnabled !== false,
735 - );
736 - }
737 - const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);
738 - logRegistrationDebug("device registration local state ready", {
739 - expectedGeneration,
740 - notificationsEnabled: pushTokenRegistration.notificationsEnabled,
741 - });
742 - const bundleId =
743 - Platform.OS === "android"
744 - ? Constants.expoConfig?.android?.package?.trim()
745 - : Constants.expoConfig?.ios?.bundleIdentifier?.trim();
746 - yield* registerDeviceWithRelay(
747 - makeRelayDeviceRegistrationRequest({
748 - deviceId,
749 - label:
750 - Constants.deviceName?.trim() ||
751 - (Platform.OS === "android" ? "Android device" : "iOS device"),
752 - ...(Platform.OS === "android"
753 - ? { platform: "android" as const, androidApiLevel: Number(Platform.Version) }
754 - : { platform: "ios" as const, iosMajorVersion: iosMajorVersion() }),
755 - appVersion: Constants.expoConfig?.version,
756 - ...(bundleId ? { bundleId } : {}),
757 - ...(Platform.OS === "ios"
758 - ? { apsEnvironment: resolveApsEnvironment(Constants.expoConfig?.extra?.appVariant) }
759 - : {}),
760 - ...(pushTokenRegistration.pushToken ? { pushToken: pushTokenRegistration.pushToken } : {}),
761 - notificationsEnabled: pushTokenRegistration.notificationsEnabled,
762 - preferences,
763 - }),
764 - expectedGeneration,
701 + logRegistrationDebug("device registration loading local state", { expectedGeneration });
702 + const [deviceId, storedPreferences] = yield* Effect.all([
703 + Effect.tryPromise({
704 + try: () => loadOrCreateAgentAwarenessDeviceId(),
705 + catch: (cause) =>
706 + new AgentAwarenessOperationError({
707 + operation: "load-device-registration-identifier",
708 + cause,
709 + }),
710 + }),
711 + Effect.tryPromise({
712 + try: () => loadPreferences(),
713 + catch: (cause) =>
714 + new AgentAwarenessOperationError({
715 + operation: "load-device-registration-preferences",
716 + cause,
717 + }),
718 + }),
719 + ]);
720 + const preferences = mergeAgentAwarenessRegistrationPreferences(
721 + storedPreferences,
722 + input.preferencesOverride,
723 + );
724 + if (expectedGeneration !== deviceRegistrationGeneration) return;
725 + if (relayTokenProvider && relayTokenProviderIdentity) {
726 + configureAndroidAgentNotifications(
727 + deviceId,
728 + relayTokenProviderIdentity,
729 + preferences.liveActivitiesEnabled !== false,
730 );
731 + }
732 + const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);
733 + logRegistrationDebug("device registration local state ready", {
734 + expectedGeneration,
735 + notificationsEnabled: pushTokenRegistration.notificationsEnabled,
736 });
767 -}
737 + const bundleId =
738 + Platform.OS === "android"
739 + ? Constants.expoConfig?.android?.package?.trim()
740 + : Constants.expoConfig?.ios?.bundleIdentifier?.trim();
741 + yield* registerDeviceWithRelay(
742 + makeRelayDeviceRegistrationRequest({
743 + deviceId,
744 + label:
745 + Constants.deviceName?.trim() ||
746 + (Platform.OS === "android" ? "Android device" : "iOS device"),
747 + ...(Platform.OS === "android"
748 + ? { platform: "android" as const, androidApiLevel: Number(Platform.Version) }
749 + : { platform: "ios" as const, iosMajorVersion: iosMajorVersion() }),
750 + appVersion: Constants.expoConfig?.version,
751 + ...(bundleId ? { bundleId } : {}),
752 + ...(Platform.OS === "ios"
753 + ? { apsEnvironment: resolveApsEnvironment(Constants.expoConfig?.extra?.appVariant) }
754 + : {}),
755 + ...(pushTokenRegistration.pushToken ? { pushToken: pushTokenRegistration.pushToken } : {}),
756 + notificationsEnabled: pushTokenRegistration.notificationsEnabled,
757 + preferences,
758 + }),
759 + expectedGeneration,
760 + );
761 +});
762
763 function registerDeviceForCurrentUser(): Effect.Effect<
764 void,
@@ -902,10 +896,12 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
896 activityPushTokenLocks.clear();
897 }
898
905 -export function unregisterAgentAwarenessDeviceForCurrentUser(
899 +export const unregisterAgentAwarenessDeviceForCurrentUser: (
900 tokenProvider: () => Promise<string | null>,
907 -): Effect.Effect<void, never, ManagedRelay.ManagedRelayClient> {
908 - return Effect.gen(function* () {
901 +) => Effect.Effect<void, never, ManagedRelay.ManagedRelayClient> = Effect.fn(
902 + "remoteRegistration.unregisterAgentAwarenessDeviceForCurrentUser",
903 +)(
904 + function* (tokenProvider: () => Promise<string | null>) {
905 const deviceId = yield* Effect.tryPromise({
906 try: () => loadAgentAwarenessDeviceId(),
907 catch: (cause) =>
@@ -918,47 +914,46 @@ export function unregisterAgentAwarenessDeviceForCurrentUser(
914 return;
915 }
916 yield* unregisterDeviceWithRelay({ deviceId, tokenProvider });
921 - }).pipe(
922 - Effect.catch((error) =>
923 - Effect.sync(() => {
924 - logRegistrationError("device unregistration failed", error);
925 - }),
926 - ),
927 - );
928 -}
929 -
930 -export function registerLiveActivityPushToken(input: {
917 + },
918 + Effect.catch((error) =>
919 + Effect.sync(() => {
920 + logRegistrationError("device unregistration failed", error);
921 + }),
922 + ),
923 +);
924 +
925 +export const registerLiveActivityPushToken = Effect.fn(
926 + "remoteRegistration.registerLiveActivityPushToken",
927 +)(function* (input: {
928 readonly activity: LiveActivity<AgentActivityProps>;
932 -}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
933 - return Effect.gen(function* () {
934 - if (!canRegisterRemoteLiveActivities()) {
935 - return false;
936 - }
929 +}): Effect.fn.Return<boolean, unknown, ManagedRelay.ManagedRelayClient> {
930 + if (!canRegisterRemoteLiveActivities()) {
931 + return false;
932 + }
933
938 - const lock = observeLiveActivityPushTokens(input.activity);
939 - return yield* lock.withPermit(
940 - Effect.gen(function* () {
941 - const activityPushToken = yield* Effect.tryPromise({
942 - try: () => input.activity.getPushToken(),
943 - catch: (cause) =>
944 - new AgentAwarenessOperationError({
945 - operation: "read-live-activity-push-token",
946 - cause,
947 - }),
948 - });
949 - if (!activityPushToken) {
950 - logRegistrationDebug(
951 - "live activity push token not available yet; waiting for token event",
952 - { connectionCount: environmentConnections.size },
953 - );
954 - return false;
955 - }
934 + const lock = observeLiveActivityPushTokens(input.activity);
935 + return yield* lock.withPermit(
936 + Effect.gen(function* () {
937 + const activityPushToken = yield* Effect.tryPromise({
938 + try: () => input.activity.getPushToken(),
939 + catch: (cause) =>
940 + new AgentAwarenessOperationError({
941 + operation: "read-live-activity-push-token",
942 + cause,
943 + }),
944 + });
945 + if (!activityPushToken) {
946 + logRegistrationDebug(
947 + "live activity push token not available yet; waiting for token event",
948 + { connectionCount: environmentConnections.size },
949 + );
950 + return false;
951 + }
952
957 - return yield* registerLiveActivityPushTokenValue({ activityPushToken });
958 - }),
959 - );
960 - });
961 -}
953 + return yield* registerLiveActivityPushTokenValue({ activityPushToken });
954 + }),
955 + );
956 +});
957
958 // iOS can replace an activity's push token while it runs, not only deliver a
959 // late first one. The relay keeps pushing to the old token until APNs rejects
@@ -984,38 +979,35 @@ function observeLiveActivityPushTokens(
979 return lock;
980 }
981
987 -function registerLiveActivityPushTokenValue(input: {
982 +const registerLiveActivityPushTokenValue = Effect.fn(
983 + "remoteRegistration.registerLiveActivityPushTokenValue",
984 +)(function* (input: {
985 readonly activityPushToken: string;
989 -}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
990 - return Effect.gen(function* () {
991 - const acceptedAt = registeredActivityPushTokens.get(input.activityPushToken);
992 - if (
993 - acceptedAt !== undefined &&
994 - Date.now() - acceptedAt < ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS
995 - ) {
996 - return true;
997 - }
998 - const deviceId = yield* Effect.tryPromise({
999 - try: () => loadOrCreateAgentAwarenessDeviceId(),
1000 - catch: (cause) =>
1001 - new AgentAwarenessOperationError({
1002 - operation: "load-live-activity-registration-identifier",
1003 - cause,
1004 - }),
1005 - });
1006 - const registered = yield* registerLiveActivityWithRelay({
1007 - deviceId,
1008 - activityPushToken: input.activityPushToken,
1009 - });
1010 - if (registered) {
1011 - registeredActivityPushTokens.set(input.activityPushToken, Date.now());
1012 - logRegistrationDebug("live activity push token registered", {
1013 - tokenSuffix: input.activityPushToken.slice(-8),
1014 - });
1015 - }
1016 - return registered;
986 +}): Effect.fn.Return<boolean, unknown, ManagedRelay.ManagedRelayClient> {
987 + const acceptedAt = registeredActivityPushTokens.get(input.activityPushToken);
988 + if (acceptedAt !== undefined && Date.now() - acceptedAt < ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS) {
989 + return true;
990 + }
991 + const deviceId = yield* Effect.tryPromise({
992 + try: () => loadOrCreateAgentAwarenessDeviceId(),
993 + catch: (cause) =>
994 + new AgentAwarenessOperationError({
995 + operation: "load-live-activity-registration-identifier",
996 + cause,
997 + }),
998 });
1018 -}
999 + const registered = yield* registerLiveActivityWithRelay({
1000 + deviceId,
1001 + activityPushToken: input.activityPushToken,
1002 + });
1003 + if (registered) {
1004 + registeredActivityPushTokens.set(input.activityPushToken, Date.now());
1005 + logRegistrationDebug("live activity push token registered", {
1006 + tokenSuffix: input.activityPushToken.slice(-8),
1007 + });
1008 + }
1009 + return registered;
1010 +});
1011
1012 function scheduleActiveLiveActivityRegistrationRetry(): void {
1013 if (activeLiveActivityRegistrationRetry || !relayTokenProvider) {
@@ -1031,117 +1023,113 @@ function scheduleActiveLiveActivityRegistrationRetry(): void {
1023 }, REMOTE_ACTIVITY_REGISTRATION_RETRY_MS);
1024 }
1025
1034 -export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
1035 - void,
1036 - never,
1037 - ManagedRelay.ManagedRelayClient
1038 -> {
1039 - return Effect.gen(function* () {
1040 - if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
1041 - return;
1026 +export const refreshActiveLiveActivityRemoteRegistration = Effect.fn(
1027 + "remoteRegistration.refreshActiveLiveActivityRemoteRegistration",
1028 +)(function* (): Effect.fn.Return<void, never, ManagedRelay.ManagedRelayClient> {
1029 + if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
1030 + return;
1031 + }
1032 +
1033 + let activities = yield* Effect.try({
1034 + try: () => getAgentLiveActivities(),
1035 + catch: (cause) =>
1036 + new AgentAwarenessOperationError({
1037 + operation: "list-active-live-activities",
1038 + cause,
1039 + }),
1040 + }).pipe(
1041 + Effect.catch((error) =>
1042 + Effect.sync(() => {
1043 + logRegistrationError("active live activity lookup failed", error);
1044 + return [] as ReadonlyArray<LiveActivity<AgentActivityProps>>;
1045 + }),
1046 + ),
1047 + );
1048 +
1049 + // The relay tracks exactly one card per device; if concurrent arming ever
1050 + // produced extras, end them so only one keeps receiving updates.
1051 + if (activities.length > 1) {
1052 + for (const extra of activities.slice(1)) {
1053 + extra.end("immediate").catch((error: unknown) => {
1054 + logRegistrationError("duplicate live activity cleanup failed", error);
1055 + });
1056 }
1057 + activities = activities.slice(0, 1);
1058 + }
1059
1044 - let activities = yield* Effect.try({
1045 - try: () => getAgentLiveActivities(),
1060 + // Activities are only ever created here, in the foreground, where the
1061 + // update token can be observed and registered immediately — the relay never
1062 + // remote-starts one (background push-to-start wakes proved too unreliable
1063 + // to hand the token over).
1064 + if (activities.length === 0) {
1065 + const preferences = yield* Effect.tryPromise({
1066 + try: () => loadPreferences(),
1067 catch: (cause) =>
1068 new AgentAwarenessOperationError({
1048 - operation: "list-active-live-activities",
1069 + operation: "load-live-activity-prime-preferences",
1070 cause,
1071 }),
1051 - }).pipe(
1052 - Effect.catch((error) =>
1053 - Effect.sync(() => {
1054 - logRegistrationError("active live activity lookup failed", error);
1055 - return [] as ReadonlyArray<LiveActivity<AgentActivityProps>>;
1056 - }),
1057 - ),
1058 - );
1059 -
1060 - // The relay tracks exactly one card per device; if concurrent arming ever
1061 - // produced extras, end them so only one keeps receiving updates.
1062 - if (activities.length > 1) {
1063 - for (const extra of activities.slice(1)) {
1064 - extra.end("immediate").catch((error: unknown) => {
1065 - logRegistrationError("duplicate live activity cleanup failed", error);
1066 - });
1067 - }
1068 - activities = activities.slice(0, 1);
1069 - }
1070 -
1071 - // Activities are only ever created here, in the foreground, where the
1072 - // update token can be observed and registered immediately — the relay never
1073 - // remote-starts one (background push-to-start wakes proved too unreliable
1074 - // to hand the token over).
1075 - if (activities.length === 0) {
1076 - const preferences = yield* Effect.tryPromise({
1077 - try: () => loadPreferences(),
1078 - catch: (cause) =>
1079 - new AgentAwarenessOperationError({
1080 - operation: "load-live-activity-prime-preferences",
1081 - cause,
1082 - }),
1083 - }).pipe(Effect.orElseSucceed(() => null));
1084 - if (preferences?.liveActivitiesEnabled !== false) {
1085 - const snapshot = yield* readAgentActivitySnapshot();
1086 - // The snapshot request yields; an arm-on-send may have created the
1087 - // card in the meantime. Re-check so two cards are never started.
1088 - const armedMeanwhile = yield* Effect.try({
1089 - try: () => getAgentLiveActivities(),
1090 - catch: () => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>,
1091 - }).pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>));
1092 - if (armedMeanwhile.length > 0) {
1093 - activities = [...armedMeanwhile];
1094 - } else if (snapshot?.aggregate && snapshot.aggregate.activeCount > 0) {
1095 - const aggregate = snapshot.aggregate;
1096 - const primed = yield* Effect.try({
1097 - try: () =>
1098 - startAgentLiveActivity(
1099 - {
1100 - title: aggregate.title,
1101 - subtitle: aggregate.subtitle,
1102 - activeCount: aggregate.activeCount,
1103 - updatedAt: aggregate.updatedAt,
1104 - activities: aggregate.activities,
1105 - },
1106 - liveActivityStaleDate(),
1107 - ),
1108 - catch: (cause) =>
1109 - new AgentAwarenessOperationError({
1110 - operation: "prime-live-activity",
1111 - cause,
1112 - }),
1113 - }).pipe(
1114 - Effect.catch((error) =>
1115 - Effect.sync(() => {
1116 - logRegistrationError("live activity priming failed", error);
1117 - return null;
1118 - }),
1072 + }).pipe(Effect.orElseSucceed(() => null));
1073 + if (preferences?.liveActivitiesEnabled !== false) {
1074 + const snapshot = yield* readAgentActivitySnapshot();
1075 + // The snapshot request yields; an arm-on-send may have created the
1076 + // card in the meantime. Re-check so two cards are never started.
1077 + const armedMeanwhile = yield* Effect.try({
1078 + try: () => getAgentLiveActivities(),
1079 + catch: () => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>,
1080 + }).pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>));
1081 + if (armedMeanwhile.length > 0) {
1082 + activities = [...armedMeanwhile];
1083 + } else if (snapshot?.aggregate && snapshot.aggregate.activeCount > 0) {
1084 + const aggregate = snapshot.aggregate;
1085 + const primed = yield* Effect.try({
1086 + try: () =>
1087 + startAgentLiveActivity(
1088 + {
1089 + title: aggregate.title,
1090 + subtitle: aggregate.subtitle,
1091 + activeCount: aggregate.activeCount,
1092 + updatedAt: aggregate.updatedAt,
1093 + activities: aggregate.activities,
1094 + },
1095 + liveActivityStaleDate(),
1096 ),
1120 - );
1121 - if (primed) {
1122 - logRegistrationDebug("live activity card primed", {
1123 - activeCount: aggregate.activeCount,
1124 - });
1125 - activities = [primed];
1126 - }
1097 + catch: (cause) =>
1098 + new AgentAwarenessOperationError({
1099 + operation: "prime-live-activity",
1100 + cause,
1101 + }),
1102 + }).pipe(
1103 + Effect.catch((error) =>
1104 + Effect.sync(() => {
1105 + logRegistrationError("live activity priming failed", error);
1106 + return null;
1107 + }),
1108 + ),
1109 + );
1110 + if (primed) {
1111 + logRegistrationDebug("live activity card primed", {
1112 + activeCount: aggregate.activeCount,
1113 + });
1114 + activities = [primed];
1115 }
1116 }
1117 }
1118 + }
1119
1131 - const registrationResults = yield* Effect.forEach(activities, (activity) =>
1132 - registerLiveActivityPushToken({ activity }).pipe(
1133 - Effect.map((registered) => !registered),
1134 - Effect.catch((error) =>
1135 - Effect.sync(() => {
1136 - logRegistrationError("active live activity token registration failed", error);
1137 - return true;
1138 - }),
1139 - ),
1120 + const registrationResults = yield* Effect.forEach(activities, (activity) =>
1121 + registerLiveActivityPushToken({ activity }).pipe(
1122 + Effect.map((registered) => !registered),
1123 + Effect.catch((error) =>
1124 + Effect.sync(() => {
1125 + logRegistrationError("active live activity token registration failed", error);
1126 + return true;
1127 + }),
1128 ),
1141 - );
1129 + ),
1130 + );
1131
1143 - if (registrationResults.some(Boolean)) {
1144 - scheduleActiveLiveActivityRegistrationRetry();
1145 - }
1146 - });
1147 -}
1132 + if (registrationResults.some(Boolean)) {
1133 + scheduleActiveLiveActivityRegistrationRetry();
1134 + }
1135 +});
apps/mobile/src/features/cloud/dpop.ts
+52 -64
@@ -165,12 +165,8 @@ function privateJwkFromPrivateKey(
165 return { ...publicJwk, d: Base64Url.encode(privateKey) };
166 }
167
168 -export function generateDpopProofKeyPair(): Effect.Effect<
169 - DpopProofKeyPair,
170 - CloudDpopError,
171 - Crypto.Crypto
172 -> {
173 - return Effect.gen(function* () {
168 +export const generateDpopProofKeyPair = Effect.fn("dpop.generateDpopProofKeyPair")(
169 + function* (): Effect.fn.Return<DpopProofKeyPair, CloudDpopError, Crypto.Crypto> {
170 let privateKey: Uint8Array;
171 do {
172 privateKey = yield* secureRandomBytes(
@@ -188,15 +184,11 @@ export function generateDpopProofKeyPair(): Effect.Effect<
184 publicJwk,
185 thumbprint,
186 };
191 - });
192 -}
187 + },
188 +);
189
194 -export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
195 - DpopProofKeyPair,
196 - CloudDpopError,
197 - Crypto.Crypto
198 -> {
199 - return Effect.gen(function* () {
190 +export const loadOrCreateDpopProofKeyPair = Effect.fn("dpop.loadOrCreateDpopProofKeyPair")(
191 + function* (): Effect.fn.Return<DpopProofKeyPair, CloudDpopError, Crypto.Crypto> {
192 const stored = yield* Effect.tryPromise({
193 try: () => SecureStore.getItemAsync(DPOP_PROOF_KEY_STORAGE_KEY),
194 catch: cloudDpopError("Could not read the DPoP proof key."),
@@ -233,8 +225,8 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
225 catch: cloudDpopError("Could not store the DPoP proof key."),
226 });
227 return generated;
236 - });
237 -}
228 + },
229 +);
230
231 function normalizeHtu(url: string): Effect.Effect<string, CloudDpopError> {
232 const normalized = normalizeDpopHtu(url);
@@ -243,60 +235,56 @@ function normalizeHtu(url: string): Effect.Effect<string, CloudDpopError> {
235 : Effect.fail(new CloudDpopError({ message: "DPoP URL is invalid." }));
236 }
237
246 -export function createDpopProof(input: {
238 +export const createDpopProof = Effect.fn("dpop.createDpopProof")(function* (input: {
239 readonly method: string;
240 readonly url: string;
241 readonly accessToken?: string;
242 readonly proofKey?: DpopProofKeyPair;
251 -}): Effect.Effect<
243 +}): Effect.fn.Return<
244 { readonly proof: string; readonly thumbprint: string },
245 CloudDpopError,
246 Crypto.Crypto
247 > {
256 - return Effect.gen(function* () {
257 - const keyPair = input.proofKey ?? (yield* generateDpopProofKeyPair());
258 - const privateKey = yield* Effect.try({
259 - try: () => base64UrlToBytes(keyPair.privateJwk.d),
260 - catch: cloudDpopError("Could not import DPoP private key."),
261 - });
262 - const nowMs = yield* Clock.currentTimeMillis;
263 - const jti = yield* Crypto.Crypto.pipe(
264 - Effect.flatMap((crypto) => crypto.randomUUIDv4()),
265 - Effect.mapError(cloudDpopError("Could not generate DPoP proof identifier.")),
266 - );
267 - const htu = yield* normalizeHtu(input.url);
268 - const header = yield* encodeDpopJwtHeaderJson({
269 - typ: "dpop+jwt",
270 - alg: "ES256",
271 - jwk: keyPair.publicJwk,
272 - }).pipe(
273 - Effect.map(Base64Url.encode),
274 - Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")),
275 - );
276 - const ath = input.accessToken
277 - ? yield* computeDpopAccessTokenHashEffect(input.accessToken)
278 - : null;
279 - const payload = yield* encodeDpopJwtPayloadJson({
280 - htm: input.method.toUpperCase(),
281 - htu,
282 - jti,
283 - iat: Math.floor(nowMs / 1_000),
284 - ...(ath ? { ath } : {}),
285 - }).pipe(
286 - Effect.map(Base64Url.encode),
287 - Effect.mapError(cloudDpopError("Could not encode DPoP proof payload.")),
288 - );
289 - const signatureInputHash = yield* sha256Digest(
290 - new TextEncoder().encode(`${header}.${payload}`),
291 - "Could not hash DPoP signing input.",
292 - );
293 - const signature = yield* Effect.try({
294 - try: () => p256.sign(signatureInputHash, privateKey, { prehash: false }).toCompactRawBytes(),
295 - catch: cloudDpopError("Could not sign DPoP proof."),
296 - });
297 - return {
298 - proof: `${header}.${payload}.${Base64Url.encode(signature)}`,
299 - thumbprint: keyPair.thumbprint,
300 - };
248 + const keyPair = input.proofKey ?? (yield* generateDpopProofKeyPair());
249 + const privateKey = yield* Effect.try({
250 + try: () => base64UrlToBytes(keyPair.privateJwk.d),
251 + catch: cloudDpopError("Could not import DPoP private key."),
252 });
302 -}
253 + const nowMs = yield* Clock.currentTimeMillis;
254 + const jti = yield* Crypto.Crypto.pipe(
255 + Effect.flatMap((crypto) => crypto.randomUUIDv4()),
256 + Effect.mapError(cloudDpopError("Could not generate DPoP proof identifier.")),
257 + );
258 + const htu = yield* normalizeHtu(input.url);
259 + const header = yield* encodeDpopJwtHeaderJson({
260 + typ: "dpop+jwt",
261 + alg: "ES256",
262 + jwk: keyPair.publicJwk,
263 + }).pipe(
264 + Effect.map(Base64Url.encode),
265 + Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")),
266 + );
267 + const ath = input.accessToken ? yield* computeDpopAccessTokenHashEffect(input.accessToken) : null;
268 + const payload = yield* encodeDpopJwtPayloadJson({
269 + htm: input.method.toUpperCase(),
270 + htu,
271 + jti,
272 + iat: Math.floor(nowMs / 1_000),
273 + ...(ath ? { ath } : {}),
274 + }).pipe(
275 + Effect.map(Base64Url.encode),
276 + Effect.mapError(cloudDpopError("Could not encode DPoP proof payload.")),
277 + );
278 + const signatureInputHash = yield* sha256Digest(
279 + new TextEncoder().encode(`${header}.${payload}`),
280 + "Could not hash DPoP signing input.",
281 + );
282 + const signature = yield* Effect.try({
283 + try: () => p256.sign(signatureInputHash, privateKey, { prehash: false }).toCompactRawBytes(),
284 + catch: cloudDpopError("Could not sign DPoP proof."),
285 + });
286 + return {
287 + proof: `${header}.${payload}.${Base64Url.encode(signature)}`,
288 + thumbprint: keyPair.thumbprint,
289 + };
290 +});
apps/mobile/src/features/cloud/linkEnvironment.ts
+80 -80
@@ -153,87 +153,87 @@ type LinkEnvironmentToCloudRequirements =
153 | ManagedRelay.ManagedRelayClient
154 | MobileStorage.MobileStorage;
155
156 -export function linkEnvironmentToCloudWithPreference(
156 +export const linkEnvironmentToCloudWithPreference = Effect.fn(
157 + "linkEnvironment.linkEnvironmentToCloudWithPreference",
158 +)(function* (
159 input: LinkEnvironmentToCloudInput & { readonly liveActivitiesEnabled: boolean },
158 -): Effect.Effect<void, CloudEnvironmentLinkError, LinkEnvironmentToCloudRequirements> {
159 - return Effect.gen(function* () {
160 - if (!input.connection.bearerToken) {
161 - return yield* new CloudEnvironmentLinkError({
162 - message: "Only a locally paired bearer connection can be linked to the cloud.",
163 - });
164 - }
165 - const localBearerToken = input.connection.bearerToken;
166 - const relayUrl = yield* requireRelayUrl();
167 - const relayClient = yield* ManagedRelay.ManagedRelayClient;
168 - const storage = yield* MobileStorage.MobileStorage;
169 - const deviceId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(
170 - Effect.mapError(cloudEnvironmentLinkError("Could not load the mobile device id.")),
171 - );
172 - const liveActivitiesEnabled = input.liveActivitiesEnabled;
173 - const challenge = yield* relayClient
174 - .createEnvironmentLinkChallenge({
175 - clerkToken: input.clerkToken,
176 - payload: {
177 - notificationsEnabled: true,
178 - liveActivitiesEnabled,
179 - managedTunnelsEnabled: true,
180 - },
181 - })
182 - .pipe(
183 - Effect.mapError(
184 - decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`),
185 - ),
186 - );
187 - const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);
188 - const proof = yield* environmentClient.connect
189 - .linkProof({
190 - headers: { authorization: `Bearer ${localBearerToken}` },
191 - payload: {
192 - challenge: challenge.challenge,
193 - relayIssuer: relayUrl,
194 - endpoint: {
195 - httpBaseUrl: input.connection.httpBaseUrl,
196 - wsBaseUrl: input.connection.wsBaseUrl,
197 - providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,
198 - },
199 - origin: endpointOrigin(input.connection.httpBaseUrl),
200 - },
201 - })
202 - .pipe(Effect.mapError(cloudEnvironmentLinkError("Could not obtain environment link proof.")));
203 - const link = yield* relayClient
204 - .linkEnvironment({
205 - clerkToken: input.clerkToken,
206 - payload: {
207 - deviceId,
208 - proof,
209 - notificationsEnabled: true,
210 - liveActivitiesEnabled,
211 - managedTunnelsEnabled: true,
212 - },
213 - })
214 - .pipe(
215 - Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)),
216 - );
217 - yield* ensureLinkedEnvironmentMatches({
218 - expectedEnvironmentId: input.connection.environmentId,
219 - expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND,
220 - link,
160 +): Effect.fn.Return<void, CloudEnvironmentLinkError, LinkEnvironmentToCloudRequirements> {
161 + if (!input.connection.bearerToken) {
162 + return yield* new CloudEnvironmentLinkError({
163 + message: "Only a locally paired bearer connection can be linked to the cloud.",
164 });
222 -
223 - yield* environmentClient.connect
224 - .relayConfig({
225 - headers: { authorization: `Bearer ${localBearerToken}` },
226 - payload: {
227 - relayUrl,
228 - relayIssuer: link.relayIssuer,
229 - cloudUserId: link.cloudUserId,
230 - environmentCredential: link.environmentCredential,
231 - cloudMintPublicKey: link.cloudMintPublicKey,
232 - endpointRuntime: link.endpointRuntime,
165 + }
166 + const localBearerToken = input.connection.bearerToken;
167 + const relayUrl = yield* requireRelayUrl();
168 + const relayClient = yield* ManagedRelay.ManagedRelayClient;
169 + const storage = yield* MobileStorage.MobileStorage;
170 + const deviceId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(
171 + Effect.mapError(cloudEnvironmentLinkError("Could not load the mobile device id.")),
172 + );
173 + const liveActivitiesEnabled = input.liveActivitiesEnabled;
174 + const challenge = yield* relayClient
175 + .createEnvironmentLinkChallenge({
176 + clerkToken: input.clerkToken,
177 + payload: {
178 + notificationsEnabled: true,
179 + liveActivitiesEnabled,
180 + managedTunnelsEnabled: true,
181 + },
182 + })
183 + .pipe(
184 + Effect.mapError(
185 + decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`),
186 + ),
187 + );
188 + const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);
189 + const proof = yield* environmentClient.connect
190 + .linkProof({
191 + headers: { authorization: `Bearer ${localBearerToken}` },
192 + payload: {
193 + challenge: challenge.challenge,
194 + relayIssuer: relayUrl,
195 + endpoint: {
196 + httpBaseUrl: input.connection.httpBaseUrl,
197 + wsBaseUrl: input.connection.wsBaseUrl,
198 + providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,
199 },
234 - })
235 - .pipe(
236 - Effect.mapError(cloudEnvironmentLinkError("Could not configure environment relay access.")),
237 - );
200 + origin: endpointOrigin(input.connection.httpBaseUrl),
201 + },
202 + })
203 + .pipe(Effect.mapError(cloudEnvironmentLinkError("Could not obtain environment link proof.")));
204 + const link = yield* relayClient
205 + .linkEnvironment({
206 + clerkToken: input.clerkToken,
207 + payload: {
208 + deviceId,
209 + proof,
210 + notificationsEnabled: true,
211 + liveActivitiesEnabled,
212 + managedTunnelsEnabled: true,
213 + },
214 + })
215 + .pipe(
216 + Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)),
217 + );
218 + yield* ensureLinkedEnvironmentMatches({
219 + expectedEnvironmentId: input.connection.environmentId,
220 + expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND,
221 + link,
222 });
239 -}
223 +
224 + yield* environmentClient.connect
225 + .relayConfig({
226 + headers: { authorization: `Bearer ${localBearerToken}` },
227 + payload: {
228 + relayUrl,
229 + relayIssuer: link.relayIssuer,
230 + cloudUserId: link.cloudUserId,
231 + environmentCredential: link.environmentCredential,
232 + cloudMintPublicKey: link.cloudMintPublicKey,
233 + endpointRuntime: link.endpointRuntime,
234 + },
235 + })
236 + .pipe(
237 + Effect.mapError(cloudEnvironmentLinkError("Could not configure environment relay access.")),
238 + );
239 +});
apps/web/src/cloud/dpop.ts
+29 -31
@@ -142,44 +142,42 @@ export const generateBrowserDpopKey = Effect.gen(function* () {
142 };
143 });
144
145 -export function createBrowserDpopProof(input: {
145 +export const createBrowserDpopProof = Effect.fn("dpop.createBrowserDpopProof")(function* (input: {
146 readonly method: string;
147 readonly url: string;
148 readonly accessToken?: string;
149 readonly proofKey: BrowserDpopKey;
150 -}): Effect.Effect<
150 +}): Effect.fn.Return<
151 { readonly proof: string; readonly thumbprint: string },
152 BrowserDpopError,
153 Crypto.Crypto
154 > {
155 - return Effect.gen(function* () {
156 - const normalizedUrl = yield* Effect.try({
157 - try: () => new URL(input.url),
158 - catch: (cause) => dpopError("Could not normalize DPoP proof URL.", cause),
159 - });
160 - normalizedUrl.search = "";
161 - normalizedUrl.hash = "";
162 - const jti = yield* Crypto.Crypto.pipe(
163 - Effect.flatMap((crypto) => crypto.randomUUIDv4()),
164 - Effect.mapError((cause) => dpopError("Could not generate DPoP proof identifier.", cause)),
165 - );
166 - const proof = yield* Effect.tryPromise({
167 - try: () =>
168 - new SignJWT({
169 - htm: input.method.toUpperCase(),
170 - htu: normalizedUrl.toString(),
171 - jti,
172 - ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}),
155 + const normalizedUrl = yield* Effect.try({
156 + try: () => new URL(input.url),
157 + catch: (cause) => dpopError("Could not normalize DPoP proof URL.", cause),
158 + });
159 + normalizedUrl.search = "";
160 + normalizedUrl.hash = "";
161 + const jti = yield* Crypto.Crypto.pipe(
162 + Effect.flatMap((crypto) => crypto.randomUUIDv4()),
163 + Effect.mapError((cause) => dpopError("Could not generate DPoP proof identifier.", cause)),
164 + );
165 + const proof = yield* Effect.tryPromise({
166 + try: () =>
167 + new SignJWT({
168 + htm: input.method.toUpperCase(),
169 + htu: normalizedUrl.toString(),
170 + jti,
171 + ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}),
172 + })
173 + .setProtectedHeader({
174 + typ: "dpop+jwt",
175 + alg: "ES256",
176 + jwk: input.proofKey.publicJwk,
177 })
174 - .setProtectedHeader({
175 - typ: "dpop+jwt",
176 - alg: "ES256",
177 - jwk: input.proofKey.publicJwk,
178 - })
179 - .setIssuedAt()
180 - .sign(input.proofKey.privateKey),
181 - catch: (cause) => dpopError("Could not sign DPoP proof.", cause),
182 - });
183 - return { proof, thumbprint: input.proofKey.thumbprint };
178 + .setIssuedAt()
179 + .sign(input.proofKey.privateKey),
180 + catch: (cause) => dpopError("Could not sign DPoP proof.", cause),
181 });
185 -}
182 + return { proof, thumbprint: input.proofKey.thumbprint };
183 +});
apps/web/src/cloud/linkEnvironment.ts
+141 -135
@@ -48,10 +48,10 @@ const relayClientRpcError = (message: string) => (cause: unknown) =>
48 cause,
49 });
50
51 -function ensureRelayClientAvailable(
52 - environmentId: EnvironmentId,
53 -): Effect.Effect<void, CloudEnvironmentLinkError, EnvironmentRegistry.EnvironmentRegistry> {
54 - return Effect.gen(function* () {
51 +const ensureRelayClientAvailable = Effect.fn("linkEnvironment.ensureRelayClientAvailable")(
52 + function* (
53 + environmentId: EnvironmentId,
54 + ): Effect.fn.Return<void, CloudEnvironmentLinkError, EnvironmentRegistry.EnvironmentRegistry> {
55 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
56 const status = yield* registry
57 .run(environmentId, request(WS_METHODS.cloudGetRelayClientStatus, {}))
@@ -99,8 +99,8 @@ function ensureRelayClientAvailable(
99 : "The relay client is still unavailable after installation.",
100 });
101 }
102 - });
103 -}
102 + },
103 +);
104
105 const isEnvironmentCloudApiError = Schema.is(
106 Schema.Union([
@@ -184,163 +184,169 @@ export interface CloudLinkTarget {
184
185 export type CloudLinkState = EnvironmentCloudLinkStateResult;
186
187 -export function readPrimaryCloudLinkState(input: {
187 +export const readPrimaryCloudLinkState: (input: {
188 readonly target: CloudLinkTarget;
189 -}): Effect.Effect<CloudLinkState | null, CloudEnvironmentLinkError, HttpClient.HttpClient> {
190 - return Effect.gen(function* () {
189 +}) => Effect.Effect<CloudLinkState | null, CloudEnvironmentLinkError, HttpClient.HttpClient> =
190 + Effect.fn("linkEnvironment.readPrimaryCloudLinkState")(function* (input: {
191 + readonly target: CloudLinkTarget;
192 + }) {
193 const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
194 return yield* client.connect
195 .linkState({ headers: {} })
196 .pipe(Effect.mapError(environmentApiError("Could not read environment cloud link state.")));
195 - }).pipe(Effect.provide(PrimaryEnvironmentHttpLayer.layer));
196 -}
197 + }, Effect.provide(PrimaryEnvironmentHttpLayer.layer));
198
198 -export function updatePrimaryCloudPreferences(input: {
199 +export const updatePrimaryCloudPreferences: (input: {
200 readonly target: CloudLinkTarget;
201 readonly publishAgentActivity: boolean;
202 readonly holdWebhooksWhileOffline?: boolean;
202 -}): Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, HttpClient.HttpClient> {
203 - return Effect.gen(function* () {
204 - const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
205 - const { target: _target, ...payload } = input;
206 - return yield* client.connect
207 - .preferences({
208 - headers: {},
209 - payload,
210 - })
211 - .pipe(
212 - Effect.mapError(environmentApiError("Could not update environment cloud preferences.")),
213 - );
214 - }).pipe(Effect.provide(PrimaryEnvironmentHttpLayer.layer));
215 -}
203 +}) => Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, HttpClient.HttpClient> = Effect.fn(
204 + "linkEnvironment.updatePrimaryCloudPreferences",
205 +)(function* (input: {
206 + readonly target: CloudLinkTarget;
207 + readonly publishAgentActivity: boolean;
208 + readonly holdWebhooksWhileOffline?: boolean;
209 +}) {
210 + const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
211 + const { target: _target, ...payload } = input;
212 + return yield* client.connect
213 + .preferences({
214 + headers: {},
215 + payload,
216 + })
217 + .pipe(Effect.mapError(environmentApiError("Could not update environment cloud preferences.")));
218 +}, Effect.provide(PrimaryEnvironmentHttpLayer.layer));
219
217 -export function unlinkPrimaryEnvironmentFromCloud(input: {
220 +export const unlinkPrimaryEnvironmentFromCloud: (input: {
221 readonly target: CloudLinkTarget;
222 readonly clerkToken: string | null;
220 -}): Effect.Effect<
223 +}) => Effect.Effect<
224 void,
225 CloudEnvironmentLinkError,
226 HttpClient.HttpClient | ManagedRelay.ManagedRelayClient
224 -> {
225 - return Effect.gen(function* () {
226 - const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
227 - yield* client.connect
228 - .unlink({ headers: {} })
229 - .pipe(Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")));
227 +> = Effect.fn("linkEnvironment.unlinkPrimaryEnvironmentFromCloud")(function* (input: {
228 + readonly target: CloudLinkTarget;
229 + readonly clerkToken: string | null;
230 +}) {
231 + const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
232 + yield* client.connect
233 + .unlink({ headers: {} })
234 + .pipe(Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")));
235
231 - const configuredRelayUrl = relayUrl();
232 - if (configuredRelayUrl && input.clerkToken) {
233 - const relayClient = yield* ManagedRelay.ManagedRelayClient;
234 - yield* relayClient
235 - .unlinkEnvironment({
236 - clerkToken: input.clerkToken,
237 - environmentId: EnvironmentId.make(input.target.environmentId),
238 - })
239 - .pipe(
240 - Effect.catch((cause) =>
241 - Effect.logWarning("Could not revoke cloud environment link after local unlink.", {
242 - cause,
243 - }),
244 - ),
245 - );
246 - }
247 - }).pipe(Effect.provide(PrimaryEnvironmentHttpLayer.layer));
248 -}
236 + const configuredRelayUrl = relayUrl();
237 + if (configuredRelayUrl && input.clerkToken) {
238 + const relayClient = yield* ManagedRelay.ManagedRelayClient;
239 + yield* relayClient
240 + .unlinkEnvironment({
241 + clerkToken: input.clerkToken,
242 + environmentId: EnvironmentId.make(input.target.environmentId),
243 + })
244 + .pipe(
245 + Effect.catch((cause) =>
246 + Effect.logWarning("Could not revoke cloud environment link after local unlink.", {
247 + cause,
248 + }),
249 + ),
250 + );
251 + }
252 +}, Effect.provide(PrimaryEnvironmentHttpLayer.layer));
253
254 export type CloudLinkMode = "managed" | "publish_only";
255
256 const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind;
257
254 -export function linkPrimaryEnvironmentToCloud(input: {
258 +export const linkPrimaryEnvironmentToCloud: (input: {
259 readonly target: CloudLinkTarget;
260 readonly clerkToken: string;
261 readonly mode?: CloudLinkMode;
258 -}): Effect.Effect<
262 +}) => Effect.Effect<
263 void,
264 CloudEnvironmentLinkError,
265 EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient | ManagedRelay.ManagedRelayClient
262 -> {
263 - return Effect.gen(function* () {
264 - const configuredRelayUrl = relayUrl();
265 - if (!configuredRelayUrl) {
266 - return yield* new CloudEnvironmentLinkError({
267 - message: "T3CODE_RELAY_URL is not configured.",
268 - });
269 - }
270 - const managedTunnelsEnabled = (input.mode ?? "managed") === "managed";
271 - const providerKind = managedTunnelsEnabled
272 - ? MANAGED_ENDPOINT_PROVIDER_KIND
273 - : PUBLISH_ONLY_PROVIDER_KIND;
274 - const relayClient = yield* ManagedRelay.ManagedRelayClient;
275 - const environmentClient = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
276 - if (managedTunnelsEnabled) {
277 - yield* ensureRelayClientAvailable(EnvironmentId.make(input.target.environmentId));
278 - }
266 +> = Effect.fn("linkEnvironment.linkPrimaryEnvironmentToCloud")(function* (input: {
267 + readonly target: CloudLinkTarget;
268 + readonly clerkToken: string;
269 + readonly mode?: CloudLinkMode;
270 +}) {
271 + const configuredRelayUrl = relayUrl();
272 + if (!configuredRelayUrl) {
273 + return yield* new CloudEnvironmentLinkError({
274 + message: "T3CODE_RELAY_URL is not configured.",
275 + });
276 + }
277 + const managedTunnelsEnabled = (input.mode ?? "managed") === "managed";
278 + const providerKind = managedTunnelsEnabled
279 + ? MANAGED_ENDPOINT_PROVIDER_KIND
280 + : PUBLISH_ONLY_PROVIDER_KIND;
281 + const relayClient = yield* ManagedRelay.ManagedRelayClient;
282 + const environmentClient = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
283 + if (managedTunnelsEnabled) {
284 + yield* ensureRelayClientAvailable(EnvironmentId.make(input.target.environmentId));
285 + }
286
280 - const challenge = yield* relayClient
281 - .createEnvironmentLinkChallenge({
282 - clerkToken: input.clerkToken,
283 - payload: {
284 - notificationsEnabled: true,
285 - liveActivitiesEnabled: true,
286 - managedTunnelsEnabled,
287 - },
288 - })
289 - .pipe(
290 - Effect.mapError(
291 - decodedRelayClientError(
292 - `${configuredRelayUrl}/v1/client/environment-link-challenges failed`,
293 - ),
287 + const challenge = yield* relayClient
288 + .createEnvironmentLinkChallenge({
289 + clerkToken: input.clerkToken,
290 + payload: {
291 + notificationsEnabled: true,
292 + liveActivitiesEnabled: true,
293 + managedTunnelsEnabled,
294 + },
295 + })
296 + .pipe(
297 + Effect.mapError(
298 + decodedRelayClientError(
299 + `${configuredRelayUrl}/v1/client/environment-link-challenges failed`,
300 ),
295 - );
296 - const proof = yield* environmentClient.connect
297 - .linkProof({
298 - headers: {},
299 - payload: {
300 - challenge: challenge.challenge,
301 - relayIssuer: configuredRelayUrl,
302 - endpoint: {
303 - httpBaseUrl: input.target.httpBaseUrl,
304 - wsBaseUrl: input.target.wsBaseUrl,
305 - providerKind,
306 - },
307 - origin: endpointOrigin(input.target.httpBaseUrl),
308 - },
309 - })
310 - .pipe(Effect.mapError(environmentApiError("Could not obtain environment link proof.")));
311 - const link = yield* relayClient
312 - .linkEnvironment({
313 - clerkToken: input.clerkToken,
314 - payload: {
315 - proof,
316 - notificationsEnabled: true,
317 - liveActivitiesEnabled: true,
318 - managedTunnelsEnabled,
301 + ),
302 + );
303 + const proof = yield* environmentClient.connect
304 + .linkProof({
305 + headers: {},
306 + payload: {
307 + challenge: challenge.challenge,
308 + relayIssuer: configuredRelayUrl,
309 + endpoint: {
310 + httpBaseUrl: input.target.httpBaseUrl,
311 + wsBaseUrl: input.target.wsBaseUrl,
312 + providerKind,
313 },
320 - })
321 - .pipe(
322 - Effect.mapError(
323 - decodedRelayClientError(`${configuredRelayUrl}/v1/client/environment-links failed`),
324 - ),
325 - );
326 - yield* ensureLinkedEnvironmentMatches({
327 - expectedEnvironmentId: input.target.environmentId,
328 - expectedProviderKind: providerKind,
329 - link,
330 - });
314 + origin: endpointOrigin(input.target.httpBaseUrl),
315 + },
316 + })
317 + .pipe(Effect.mapError(environmentApiError("Could not obtain environment link proof.")));
318 + const link = yield* relayClient
319 + .linkEnvironment({
320 + clerkToken: input.clerkToken,
321 + payload: {
322 + proof,
323 + notificationsEnabled: true,
324 + liveActivitiesEnabled: true,
325 + managedTunnelsEnabled,
326 + },
327 + })
328 + .pipe(
329 + Effect.mapError(
330 + decodedRelayClientError(`${configuredRelayUrl}/v1/client/environment-links failed`),
331 + ),
332 + );
333 + yield* ensureLinkedEnvironmentMatches({
334 + expectedEnvironmentId: input.target.environmentId,
335 + expectedProviderKind: providerKind,
336 + link,
337 + });
338
332 - yield* environmentClient.connect
333 - .relayConfig({
334 - headers: {},
335 - payload: {
336 - relayUrl: configuredRelayUrl,
337 - relayIssuer: link.relayIssuer,
338 - cloudUserId: link.cloudUserId,
339 - environmentCredential: link.environmentCredential,
340 - cloudMintPublicKey: link.cloudMintPublicKey,
341 - endpointRuntime: link.endpointRuntime,
342 - },
343 - })
344 - .pipe(Effect.mapError(environmentApiError("Could not configure environment relay access.")));
345 - }).pipe(Effect.provide(PrimaryEnvironmentHttpLayer.layer));
346 -}
339 + yield* environmentClient.connect
340 + .relayConfig({
341 + headers: {},
342 + payload: {
343 + relayUrl: configuredRelayUrl,
344 + relayIssuer: link.relayIssuer,
345 + cloudUserId: link.cloudUserId,
346 + environmentCredential: link.environmentCredential,
347 + cloudMintPublicKey: link.cloudMintPublicKey,
348 + endpointRuntime: link.endpointRuntime,
349 + },
350 + })
351 + .pipe(Effect.mapError(environmentApiError("Could not configure environment relay access.")));
352 +}, Effect.provide(PrimaryEnvironmentHttpLayer.layer));
apps/web/src/connection/storage.ts
+32 -32
@@ -750,21 +750,21 @@ export const layer = Layer.effectContext(
750 }),
751 Effect.mapError((cause) => persistenceError("load-shell", cause)),
752 ),
753 - saveShell: (environmentId, snapshot) =>
754 - Effect.gen(function* () {
753 + saveShell: Effect.fn("storage.saveShell")(
754 + function* (environmentId, snapshot) {
755 const encoded = yield* encodeStoredShellSnapshot({
756 schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
757 environmentId,
758 snapshot,
759 }).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
760 yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded);
761 - }).pipe(
762 - Effect.mapError((cause) =>
763 - cause._tag === "ConnectionPersistenceError"
764 - ? cause
765 - : persistenceError("save-shell", cause),
766 - ),
761 + },
762 + Effect.mapError((cause) =>
763 + cause._tag === "ConnectionPersistenceError"
764 + ? cause
765 + : persistenceError("save-shell", cause),
766 ),
767 + ),
768 loadServerConfig: (environmentId) =>
769 readDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId).pipe(
770 Effect.flatMap((raw) => {
@@ -784,21 +784,21 @@ export const layer = Layer.effectContext(
784 : persistenceError("load-server-config", cause),
785 ),
786 ),
787 - saveServerConfig: (environmentId, config) =>
788 - Effect.gen(function* () {
787 + saveServerConfig: Effect.fn("storage.saveServerConfig")(
788 + function* (environmentId, config) {
789 const encoded = yield* encodeStoredServerConfig({
790 schemaVersion: 1,
791 environmentId,
792 config,
793 }).pipe(Effect.mapError((cause) => persistenceError("save-server-config", cause)));
794 yield* writeDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId, encoded);
795 - }).pipe(
796 - Effect.mapError((cause) =>
797 - cause._tag === "ConnectionPersistenceError"
798 - ? cause
799 - : persistenceError("save-server-config", cause),
800 - ),
795 + },
796 + Effect.mapError((cause) =>
797 + cause._tag === "ConnectionPersistenceError"
798 + ? cause
799 + : persistenceError("save-server-config", cause),
800 ),
801 + ),
802 loadThread: (environmentId, threadId) =>
803 readDatabaseValue(
804 database,
@@ -827,8 +827,8 @@ export const layer = Layer.effectContext(
827 }),
828 Effect.mapError((cause) => persistenceError("load-thread", cause)),
829 ),
830 - saveThread: (environmentId, snapshot) =>
831 - Effect.gen(function* () {
830 + saveThread: Effect.fn("storage.saveThread")(
831 + function* (environmentId, snapshot) {
832 const encoded = yield* encodeStoredThreadSnapshot({
833 schemaVersion: ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION,
834 environmentId,
@@ -841,13 +841,13 @@ export const layer = Layer.effectContext(
841 threadCacheKey(environmentId, snapshot.projection.thread.id),
842 encoded,
843 );
844 - }).pipe(
845 - Effect.mapError((cause) =>
846 - cause._tag === "ConnectionPersistenceError"
847 - ? cause
848 - : persistenceError("save-thread", cause),
849 - ),
844 + },
845 + Effect.mapError((cause) =>
846 + cause._tag === "ConnectionPersistenceError"
847 + ? cause
848 + : persistenceError("save-thread", cause),
849 ),
850 + ),
851 loadVcsRefs: (environmentId, cwd) =>
852 readDatabaseValue(database, VCS_REFS_STORE_NAME, vcsRefsCacheKey(environmentId, cwd)).pipe(
853 Effect.flatMap((raw) => {
@@ -869,8 +869,8 @@ export const layer = Layer.effectContext(
869 : persistenceError("load-vcs-refs", cause),
870 ),
871 ),
872 - saveVcsRefs: (environmentId, cwd, refs) =>
873 - Effect.gen(function* () {
872 + saveVcsRefs: Effect.fn("storage.saveVcsRefs")(
873 + function* (environmentId, cwd, refs) {
874 const encoded = yield* encodeStoredVcsRefs({
875 schemaVersion: 1,
876 environmentId,
@@ -883,13 +883,13 @@ export const layer = Layer.effectContext(
883 vcsRefsCacheKey(environmentId, cwd),
884 encoded,
885 );
886 - }).pipe(
887 - Effect.mapError((cause) =>
888 - cause._tag === "ConnectionPersistenceError"
889 - ? cause
890 - : persistenceError("save-vcs-refs", cause),
891 - ),
886 + },
887 + Effect.mapError((cause) =>
888 + cause._tag === "ConnectionPersistenceError"
889 + ? cause
890 + : persistenceError("save-vcs-refs", cause),
891 ),
892 + ),
893 removeVcsRefs: (environmentId, cwd) =>
894 removeDatabaseValue(
895 database,
packages/client-runtime/src/platform/shellCacheEncoding.ts
+6 -4
@@ -51,14 +51,16 @@ export function makeStoredShellSnapshotEncoder(
51 hasWorked = true;
52 return Effect.void;
53 });
54 - const encodeMisses = (misses: ReadonlyArray<OrchestrationV2ThreadShellJson>) =>
55 - Effect.gen(function* () {
54 + const encodeMisses =
55 + /* Cache encoding runs for shell update batches; avoid tracing each batch. */
56 + Effect.fnUntraced(function* (misses: ReadonlyArray<OrchestrationV2ThreadShellJson>) {
57 yield* yieldBetweenChunks;
58 const chunk = yield* encodeThreadChunk(misses);
59 chunk.forEach((row, index) => encodedRows.set(misses[index]!, row));
60 });
60 - const encodeRows = (rows: ReadonlyArray<OrchestrationV2ThreadShellJson>) =>
61 - Effect.gen(function* () {
61 + const encodeRows =
62 + /* Cache encoding runs for shell update batches; avoid tracing each batch. */
63 + Effect.fnUntraced(function* (rows: ReadonlyArray<OrchestrationV2ThreadShellJson>) {
64 let misses: Array<OrchestrationV2ThreadShellJson> = [];
65 for (const row of rows) {
66 if (encodedRows.has(row)) continue;
packages/client-runtime/src/relay/managedRelayState.ts
+21 -22
@@ -311,30 +311,29 @@ export function createManagedRelayQueryManager(
311 ) {
312 const staleTime = options?.staleTimeMs ?? DEFAULT_STALE_TIME_MS;
313 const idleTtl = options?.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
314 - const observe = <A, E, R>(
314 + const observe = Effect.fn("managedRelayState.observe")(function* <A, E, R>(
315 input: Omit<ManagedRelayQueryEvent, "phase" | "message" | "traceId">,
316 effect: Effect.Effect<A, E, R>,
317 - ): Effect.Effect<A, E, R> =>
318 - Effect.gen(function* () {
319 - options?.onQueryEvent?.({ ...input, phase: "start" });
320 - return yield* effect.pipe(
321 - Effect.onExit((exit) =>
322 - Effect.sync(() => {
323 - if (exit._tag === "Success") {
324 - options?.onQueryEvent?.({ ...input, phase: "success" });
325 - return;
326 - }
327 - const error = Cause.squash(exit.cause);
328 - options?.onQueryEvent?.({
329 - ...input,
330 - phase: "failure",
331 - message: error instanceof Error ? error.message : String(error),
332 - traceId: findErrorTraceId(error),
333 - });
334 - }),
335 - ),
336 - );
337 - });
317 + ): Effect.fn.Return<A, E, R> {
318 + options?.onQueryEvent?.({ ...input, phase: "start" });
319 + return yield* effect.pipe(
320 + Effect.onExit((exit) =>
321 + Effect.sync(() => {
322 + if (exit._tag === "Success") {
323 + options?.onQueryEvent?.({ ...input, phase: "success" });
324 + return;
325 + }
326 + const error = Cause.squash(exit.cause);
327 + options?.onQueryEvent?.({
328 + ...input,
329 + phase: "failure",
330 + message: error instanceof Error ? error.message : String(error),
331 + traceId: findErrorTraceId(error),
332 + });
333 + }),
334 + ),
335 + );
336 + });
337
338 const environmentsAtom = Atom.family((accountId: string) =>
339 runtime
packages/client-runtime/src/state/environmentHttpAuth.ts
+9 -8
@@ -52,13 +52,13 @@ const withEnvironmentCredentials = <A, E, R>(
52 ? request.pipe(Effect.provideService(FetchHttpClient.RequestInit, { credentials: "include" }))
53 : request;
54
55 -const buildEnvironmentAuthHeaders = (
56 - authorization: PreparedHttpAuthorization | null,
57 - method: HttpMethod.HttpMethod,
58 - url: string,
59 - signer: Option.Option<ManagedRelayDpopSigner["Service"]>,
60 -): Effect.Effect<EnvironmentHttpAuthHeaders, RemoteEnvironmentAuthFetchError> =>
61 - Effect.gen(function* () {
55 +const buildEnvironmentAuthHeaders = Effect.fn("environmentHttpAuth.buildEnvironmentAuthHeaders")(
56 + function* (
57 + authorization: PreparedHttpAuthorization | null,
58 + method: HttpMethod.HttpMethod,
59 + url: string,
60 + signer: Option.Option<ManagedRelayDpopSigner["Service"]>,
61 + ): Effect.fn.Return<EnvironmentHttpAuthHeaders, RemoteEnvironmentAuthFetchError> {
62 if (authorization === null) {
63 return {};
64 }
@@ -83,7 +83,8 @@ const buildEnvironmentAuthHeaders = (
83 ),
84 );
85 return { authorization: `DPoP ${authorization.accessToken}`, dpop: proof };
86 - });
86 + },
87 +);
88
89 /**
90 * A DPoP request is T3 Connect work, so its span starts an exported trace that
packages/client-runtime/src/state/fileMetadata.ts
+9 -8
@@ -290,14 +290,15 @@ export function createFileMetadataAtoms<R, E>(
290 );
291 });
292
293 - const seedAfterRead = <A, ReadError, ReadServices>(
294 - read: Effect.Effect<A, ReadError, ReadServices>,
295 - seed: (
296 - result: A,
297 - isCurrent: (session: RpcSession) => boolean,
298 - ) => Effect.Effect<void, never, EnvironmentSupervisor.EnvironmentSupervisor>,
299 - ) =>
300 - Effect.gen(function* () {
293 + const seedAfterRead =
294 + /* Metadata seeding runs on every file read and is covered by the read operation. */
295 + Effect.fnUntraced(function* <A, ReadError, ReadServices>(
296 + read: Effect.Effect<A, ReadError, ReadServices>,
297 + seed: (
298 + result: A,
299 + isCurrent: (session: RpcSession) => boolean,
300 + ) => Effect.Effect<void, never, EnvironmentSupervisor.EnvironmentSupervisor>,
301 + ) {
302 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
303 const session = yield* SubscriptionRef.get(supervisor.session);
304 const version = session._tag === "Some" ? (invalidationVersions.get(session.value) ?? 0) : 0;
packages/client-runtime/src/state/orchestration.ts
+19 -18
@@ -27,25 +27,26 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
27 return {
28 threadTranscript: createEnvironmentCommand(runtime, {
29 label: "environment-data:orchestration:thread-transcript",
30 - execute: (input: { readonly threadId: ThreadId }) =>
31 - Effect.gen(function* () {
32 - const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
33 - const prepared = yield* SubscriptionRef.get(supervisor.prepared);
34 - if (Option.isNone(prepared)) {
35 - return yield* new EnvironmentRpcUnavailableError({
36 - environmentId: supervisor.target.environmentId,
37 - message: "The source environment is not connected.",
38 - });
39 - }
40 - return yield* fetchEnvironmentThreadTranscript({
41 - prepared: prepared.value,
42 - threadId: input.threadId,
43 - signer: yield* Effect.serviceOption(ManagedRelayDpopSigner.ManagedRelayDpopSigner),
44 - remoteAuthorization: yield* Effect.serviceOption(
45 - RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
46 - ),
30 + execute: Effect.fn("orchestration.execute")(function* (input: {
31 + readonly threadId: ThreadId;
32 + }) {
33 + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
34 + const prepared = yield* SubscriptionRef.get(supervisor.prepared);
35 + if (Option.isNone(prepared)) {
36 + return yield* new EnvironmentRpcUnavailableError({
37 + environmentId: supervisor.target.environmentId,
38 + message: "The source environment is not connected.",
39 });
48 - }),
40 + }
41 + return yield* fetchEnvironmentThreadTranscript({
42 + prepared: prepared.value,
43 + threadId: input.threadId,
44 + signer: yield* Effect.serviceOption(ManagedRelayDpopSigner.ManagedRelayDpopSigner),
45 + remoteAuthorization: yield* Effect.serviceOption(
46 + RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
47 + ),
48 + });
49 + }),
50 }),
51 v2: {
52 dispatchCommand: createEnvironmentRpcCommand(runtime, {
packages/client-runtime/src/state/pullRequestStatsPersistence.ts
+10 -6
@@ -16,17 +16,19 @@ const statKey = (ref: PullRequestRef) =>
16 export function persistPullRequestStats(): QueryPersistence<PullRequestListStatsResult> {
17 const row = persistQuery(PullRequestDiffStat);
18 return {
19 - load: (environmentId, key) =>
20 - Effect.gen(function* () {
19 + load: Effect.fn("pullRequestStatsPersistence.load")(
20 + function* (environmentId, key) {
21 const [, input] = yield* Schema.decodeEffect(requestKey)(key);
22 const rows = yield* Effect.forEach(input.refs, (ref) =>
23 row.load(environmentId, statKey(ref)),
24 );
25 const stats = rows.flatMap((value) => (Option.isSome(value) ? [value.value] : []));
26 return stats.length ? Option.some({ stats }) : Option.none();
27 - }).pipe(Effect.orElseSucceed(() => Option.none())),
28 - save: (environmentId, key, result) =>
29 - Effect.gen(function* () {
27 + },
28 + Effect.orElseSucceed(() => Option.none()),
29 + ),
30 + save: Effect.fn("pullRequestStatsPersistence.save")(
31 + function* (environmentId, key, result) {
32 const [, input] = yield* Schema.decodeEffect(requestKey)(key);
33 yield* Effect.forEach(result.stats, (stat) => {
34 const ref = input.refs.find(
@@ -37,6 +39,8 @@ export function persistPullRequestStats(): QueryPersistence<PullRequestListStats
39 );
40 return ref ? row.save(environmentId, statKey(ref), stat) : Effect.void;
41 });
40 - }).pipe(Effect.ignore),
42 + },
43 + (effect, _environmentId, _key, _result) => effect.pipe(Effect.ignore),
44 + ),
45 };
46 }
packages/client-runtime/src/state/pullRequests.ts
+58 -57
@@ -230,6 +230,62 @@ export function createPullRequestEnvironmentAtoms<R, E>(
230 staleTimeMs: 60_000,
231 }),
232 );
233 + const loadDiff = Effect.fn("PullRequests.loadDiff")(function* (input: PullRequestDiffInput) {
234 + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
235 + const loader = yield* PullRequestDiffLoader.PullRequestDiffLoader;
236 + const prepared = yield* SubscriptionRef.get(supervisor.prepared);
237 + if (Option.isNone(prepared)) {
238 + return yield* new EnvironmentHttpConnectionNotReadyError({
239 + message: "The environment HTTP connection is not ready.",
240 + });
241 + }
242 + return yield* loader.load(prepared.value, input);
243 + });
244 +
245 + const runAction = Effect.fn("PullRequests.runAction")(function* (
246 + input: PullRequestActionInput & {
247 + readonly resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;
248 + },
249 + ) {
250 + const { resolveMergeMethod, ...actionInput } = input;
251 + let preparedInput = actionInput;
252 + if (actionInput.action === "merge" && resolveMergeMethod !== undefined) {
253 + const { projectId, host, repository, number } = actionInput;
254 + const reference = { projectId, host, repository, number, allowStale: false };
255 + const detail = yield* routedRequest(WS_METHODS.pullRequestsDetail, reference);
256 + if (
257 + detail.state !== "open" ||
258 + detail.isDraft ||
259 + !detail.capabilities.actions.includes("merge") ||
260 + !detail.viewerPermissions.actions.includes("merge")
261 + ) {
262 + return yield* new PullRequestOperationError({
263 + operation: "runAction",
264 + detail: "This pull request cannot be merged.",
265 + });
266 + }
267 + if (detail.capabilities.stackActions) {
268 + const stack = yield* routedRequest(WS_METHODS.pullRequestsStack, reference);
269 + if (stack !== null) {
270 + return yield* new PullRequestOperationError({
271 + operation: "runAction",
272 + detail: "Open this pull request to merge its stack.",
273 + });
274 + }
275 + }
276 + const mergeMethod = yield* Effect.try({
277 + try: () => resolveMergeMethod(detail),
278 + catch: (cause) =>
279 + new PullRequestOperationError({
280 + operation: "runAction",
281 + detail: cause instanceof Error ? cause.message : "Could not choose a merge method.",
282 + }),
283 + });
284 + preparedInput = { ...actionInput, mergeMethod };
285 + }
286 + return yield* routedRequest(WS_METHODS.pullRequestsRunAction, preparedInput);
287 + });
288 +
289 return {
290 refreshes,
291 linkedThreads: createEnvironmentRpcQueryAtomFamily(runtime, {
@@ -286,18 +342,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(
342 label: "environment-data:pull-requests:diff",
343 persistence: persistQuery(PullRequestDiffResult),
344 staleTimeMs: 60_000,
289 - execute: (input: PullRequestDiffInput) =>
290 - Effect.gen(function* () {
291 - const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
292 - const loader = yield* PullRequestDiffLoader.PullRequestDiffLoader;
293 - const prepared = yield* SubscriptionRef.get(supervisor.prepared);
294 - if (Option.isNone(prepared)) {
295 - return yield* new EnvironmentHttpConnectionNotReadyError({
296 - message: "The environment HTTP connection is not ready.",
297 - });
298 - }
299 - return yield* loader.load(prepared.value, input);
300 - }),
345 + execute: loadDiff,
346 }),
347 diffFileContents: createEnvironmentRpcCommand(runtime, {
348 label: "environment-data:pull-requests:diff-file-contents",
@@ -347,51 +392,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(
392 label: "environment-data:pull-requests:run-action",
393 // Preparation belongs to the write's lane. Refreshable queries would restart it after
394 // every preceding action, and preparing outside the lane could reorder the clicks.
350 - execute: (
351 - input: PullRequestActionInput & {
352 - readonly resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;
353 - },
354 - ) =>
355 - Effect.gen(function* () {
356 - const { resolveMergeMethod, ...actionInput } = input;
357 - let preparedInput = actionInput;
358 - if (actionInput.action === "merge" && resolveMergeMethod !== undefined) {
359 - const { projectId, host, repository, number } = actionInput;
360 - const reference = { projectId, host, repository, number, allowStale: false };
361 - const detail = yield* routedRequest(WS_METHODS.pullRequestsDetail, reference);
362 - if (
363 - detail.state !== "open" ||
364 - detail.isDraft ||
365 - !detail.capabilities.actions.includes("merge") ||
366 - !detail.viewerPermissions.actions.includes("merge")
367 - ) {
368 - return yield* new PullRequestOperationError({
369 - operation: "runAction",
370 - detail: "This pull request cannot be merged.",
371 - });
372 - }
373 - if (detail.capabilities.stackActions) {
374 - const stack = yield* routedRequest(WS_METHODS.pullRequestsStack, reference);
375 - if (stack !== null) {
376 - return yield* new PullRequestOperationError({
377 - operation: "runAction",
378 - detail: "Open this pull request to merge its stack.",
379 - });
380 - }
381 - }
382 - const mergeMethod = yield* Effect.try({
383 - try: () => resolveMergeMethod(detail),
384 - catch: (cause) =>
385 - new PullRequestOperationError({
386 - operation: "runAction",
387 - detail:
388 - cause instanceof Error ? cause.message : "Could not choose a merge method.",
389 - }),
390 - });
391 - preparedInput = { ...actionInput, mergeMethod };
392 - }
393 - return yield* routedRequest(WS_METHODS.pullRequestsRunAction, preparedInput);
394 - }),
395 + execute: runAction,
396 onSuccess: ({ environmentId, input }, registry) =>
397 Effect.sync(() => registry.refresh(preview({ environmentId, input }))),
398 scheduler: commandScheduler,
packages/client-runtime/src/state/queryPersistence.ts
+15 -14
@@ -26,23 +26,24 @@ export interface QueryPersistence<A> {
26 export function persistQuery<A, I>(schema: Schema.Codec<A, I>): QueryPersistence<A> {
27 const codec = Schema.fromJsonString(Schema.toCodecJson(schema));
28 return {
29 - load: (environmentId, key) =>
30 - Effect.gen(function* () {
31 - const store = yield* EnvironmentQueryStore;
32 - if (store === null) return Option.none<A>();
33 - const stored = yield* store.load(environmentId, key);
34 - if (Option.isNone(stored)) return Option.none<A>();
35 - return yield* Schema.decodeUnknownEffect(codec)(stored.value).pipe(
36 - Effect.map(Option.some),
37 - Effect.catch(() => Effect.succeedNone),
38 - );
39 - }),
40 - save: (environmentId, key, value) =>
41 - Effect.gen(function* () {
29 + load: Effect.fn("queryPersistence.load")(function* (environmentId, key) {
30 + const store = yield* EnvironmentQueryStore;
31 + if (store === null) return Option.none<A>();
32 + const stored = yield* store.load(environmentId, key);
33 + if (Option.isNone(stored)) return Option.none<A>();
34 + return yield* Schema.decodeUnknownEffect(codec)(stored.value).pipe(
35 + Effect.map(Option.some),
36 + Effect.catch(() => Effect.succeedNone),
37 + );
38 + }),
39 + save: Effect.fn("queryPersistence.save")(
40 + function* (environmentId, key, value) {
41 const store = yield* EnvironmentQueryStore;
42 if (store === null) return;
43 const payload = yield* Schema.encodeEffect(codec)(value);
44 yield* store.save(environmentId, key, payload);
46 - }).pipe(Effect.catch(() => Effect.logWarning("Offline query cache save failed"))),
45 + },
46 + Effect.catch(() => Effect.logWarning("Offline query cache save failed")),
47 + ),
48 };
49 }
packages/client-runtime/src/state/runtime.ts
+9 -9
@@ -299,14 +299,15 @@ export function createAtomCommandScheduler(): AtomCommandScheduler {
299 };
300 }
301
302 -export function scheduleAtomCommandEffect<W, A, E, R>(
303 - registry: AtomRegistry.AtomRegistry,
304 - scheduler: AtomCommandScheduler,
305 - concurrency: AtomCommandConcurrency<W>,
306 - input: W,
307 - effect: Effect.Effect<A, E, R>,
308 -): Effect.Effect<A, E, R> {
309 - return Effect.gen(function* () {
302 +export const scheduleAtomCommandEffect =
303 + /* Every atom command passes through this scheduler; the command owns its tracing boundary. */
304 + Effect.fnUntraced(function* <W, A, E, R>(
305 + registry: AtomRegistry.AtomRegistry,
306 + scheduler: AtomCommandScheduler,
307 + concurrency: AtomCommandConcurrency<W>,
308 + input: W,
309 + effect: Effect.Effect<A, E, R>,
310 + ): Effect.fn.Return<A, E, R> {
311 const context = yield* Effect.context<R>();
312 const result = yield* Effect.promise((signal) =>
313 scheduler.schedule<W, A, E>(registry, concurrency, input, async () => {
@@ -318,7 +319,6 @@ export function scheduleAtomCommandEffect<W, A, E, R>(
319 );
320 return result._tag === "Success" ? result.value : yield* Effect.failCause(result.cause);
321 });
321 -}
322
323 export async function runAtomCommand<W, A, E>(
324 registry: AtomRegistry.AtomRegistry,
packages/client-runtime/src/state/threadCommands.ts
+18 -17
@@ -149,6 +149,23 @@ export function createThreadEnvironmentAtoms<R, E>(
149 key: ({ environmentId, input }: { environmentId: string; input: { threadId: string } }) =>
150 JSON.stringify([environmentId, input.threadId]),
151 };
152 + const loadEarlierHistory = Effect.fn("ThreadCommands.loadEarlierHistory")(function* (
153 + input: LoadEarlierThreadHistoryInput,
154 + ) {
155 + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
156 + const controller = yield* Effect.serviceOption(ThreadHistoryController.ThreadHistoryController);
157 + if (Option.isNone(controller)) {
158 + return {
159 + _tag: "noop",
160 + } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult;
161 + }
162 + return yield* controller.value.loadEarlier(
163 + supervisor.target.environmentId,
164 + input.threadId,
165 + input.throughEntryId,
166 + );
167 + });
168 +
169 const commands = {
170 create: createEnvironmentCommand(runtime, {
171 label: "environment-data:commands:thread:create",
@@ -375,23 +392,7 @@ export function createThreadEnvironmentAtoms<R, E>(
392 }),
393 loadEarlierHistory: createEnvironmentCommand(runtime, {
394 label: "environment-data:commands:thread:load-earlier-history",
378 - execute: (input: LoadEarlierThreadHistoryInput) =>
379 - Effect.gen(function* () {
380 - const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
381 - const controller = yield* Effect.serviceOption(
382 - ThreadHistoryController.ThreadHistoryController,
383 - );
384 - if (Option.isNone(controller)) {
385 - return {
386 - _tag: "noop",
387 - } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult;
388 - }
389 - return yield* controller.value.loadEarlier(
390 - supervisor.target.environmentId,
391 - input.threadId,
392 - input.throughEntryId,
393 - );
394 - }),
395 + execute: loadEarlierHistory,
396 scheduler,
397 concurrency: {
398 mode: "serial",