TypeScript
refactor(client): use Effect functions across web desktop and mobile (#21998)
Julius Marminge669445a7705c
diff --git a/apps/desktop/src/app/DesktopCliCommand.ts b/apps/desktop/src/app/DesktopCliCommand.tsindex aebe8adb4a0..294f8a8b984 100644--- a/apps/desktop/src/app/DesktopCliCommand.ts+++ b/apps/desktop/src/app/DesktopCliCommand.ts@@ -83,15 +83,17 @@ export const make = Effect.gen(function* () {Effect.orElseSucceed(() => false),);- const isOurLink = (link: string) =>- Effect.gen(function* () {+ const isOurLink = Effect.fn("DesktopCliCommand.isOurLink")(+ function* (link: string) {yield* fs.readLink(link);// The launcher is a few KB; never read a large binary another `t3` links to.const info = yield* fs.stat(link);if (info.type !== "File" || Number(info.size) > 16_384) return false;const content = yield* fs.readFileString(link);return content.includes(DesktopCliShim.MARKER);- }).pipe(Effect.orElseSucceed(() => false));+ },+ Effect.orElseSucceed(() => false),+ );const powershell = (env: Record<string, string>) =>Effect.scoped(diff --git a/apps/desktop/src/app/DesktopLegacyLocalStorage.ts b/apps/desktop/src/app/DesktopLegacyLocalStorage.tsindex 9deba238992..122aa3393f9 100644--- a/apps/desktop/src/app/DesktopLegacyLocalStorage.ts+++ b/apps/desktop/src/app/DesktopLegacyLocalStorage.ts@@ -34,8 +34,8 @@ const make = Effect.gen(function* () {const markerPath = yield* Ref.make(Option.none<string>());/** Newest file mtime in a directory; appending to a log leaves the directory's own mtime alone. */- const newestFileMtime = (directory: string) =>- Effect.gen(function* () {+ const newestFileMtime = Effect.fn("DesktopLegacyLocalStorage.newestFileMtime")(+ function* (directory: string) {let newest = 0;for (const name of yield* fs.readDirectory(directory)) {const info = yield* fs.stat(path.join(directory, name)).pipe(Effect.option);@@ -47,7 +47,9 @@ const make = Effect.gen(function* () {newest = Math.max(newest, mtime);}return newest;- }).pipe(Effect.option);+ },+ (effect, _directory) => effect.pipe(Effect.option),+ );const findV1LocalStorage = Effect.gen(function* () {let newest: { readonly directory: string; readonly mtime: number } | null = null;diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.tsindex 77a90e0512a..dadbe8acc74 100644--- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts@@ -875,8 +875,9 @@ export const make = Effect.gen(function* () {}return distro ? `WSL (${distro})` : "WSL";}).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")),- resolveWsl: (input) =>- Effect.gen(function* () {+ // The span options depend on each request's port and distro.+ resolveWsl: Effect.fnUntraced(+ function* (input) {const shared = yield* sharedInputs;return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),@@ -884,11 +885,14 @@ export const make = Effect.gen(function* () {Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),Effect.provideService(FileSystem.FileSystem, fileSystem),);- }).pipe(- Effect.withSpan("desktop.backendConfiguration.resolveWsl", {- attributes: { port: input.port, distro: input.distro ?? null },- }),- ),+ },+ (effect, input) =>+ effect.pipe(+ Effect.withSpan("desktop.backendConfiguration.resolveWsl", {+ attributes: { port: input.port, distro: input.distro ?? null },+ }),+ ),+ ),});});diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.tsindex 5ad864f945d..e74e98a079b 100644--- a/apps/desktop/src/backend/DesktopBackendManager.ts+++ b/apps/desktop/src/backend/DesktopBackendManager.ts@@ -1114,20 +1114,25 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (});});- const waitForReady = (timeout: Duration.Duration): Effect.Effect<boolean> =>- Effect.gen(function* () {+ const waitForReady: (timeout: Duration.Duration) => Effect.Effect<boolean> = Effect.fn(+ "DesktopBackendManager.waitForReady",+ )(+ function* (_timeout: Duration.Duration) {const current = yield* Ref.get(state);if (!current.desiredRunning) return { done: true, ready: false };return current.ready ? { done: true, ready: true } : { done: false, ready: false };- }).pipe(- Effect.repeat({- until: (status) => status.done,- schedule: Schedule.spaced(Duration.millis(100)),- }),- Effect.map((status) => status.ready),- Effect.timeoutOption(timeout),- Effect.map(Option.getOrElse(() => false)),- );+ },+ (effect, timeout) =>+ effect.pipe(+ Effect.repeat({+ until: (status) => status.done,+ schedule: Schedule.spaced(Duration.millis(100)),+ }),+ Effect.map((status) => status.ready),+ Effect.timeoutOption(timeout),+ Effect.map(Option.getOrElse(() => false)),+ ),+ );yield* Effect.addFinalizer(() => stop());diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.tsindex a0e6d4377f2..0ee88b04667 100644--- a/apps/desktop/src/backend/DesktopBackendPool.ts+++ b/apps/desktop/src/backend/DesktopBackendPool.ts@@ -249,61 +249,59 @@ export const layer = Layer.effect(),);- const unregister: DesktopBackendPool["Service"]["unregister"] = (id) =>- Effect.gen(function* () {- if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {- return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();- }- const done = yield* Deferred.make<void>();- const action = yield* SynchronizedRef.modifyEffect(- instancesRef,- (- current,- ): Effect.Effect<- readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]- > => {- const entry = current.get(id);- if (entry === undefined) {- return Effect.succeed([{ _tag: "Absent" } as const, current] as const);- }- if (entry._tag === "Closing") {- return Effect.succeed([- { _tag: "Wait", done: entry.done } as const,- current,- ] as const);- }- const next = new Map(current);- next.set(id, { _tag: "Closing", done });- return Effect.succeed([- { _tag: "Close", entry } as const,- next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,- ] as const);- },- );-- if (action._tag === "Absent") return;- if (action._tag === "Wait") {- yield* Deferred.await(action.done);- return;- }-- const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {- const closing = current.get(id);- if (closing?._tag !== "Closing" || closing.done !== done) {- return Effect.succeed([undefined, current] as const);+ const unregister: DesktopBackendPool["Service"]["unregister"] = Effect.fn(+ "DesktopBackendPool.unregister",+ )(function* (id) {+ if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {+ return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();+ }+ const done = yield* Deferred.make<void>();+ const action = yield* SynchronizedRef.modifyEffect(+ instancesRef,+ (+ current,+ ): Effect.Effect<+ readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]+ > => {+ const entry = current.get(id);+ if (entry === undefined) {+ return Effect.succeed([{ _tag: "Absent" } as const, current] as const);+ }+ if (entry._tag === "Closing") {+ return Effect.succeed([{ _tag: "Wait", done: entry.done } as const, current] as const);}const next = new Map(current);- next.delete(id);+ next.set(id, { _tag: "Closing", done });return Effect.succeed([- undefined,+ { _tag: "Close", entry } as const,next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,] as const);- }).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);- yield* Option.match(action.entry.scope, {- onNone: () => Effect.void,- onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),- }).pipe(Effect.ensuring(finish));- });+ },+ );++ if (action._tag === "Absent") return;+ if (action._tag === "Wait") {+ yield* Deferred.await(action.done);+ return;+ }++ const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {+ const closing = current.get(id);+ if (closing?._tag !== "Closing" || closing.done !== done) {+ return Effect.succeed([undefined, current] as const);+ }+ const next = new Map(current);+ next.delete(id);+ return Effect.succeed([+ undefined,+ next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,+ ] as const);+ }).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);+ yield* Option.match(action.entry.scope, {+ onNone: () => Effect.void,+ onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),+ }).pipe(Effect.ensuring(finish));+ });return DesktopBackendPool.of({get: (id) =>diff --git a/apps/desktop/src/electron/ElectronWindow.ts b/apps/desktop/src/electron/ElectronWindow.tsindex a7ab05303f7..993e930678e 100644--- a/apps/desktop/src/electron/ElectronWindow.ts+++ b/apps/desktop/src/electron/ElectronWindow.ts@@ -324,8 +324,9 @@ export const make = Effect.gen(function* () {cause,}),}).pipe(Effect.orDie),- sendAll: (channel, ...args) =>- Effect.gen(function* () {+ sendAll:+ /* Window broadcasts run for streamed updates; avoid a span per broadcast. */+ Effect.fnUntraced(function* (channel, ...args) {for (const window of yield* listWindows) {if (yield* isWindowDestroyed(window)) {continue;diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.tsindex 7a1ff6dff1d..b036a67ac8b 100644--- a/apps/desktop/src/preview/Manager.ts+++ b/apps/desktop/src/preview/Manager.ts@@ -2375,8 +2375,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function// The scheme is read after the session attaches so a concurrent setColorScheme is not// overwritten with a stale snapshot.- const restoreControlSession = (tabId: string, wc: Electron.WebContents) =>- Effect.gen(function* () {+ const restoreControlSession = Effect.fn("PreviewManager.restoreControlSession")(+ function* (tabId: string, wc: Electron.WebContents) {const beforeAttach = (yield* SynchronizedRef.get(tabsRef)).get(tabId);if (beforeAttach?.webContentsId !== wc.id) return;const control = yield* ensureControlSession(wc);@@ -2401,7 +2401,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function}),);}- }).pipe(Effect.ignore);+ },+ (effect, _tabId, _wc) => effect.pipe(Effect.ignore),+ );// Only the session that saw the detach is replaced: by the time the event is// handled the guest may already hold a newer one, which must stay.diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.ts b/apps/desktop/src/snapShot/DesktopSnapShot.tsindex 539d9019bd5..569bf732df6 100644--- a/apps/desktop/src/snapShot/DesktopSnapShot.ts+++ b/apps/desktop/src/snapShot/DesktopSnapShot.ts@@ -1708,8 +1708,8 @@ export const make = Effect.gen(function* () {),Effect.mapError((cause) => new DesktopSnapShotError({ operation: "list-pending", cause })),),- read: (id) =>- Effect.gen(function* () {+ read: Effect.fn("DesktopSnapShot.read")(+ function* (id) {const metadata = yield* fileSystem.readFileString(path.join(captureDirectory, `${id}.json`)).pipe(Effect.flatMap(decodePendingCaptureJson));@@ -1718,11 +1718,14 @@ export const make = Effect.gen(function* () {...metadata,dataUrl: `data:image/png;base64,${Base64.encode(png)}`,};- }).pipe(- Effect.mapError(- (cause) => new DesktopSnapShotError({ operation: "read", captureId: id, cause }),+ },+ (effect, id) =>+ effect.pipe(+ Effect.mapError(+ (cause) => new DesktopSnapShotError({ operation: "read", captureId: id, cause }),+ ),),- ),+ ),setAnimationDestination: (id, destination) =>Effect.promise(async () => {if (linuxFeedback?.id === id && destination.relativeFrame) {diff --git a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.tsindex 1155a2b15b0..5e4b1de81b8 100644--- a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts+++ b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts@@ -199,96 +199,98 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {),).pipe(Effect.forkScoped);- const sampleOnce = (allowSuspendRecovery: boolean) =>- Effect.gen(function* () {- const sampledAt = yield* DateTime.now;- const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);- const demand = (yield* Ref.get(diagnosticsDemandSources)).size > 0;- const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(- [- Ref.get(powerState),- powerMonitor.getSystemIdleTime,- powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),- powerMonitor.isOnBatteryPower,- electronApp.getAppMetrics,- ],- { concurrency: "unbounded" },- );- // One Electron sampler preserves the shared CPU measurement interval.- yield* rendererHistory.recordMetrics(metrics);- const polledLocked =- systemIdleState === "unknown"- ? currentPower.locked- : booleanState(systemIdleState === "locked");- const polledOnBattery = booleanState(onBattery);- const observedPower = yield* Ref.modify(powerState, (latestPower) => {- const preserveEventLocked =- latestPower.lockedEventPending ||- latestPower.locked !== currentPower.locked ||- latestPower.lockedEventPending !== currentPower.lockedEventPending;- const preserveEventOnBattery =- latestPower.onBatteryEventPending ||- latestPower.onBattery !== currentPower.onBattery ||- latestPower.onBatteryEventPending !== currentPower.onBatteryEventPending;- const preserveEventSuspended =- latestPower.suspendedEventPending ||- latestPower.suspended !== currentPower.suspended ||- latestPower.suspendedEventPending !== currentPower.suspendedEventPending;- const next: PowerState = {- ...latestPower,- idle: idleState(systemIdleState),- locked: preserveEventLocked ? latestPower.locked : polledLocked,- lockedEventPending:- latestPower.lockedEventPending &&- (systemIdleState === "unknown" || polledLocked !== latestPower.locked),- suspended:- allowSuspendRecovery && !preserveEventSuspended ? false : latestPower.suspended,- suspendedEventPending: false,- onBattery: preserveEventOnBattery ? latestPower.onBattery : polledOnBattery,- onBatteryEventPending:- latestPower.onBatteryEventPending && polledOnBattery !== latestPower.onBattery,+ const sampleOnce =+ /* Periodic telemetry sampling should not generate its own tracing traffic. */+ Effect.fnUntraced(+ function* (allowSuspendRecovery: boolean) {+ const sampledAt = yield* DateTime.now;+ const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);+ const demand = (yield* Ref.get(diagnosticsDemandSources)).size > 0;+ const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(+ [+ Ref.get(powerState),+ powerMonitor.getSystemIdleTime,+ powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),+ powerMonitor.isOnBatteryPower,+ electronApp.getAppMetrics,+ ],+ { concurrency: "unbounded" },+ );+ // One Electron sampler preserves the shared CPU measurement interval.+ yield* rendererHistory.recordMetrics(metrics);+ const polledLocked =+ systemIdleState === "unknown"+ ? currentPower.locked+ : booleanState(systemIdleState === "locked");+ const polledOnBattery = booleanState(onBattery);+ const observedPower = yield* Ref.modify(powerState, (latestPower) => {+ const preserveEventLocked =+ latestPower.lockedEventPending ||+ latestPower.locked !== currentPower.locked ||+ latestPower.lockedEventPending !== currentPower.lockedEventPending;+ const preserveEventOnBattery =+ latestPower.onBatteryEventPending ||+ latestPower.onBattery !== currentPower.onBattery ||+ latestPower.onBatteryEventPending !== currentPower.onBatteryEventPending;+ const preserveEventSuspended =+ latestPower.suspendedEventPending ||+ latestPower.suspended !== currentPower.suspended ||+ latestPower.suspendedEventPending !== currentPower.suspendedEventPending;+ const next: PowerState = {+ ...latestPower,+ idle: idleState(systemIdleState),+ locked: preserveEventLocked ? latestPower.locked : polledLocked,+ lockedEventPending:+ latestPower.lockedEventPending &&+ (systemIdleState === "unknown" || polledLocked !== latestPower.locked),+ suspended:+ allowSuspendRecovery && !preserveEventSuspended ? false : latestPower.suspended,+ suspendedEventPending: false,+ onBattery: preserveEventOnBattery ? latestPower.onBattery : polledOnBattery,+ onBatteryEventPending:+ latestPower.onBatteryEventPending && polledOnBattery !== latestPower.onBattery,+ };+ return [next, next] as const;+ });+ const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);+ const snapshot: DesktopHostTelemetrySnapshot = {+ version: 1,+ type: "desktopTelemetry",+ sequence: nextSequence,+ sampledAtUnixMs,+ electronPid: process.pid,+ power: {+ source: "electron-main",+ idle: observedPower.idle,+ idleSeconds,+ locked: observedPower.locked,+ suspended: observedPower.suspended,+ onBattery: observedPower.onBattery,+ lowPowerMode: "unknown",+ thermalState: observedPower.thermalState,+ stale: false,+ updatedAt: sampledAt,+ },+ speedLimitPercent: observedPower.speedLimitPercent,+ electronProcesses: (demand ? metrics : []).map((metric) => ({+ pid: metric.pid,+ creationTimeMs: Math.max(0, Math.round(metric.creationTime)),+ type: metric.type,+ ...(metric.name === undefined ? {} : { name: metric.name }),+ ...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }),+ cpuPercent: metric.cpu.percentCPUUsage,+ ...(metric.cpu.cumulativeCPUUsage === undefined+ ? {}+ : { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }),+ idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond,+ workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)),+ peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)),+ })),};- return [next, next] as const;- });- const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);- const snapshot: DesktopHostTelemetrySnapshot = {- version: 1,- type: "desktopTelemetry",- sequence: nextSequence,- sampledAtUnixMs,- electronPid: process.pid,- power: {- source: "electron-main",- idle: observedPower.idle,- idleSeconds,- locked: observedPower.locked,- suspended: observedPower.suspended,- onBattery: observedPower.onBattery,- lowPowerMode: "unknown",- thermalState: observedPower.thermalState,- stale: false,- updatedAt: sampledAt,- },- speedLimitPercent: observedPower.speedLimitPercent,- electronProcesses: (demand ? metrics : []).map((metric) => ({- pid: metric.pid,- creationTimeMs: Math.max(0, Math.round(metric.creationTime)),- type: metric.type,- ...(metric.name === undefined ? {} : { name: metric.name }),- ...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }),- cpuPercent: metric.cpu.percentCPUUsage,- ...(metric.cpu.cumulativeCPUUsage === undefined- ? {}- : { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }),- idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond,- workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)),- peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)),- })),- };- yield* Ref.set(latest, Option.some(snapshot));- yield* PubSub.publish(changes, snapshot);- }).pipe(+ yield* Ref.set(latest, Option.some(snapshot));+ yield* PubSub.publish(changes, snapshot);+ },Effect.catchCauseIf((cause) => !Cause.hasInterrupts(cause),(cause) =>diff --git a/apps/desktop/src/updates/DesktopRemoteUpdates.ts b/apps/desktop/src/updates/DesktopRemoteUpdates.tsindex 716a73c199a..cb1b86c0775 100644--- a/apps/desktop/src/updates/DesktopRemoteUpdates.ts+++ b/apps/desktop/src/updates/DesktopRemoteUpdates.ts@@ -188,84 +188,85 @@ export const listen: Effect.Effect<Effect.forkScoped,);- const step = (state: DesktopUpdateState): Effect.Effect<boolean, never, Scope.Scope> =>- Effect.gen(function* () {- const next = nextRemoteDesktopUpdateStep(state, attempts, disabledReason);- switch (next.action) {- case "wait":- return false;- case "check":- attempts = { ...attempts, checks: attempts.checks + 1 };- yield* updates.check("remote-update").pipe(- Effect.flatMap((result) => {- if (result.checked) return Effect.void;- attempts = { ...attempts, checks: attempts.checks - 1 };- return retryLater(state);- }),- Effect.forkScoped,- );+ const step = Effect.fn("DesktopRemoteUpdates.step")(function* (+ state: DesktopUpdateState,+ ): Effect.fn.Return<boolean, never, Scope.Scope> {+ const next = nextRemoteDesktopUpdateStep(state, attempts, disabledReason);+ switch (next.action) {+ case "wait":+ return false;+ case "check":+ attempts = { ...attempts, checks: attempts.checks + 1 };+ yield* updates.check("remote-update").pipe(+ Effect.flatMap((result) => {+ if (result.checked) return Effect.void;+ attempts = { ...attempts, checks: attempts.checks - 1 };+ return retryLater(state);+ }),+ Effect.forkScoped,+ );+ return false;+ case "download":+ attempts = { ...attempts, downloads: attempts.downloads + 1 };+ yield* updates.download.pipe(+ Effect.flatMap((result) => {+ if (result.accepted) return Effect.void;+ attempts = { ...attempts, downloads: attempts.downloads - 1 };+ return retryLater(state);+ }),+ Effect.forkScoped,+ );+ return false;+ case "install": {+ // The download event fires before its action releases the+ // updater reservation. Wait until the prepared install can+ // be committed by the client in a separate RPC.+ if (yield* updates.isActionActive) {+ yield* retryLater(state);return false;- case "download":- attempts = { ...attempts, downloads: attempts.downloads + 1 };- yield* updates.download.pipe(- Effect.flatMap((result) => {- if (result.accepted) return Effect.void;- attempts = { ...attempts, downloads: attempts.downloads - 1 };- return retryLater(state);- }),- Effect.forkScoped,- );- return false;- case "install": {- // The download event fires before its action releases the- // updater reservation. Wait until the prepared install can- // be committed by the client in a separate RPC.- if (yield* updates.isActionActive) {- yield* retryLater(state);- return false;- }- if (state.downloadedVersion === null) {- yield* publishReport(- state,- {- outcome: "failed",- reason: "The desktop app lost the downloaded update.",- },- request.requestId,- );- return true;- }- yield* Ref.set(- preparedUpdateRef,- Option.some({- requestId: request.requestId,- downloadedVersion: state.downloadedVersion,- status: "prepared",- expiresAt:- (yield* Clock.currentTimeMillis) + Duration.toMillis(PREPARED_UPDATE_TTL),- }),- );- yield* publishReport(state, { outcome: "ready-to-install" }, request.requestId);- yield* logInfo("remote update prepared", { requestId: request.requestId });- return true;}- case "done":+ if (state.downloadedVersion === null) {yield* publishReport(state,{- outcome: next.outcome,- ...(next.reason === undefined ? {} : { reason: next.reason }),+ outcome: "failed",+ reason: "The desktop app lost the downloaded update.",},request.requestId,);- yield* logInfo("remote update finished", {- requestId: request.requestId,- outcome: next.outcome,- reason: next.reason ?? null,- });return true;+ }+ yield* Ref.set(+ preparedUpdateRef,+ Option.some({+ requestId: request.requestId,+ downloadedVersion: state.downloadedVersion,+ status: "prepared",+ expiresAt:+ (yield* Clock.currentTimeMillis) + Duration.toMillis(PREPARED_UPDATE_TTL),+ }),+ );+ yield* publishReport(state, { outcome: "ready-to-install" }, request.requestId);+ yield* logInfo("remote update prepared", { requestId: request.requestId });+ return true;}- });+ case "done":+ yield* publishReport(+ state,+ {+ outcome: next.outcome,+ ...(next.reason === undefined ? {} : { reason: next.reason }),+ },+ request.requestId,+ );+ yield* logInfo("remote update finished", {+ requestId: request.requestId,+ outcome: next.outcome,+ reason: next.reason ?? null,+ });+ return true;+ }+ });yield* Effect.raceFirst(Effect.gen(function* () {diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.tsindex d3d5b9877be..25877552671 100644--- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts+++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts@@ -599,141 +599,70 @@ export const formatMissingToolsReason = (return `WSL distro is missing required tools: ${issues.join(", ")}. Install ${remediations.join(" and ")}, then retry.`;};-const probeWslRuntimeImpl = (+const probeWslRuntimeImpl = Effect.fn("DesktopWslEnvironment.probeWslRuntimeImpl")(function* (distro: string | null,linuxAppRoot: string,-): Effect.Effect<ProbeWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> =>- Effect.gen(function* () {- const probe = yield* runWslShell(- distro,- buildWslRuntimeProbeScript(linuxAppRoot),- PROBE_TIMEOUT,- {- resolveNode: false,- },- );- const transportFailureReason = formatWslShellTransportFailureReason(- probe.transportFailure,- "the staged runtime",- );- if (transportFailureReason !== null) {- return { ok: false, reason: transportFailureReason } as const;- }- if (probe.exitCode !== 0) {- const trimmedTail = probe.stderr.trim().slice(-500);- return {- ok: false,- reason: `${linuxAppRoot}/t3 --version failed (exit ${probe.exitCode})${trimmedTail ? `: ${trimmedTail}` : ""}`,- } as const;- }- const resolvedPath = parseResolvedPath(probe.stdout);- if (resolvedPath === null) {- return {- ok: false,- reason: "WSL login-shell PATH could not be resolved during backend preflight.",- } as const;- }- return { ok: true, resolvedPath } as const;- });+): Effect.fn.Return<ProbeWslRuntimeResult, never, ChildProcessSpawner.ChildProcessSpawner> {+ const probe = yield* runWslShell(+ distro,+ buildWslRuntimeProbeScript(linuxAppRoot),+ PROBE_TIMEOUT,+ {+ resolveNode: false,+ },+ );+ const transportFailureReason = formatWslShellTransportFailureReason(+ probe.transportFailure,+ "the staged runtime",+ );+ if (transportFailureReason !== null) {+ return { ok: false, reason: transportFailureReason } as const;+ }+ if (probe.exitCode !== 0) {+ const trimmedTail = probe.stderr.trim().slice(-500);+ return {+ ok: false,+ reason: `${linuxAppRoot}/t3 --version failed (exit ${probe.exitCode})${trimmedTail ? `: ${trimmedTail}` : ""}`,+ } as const;+ }+ const resolvedPath = parseResolvedPath(probe.stdout);+ if (resolvedPath === null) {+ return {+ ok: false,+ reason: "WSL login-shell PATH could not be resolved during backend preflight.",+ } as const;+ }+ return { ok: true, resolvedPath } as const;+});-const ensureNodePtyImpl = (+const ensureNodePtyImpl = Effect.fn("DesktopWslEnvironment.ensureNodePtyImpl")(function* (distro: string | null,linuxRepoRoot: string,options: EnsureWslNodePtyOptions = {},-): Effect.Effect<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> =>- Effect.gen(function* () {- // node-pty lives in the apps/server workspace's node_modules; resolve from- // there rather than the monorepo root, where Bun's hoist layout omits it.- const linuxServerDir = `${linuxRepoRoot}/apps/server`;+): Effect.fn.Return<EnsureWslNodePtyResult, never, ChildProcessSpawner.ChildProcessSpawner> {+ // node-pty lives in the apps/server workspace's node_modules; resolve from+ // there rather than the monorepo root, where Bun's hoist layout omits it.+ const linuxServerDir = `${linuxRepoRoot}/apps/server`;- const probe = yield* runWslShell(- distro,- NODE_PTY_PROBE_SCRIPT(linuxServerDir),- PROBE_TIMEOUT,- options,- );- const nodePath = parseNodePath(probe.stdout);- const resolvedPath = parseResolvedPath(probe.stdout);-- const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);- if (transportFailureReason !== null) {- return {- ok: false,- reason: transportFailureReason,- fatal: false,- } as const;- }-- if (nodePath === null) {- const toolchainCheck = yield* runWslShell(- distro,- TOOLCHAIN_CHECK_SCRIPT,- TOOLCHAIN_TIMEOUT,- options,- );- const toolchainTransportFailure = formatWslShellTransportFailureReason(- toolchainCheck.transportFailure,- );- if (toolchainTransportFailure !== null) {- return {- ok: false,- reason: toolchainTransportFailure,- fatal: false,- retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,- } as const;- }- const report = parseToolchainReport(toolchainCheck.stdout);- const reason =- formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null) ??- "Node.js was not found in the WSL distro. Install it (e.g. via nvm) and restart the desktop app.";- return { ok: false, reason, fatal: true } as const;- }-- if (resolvedPath === null) {- return {- ok: false,- reason: "WSL login-shell PATH could not be resolved during backend preflight.",- fatal: true,- } as const;- }-- if (probe.exitCode === 3) {- return {- ok: false,- reason:- '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.',- fatal: true,- } as const;- }-- if (probe.exitCode === 0) {- const rawVersion = parseNodeVersion(probe.stdout);- if (- rawVersion !== null &&- options.nodeEngineRange &&- !satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())- ) {- const range = options.nodeEngineRange.trim();- return {- ok: false,- reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,- fatal: true,- } as const;- }- return { ok: true, nodePath, resolvedPath } as const;- }+ const probe = yield* runWslShell(+ distro,+ NODE_PTY_PROBE_SCRIPT(linuxServerDir),+ PROBE_TIMEOUT,+ options,+ );+ const nodePath = parseNodePath(probe.stdout);+ const resolvedPath = parseResolvedPath(probe.stdout);- if (options.allowBuild !== true) {- const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);- if (packagedProbeFailure !== null) {- return {- ok: false,- reason: packagedProbeFailure,- fatal: true,- } as const;- }- }+ const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);+ if (transportFailureReason !== null) {+ return {+ ok: false,+ reason: transportFailureReason,+ fatal: false,+ } as const;+ }+ if (nodePath === null) {const toolchainCheck = yield* runWslShell(distro,TOOLCHAIN_CHECK_SCRIPT,@@ -752,55 +681,124 @@ const ensureNodePtyImpl = (} as const;}const report = parseToolchainReport(toolchainCheck.stdout);+ const reason =+ formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null) ??+ "Node.js was not found in the WSL distro. Install it (e.g. via nvm) and restart the desktop app.";+ return { ok: false, reason, fatal: true } as const;+ }- if (options.allowBuild !== true) {- // Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp,- // or network is needed — and we must not nag the user to install build- // tools they don't need.- const nodeOnlyReason = formatMissingToolsReason(- {- missingTools: report.missingTools.filter((tool) => tool === "node"),- nodeVersion: report.nodeVersion,- },- options.nodeEngineRange?.trim() || null,- );+ if (resolvedPath === null) {+ return {+ ok: false,+ reason: "WSL login-shell PATH could not be resolved during backend preflight.",+ fatal: true,+ } as const;+ }++ if (probe.exitCode === 3) {+ return {+ ok: false,+ reason:+ '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.',+ fatal: true,+ } as const;+ }++ if (probe.exitCode === 0) {+ const rawVersion = parseNodeVersion(probe.stdout);+ if (+ rawVersion !== null &&+ options.nodeEngineRange &&+ !satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())+ ) {+ const range = options.nodeEngineRange.trim();return {ok: false,- reason:- nodeOnlyReason ??- "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`.",+ reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,fatal: true,} as const;}+ return { ok: true, nodePath, resolvedPath } as const;+ }- const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);- if (missingReason !== null) {- return { ok: false, reason: missingReason, fatal: true } as const;- }-- const build = yield* runWslShell(- distro,- NODE_PTY_BUILD_SCRIPT(linuxServerDir),- BUILD_TIMEOUT,- options,- );- const buildTransportFailure = formatWslShellTransportFailureReason(build.transportFailure);- if (buildTransportFailure !== null) {+ if (options.allowBuild !== true) {+ const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);+ if (packagedProbeFailure !== null) {return {ok: false,- reason: buildTransportFailure,- fatal: false,- retryLimit: BUILD_TRANSPORT_RETRY_LIMIT,+ reason: packagedProbeFailure,+ fatal: true,} as const;}- if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;- const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500);+ }++ const toolchainCheck = yield* runWslShell(+ distro,+ TOOLCHAIN_CHECK_SCRIPT,+ TOOLCHAIN_TIMEOUT,+ options,+ );+ const toolchainTransportFailure = formatWslShellTransportFailureReason(+ toolchainCheck.transportFailure,+ );+ if (toolchainTransportFailure !== null) {+ return {+ ok: false,+ reason: toolchainTransportFailure,+ fatal: false,+ retryLimit: TOOLCHAIN_TRANSPORT_RETRY_LIMIT,+ } as const;+ }+ const report = parseToolchainReport(toolchainCheck.stdout);++ if (options.allowBuild !== true) {+ // Packaged builds ship a prebuilt Linux node-pty, so no compiler, node-gyp,+ // or network is needed — and we must not nag the user to install build+ // tools they don't need.+ const nodeOnlyReason = formatMissingToolsReason(+ {+ missingTools: report.missingTools.filter((tool) => tool === "node"),+ nodeVersion: report.nodeVersion,+ },+ options.nodeEngineRange?.trim() || null,+ );return {ok: false,- reason: `node-pty Linux build failed (exit ${build.exitCode}): ${trimmedTail || "no stderr captured"}`,+ reason:+ nodeOnlyReason ??+ "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`.",fatal: true,} as const;- });+ }++ const missingReason = formatMissingToolsReason(report, options.nodeEngineRange?.trim() || null);+ if (missingReason !== null) {+ return { ok: false, reason: missingReason, fatal: true } as const;+ }++ const build = yield* runWslShell(+ distro,+ NODE_PTY_BUILD_SCRIPT(linuxServerDir),+ BUILD_TIMEOUT,+ options,+ );+ const buildTransportFailure = formatWslShellTransportFailureReason(build.transportFailure);+ if (buildTransportFailure !== null) {+ return {+ ok: false,+ reason: buildTransportFailure,+ fatal: false,+ retryLimit: BUILD_TRANSPORT_RETRY_LIMIT,+ } as const;+ }+ if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;+ const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500);+ return {+ ok: false,+ reason: `node-pty Linux build failed (exit ${build.exitCode}): ${trimmedTail || "no stderr captured"}`,+ fatal: true,+ } as const;+});const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(function* (distro: string | null,@@ -1059,17 +1057,16 @@ const getUserHomeImpl = (Effect.orElseSucceed(() => Option.none<string>()),);-const makeIsAvailable = (+const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable")(function* (platform: NodeJS.Platform,windir: string,-): Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path> =>- Effect.gen(function* () {- if (platform !== "win32") return false;- const path = yield* Path.Path;- const fileSystem = yield* FileSystem.FileSystem;- const wslExePath = path.join(windir, "System32", "wsl.exe");- return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));- });+): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {+ if (platform !== "win32") return false;+ const path = yield* Path.Path;+ const fileSystem = yield* FileSystem.FileSystem;+ const wslExePath = path.join(windir, "System32", "wsl.exe");+ return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));+});export interface DesktopWslEnvironmentTestStub {readonly isAvailable?: boolean;diff --git a/apps/desktop/src/wsl/DesktopWslServerTree.ts b/apps/desktop/src/wsl/DesktopWslServerTree.tsindex 37d5d78d9b6..61a461787aa 100644--- a/apps/desktop/src/wsl/DesktopWslServerTree.ts+++ b/apps/desktop/src/wsl/DesktopWslServerTree.ts@@ -48,22 +48,25 @@ export class DesktopWslServerTree extends Context.Service<}>()("@t3tools/desktop/wsl/DesktopWslServerTree") {}-export const forEachBoundedTree = <Node, E, R>(+export const forEachBoundedTree = Effect.fn("DesktopWslServerTree.forEachBoundedTree")(function* <+ Node,+ E,+ R,+>(roots: ReadonlyArray<Node>,visit: (node: Node) => Effect.Effect<ReadonlyArray<Node>, E, R>,-): Effect.Effect<void, E, R> =>- Effect.gen(function* () {- const pending = [...roots];- while (pending.length > 0) {- const batch = pending.splice(-COPY_CONCURRENCY);- const children = yield* Effect.forEach(batch, visit, {- concurrency: COPY_CONCURRENCY,- });- for (const entries of children) {- pending.push(...entries);- }+): Effect.fn.Return<void, E, R> {+ const pending = [...roots];+ while (pending.length > 0) {+ const batch = pending.splice(-COPY_CONCURRENCY);+ const children = yield* Effect.forEach(batch, visit, {+ concurrency: COPY_CONCURRENCY,+ });+ for (const entries of children) {+ pending.push(...entries);}- });+ }+});interface CopyTreeEntry {readonly sourcePath: string;diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.tsindex cccb7056cb2..4ab65816c7f 100644--- a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts+++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts@@ -255,8 +255,8 @@ function iosMajorVersion(): number {return Number.isFinite(major) ? major : 18;}-function nativePushTokenRegistration(observedPushToken?: string) {- return Effect.gen(function* () {+const nativePushTokenRegistration = Effect.fn("remoteRegistration.nativePushTokenRegistration")(+ function* (observedPushToken?: string) {if (!canRegisterPushNotifications() || !supportsAgentAwarenessPush()) {return { notificationsEnabled: false, pushToken: null };}@@ -294,22 +294,21 @@ function nativePushTokenRegistration(observedPushToken?: string) {? token.data.trim(): null;return { notificationsEnabled: pushToken !== null, pushToken };- });-}+ },+);-const relayToken = (+const relayToken = Effect.fn("remoteRegistration.relayToken")(function* (operation: "read-device-registration-relay-token" | "read-live-activity-registration-relay-token",-) =>- Effect.gen(function* () {- const provider = relayTokenProvider;- if (!provider) {- return null;- }- return yield* Effect.tryPromise({- try: provider,- catch: (cause) => new AgentAwarenessOperationError({ operation, cause }),- });+) {+ const provider = relayTokenProvider;+ if (!provider) {+ return null;+ }+ return yield* Effect.tryPromise({+ try: provider,+ catch: (cause) => new AgentAwarenessOperationError({ operation, cause }),});+});function registrationSignature(body: RelayDeviceRegistrationRequest): string {return [@@ -331,112 +330,110 @@ function registrationSignature(body: RelayDeviceRegistrationRequest): string {].join("|");}-function registerDeviceWithRelay(+const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWithRelay")(function* (body: RelayDeviceRegistrationRequest,expectedGeneration: number,-): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {- return Effect.gen(function* () {- if (expectedGeneration !== deviceRegistrationGeneration) {- logRegistrationDebug("device registration cancelled before relay request", {- expectedGeneration,- currentGeneration: deviceRegistrationGeneration,- });- return;- }- const relayConfig = readRelayConfig();- if (!relayConfig) {- setRegistrationStatus("unknown");- return;- }- const token = yield* relayToken("read-device-registration-relay-token");- if (expectedGeneration !== deviceRegistrationGeneration) {- logRegistrationDebug("device registration cancelled after auth lookup", {- expectedGeneration,- currentGeneration: deviceRegistrationGeneration,- });- return;- }- if (!token) {- logRegistrationDebug("relay device registration skipped; user is not signed in");- setRegistrationStatus("unknown");- return;- }-- const identity = relayTokenProviderIdentity ?? "";- const persisted = yield* Effect.tryPromise({- try: () => loadAgentAwarenessRegistrationRecord(),- catch: (cause) => cause,- }).pipe(Effect.orElseSucceed(() => null));- if (expectedGeneration !== deviceRegistrationGeneration) {- // Signed out while the record loaded — do not resurrect the cleared- // record or report the previous account's registration as current.- logRegistrationDebug("device registration cancelled after record lookup", {- expectedGeneration,- currentGeneration: deviceRegistrationGeneration,- });- return;- }- const payload = body;- const signature = `${relayConfig.url}|${registrationSignature(payload)}`;- // Android registration also silently replays the current card. Collapse- // foreground bursts, but repair missed pushes on cold start or a return- // after time away, just like re-registering an iOS activity token.- const needsAndroidReplay =- body.platform === "android" &&- (androidDeviceReplayedAt === null ||- Date.now() - androidDeviceReplayedAt >= ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS);- if (- persisted &&- persisted.identity === identity &&- persisted.signature === signature &&- !needsAndroidReplay- ) {- setRegistrationStatus("registered");- logRegistrationDebug("relay device registration skipped; already registered for account", {- expectedGeneration,- });- return;- }-- const client = yield* ManagedRelay.ManagedRelayClient;- logRegistrationDebug("relay device registration request started", {+): Effect.fn.Return<void, unknown, ManagedRelay.ManagedRelayClient> {+ if (expectedGeneration !== deviceRegistrationGeneration) {+ logRegistrationDebug("device registration cancelled before relay request", {expectedGeneration,+ currentGeneration: deviceRegistrationGeneration,});- yield* client.registerDevice({- clerkToken: token,- payload,+ return;+ }+ const relayConfig = readRelayConfig();+ if (!relayConfig) {+ setRegistrationStatus("unknown");+ return;+ }+ const token = yield* relayToken("read-device-registration-relay-token");+ if (expectedGeneration !== deviceRegistrationGeneration) {+ logRegistrationDebug("device registration cancelled after auth lookup", {+ expectedGeneration,+ currentGeneration: deviceRegistrationGeneration,});- if (expectedGeneration !== deviceRegistrationGeneration) {- // Signed out while the request was in flight: the sign-out path already- // reset the status and cleared the record for the next account, so a- // stale success must not overwrite either.- logRegistrationDebug("device registration completed after sign-out; result discarded", {- expectedGeneration,- currentGeneration: deviceRegistrationGeneration,- });- return;- }- if (body.platform === "android") androidDeviceReplayedAt = Date.now();+ return;+ }+ if (!token) {+ logRegistrationDebug("relay device registration skipped; user is not signed in");+ setRegistrationStatus("unknown");+ return;+ }++ const identity = relayTokenProviderIdentity ?? "";+ const persisted = yield* Effect.tryPromise({+ try: () => loadAgentAwarenessRegistrationRecord(),+ catch: (cause) => cause,+ }).pipe(Effect.orElseSucceed(() => null));+ if (expectedGeneration !== deviceRegistrationGeneration) {+ // Signed out while the record loaded — do not resurrect the cleared+ // record or report the previous account's registration as current.+ logRegistrationDebug("device registration cancelled after record lookup", {+ expectedGeneration,+ currentGeneration: deviceRegistrationGeneration,+ });+ return;+ }+ const payload = body;+ const signature = `${relayConfig.url}|${registrationSignature(payload)}`;+ // Android registration also silently replays the current card. Collapse+ // foreground bursts, but repair missed pushes on cold start or a return+ // after time away, just like re-registering an iOS activity token.+ const needsAndroidReplay =+ body.platform === "android" &&+ (androidDeviceReplayedAt === null ||+ Date.now() - androidDeviceReplayedAt >= ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS);+ if (+ persisted &&+ persisted.identity === identity &&+ persisted.signature === signature &&+ !needsAndroidReplay+ ) {setRegistrationStatus("registered");- yield* Effect.promise(() =>- saveAgentAwarenessRegistrationRecord({- identity,- signature,- }).catch((error: unknown) => {- logRegistrationError("persist registration record failed", error);- }),- );- logRegistrationDebug("relay device registration request completed", {+ logRegistrationDebug("relay device registration skipped; already registered for account", {expectedGeneration,});+ return;+ }++ const client = yield* ManagedRelay.ManagedRelayClient;+ logRegistrationDebug("relay device registration request started", {+ expectedGeneration,});-}+ yield* client.registerDevice({+ clerkToken: token,+ payload,+ });+ if (expectedGeneration !== deviceRegistrationGeneration) {+ // Signed out while the request was in flight: the sign-out path already+ // reset the status and cleared the record for the next account, so a+ // stale success must not overwrite either.+ logRegistrationDebug("device registration completed after sign-out; result discarded", {+ expectedGeneration,+ currentGeneration: deviceRegistrationGeneration,+ });+ return;+ }+ if (body.platform === "android") androidDeviceReplayedAt = Date.now();+ setRegistrationStatus("registered");+ yield* Effect.promise(() =>+ saveAgentAwarenessRegistrationRecord({+ identity,+ signature,+ }).catch((error: unknown) => {+ logRegistrationError("persist registration record failed", error);+ }),+ );+ logRegistrationDebug("relay device registration request completed", {+ expectedGeneration,+ });+});-function unregisterDeviceWithRelay(input: {- readonly deviceId: string;- readonly tokenProvider: () => Promise<string | null>;-}): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {- return Effect.gen(function* () {+const unregisterDeviceWithRelay = Effect.fn("remoteRegistration.unregisterDeviceWithRelay")(+ function* (input: {+ readonly deviceId: string;+ readonly tokenProvider: () => Promise<string | null>;+ }): Effect.fn.Return<void, unknown, ManagedRelay.ManagedRelayClient> {if (!readRelayConfig()) return;const token = yield* Effect.tryPromise({try: input.tokenProvider,@@ -456,8 +453,8 @@ function unregisterDeviceWithRelay(input: {clerkToken: token,deviceId: input.deviceId,});- });-}+ },+);function environmentPublishesAgentActivity(environmentId: EnvironmentId): boolean {return (@@ -536,12 +533,12 @@ function armAgentAwarenessLiveActivityForLocalWorkNow(input: {}}-function readAgentActivitySnapshot(): Effect.Effect<+const readAgentActivitySnapshot: () => Effect.Effect<RelayAgentActivitySnapshotResponse | null,never,ManagedRelay.ManagedRelayClient-> {- return Effect.gen(function* () {+> = Effect.fn("remoteRegistration.readAgentActivitySnapshot")(+ function* () {if (!readRelayConfig()) return null;const token = yield* relayToken("read-live-activity-registration-relay-token");if (!token) {@@ -549,20 +546,19 @@ function readAgentActivitySnapshot(): Effect.Effect<}const client = yield* ManagedRelay.ManagedRelayClient;return yield* client.getAgentActivitySnapshot({ clerkToken: token });- }).pipe(- Effect.catch((error) =>- Effect.sync(() => {- logRegistrationError("agent activity snapshot read failed", error);- return null;- }),- ),- );-}--function registerLiveActivityWithRelay(- body: RelayLiveActivityRegistrationRequest,-): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {- return Effect.gen(function* () {+ },+ Effect.catch((error) =>+ Effect.sync(() => {+ logRegistrationError("agent activity snapshot read failed", error);+ return null;+ }),+ ),+);++const registerLiveActivityWithRelay = Effect.fn("remoteRegistration.registerLiveActivityWithRelay")(+ function* (+ body: RelayLiveActivityRegistrationRequest,+ ): Effect.fn.Return<boolean, unknown, ManagedRelay.ManagedRelayClient> {if (!readRelayConfig()) return false;const token = yield* relayToken("read-live-activity-registration-relay-token");if (!token) {@@ -576,8 +572,8 @@ function registerLiveActivityWithRelay(payload: body,});return true;- });-}+ },+);function logRegistrationError(context: string, error: unknown): void {if (!__DEV__) {@@ -693,78 +689,76 @@ function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: stristartPendingDeviceRegistration();}-function registerDevice(+const registerDevice = Effect.fn("remoteRegistration.registerDevice")(function* (input: RegisterDeviceInput = {},expectedGeneration = deviceRegistrationGeneration,-): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {- return Effect.gen(function* () {- if (!canRegisterPushNotifications()) {- logRegistrationDebug("device registration skipped; platform does not support it");- return;- }+): Effect.fn.Return<void, unknown, ManagedRelay.ManagedRelayClient> {+ if (!canRegisterPushNotifications()) {+ logRegistrationDebug("device registration skipped; platform does not support it");+ return;+ }- logRegistrationDebug("device registration loading local state", { expectedGeneration });- const [deviceId, storedPreferences] = yield* Effect.all([- Effect.tryPromise({- try: () => loadOrCreateAgentAwarenessDeviceId(),- catch: (cause) =>- new AgentAwarenessOperationError({- operation: "load-device-registration-identifier",- cause,- }),- }),- Effect.tryPromise({- try: () => loadPreferences(),- catch: (cause) =>- new AgentAwarenessOperationError({- operation: "load-device-registration-preferences",- cause,- }),- }),- ]);- const preferences = mergeAgentAwarenessRegistrationPreferences(- storedPreferences,- input.preferencesOverride,- );- if (expectedGeneration !== deviceRegistrationGeneration) return;- if (relayTokenProvider && relayTokenProviderIdentity) {- configureAndroidAgentNotifications(- deviceId,- relayTokenProviderIdentity,- preferences.liveActivitiesEnabled !== false,- );- }- const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);- logRegistrationDebug("device registration local state ready", {- expectedGeneration,- notificationsEnabled: pushTokenRegistration.notificationsEnabled,- });- const bundleId =- Platform.OS === "android"- ? Constants.expoConfig?.android?.package?.trim()- : Constants.expoConfig?.ios?.bundleIdentifier?.trim();- yield* registerDeviceWithRelay(- makeRelayDeviceRegistrationRequest({- deviceId,- label:- Constants.deviceName?.trim() ||- (Platform.OS === "android" ? "Android device" : "iOS device"),- ...(Platform.OS === "android"- ? { platform: "android" as const, androidApiLevel: Number(Platform.Version) }- : { platform: "ios" as const, iosMajorVersion: iosMajorVersion() }),- appVersion: Constants.expoConfig?.version,- ...(bundleId ? { bundleId } : {}),- ...(Platform.OS === "ios"- ? { apsEnvironment: resolveApsEnvironment(Constants.expoConfig?.extra?.appVariant) }- : {}),- ...(pushTokenRegistration.pushToken ? { pushToken: pushTokenRegistration.pushToken } : {}),- notificationsEnabled: pushTokenRegistration.notificationsEnabled,- preferences,- }),- expectedGeneration,+ logRegistrationDebug("device registration loading local state", { expectedGeneration });+ const [deviceId, storedPreferences] = yield* Effect.all([+ Effect.tryPromise({+ try: () => loadOrCreateAgentAwarenessDeviceId(),+ catch: (cause) =>+ new AgentAwarenessOperationError({+ operation: "load-device-registration-identifier",+ cause,+ }),+ }),+ Effect.tryPromise({+ try: () => loadPreferences(),+ catch: (cause) =>+ new AgentAwarenessOperationError({+ operation: "load-device-registration-preferences",+ cause,+ }),+ }),+ ]);+ const preferences = mergeAgentAwarenessRegistrationPreferences(+ storedPreferences,+ input.preferencesOverride,+ );+ if (expectedGeneration !== deviceRegistrationGeneration) return;+ if (relayTokenProvider && relayTokenProviderIdentity) {+ configureAndroidAgentNotifications(+ deviceId,+ relayTokenProviderIdentity,+ preferences.liveActivitiesEnabled !== false,);+ }+ const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);+ logRegistrationDebug("device registration local state ready", {+ expectedGeneration,+ notificationsEnabled: pushTokenRegistration.notificationsEnabled,});-}+ const bundleId =+ Platform.OS === "android"+ ? Constants.expoConfig?.android?.package?.trim()+ : Constants.expoConfig?.ios?.bundleIdentifier?.trim();+ yield* registerDeviceWithRelay(+ makeRelayDeviceRegistrationRequest({+ deviceId,+ label:+ Constants.deviceName?.trim() ||+ (Platform.OS === "android" ? "Android device" : "iOS device"),+ ...(Platform.OS === "android"+ ? { platform: "android" as const, androidApiLevel: Number(Platform.Version) }+ : { platform: "ios" as const, iosMajorVersion: iosMajorVersion() }),+ appVersion: Constants.expoConfig?.version,+ ...(bundleId ? { bundleId } : {}),+ ...(Platform.OS === "ios"+ ? { apsEnvironment: resolveApsEnvironment(Constants.expoConfig?.extra?.appVariant) }+ : {}),+ ...(pushTokenRegistration.pushToken ? { pushToken: pushTokenRegistration.pushToken } : {}),+ notificationsEnabled: pushTokenRegistration.notificationsEnabled,+ preferences,+ }),+ expectedGeneration,+ );+});function registerDeviceForCurrentUser(): Effect.Effect<void,@@ -902,10 +896,12 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {activityPushTokenLocks.clear();}-export function unregisterAgentAwarenessDeviceForCurrentUser(+export const unregisterAgentAwarenessDeviceForCurrentUser: (tokenProvider: () => Promise<string | null>,-): Effect.Effect<void, never, ManagedRelay.ManagedRelayClient> {- return Effect.gen(function* () {+) => Effect.Effect<void, never, ManagedRelay.ManagedRelayClient> = Effect.fn(+ "remoteRegistration.unregisterAgentAwarenessDeviceForCurrentUser",+)(+ function* (tokenProvider: () => Promise<string | null>) {const deviceId = yield* Effect.tryPromise({try: () => loadAgentAwarenessDeviceId(),catch: (cause) =>@@ -918,47 +914,46 @@ export function unregisterAgentAwarenessDeviceForCurrentUser(return;}yield* unregisterDeviceWithRelay({ deviceId, tokenProvider });- }).pipe(- Effect.catch((error) =>- Effect.sync(() => {- logRegistrationError("device unregistration failed", error);- }),- ),- );-}--export function registerLiveActivityPushToken(input: {+ },+ Effect.catch((error) =>+ Effect.sync(() => {+ logRegistrationError("device unregistration failed", error);+ }),+ ),+);++export const registerLiveActivityPushToken = Effect.fn(+ "remoteRegistration.registerLiveActivityPushToken",+)(function* (input: {readonly activity: LiveActivity<AgentActivityProps>;-}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {- return Effect.gen(function* () {- if (!canRegisterRemoteLiveActivities()) {- return false;- }+}): Effect.fn.Return<boolean, unknown, ManagedRelay.ManagedRelayClient> {+ if (!canRegisterRemoteLiveActivities()) {+ return false;+ }- const lock = observeLiveActivityPushTokens(input.activity);- return yield* lock.withPermit(- Effect.gen(function* () {- const activityPushToken = yield* Effect.tryPromise({- try: () => input.activity.getPushToken(),- catch: (cause) =>- new AgentAwarenessOperationError({- operation: "read-live-activity-push-token",- cause,- }),- });- if (!activityPushToken) {- logRegistrationDebug(- "live activity push token not available yet; waiting for token event",- { connectionCount: environmentConnections.size },- );- return false;- }+ const lock = observeLiveActivityPushTokens(input.activity);+ return yield* lock.withPermit(+ Effect.gen(function* () {+ const activityPushToken = yield* Effect.tryPromise({+ try: () => input.activity.getPushToken(),+ catch: (cause) =>+ new AgentAwarenessOperationError({+ operation: "read-live-activity-push-token",+ cause,+ }),+ });+ if (!activityPushToken) {+ logRegistrationDebug(+ "live activity push token not available yet; waiting for token event",+ { connectionCount: environmentConnections.size },+ );+ return false;+ }- return yield* registerLiveActivityPushTokenValue({ activityPushToken });- }),- );- });-}+ return yield* registerLiveActivityPushTokenValue({ activityPushToken });+ }),+ );+});// iOS can replace an activity's push token while it runs, not only deliver a// late first one. The relay keeps pushing to the old token until APNs rejects@@ -984,38 +979,35 @@ function observeLiveActivityPushTokens(return lock;}-function registerLiveActivityPushTokenValue(input: {+const registerLiveActivityPushTokenValue = Effect.fn(+ "remoteRegistration.registerLiveActivityPushTokenValue",+)(function* (input: {readonly activityPushToken: string;-}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {- return Effect.gen(function* () {- const acceptedAt = registeredActivityPushTokens.get(input.activityPushToken);- if (- acceptedAt !== undefined &&- Date.now() - acceptedAt < ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS- ) {- return true;- }- const deviceId = yield* Effect.tryPromise({- try: () => loadOrCreateAgentAwarenessDeviceId(),- catch: (cause) =>- new AgentAwarenessOperationError({- operation: "load-live-activity-registration-identifier",- cause,- }),- });- const registered = yield* registerLiveActivityWithRelay({- deviceId,- activityPushToken: input.activityPushToken,- });- if (registered) {- registeredActivityPushTokens.set(input.activityPushToken, Date.now());- logRegistrationDebug("live activity push token registered", {- tokenSuffix: input.activityPushToken.slice(-8),- });- }- return registered;+}): Effect.fn.Return<boolean, unknown, ManagedRelay.ManagedRelayClient> {+ const acceptedAt = registeredActivityPushTokens.get(input.activityPushToken);+ if (acceptedAt !== undefined && Date.now() - acceptedAt < ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS) {+ return true;+ }+ const deviceId = yield* Effect.tryPromise({+ try: () => loadOrCreateAgentAwarenessDeviceId(),+ catch: (cause) =>+ new AgentAwarenessOperationError({+ operation: "load-live-activity-registration-identifier",+ cause,+ }),});-}+ const registered = yield* registerLiveActivityWithRelay({+ deviceId,+ activityPushToken: input.activityPushToken,+ });+ if (registered) {+ registeredActivityPushTokens.set(input.activityPushToken, Date.now());+ logRegistrationDebug("live activity push token registered", {+ tokenSuffix: input.activityPushToken.slice(-8),+ });+ }+ return registered;+});function scheduleActiveLiveActivityRegistrationRetry(): void {if (activeLiveActivityRegistrationRetry || !relayTokenProvider) {@@ -1031,117 +1023,113 @@ function scheduleActiveLiveActivityRegistrationRetry(): void {}, REMOTE_ACTIVITY_REGISTRATION_RETRY_MS);}-export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<- void,- never,- ManagedRelay.ManagedRelayClient-> {- return Effect.gen(function* () {- if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {- return;+export const refreshActiveLiveActivityRemoteRegistration = Effect.fn(+ "remoteRegistration.refreshActiveLiveActivityRemoteRegistration",+)(function* (): Effect.fn.Return<void, never, ManagedRelay.ManagedRelayClient> {+ if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {+ return;+ }++ let activities = yield* Effect.try({+ try: () => getAgentLiveActivities(),+ catch: (cause) =>+ new AgentAwarenessOperationError({+ operation: "list-active-live-activities",+ cause,+ }),+ }).pipe(+ Effect.catch((error) =>+ Effect.sync(() => {+ logRegistrationError("active live activity lookup failed", error);+ return [] as ReadonlyArray<LiveActivity<AgentActivityProps>>;+ }),+ ),+ );++ // The relay tracks exactly one card per device; if concurrent arming ever+ // produced extras, end them so only one keeps receiving updates.+ if (activities.length > 1) {+ for (const extra of activities.slice(1)) {+ extra.end("immediate").catch((error: unknown) => {+ logRegistrationError("duplicate live activity cleanup failed", error);+ });}+ activities = activities.slice(0, 1);+ }- let activities = yield* Effect.try({- try: () => getAgentLiveActivities(),+ // Activities are only ever created here, in the foreground, where the+ // update token can be observed and registered immediately — the relay never+ // remote-starts one (background push-to-start wakes proved too unreliable+ // to hand the token over).+ if (activities.length === 0) {+ const preferences = yield* Effect.tryPromise({+ try: () => loadPreferences(),catch: (cause) =>new AgentAwarenessOperationError({- operation: "list-active-live-activities",+ operation: "load-live-activity-prime-preferences",cause,}),- }).pipe(- Effect.catch((error) =>- Effect.sync(() => {- logRegistrationError("active live activity lookup failed", error);- return [] as ReadonlyArray<LiveActivity<AgentActivityProps>>;- }),- ),- );-- // The relay tracks exactly one card per device; if concurrent arming ever- // produced extras, end them so only one keeps receiving updates.- if (activities.length > 1) {- for (const extra of activities.slice(1)) {- extra.end("immediate").catch((error: unknown) => {- logRegistrationError("duplicate live activity cleanup failed", error);- });- }- activities = activities.slice(0, 1);- }-- // Activities are only ever created here, in the foreground, where the- // update token can be observed and registered immediately — the relay never- // remote-starts one (background push-to-start wakes proved too unreliable- // to hand the token over).- if (activities.length === 0) {- const preferences = yield* Effect.tryPromise({- try: () => loadPreferences(),- catch: (cause) =>- new AgentAwarenessOperationError({- operation: "load-live-activity-prime-preferences",- cause,- }),- }).pipe(Effect.orElseSucceed(() => null));- if (preferences?.liveActivitiesEnabled !== false) {- const snapshot = yield* readAgentActivitySnapshot();- // The snapshot request yields; an arm-on-send may have created the- // card in the meantime. Re-check so two cards are never started.- const armedMeanwhile = yield* Effect.try({- try: () => getAgentLiveActivities(),- catch: () => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>,- }).pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>));- if (armedMeanwhile.length > 0) {- activities = [...armedMeanwhile];- } else if (snapshot?.aggregate && snapshot.aggregate.activeCount > 0) {- const aggregate = snapshot.aggregate;- const primed = yield* Effect.try({- try: () =>- startAgentLiveActivity(- {- title: aggregate.title,- subtitle: aggregate.subtitle,- activeCount: aggregate.activeCount,- updatedAt: aggregate.updatedAt,- activities: aggregate.activities,- },- liveActivityStaleDate(),- ),- catch: (cause) =>- new AgentAwarenessOperationError({- operation: "prime-live-activity",- cause,- }),- }).pipe(- Effect.catch((error) =>- Effect.sync(() => {- logRegistrationError("live activity priming failed", error);- return null;- }),+ }).pipe(Effect.orElseSucceed(() => null));+ if (preferences?.liveActivitiesEnabled !== false) {+ const snapshot = yield* readAgentActivitySnapshot();+ // The snapshot request yields; an arm-on-send may have created the+ // card in the meantime. Re-check so two cards are never started.+ const armedMeanwhile = yield* Effect.try({+ try: () => getAgentLiveActivities(),+ catch: () => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>,+ }).pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>));+ if (armedMeanwhile.length > 0) {+ activities = [...armedMeanwhile];+ } else if (snapshot?.aggregate && snapshot.aggregate.activeCount > 0) {+ const aggregate = snapshot.aggregate;+ const primed = yield* Effect.try({+ try: () =>+ startAgentLiveActivity(+ {+ title: aggregate.title,+ subtitle: aggregate.subtitle,+ activeCount: aggregate.activeCount,+ updatedAt: aggregate.updatedAt,+ activities: aggregate.activities,+ },+ liveActivityStaleDate(),),- );- if (primed) {- logRegistrationDebug("live activity card primed", {- activeCount: aggregate.activeCount,- });- activities = [primed];- }+ catch: (cause) =>+ new AgentAwarenessOperationError({+ operation: "prime-live-activity",+ cause,+ }),+ }).pipe(+ Effect.catch((error) =>+ Effect.sync(() => {+ logRegistrationError("live activity priming failed", error);+ return null;+ }),+ ),+ );+ if (primed) {+ logRegistrationDebug("live activity card primed", {+ activeCount: aggregate.activeCount,+ });+ activities = [primed];}}}+ }- const registrationResults = yield* Effect.forEach(activities, (activity) =>- registerLiveActivityPushToken({ activity }).pipe(- Effect.map((registered) => !registered),- Effect.catch((error) =>- Effect.sync(() => {- logRegistrationError("active live activity token registration failed", error);- return true;- }),- ),+ const registrationResults = yield* Effect.forEach(activities, (activity) =>+ registerLiveActivityPushToken({ activity }).pipe(+ Effect.map((registered) => !registered),+ Effect.catch((error) =>+ Effect.sync(() => {+ logRegistrationError("active live activity token registration failed", error);+ return true;+ }),),- );+ ),+ );- if (registrationResults.some(Boolean)) {- scheduleActiveLiveActivityRegistrationRetry();- }- });-}+ if (registrationResults.some(Boolean)) {+ scheduleActiveLiveActivityRegistrationRetry();+ }+});diff --git a/apps/mobile/src/features/cloud/dpop.ts b/apps/mobile/src/features/cloud/dpop.tsindex da2e6187c1d..a3263ddc770 100644--- a/apps/mobile/src/features/cloud/dpop.ts+++ b/apps/mobile/src/features/cloud/dpop.ts@@ -165,12 +165,8 @@ function privateJwkFromPrivateKey(return { ...publicJwk, d: Base64Url.encode(privateKey) };}-export function generateDpopProofKeyPair(): Effect.Effect<- DpopProofKeyPair,- CloudDpopError,- Crypto.Crypto-> {- return Effect.gen(function* () {+export const generateDpopProofKeyPair = Effect.fn("dpop.generateDpopProofKeyPair")(+ function* (): Effect.fn.Return<DpopProofKeyPair, CloudDpopError, Crypto.Crypto> {let privateKey: Uint8Array;do {privateKey = yield* secureRandomBytes(@@ -188,15 +184,11 @@ export function generateDpopProofKeyPair(): Effect.Effect<publicJwk,thumbprint,};- });-}+ },+);-export function loadOrCreateDpopProofKeyPair(): Effect.Effect<- DpopProofKeyPair,- CloudDpopError,- Crypto.Crypto-> {- return Effect.gen(function* () {+export const loadOrCreateDpopProofKeyPair = Effect.fn("dpop.loadOrCreateDpopProofKeyPair")(+ function* (): Effect.fn.Return<DpopProofKeyPair, CloudDpopError, Crypto.Crypto> {const stored = yield* Effect.tryPromise({try: () => SecureStore.getItemAsync(DPOP_PROOF_KEY_STORAGE_KEY),catch: cloudDpopError("Could not read the DPoP proof key."),@@ -233,8 +225,8 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<catch: cloudDpopError("Could not store the DPoP proof key."),});return generated;- });-}+ },+);function normalizeHtu(url: string): Effect.Effect<string, CloudDpopError> {const normalized = normalizeDpopHtu(url);@@ -243,60 +235,56 @@ function normalizeHtu(url: string): Effect.Effect<string, CloudDpopError> {: Effect.fail(new CloudDpopError({ message: "DPoP URL is invalid." }));}-export function createDpopProof(input: {+export const createDpopProof = Effect.fn("dpop.createDpopProof")(function* (input: {readonly method: string;readonly url: string;readonly accessToken?: string;readonly proofKey?: DpopProofKeyPair;-}): Effect.Effect<+}): Effect.fn.Return<{ readonly proof: string; readonly thumbprint: string },CloudDpopError,Crypto.Crypto> {- return Effect.gen(function* () {- const keyPair = input.proofKey ?? (yield* generateDpopProofKeyPair());- const privateKey = yield* Effect.try({- try: () => base64UrlToBytes(keyPair.privateJwk.d),- catch: cloudDpopError("Could not import DPoP private key."),- });- const nowMs = yield* Clock.currentTimeMillis;- const jti = yield* Crypto.Crypto.pipe(- Effect.flatMap((crypto) => crypto.randomUUIDv4()),- Effect.mapError(cloudDpopError("Could not generate DPoP proof identifier.")),- );- const htu = yield* normalizeHtu(input.url);- const header = yield* encodeDpopJwtHeaderJson({- typ: "dpop+jwt",- alg: "ES256",- jwk: keyPair.publicJwk,- }).pipe(- Effect.map(Base64Url.encode),- Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")),- );- const ath = input.accessToken- ? yield* computeDpopAccessTokenHashEffect(input.accessToken)- : null;- const payload = yield* encodeDpopJwtPayloadJson({- htm: input.method.toUpperCase(),- htu,- jti,- iat: Math.floor(nowMs / 1_000),- ...(ath ? { ath } : {}),- }).pipe(- Effect.map(Base64Url.encode),- Effect.mapError(cloudDpopError("Could not encode DPoP proof payload.")),- );- const signatureInputHash = yield* sha256Digest(- new TextEncoder().encode(`${header}.${payload}`),- "Could not hash DPoP signing input.",- );- const signature = yield* Effect.try({- try: () => p256.sign(signatureInputHash, privateKey, { prehash: false }).toCompactRawBytes(),- catch: cloudDpopError("Could not sign DPoP proof."),- });- return {- proof: `${header}.${payload}.${Base64Url.encode(signature)}`,- thumbprint: keyPair.thumbprint,- };+ const keyPair = input.proofKey ?? (yield* generateDpopProofKeyPair());+ const privateKey = yield* Effect.try({+ try: () => base64UrlToBytes(keyPair.privateJwk.d),+ catch: cloudDpopError("Could not import DPoP private key."),});-}+ const nowMs = yield* Clock.currentTimeMillis;+ const jti = yield* Crypto.Crypto.pipe(+ Effect.flatMap((crypto) => crypto.randomUUIDv4()),+ Effect.mapError(cloudDpopError("Could not generate DPoP proof identifier.")),+ );+ const htu = yield* normalizeHtu(input.url);+ const header = yield* encodeDpopJwtHeaderJson({+ typ: "dpop+jwt",+ alg: "ES256",+ jwk: keyPair.publicJwk,+ }).pipe(+ Effect.map(Base64Url.encode),+ Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")),+ );+ const ath = input.accessToken ? yield* computeDpopAccessTokenHashEffect(input.accessToken) : null;+ const payload = yield* encodeDpopJwtPayloadJson({+ htm: input.method.toUpperCase(),+ htu,+ jti,+ iat: Math.floor(nowMs / 1_000),+ ...(ath ? { ath } : {}),+ }).pipe(+ Effect.map(Base64Url.encode),+ Effect.mapError(cloudDpopError("Could not encode DPoP proof payload.")),+ );+ const signatureInputHash = yield* sha256Digest(+ new TextEncoder().encode(`${header}.${payload}`),+ "Could not hash DPoP signing input.",+ );+ const signature = yield* Effect.try({+ try: () => p256.sign(signatureInputHash, privateKey, { prehash: false }).toCompactRawBytes(),+ catch: cloudDpopError("Could not sign DPoP proof."),+ });+ return {+ proof: `${header}.${payload}.${Base64Url.encode(signature)}`,+ thumbprint: keyPair.thumbprint,+ };+});diff --git a/apps/mobile/src/features/cloud/linkEnvironment.ts b/apps/mobile/src/features/cloud/linkEnvironment.tsindex ee5e4a2fc54..3aef6925293 100644--- a/apps/mobile/src/features/cloud/linkEnvironment.ts+++ b/apps/mobile/src/features/cloud/linkEnvironment.ts@@ -153,87 +153,87 @@ type LinkEnvironmentToCloudRequirements =| ManagedRelay.ManagedRelayClient| MobileStorage.MobileStorage;-export function linkEnvironmentToCloudWithPreference(+export const linkEnvironmentToCloudWithPreference = Effect.fn(+ "linkEnvironment.linkEnvironmentToCloudWithPreference",+)(function* (input: LinkEnvironmentToCloudInput & { readonly liveActivitiesEnabled: boolean },-): Effect.Effect<void, CloudEnvironmentLinkError, LinkEnvironmentToCloudRequirements> {- return Effect.gen(function* () {- if (!input.connection.bearerToken) {- return yield* new CloudEnvironmentLinkError({- message: "Only a locally paired bearer connection can be linked to the cloud.",- });- }- const localBearerToken = input.connection.bearerToken;- const relayUrl = yield* requireRelayUrl();- const relayClient = yield* ManagedRelay.ManagedRelayClient;- const storage = yield* MobileStorage.MobileStorage;- const deviceId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(- Effect.mapError(cloudEnvironmentLinkError("Could not load the mobile device id.")),- );- const liveActivitiesEnabled = input.liveActivitiesEnabled;- const challenge = yield* relayClient- .createEnvironmentLinkChallenge({- clerkToken: input.clerkToken,- payload: {- notificationsEnabled: true,- liveActivitiesEnabled,- managedTunnelsEnabled: true,- },- })- .pipe(- Effect.mapError(- decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`),- ),- );- const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);- const proof = yield* environmentClient.connect- .linkProof({- headers: { authorization: `Bearer ${localBearerToken}` },- payload: {- challenge: challenge.challenge,- relayIssuer: relayUrl,- endpoint: {- httpBaseUrl: input.connection.httpBaseUrl,- wsBaseUrl: input.connection.wsBaseUrl,- providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,- },- origin: endpointOrigin(input.connection.httpBaseUrl),- },- })- .pipe(Effect.mapError(cloudEnvironmentLinkError("Could not obtain environment link proof.")));- const link = yield* relayClient- .linkEnvironment({- clerkToken: input.clerkToken,- payload: {- deviceId,- proof,- notificationsEnabled: true,- liveActivitiesEnabled,- managedTunnelsEnabled: true,- },- })- .pipe(- Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)),- );- yield* ensureLinkedEnvironmentMatches({- expectedEnvironmentId: input.connection.environmentId,- expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND,- link,+): Effect.fn.Return<void, CloudEnvironmentLinkError, LinkEnvironmentToCloudRequirements> {+ if (!input.connection.bearerToken) {+ return yield* new CloudEnvironmentLinkError({+ message: "Only a locally paired bearer connection can be linked to the cloud.",});-- yield* environmentClient.connect- .relayConfig({- headers: { authorization: `Bearer ${localBearerToken}` },- payload: {- relayUrl,- relayIssuer: link.relayIssuer,- cloudUserId: link.cloudUserId,- environmentCredential: link.environmentCredential,- cloudMintPublicKey: link.cloudMintPublicKey,- endpointRuntime: link.endpointRuntime,+ }+ const localBearerToken = input.connection.bearerToken;+ const relayUrl = yield* requireRelayUrl();+ const relayClient = yield* ManagedRelay.ManagedRelayClient;+ const storage = yield* MobileStorage.MobileStorage;+ const deviceId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(+ Effect.mapError(cloudEnvironmentLinkError("Could not load the mobile device id.")),+ );+ const liveActivitiesEnabled = input.liveActivitiesEnabled;+ const challenge = yield* relayClient+ .createEnvironmentLinkChallenge({+ clerkToken: input.clerkToken,+ payload: {+ notificationsEnabled: true,+ liveActivitiesEnabled,+ managedTunnelsEnabled: true,+ },+ })+ .pipe(+ Effect.mapError(+ decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`),+ ),+ );+ const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);+ const proof = yield* environmentClient.connect+ .linkProof({+ headers: { authorization: `Bearer ${localBearerToken}` },+ payload: {+ challenge: challenge.challenge,+ relayIssuer: relayUrl,+ endpoint: {+ httpBaseUrl: input.connection.httpBaseUrl,+ wsBaseUrl: input.connection.wsBaseUrl,+ providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,},- })- .pipe(- Effect.mapError(cloudEnvironmentLinkError("Could not configure environment relay access.")),- );+ origin: endpointOrigin(input.connection.httpBaseUrl),+ },+ })+ .pipe(Effect.mapError(cloudEnvironmentLinkError("Could not obtain environment link proof.")));+ const link = yield* relayClient+ .linkEnvironment({+ clerkToken: input.clerkToken,+ payload: {+ deviceId,+ proof,+ notificationsEnabled: true,+ liveActivitiesEnabled,+ managedTunnelsEnabled: true,+ },+ })+ .pipe(+ Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)),+ );+ yield* ensureLinkedEnvironmentMatches({+ expectedEnvironmentId: input.connection.environmentId,+ expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND,+ link,});-}++ yield* environmentClient.connect+ .relayConfig({+ headers: { authorization: `Bearer ${localBearerToken}` },+ payload: {+ relayUrl,+ relayIssuer: link.relayIssuer,+ cloudUserId: link.cloudUserId,+ environmentCredential: link.environmentCredential,+ cloudMintPublicKey: link.cloudMintPublicKey,+ endpointRuntime: link.endpointRuntime,+ },+ })+ .pipe(+ Effect.mapError(cloudEnvironmentLinkError("Could not configure environment relay access.")),+ );+});diff --git a/apps/web/src/cloud/dpop.ts b/apps/web/src/cloud/dpop.tsindex 2569108563b..97da6d4ca8a 100644--- a/apps/web/src/cloud/dpop.ts+++ b/apps/web/src/cloud/dpop.ts@@ -142,44 +142,42 @@ export const generateBrowserDpopKey = Effect.gen(function* () {};});-export function createBrowserDpopProof(input: {+export const createBrowserDpopProof = Effect.fn("dpop.createBrowserDpopProof")(function* (input: {readonly method: string;readonly url: string;readonly accessToken?: string;readonly proofKey: BrowserDpopKey;-}): Effect.Effect<+}): Effect.fn.Return<{ readonly proof: string; readonly thumbprint: string },BrowserDpopError,Crypto.Crypto> {- return Effect.gen(function* () {- const normalizedUrl = yield* Effect.try({- try: () => new URL(input.url),- catch: (cause) => dpopError("Could not normalize DPoP proof URL.", cause),- });- normalizedUrl.search = "";- normalizedUrl.hash = "";- const jti = yield* Crypto.Crypto.pipe(- Effect.flatMap((crypto) => crypto.randomUUIDv4()),- Effect.mapError((cause) => dpopError("Could not generate DPoP proof identifier.", cause)),- );- const proof = yield* Effect.tryPromise({- try: () =>- new SignJWT({- htm: input.method.toUpperCase(),- htu: normalizedUrl.toString(),- jti,- ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}),+ const normalizedUrl = yield* Effect.try({+ try: () => new URL(input.url),+ catch: (cause) => dpopError("Could not normalize DPoP proof URL.", cause),+ });+ normalizedUrl.search = "";+ normalizedUrl.hash = "";+ const jti = yield* Crypto.Crypto.pipe(+ Effect.flatMap((crypto) => crypto.randomUUIDv4()),+ Effect.mapError((cause) => dpopError("Could not generate DPoP proof identifier.", cause)),+ );+ const proof = yield* Effect.tryPromise({+ try: () =>+ new SignJWT({+ htm: input.method.toUpperCase(),+ htu: normalizedUrl.toString(),+ jti,+ ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}),+ })+ .setProtectedHeader({+ typ: "dpop+jwt",+ alg: "ES256",+ jwk: input.proofKey.publicJwk,})- .setProtectedHeader({- typ: "dpop+jwt",- alg: "ES256",- jwk: input.proofKey.publicJwk,- })- .setIssuedAt()- .sign(input.proofKey.privateKey),- catch: (cause) => dpopError("Could not sign DPoP proof.", cause),- });- return { proof, thumbprint: input.proofKey.thumbprint };+ .setIssuedAt()+ .sign(input.proofKey.privateKey),+ catch: (cause) => dpopError("Could not sign DPoP proof.", cause),});-}+ return { proof, thumbprint: input.proofKey.thumbprint };+});diff --git a/apps/web/src/cloud/linkEnvironment.ts b/apps/web/src/cloud/linkEnvironment.tsindex d7a4c3fe8ce..e6e42dc9218 100644--- a/apps/web/src/cloud/linkEnvironment.ts+++ b/apps/web/src/cloud/linkEnvironment.ts@@ -48,10 +48,10 @@ const relayClientRpcError = (message: string) => (cause: unknown) =>cause,});-function ensureRelayClientAvailable(- environmentId: EnvironmentId,-): Effect.Effect<void, CloudEnvironmentLinkError, EnvironmentRegistry.EnvironmentRegistry> {- return Effect.gen(function* () {+const ensureRelayClientAvailable = Effect.fn("linkEnvironment.ensureRelayClientAvailable")(+ function* (+ environmentId: EnvironmentId,+ ): Effect.fn.Return<void, CloudEnvironmentLinkError, EnvironmentRegistry.EnvironmentRegistry> {const registry = yield* EnvironmentRegistry.EnvironmentRegistry;const status = yield* registry.run(environmentId, request(WS_METHODS.cloudGetRelayClientStatus, {}))@@ -99,8 +99,8 @@ function ensureRelayClientAvailable(: "The relay client is still unavailable after installation.",});}- });-}+ },+);const isEnvironmentCloudApiError = Schema.is(Schema.Union([@@ -184,163 +184,169 @@ export interface CloudLinkTarget {export type CloudLinkState = EnvironmentCloudLinkStateResult;-export function readPrimaryCloudLinkState(input: {+export const readPrimaryCloudLinkState: (input: {readonly target: CloudLinkTarget;-}): Effect.Effect<CloudLinkState | null, CloudEnvironmentLinkError, HttpClient.HttpClient> {- return Effect.gen(function* () {+}) => Effect.Effect<CloudLinkState | null, CloudEnvironmentLinkError, HttpClient.HttpClient> =+ Effect.fn("linkEnvironment.readPrimaryCloudLinkState")(function* (input: {+ readonly target: CloudLinkTarget;+ }) {const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);return yield* client.connect.linkState({ headers: {} }).pipe(Effect.mapError(environmentApiError("Could not read environment cloud link state.")));- }).pipe(Effect.provide(PrimaryEnvironmentHttpLayer.layer));-}+ }, Effect.provide(PrimaryEnvironmentHttpLayer.layer));-export function updatePrimaryCloudPreferences(input: {+export const updatePrimaryCloudPreferences: (input: {readonly target: CloudLinkTarget;readonly publishAgentActivity: boolean;readonly holdWebhooksWhileOffline?: boolean;-}): Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, HttpClient.HttpClient> {- return Effect.gen(function* () {- const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);- const { target: _target, ...payload } = input;- return yield* client.connect- .preferences({- headers: {},- payload,- })- .pipe(- Effect.mapError(environmentApiError("Could not update environment cloud preferences.")),- );- }).pipe(Effect.provide(PrimaryEnvironmentHttpLayer.layer));-}+}) => Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, HttpClient.HttpClient> = Effect.fn(+ "linkEnvironment.updatePrimaryCloudPreferences",+)(function* (input: {+ readonly target: CloudLinkTarget;+ readonly publishAgentActivity: boolean;+ readonly holdWebhooksWhileOffline?: boolean;+}) {+ const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);+ const { target: _target, ...payload } = input;+ return yield* client.connect+ .preferences({+ headers: {},+ payload,+ })+ .pipe(Effect.mapError(environmentApiError("Could not update environment cloud preferences.")));+}, Effect.provide(PrimaryEnvironmentHttpLayer.layer));-export function unlinkPrimaryEnvironmentFromCloud(input: {+export const unlinkPrimaryEnvironmentFromCloud: (input: {readonly target: CloudLinkTarget;readonly clerkToken: string | null;-}): Effect.Effect<+}) => Effect.Effect<void,CloudEnvironmentLinkError,HttpClient.HttpClient | ManagedRelay.ManagedRelayClient-> {- return Effect.gen(function* () {- const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);- yield* client.connect- .unlink({ headers: {} })- .pipe(Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")));+> = Effect.fn("linkEnvironment.unlinkPrimaryEnvironmentFromCloud")(function* (input: {+ readonly target: CloudLinkTarget;+ readonly clerkToken: string | null;+}) {+ const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);+ yield* client.connect+ .unlink({ headers: {} })+ .pipe(Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")));- const configuredRelayUrl = relayUrl();- if (configuredRelayUrl && input.clerkToken) {- const relayClient = yield* ManagedRelay.ManagedRelayClient;- yield* relayClient- .unlinkEnvironment({- clerkToken: input.clerkToken,- environmentId: EnvironmentId.make(input.target.environmentId),- })- .pipe(- Effect.catch((cause) =>- Effect.logWarning("Could not revoke cloud environment link after local unlink.", {- cause,- }),- ),- );- }- }).pipe(Effect.provide(PrimaryEnvironmentHttpLayer.layer));-}+ const configuredRelayUrl = relayUrl();+ if (configuredRelayUrl && input.clerkToken) {+ const relayClient = yield* ManagedRelay.ManagedRelayClient;+ yield* relayClient+ .unlinkEnvironment({+ clerkToken: input.clerkToken,+ environmentId: EnvironmentId.make(input.target.environmentId),+ })+ .pipe(+ Effect.catch((cause) =>+ Effect.logWarning("Could not revoke cloud environment link after local unlink.", {+ cause,+ }),+ ),+ );+ }+}, Effect.provide(PrimaryEnvironmentHttpLayer.layer));export type CloudLinkMode = "managed" | "publish_only";const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind;-export function linkPrimaryEnvironmentToCloud(input: {+export const linkPrimaryEnvironmentToCloud: (input: {readonly target: CloudLinkTarget;readonly clerkToken: string;readonly mode?: CloudLinkMode;-}): Effect.Effect<+}) => Effect.Effect<void,CloudEnvironmentLinkError,EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient | ManagedRelay.ManagedRelayClient-> {- return Effect.gen(function* () {- const configuredRelayUrl = relayUrl();- if (!configuredRelayUrl) {- return yield* new CloudEnvironmentLinkError({- message: "T3CODE_RELAY_URL is not configured.",- });- }- const managedTunnelsEnabled = (input.mode ?? "managed") === "managed";- const providerKind = managedTunnelsEnabled- ? MANAGED_ENDPOINT_PROVIDER_KIND- : PUBLISH_ONLY_PROVIDER_KIND;- const relayClient = yield* ManagedRelay.ManagedRelayClient;- const environmentClient = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);- if (managedTunnelsEnabled) {- yield* ensureRelayClientAvailable(EnvironmentId.make(input.target.environmentId));- }+> = Effect.fn("linkEnvironment.linkPrimaryEnvironmentToCloud")(function* (input: {+ readonly target: CloudLinkTarget;+ readonly clerkToken: string;+ readonly mode?: CloudLinkMode;+}) {+ const configuredRelayUrl = relayUrl();+ if (!configuredRelayUrl) {+ return yield* new CloudEnvironmentLinkError({+ message: "T3CODE_RELAY_URL is not configured.",+ });+ }+ const managedTunnelsEnabled = (input.mode ?? "managed") === "managed";+ const providerKind = managedTunnelsEnabled+ ? MANAGED_ENDPOINT_PROVIDER_KIND+ : PUBLISH_ONLY_PROVIDER_KIND;+ const relayClient = yield* ManagedRelay.ManagedRelayClient;+ const environmentClient = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);+ if (managedTunnelsEnabled) {+ yield* ensureRelayClientAvailable(EnvironmentId.make(input.target.environmentId));+ }- const challenge = yield* relayClient- .createEnvironmentLinkChallenge({- clerkToken: input.clerkToken,- payload: {- notificationsEnabled: true,- liveActivitiesEnabled: true,- managedTunnelsEnabled,- },- })- .pipe(- Effect.mapError(- decodedRelayClientError(- `${configuredRelayUrl}/v1/client/environment-link-challenges failed`,- ),+ const challenge = yield* relayClient+ .createEnvironmentLinkChallenge({+ clerkToken: input.clerkToken,+ payload: {+ notificationsEnabled: true,+ liveActivitiesEnabled: true,+ managedTunnelsEnabled,+ },+ })+ .pipe(+ Effect.mapError(+ decodedRelayClientError(+ `${configuredRelayUrl}/v1/client/environment-link-challenges failed`,),- );- const proof = yield* environmentClient.connect- .linkProof({- headers: {},- payload: {- challenge: challenge.challenge,- relayIssuer: configuredRelayUrl,- endpoint: {- httpBaseUrl: input.target.httpBaseUrl,- wsBaseUrl: input.target.wsBaseUrl,- providerKind,- },- origin: endpointOrigin(input.target.httpBaseUrl),- },- })- .pipe(Effect.mapError(environmentApiError("Could not obtain environment link proof.")));- const link = yield* relayClient- .linkEnvironment({- clerkToken: input.clerkToken,- payload: {- proof,- notificationsEnabled: true,- liveActivitiesEnabled: true,- managedTunnelsEnabled,+ ),+ );+ const proof = yield* environmentClient.connect+ .linkProof({+ headers: {},+ payload: {+ challenge: challenge.challenge,+ relayIssuer: configuredRelayUrl,+ endpoint: {+ httpBaseUrl: input.target.httpBaseUrl,+ wsBaseUrl: input.target.wsBaseUrl,+ providerKind,},- })- .pipe(- Effect.mapError(- decodedRelayClientError(`${configuredRelayUrl}/v1/client/environment-links failed`),- ),- );- yield* ensureLinkedEnvironmentMatches({- expectedEnvironmentId: input.target.environmentId,- expectedProviderKind: providerKind,- link,- });+ origin: endpointOrigin(input.target.httpBaseUrl),+ },+ })+ .pipe(Effect.mapError(environmentApiError("Could not obtain environment link proof.")));+ const link = yield* relayClient+ .linkEnvironment({+ clerkToken: input.clerkToken,+ payload: {+ proof,+ notificationsEnabled: true,+ liveActivitiesEnabled: true,+ managedTunnelsEnabled,+ },+ })+ .pipe(+ Effect.mapError(+ decodedRelayClientError(`${configuredRelayUrl}/v1/client/environment-links failed`),+ ),+ );+ yield* ensureLinkedEnvironmentMatches({+ expectedEnvironmentId: input.target.environmentId,+ expectedProviderKind: providerKind,+ link,+ });- yield* environmentClient.connect- .relayConfig({- headers: {},- payload: {- relayUrl: configuredRelayUrl,- relayIssuer: link.relayIssuer,- cloudUserId: link.cloudUserId,- environmentCredential: link.environmentCredential,- cloudMintPublicKey: link.cloudMintPublicKey,- endpointRuntime: link.endpointRuntime,- },- })- .pipe(Effect.mapError(environmentApiError("Could not configure environment relay access.")));- }).pipe(Effect.provide(PrimaryEnvironmentHttpLayer.layer));-}+ yield* environmentClient.connect+ .relayConfig({+ headers: {},+ payload: {+ relayUrl: configuredRelayUrl,+ relayIssuer: link.relayIssuer,+ cloudUserId: link.cloudUserId,+ environmentCredential: link.environmentCredential,+ cloudMintPublicKey: link.cloudMintPublicKey,+ endpointRuntime: link.endpointRuntime,+ },+ })+ .pipe(Effect.mapError(environmentApiError("Could not configure environment relay access.")));+}, Effect.provide(PrimaryEnvironmentHttpLayer.layer));diff --git a/apps/web/src/connection/storage.ts b/apps/web/src/connection/storage.tsindex c57ade36f9a..4e7bcf3e58e 100644--- a/apps/web/src/connection/storage.ts+++ b/apps/web/src/connection/storage.ts@@ -750,21 +750,21 @@ export const layer = Layer.effectContext(}),Effect.mapError((cause) => persistenceError("load-shell", cause)),),- saveShell: (environmentId, snapshot) =>- Effect.gen(function* () {+ saveShell: Effect.fn("storage.saveShell")(+ function* (environmentId, snapshot) {const encoded = yield* encodeStoredShellSnapshot({schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,environmentId,snapshot,}).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded);- }).pipe(- Effect.mapError((cause) =>- cause._tag === "ConnectionPersistenceError"- ? cause- : persistenceError("save-shell", cause),- ),+ },+ Effect.mapError((cause) =>+ cause._tag === "ConnectionPersistenceError"+ ? cause+ : persistenceError("save-shell", cause),),+ ),loadServerConfig: (environmentId) =>readDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId).pipe(Effect.flatMap((raw) => {@@ -784,21 +784,21 @@ export const layer = Layer.effectContext(: persistenceError("load-server-config", cause),),),- saveServerConfig: (environmentId, config) =>- Effect.gen(function* () {+ saveServerConfig: Effect.fn("storage.saveServerConfig")(+ function* (environmentId, config) {const encoded = yield* encodeStoredServerConfig({schemaVersion: 1,environmentId,config,}).pipe(Effect.mapError((cause) => persistenceError("save-server-config", cause)));yield* writeDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId, encoded);- }).pipe(- Effect.mapError((cause) =>- cause._tag === "ConnectionPersistenceError"- ? cause- : persistenceError("save-server-config", cause),- ),+ },+ Effect.mapError((cause) =>+ cause._tag === "ConnectionPersistenceError"+ ? cause+ : persistenceError("save-server-config", cause),),+ ),loadThread: (environmentId, threadId) =>readDatabaseValue(database,@@ -827,8 +827,8 @@ export const layer = Layer.effectContext(}),Effect.mapError((cause) => persistenceError("load-thread", cause)),),- saveThread: (environmentId, snapshot) =>- Effect.gen(function* () {+ saveThread: Effect.fn("storage.saveThread")(+ function* (environmentId, snapshot) {const encoded = yield* encodeStoredThreadSnapshot({schemaVersion: ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION,environmentId,@@ -841,13 +841,13 @@ export const layer = Layer.effectContext(threadCacheKey(environmentId, snapshot.projection.thread.id),encoded,);- }).pipe(- Effect.mapError((cause) =>- cause._tag === "ConnectionPersistenceError"- ? cause- : persistenceError("save-thread", cause),- ),+ },+ Effect.mapError((cause) =>+ cause._tag === "ConnectionPersistenceError"+ ? cause+ : persistenceError("save-thread", cause),),+ ),loadVcsRefs: (environmentId, cwd) =>readDatabaseValue(database, VCS_REFS_STORE_NAME, vcsRefsCacheKey(environmentId, cwd)).pipe(Effect.flatMap((raw) => {@@ -869,8 +869,8 @@ export const layer = Layer.effectContext(: persistenceError("load-vcs-refs", cause),),),- saveVcsRefs: (environmentId, cwd, refs) =>- Effect.gen(function* () {+ saveVcsRefs: Effect.fn("storage.saveVcsRefs")(+ function* (environmentId, cwd, refs) {const encoded = yield* encodeStoredVcsRefs({schemaVersion: 1,environmentId,@@ -883,13 +883,13 @@ export const layer = Layer.effectContext(vcsRefsCacheKey(environmentId, cwd),encoded,);- }).pipe(- Effect.mapError((cause) =>- cause._tag === "ConnectionPersistenceError"- ? cause- : persistenceError("save-vcs-refs", cause),- ),+ },+ Effect.mapError((cause) =>+ cause._tag === "ConnectionPersistenceError"+ ? cause+ : persistenceError("save-vcs-refs", cause),),+ ),removeVcsRefs: (environmentId, cwd) =>removeDatabaseValue(database,diff --git a/packages/client-runtime/src/platform/shellCacheEncoding.ts b/packages/client-runtime/src/platform/shellCacheEncoding.tsindex 26a50183061..cbfe048b5ea 100644--- a/packages/client-runtime/src/platform/shellCacheEncoding.ts+++ b/packages/client-runtime/src/platform/shellCacheEncoding.ts@@ -51,14 +51,16 @@ export function makeStoredShellSnapshotEncoder(hasWorked = true;return Effect.void;});- const encodeMisses = (misses: ReadonlyArray<OrchestrationV2ThreadShellJson>) =>- Effect.gen(function* () {+ const encodeMisses =+ /* Cache encoding runs for shell update batches; avoid tracing each batch. */+ Effect.fnUntraced(function* (misses: ReadonlyArray<OrchestrationV2ThreadShellJson>) {yield* yieldBetweenChunks;const chunk = yield* encodeThreadChunk(misses);chunk.forEach((row, index) => encodedRows.set(misses[index]!, row));});- const encodeRows = (rows: ReadonlyArray<OrchestrationV2ThreadShellJson>) =>- Effect.gen(function* () {+ const encodeRows =+ /* Cache encoding runs for shell update batches; avoid tracing each batch. */+ Effect.fnUntraced(function* (rows: ReadonlyArray<OrchestrationV2ThreadShellJson>) {let misses: Array<OrchestrationV2ThreadShellJson> = [];for (const row of rows) {if (encodedRows.has(row)) continue;diff --git a/packages/client-runtime/src/relay/managedRelayState.ts b/packages/client-runtime/src/relay/managedRelayState.tsindex af8fc0a8366..cfe99e8abce 100644--- a/packages/client-runtime/src/relay/managedRelayState.ts+++ b/packages/client-runtime/src/relay/managedRelayState.ts@@ -311,30 +311,29 @@ export function createManagedRelayQueryManager() {const staleTime = options?.staleTimeMs ?? DEFAULT_STALE_TIME_MS;const idleTtl = options?.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;- const observe = <A, E, R>(+ const observe = Effect.fn("managedRelayState.observe")(function* <A, E, R>(input: Omit<ManagedRelayQueryEvent, "phase" | "message" | "traceId">,effect: Effect.Effect<A, E, R>,- ): Effect.Effect<A, E, R> =>- Effect.gen(function* () {- options?.onQueryEvent?.({ ...input, phase: "start" });- return yield* effect.pipe(- Effect.onExit((exit) =>- Effect.sync(() => {- if (exit._tag === "Success") {- options?.onQueryEvent?.({ ...input, phase: "success" });- return;- }- const error = Cause.squash(exit.cause);- options?.onQueryEvent?.({- ...input,- phase: "failure",- message: error instanceof Error ? error.message : String(error),- traceId: findErrorTraceId(error),- });- }),- ),- );- });+ ): Effect.fn.Return<A, E, R> {+ options?.onQueryEvent?.({ ...input, phase: "start" });+ return yield* effect.pipe(+ Effect.onExit((exit) =>+ Effect.sync(() => {+ if (exit._tag === "Success") {+ options?.onQueryEvent?.({ ...input, phase: "success" });+ return;+ }+ const error = Cause.squash(exit.cause);+ options?.onQueryEvent?.({+ ...input,+ phase: "failure",+ message: error instanceof Error ? error.message : String(error),+ traceId: findErrorTraceId(error),+ });+ }),+ ),+ );+ });const environmentsAtom = Atom.family((accountId: string) =>runtimediff --git a/packages/client-runtime/src/state/environmentHttpAuth.ts b/packages/client-runtime/src/state/environmentHttpAuth.tsindex 6f75be719ab..e89d87ffaef 100644--- a/packages/client-runtime/src/state/environmentHttpAuth.ts+++ b/packages/client-runtime/src/state/environmentHttpAuth.ts@@ -52,13 +52,13 @@ const withEnvironmentCredentials = <A, E, R>(? request.pipe(Effect.provideService(FetchHttpClient.RequestInit, { credentials: "include" })): request;-const buildEnvironmentAuthHeaders = (- authorization: PreparedHttpAuthorization | null,- method: HttpMethod.HttpMethod,- url: string,- signer: Option.Option<ManagedRelayDpopSigner["Service"]>,-): Effect.Effect<EnvironmentHttpAuthHeaders, RemoteEnvironmentAuthFetchError> =>- Effect.gen(function* () {+const buildEnvironmentAuthHeaders = Effect.fn("environmentHttpAuth.buildEnvironmentAuthHeaders")(+ function* (+ authorization: PreparedHttpAuthorization | null,+ method: HttpMethod.HttpMethod,+ url: string,+ signer: Option.Option<ManagedRelayDpopSigner["Service"]>,+ ): Effect.fn.Return<EnvironmentHttpAuthHeaders, RemoteEnvironmentAuthFetchError> {if (authorization === null) {return {};}@@ -83,7 +83,8 @@ const buildEnvironmentAuthHeaders = (),);return { authorization: `DPoP ${authorization.accessToken}`, dpop: proof };- });+ },+);/*** A DPoP request is T3 Connect work, so its span starts an exported trace thatdiff --git a/packages/client-runtime/src/state/fileMetadata.ts b/packages/client-runtime/src/state/fileMetadata.tsindex cf58cfb015b..d079f08c00b 100644--- a/packages/client-runtime/src/state/fileMetadata.ts+++ b/packages/client-runtime/src/state/fileMetadata.ts@@ -290,14 +290,15 @@ export function createFileMetadataAtoms<R, E>();});- const seedAfterRead = <A, ReadError, ReadServices>(- read: Effect.Effect<A, ReadError, ReadServices>,- seed: (- result: A,- isCurrent: (session: RpcSession) => boolean,- ) => Effect.Effect<void, never, EnvironmentSupervisor.EnvironmentSupervisor>,- ) =>- Effect.gen(function* () {+ const seedAfterRead =+ /* Metadata seeding runs on every file read and is covered by the read operation. */+ Effect.fnUntraced(function* <A, ReadError, ReadServices>(+ read: Effect.Effect<A, ReadError, ReadServices>,+ seed: (+ result: A,+ isCurrent: (session: RpcSession) => boolean,+ ) => Effect.Effect<void, never, EnvironmentSupervisor.EnvironmentSupervisor>,+ ) {const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;const session = yield* SubscriptionRef.get(supervisor.session);const version = session._tag === "Some" ? (invalidationVersions.get(session.value) ?? 0) : 0;diff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.tsindex e01759225aa..8bef9762a29 100644--- a/packages/client-runtime/src/state/orchestration.ts+++ b/packages/client-runtime/src/state/orchestration.ts@@ -27,25 +27,26 @@ export function createOrchestrationEnvironmentAtoms<R, E>(return {threadTranscript: createEnvironmentCommand(runtime, {label: "environment-data:orchestration:thread-transcript",- execute: (input: { readonly threadId: ThreadId }) =>- Effect.gen(function* () {- const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;- const prepared = yield* SubscriptionRef.get(supervisor.prepared);- if (Option.isNone(prepared)) {- return yield* new EnvironmentRpcUnavailableError({- environmentId: supervisor.target.environmentId,- message: "The source environment is not connected.",- });- }- return yield* fetchEnvironmentThreadTranscript({- prepared: prepared.value,- threadId: input.threadId,- signer: yield* Effect.serviceOption(ManagedRelayDpopSigner.ManagedRelayDpopSigner),- remoteAuthorization: yield* Effect.serviceOption(- RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,- ),+ execute: Effect.fn("orchestration.execute")(function* (input: {+ readonly threadId: ThreadId;+ }) {+ const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;+ const prepared = yield* SubscriptionRef.get(supervisor.prepared);+ if (Option.isNone(prepared)) {+ return yield* new EnvironmentRpcUnavailableError({+ environmentId: supervisor.target.environmentId,+ message: "The source environment is not connected.",});- }),+ }+ return yield* fetchEnvironmentThreadTranscript({+ prepared: prepared.value,+ threadId: input.threadId,+ signer: yield* Effect.serviceOption(ManagedRelayDpopSigner.ManagedRelayDpopSigner),+ remoteAuthorization: yield* Effect.serviceOption(+ RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,+ ),+ });+ }),}),v2: {dispatchCommand: createEnvironmentRpcCommand(runtime, {diff --git a/packages/client-runtime/src/state/pullRequestStatsPersistence.ts b/packages/client-runtime/src/state/pullRequestStatsPersistence.tsindex 41b45876b77..2d97ce23d1c 100644--- a/packages/client-runtime/src/state/pullRequestStatsPersistence.ts+++ b/packages/client-runtime/src/state/pullRequestStatsPersistence.ts@@ -16,17 +16,19 @@ const statKey = (ref: PullRequestRef) =>export function persistPullRequestStats(): QueryPersistence<PullRequestListStatsResult> {const row = persistQuery(PullRequestDiffStat);return {- load: (environmentId, key) =>- Effect.gen(function* () {+ load: Effect.fn("pullRequestStatsPersistence.load")(+ function* (environmentId, key) {const [, input] = yield* Schema.decodeEffect(requestKey)(key);const rows = yield* Effect.forEach(input.refs, (ref) =>row.load(environmentId, statKey(ref)),);const stats = rows.flatMap((value) => (Option.isSome(value) ? [value.value] : []));return stats.length ? Option.some({ stats }) : Option.none();- }).pipe(Effect.orElseSucceed(() => Option.none())),- save: (environmentId, key, result) =>- Effect.gen(function* () {+ },+ Effect.orElseSucceed(() => Option.none()),+ ),+ save: Effect.fn("pullRequestStatsPersistence.save")(+ function* (environmentId, key, result) {const [, input] = yield* Schema.decodeEffect(requestKey)(key);yield* Effect.forEach(result.stats, (stat) => {const ref = input.refs.find(@@ -37,6 +39,8 @@ export function persistPullRequestStats(): QueryPersistence<PullRequestListStats);return ref ? row.save(environmentId, statKey(ref), stat) : Effect.void;});- }).pipe(Effect.ignore),+ },+ (effect, _environmentId, _key, _result) => effect.pipe(Effect.ignore),+ ),};}diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.tsindex be7d22c0eb6..684c3d1999f 100644--- a/packages/client-runtime/src/state/pullRequests.ts+++ b/packages/client-runtime/src/state/pullRequests.ts@@ -230,6 +230,62 @@ export function createPullRequestEnvironmentAtoms<R, E>(staleTimeMs: 60_000,}),);+ const loadDiff = Effect.fn("PullRequests.loadDiff")(function* (input: PullRequestDiffInput) {+ const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;+ const loader = yield* PullRequestDiffLoader.PullRequestDiffLoader;+ const prepared = yield* SubscriptionRef.get(supervisor.prepared);+ if (Option.isNone(prepared)) {+ return yield* new EnvironmentHttpConnectionNotReadyError({+ message: "The environment HTTP connection is not ready.",+ });+ }+ return yield* loader.load(prepared.value, input);+ });++ const runAction = Effect.fn("PullRequests.runAction")(function* (+ input: PullRequestActionInput & {+ readonly resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;+ },+ ) {+ const { resolveMergeMethod, ...actionInput } = input;+ let preparedInput = actionInput;+ if (actionInput.action === "merge" && resolveMergeMethod !== undefined) {+ const { projectId, host, repository, number } = actionInput;+ const reference = { projectId, host, repository, number, allowStale: false };+ const detail = yield* routedRequest(WS_METHODS.pullRequestsDetail, reference);+ if (+ detail.state !== "open" ||+ detail.isDraft ||+ !detail.capabilities.actions.includes("merge") ||+ !detail.viewerPermissions.actions.includes("merge")+ ) {+ return yield* new PullRequestOperationError({+ operation: "runAction",+ detail: "This pull request cannot be merged.",+ });+ }+ if (detail.capabilities.stackActions) {+ const stack = yield* routedRequest(WS_METHODS.pullRequestsStack, reference);+ if (stack !== null) {+ return yield* new PullRequestOperationError({+ operation: "runAction",+ detail: "Open this pull request to merge its stack.",+ });+ }+ }+ const mergeMethod = yield* Effect.try({+ try: () => resolveMergeMethod(detail),+ catch: (cause) =>+ new PullRequestOperationError({+ operation: "runAction",+ detail: cause instanceof Error ? cause.message : "Could not choose a merge method.",+ }),+ });+ preparedInput = { ...actionInput, mergeMethod };+ }+ return yield* routedRequest(WS_METHODS.pullRequestsRunAction, preparedInput);+ });+return {refreshes,linkedThreads: createEnvironmentRpcQueryAtomFamily(runtime, {@@ -286,18 +342,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(label: "environment-data:pull-requests:diff",persistence: persistQuery(PullRequestDiffResult),staleTimeMs: 60_000,- execute: (input: PullRequestDiffInput) =>- Effect.gen(function* () {- const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;- const loader = yield* PullRequestDiffLoader.PullRequestDiffLoader;- const prepared = yield* SubscriptionRef.get(supervisor.prepared);- if (Option.isNone(prepared)) {- return yield* new EnvironmentHttpConnectionNotReadyError({- message: "The environment HTTP connection is not ready.",- });- }- return yield* loader.load(prepared.value, input);- }),+ execute: loadDiff,}),diffFileContents: createEnvironmentRpcCommand(runtime, {label: "environment-data:pull-requests:diff-file-contents",@@ -347,51 +392,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(label: "environment-data:pull-requests:run-action",// Preparation belongs to the write's lane. Refreshable queries would restart it after// every preceding action, and preparing outside the lane could reorder the clicks.- execute: (- input: PullRequestActionInput & {- readonly resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;- },- ) =>- Effect.gen(function* () {- const { resolveMergeMethod, ...actionInput } = input;- let preparedInput = actionInput;- if (actionInput.action === "merge" && resolveMergeMethod !== undefined) {- const { projectId, host, repository, number } = actionInput;- const reference = { projectId, host, repository, number, allowStale: false };- const detail = yield* routedRequest(WS_METHODS.pullRequestsDetail, reference);- if (- detail.state !== "open" ||- detail.isDraft ||- !detail.capabilities.actions.includes("merge") ||- !detail.viewerPermissions.actions.includes("merge")- ) {- return yield* new PullRequestOperationError({- operation: "runAction",- detail: "This pull request cannot be merged.",- });- }- if (detail.capabilities.stackActions) {- const stack = yield* routedRequest(WS_METHODS.pullRequestsStack, reference);- if (stack !== null) {- return yield* new PullRequestOperationError({- operation: "runAction",- detail: "Open this pull request to merge its stack.",- });- }- }- const mergeMethod = yield* Effect.try({- try: () => resolveMergeMethod(detail),- catch: (cause) =>- new PullRequestOperationError({- operation: "runAction",- detail:- cause instanceof Error ? cause.message : "Could not choose a merge method.",- }),- });- preparedInput = { ...actionInput, mergeMethod };- }- return yield* routedRequest(WS_METHODS.pullRequestsRunAction, preparedInput);- }),+ execute: runAction,onSuccess: ({ environmentId, input }, registry) =>Effect.sync(() => registry.refresh(preview({ environmentId, input }))),scheduler: commandScheduler,diff --git a/packages/client-runtime/src/state/queryPersistence.ts b/packages/client-runtime/src/state/queryPersistence.tsindex 05fdfbc6d71..59c8d5d11f6 100644--- a/packages/client-runtime/src/state/queryPersistence.ts+++ b/packages/client-runtime/src/state/queryPersistence.ts@@ -26,23 +26,24 @@ export interface QueryPersistence<A> {export function persistQuery<A, I>(schema: Schema.Codec<A, I>): QueryPersistence<A> {const codec = Schema.fromJsonString(Schema.toCodecJson(schema));return {- load: (environmentId, key) =>- Effect.gen(function* () {- const store = yield* EnvironmentQueryStore;- if (store === null) return Option.none<A>();- const stored = yield* store.load(environmentId, key);- if (Option.isNone(stored)) return Option.none<A>();- return yield* Schema.decodeUnknownEffect(codec)(stored.value).pipe(- Effect.map(Option.some),- Effect.catch(() => Effect.succeedNone),- );- }),- save: (environmentId, key, value) =>- Effect.gen(function* () {+ load: Effect.fn("queryPersistence.load")(function* (environmentId, key) {+ const store = yield* EnvironmentQueryStore;+ if (store === null) return Option.none<A>();+ const stored = yield* store.load(environmentId, key);+ if (Option.isNone(stored)) return Option.none<A>();+ return yield* Schema.decodeUnknownEffect(codec)(stored.value).pipe(+ Effect.map(Option.some),+ Effect.catch(() => Effect.succeedNone),+ );+ }),+ save: Effect.fn("queryPersistence.save")(+ function* (environmentId, key, value) {const store = yield* EnvironmentQueryStore;if (store === null) return;const payload = yield* Schema.encodeEffect(codec)(value);yield* store.save(environmentId, key, payload);- }).pipe(Effect.catch(() => Effect.logWarning("Offline query cache save failed"))),+ },+ Effect.catch(() => Effect.logWarning("Offline query cache save failed")),+ ),};}diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.tsindex 94530b88113..5a408d61e92 100644--- a/packages/client-runtime/src/state/runtime.ts+++ b/packages/client-runtime/src/state/runtime.ts@@ -299,14 +299,15 @@ export function createAtomCommandScheduler(): AtomCommandScheduler {};}-export function scheduleAtomCommandEffect<W, A, E, R>(- registry: AtomRegistry.AtomRegistry,- scheduler: AtomCommandScheduler,- concurrency: AtomCommandConcurrency<W>,- input: W,- effect: Effect.Effect<A, E, R>,-): Effect.Effect<A, E, R> {- return Effect.gen(function* () {+export const scheduleAtomCommandEffect =+ /* Every atom command passes through this scheduler; the command owns its tracing boundary. */+ Effect.fnUntraced(function* <W, A, E, R>(+ registry: AtomRegistry.AtomRegistry,+ scheduler: AtomCommandScheduler,+ concurrency: AtomCommandConcurrency<W>,+ input: W,+ effect: Effect.Effect<A, E, R>,+ ): Effect.fn.Return<A, E, R> {const context = yield* Effect.context<R>();const result = yield* Effect.promise((signal) =>scheduler.schedule<W, A, E>(registry, concurrency, input, async () => {@@ -318,7 +319,6 @@ export function scheduleAtomCommandEffect<W, A, E, R>();return result._tag === "Success" ? result.value : yield* Effect.failCause(result.cause);});-}export async function runAtomCommand<W, A, E>(registry: AtomRegistry.AtomRegistry,diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.tsindex c0b99600467..73e46450cfa 100644--- a/packages/client-runtime/src/state/threadCommands.ts+++ b/packages/client-runtime/src/state/threadCommands.ts@@ -149,6 +149,23 @@ export function createThreadEnvironmentAtoms<R, E>(key: ({ environmentId, input }: { environmentId: string; input: { threadId: string } }) =>JSON.stringify([environmentId, input.threadId]),};+ const loadEarlierHistory = Effect.fn("ThreadCommands.loadEarlierHistory")(function* (+ input: LoadEarlierThreadHistoryInput,+ ) {+ const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;+ const controller = yield* Effect.serviceOption(ThreadHistoryController.ThreadHistoryController);+ if (Option.isNone(controller)) {+ return {+ _tag: "noop",+ } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult;+ }+ return yield* controller.value.loadEarlier(+ supervisor.target.environmentId,+ input.threadId,+ input.throughEntryId,+ );+ });+const commands = {create: createEnvironmentCommand(runtime, {label: "environment-data:commands:thread:create",@@ -375,23 +392,7 @@ export function createThreadEnvironmentAtoms<R, E>(}),loadEarlierHistory: createEnvironmentCommand(runtime, {label: "environment-data:commands:thread:load-earlier-history",- execute: (input: LoadEarlierThreadHistoryInput) =>- Effect.gen(function* () {- const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;- const controller = yield* Effect.serviceOption(- ThreadHistoryController.ThreadHistoryController,- );- if (Option.isNone(controller)) {- return {- _tag: "noop",- } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult;- }- return yield* controller.value.loadEarlier(- supervisor.target.environmentId,- input.threadId,- input.throughEntryId,- );- }),+ execute: loadEarlierHistory,scheduler,concurrency: {mode: "serial",