TypeScript
chore(lint): enforce effectFnOpportunity (#25099)
Julius Marminge72dde22b6f09
diff --git a/apps/desktop/src/app/DesktopAppActivation.ts b/apps/desktop/src/app/DesktopAppActivation.tsindex 05d5a3254a8..340cb231364 100644--- a/apps/desktop/src/app/DesktopAppActivation.ts+++ b/apps/desktop/src/app/DesktopAppActivation.ts@@ -382,7 +382,10 @@ export const make = Effect.gen(function* () {webContents.send(DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL, request);});}),- complete: (response) => Effect.sync(() => broker.complete(response)),+ // The IPC handler owns the activation-completion span.+ complete: Effect.fnUntraced(function* (response) {+ return yield* Effect.sync(() => broker.complete(response));+ }),});});diff --git a/apps/desktop/src/app/DesktopObservability.ts b/apps/desktop/src/app/DesktopObservability.tsindex 365973f5a30..3cd3936a59b 100644--- a/apps/desktop/src/app/DesktopObservability.ts+++ b/apps/desktop/src/app/DesktopObservability.ts@@ -459,90 +459,91 @@ const makeBackendOutputLogShape = (): Effect.Effect<DesktopBackendOutputLogShape> =>Option.match(sink, {onNone: () => Effect.succeed(DesktopBackendOutputLogNoop),- onSome: (logFile) =>- Effect.gen(function* () {- const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());- const writeFailure = Effect.fn("desktop.observability.backendOutput.writeFailure")(- function* (session: BackendOutputSession, details: string) {- yield* writeBackendChildLogRecord(logFile, {- message: "backend child process failure output start",- level: "ERROR",- annotations: {- component: "desktop-backend-child",- runId: session.runId,- instanceId: id,- phase: "START",- details: session.startDetails,- },- });- for (const output of session.chunks) {- yield* writeBackendChildLogRecord(logFile, {- message: "backend child process output",- level: output.streamName === "stderr" ? "ERROR" : "INFO",- annotations: {- component: "desktop-backend-child",- runId: session.runId,- instanceId: id,- stream: output.streamName,- text: textDecoder.decode(output.chunk.subarray(output.offset)),- },- });- }- yield* writeBackendChildLogRecord(logFile, {- message: "backend child process failure output end",- level: "ERROR",- annotations: {- component: "desktop-backend-child",- runId: session.runId,- instanceId: id,- phase: "END",- details: sanitizeLogValue(details),- },- });+ // The enclosing operation owns the span for this inline handler.+ onSome: Effect.fnUntraced(function* (logFile) {+ const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());+ const writeFailure = Effect.fn("desktop.observability.backendOutput.writeFailure")(function* (+ session: BackendOutputSession,+ details: string,+ ) {+ yield* writeBackendChildLogRecord(logFile, {+ message: "backend child process failure output start",+ level: "ERROR",+ annotations: {+ component: "desktop-backend-child",+ runId: session.runId,+ instanceId: id,+ phase: "START",+ details: session.startDetails,},- );- return {- beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({- details,- }) {- const runId = yield* currentDesktopRunId;- yield* Ref.set(- sessionRef,- Option.some({- runId,- startDetails: sanitizeLogValue(details),- chunks: [],- byteLength: 0,- }),- );- }),- writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {- if (environment.isDevelopment) {- yield* writeDevelopmentConsoleOutput(streamName, chunk);- }- yield* Ref.update(- sessionRef,- Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),- );- }),- persistFailureSnapshot: Effect.fn(- "desktop.observability.backendOutput.persistFailureSnapshot",- )(function* ({ details }) {- const session = yield* Ref.get(sessionRef);- if (Option.isSome(session)) {- yield* writeFailure(session.value, details);- }- }),- persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(- function* ({ details }) {- const session = yield* Ref.modify(sessionRef, (current) => [current, Option.none()]);- if (Option.isNone(session)) return;- yield* writeFailure(session.value, details);+ });+ for (const output of session.chunks) {+ yield* writeBackendChildLogRecord(logFile, {+ message: "backend child process output",+ level: output.streamName === "stderr" ? "ERROR" : "INFO",+ annotations: {+ component: "desktop-backend-child",+ runId: session.runId,+ instanceId: id,+ stream: output.streamName,+ text: textDecoder.decode(output.chunk.subarray(output.offset)),},- ),- discardSession: Ref.set(sessionRef, Option.none()),- } satisfies DesktopBackendOutputLogShape;- }),+ });+ }+ yield* writeBackendChildLogRecord(logFile, {+ message: "backend child process failure output end",+ level: "ERROR",+ annotations: {+ component: "desktop-backend-child",+ runId: session.runId,+ instanceId: id,+ phase: "END",+ details: sanitizeLogValue(details),+ },+ });+ });+ return {+ beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({+ details,+ }) {+ const runId = yield* currentDesktopRunId;+ yield* Ref.set(+ sessionRef,+ Option.some({+ runId,+ startDetails: sanitizeLogValue(details),+ chunks: [],+ byteLength: 0,+ }),+ );+ }),+ writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {+ if (environment.isDevelopment) {+ yield* writeDevelopmentConsoleOutput(streamName, chunk);+ }+ yield* Ref.update(+ sessionRef,+ Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),+ );+ }),+ persistFailureSnapshot: Effect.fn(+ "desktop.observability.backendOutput.persistFailureSnapshot",+ )(function* ({ details }) {+ const session = yield* Ref.get(sessionRef);+ if (Option.isSome(session)) {+ yield* writeFailure(session.value, details);+ }+ }),+ persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(function* ({+ details,+ }) {+ const session = yield* Ref.modify(sessionRef, (current) => [current, Option.none()]);+ if (Option.isNone(session)) return;+ yield* writeFailure(session.value, details);+ }),+ discardSession: Ref.set(sessionRef, Option.none()),+ } satisfies DesktopBackendOutputLogShape;+ }),});const layerBackendOutputLogFactory = Layer.effect(@@ -589,7 +590,9 @@ const layerBackendOutputLogFactory = Layer.effect(});return DesktopBackendOutputLogFactory.of({- forInstance: (id) => makeForId(id),+ forInstance: Effect.fn("DesktopBackendOutputLogFactory.forInstance")(function (id) {+ return makeForId(id);+ }),});}),);diff --git a/apps/desktop/src/app/DesktopWebLinks.ts b/apps/desktop/src/app/DesktopWebLinks.tsindex f448f184b89..ce63a710f7f 100644--- a/apps/desktop/src/app/DesktopWebLinks.ts+++ b/apps/desktop/src/app/DesktopWebLinks.ts@@ -69,16 +69,15 @@ const make = Effect.gen(function* () {});return DesktopWebLinks.of({- receive: (url) =>- Effect.suspend(() => {+ receive: Effect.fn("DesktopWebLinks.receive")(function (url) {+ return Effect.suspend(() => {pending.push(url);return flush;- }).pipe(Effect.withSpan("DesktopWebLinks.receive")),- setRendererReady: (ready) =>- (ready ? startListening : Effect.sync(stopListening)).pipe(- Effect.andThen(flush),- Effect.withSpan("DesktopWebLinks.setRendererReady"),- ),+ });+ }),+ setRendererReady: Effect.fn("DesktopWebLinks.setRendererReady")(function (ready) {+ return ready ? startListening : Effect.sync(stopListening);+ }, Effect.andThen(flush)),});});diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.tsindex 007f7369365..8b5e8045ed3 100644--- a/apps/desktop/src/backend/DesktopBackendManager.ts+++ b/apps/desktop/src/backend/DesktopBackendManager.ts@@ -1043,58 +1043,58 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (});yield* Option.match(active, {onNone: () => Effect.void,- onSome: (run) =>- Effect.gen(function* () {- const closed = yield* closeRun(run, parentScope, options);- if (!closed) {- return;- }- const cleanup = yield* mutex.withPermits(1)(- Ref.modify(- state,- (- latest,- ): readonly [- {- readonly needsCleanup: boolean;- readonly shouldStart: boolean;- },- BackendManagerState,- ] => {- const current = Option.getOrUndefined(latest.active);- if (current?.id !== run.id) {- return [- {- needsCleanup: false,- shouldStart:- latest.desiredRunning &&- Option.isNone(latest.active) &&- Option.isNone(latest.restartFiber),- },- latest,- ];- }+ // The enclosing operation owns the span for this inline handler.+ onSome: Effect.fnUntraced(function* (run) {+ const closed = yield* closeRun(run, parentScope, options);+ if (!closed) {+ return;+ }+ const cleanup = yield* mutex.withPermits(1)(+ Ref.modify(+ state,+ (+ latest,+ ): readonly [+ {+ readonly needsCleanup: boolean;+ readonly shouldStart: boolean;+ },+ BackendManagerState,+ ] => {+ const current = Option.getOrUndefined(latest.active);+ if (current?.id !== run.id) {return [{- needsCleanup: true,- shouldStart: latest.desiredRunning,- },- {- ...latest,- active: Option.none<ActiveBackendRun>(),+ needsCleanup: false,+ shouldStart:+ latest.desiredRunning &&+ Option.isNone(latest.active) &&+ Option.isNone(latest.restartFiber),},+ latest,];- },- ),- );- if (cleanup.needsCleanup) {- yield* desktopTelemetryPublisher.removeControlSource(spec.id);- yield* backendOutputLog.discardSession;- }- if (cleanup.shouldStart) {- yield* start;- }- }),+ }+ return [+ {+ needsCleanup: true,+ shouldStart: latest.desiredRunning,+ },+ {+ ...latest,+ active: Option.none<ActiveBackendRun>(),+ },+ ];+ },+ ),+ );+ if (cleanup.needsCleanup) {+ yield* desktopTelemetryPublisher.removeControlSource(spec.id);+ yield* backendOutputLog.discardSession;+ }+ if (cleanup.shouldStart) {+ yield* start;+ }+ }),});});diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.tsindex 7b2f6851907..4292b92a3d0 100644--- a/apps/desktop/src/backend/DesktopBackendPool.ts+++ b/apps/desktop/src/backend/DesktopBackendPool.ts@@ -291,13 +291,14 @@ export const layer = Layer.effect(});return DesktopBackendPool.of({- get: (id) =>- SynchronizedRef.get(instancesRef).pipe(+ get: Effect.fn("DesktopBackendPool.get")(function (id) {+ return SynchronizedRef.get(instancesRef).pipe(Effect.map((instances) => {const entry = instances.get(id);return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none();}),- ),+ );+ }),list: SynchronizedRef.get(instancesRef).pipe(Effect.map((instances) =>Array.from(instances.values()).flatMap((entry) =>@@ -326,11 +327,17 @@ export const layerTest = ();const primary = instances[0]!;return DesktopBackendPool.of({- get: (id) => Effect.succeed(Option.fromNullishOr(byId.get(id))),+ get: Effect.fn("DesktopBackendPool.get")(function (id) {+ return Effect.succeed(Option.fromNullishOr(byId.get(id)));+ }),list: Effect.succeed(Array.from(byId.values())),primary: Effect.succeed(primary),- register: () => Effect.die("DesktopBackendPool.layerTest does not support register"),- unregister: () => Effect.die("DesktopBackendPool.layerTest does not support unregister"),+ register: Effect.fn("DesktopBackendPool.register")(function () {+ return Effect.die("DesktopBackendPool.layerTest does not support register");+ }),+ unregister: Effect.fn("DesktopBackendPool.unregister")(function () {+ return Effect.die("DesktopBackendPool.layerTest does not support unregister");+ }),});}),);diff --git a/apps/desktop/src/electron/ElectronApp.ts b/apps/desktop/src/electron/ElectronApp.tsindex 7190c70aedc..04f26b1bced 100644--- a/apps/desktop/src/electron/ElectronApp.ts+++ b/apps/desktop/src/electron/ElectronApp.ts@@ -135,59 +135,73 @@ export const make = ElectronApp.of({quit: Effect.sync(() => {Electron.app.quit();}),- exit: (code) =>- Effect.sync(() => {+ exit: Effect.fn("ElectronApp.exit")(function (code) {+ return Effect.sync(() => {Electron.app.exit(code);- }),- relaunch: (options) =>- Effect.sync(() => {+ });+ }),+ relaunch: Effect.fn("ElectronApp.relaunch")(function (options) {+ return Effect.sync(() => {Electron.app.relaunch(options);- }),- setPath: (name, path) =>- Effect.sync(() => {+ });+ }),+ setPath: Effect.fn("ElectronApp.setPath")(function (name, path) {+ return Effect.sync(() => {Electron.app.setPath(name, path);- }),- setName: (name) =>- Effect.sync(() => {+ });+ }),+ setName: Effect.fn("ElectronApp.setName")(function (name) {+ return Effect.sync(() => {Electron.app.setName(name);- }),- setAboutPanelOptions: (options) =>- Effect.sync(() => {+ });+ }),+ setAboutPanelOptions: Effect.fn("ElectronApp.setAboutPanelOptions")(function (options) {+ return Effect.sync(() => {Electron.app.setAboutPanelOptions(options);- }),- setAppUserModelId: (id) =>- Effect.sync(() => {+ });+ }),+ setAppUserModelId: Effect.fn("ElectronApp.setAppUserModelId")(function (id) {+ return Effect.sync(() => {Electron.app.setAppUserModelId(id);- }),+ });+ }),getAppMetrics: Effect.sync(() => Electron.app.getAppMetrics()),- setAsDefaultProtocolClient: (protocol, path, args) =>- Effect.sync(() => {- if (path === undefined) {- return Electron.app.setAsDefaultProtocolClient(protocol);- }- return Electron.app.setAsDefaultProtocolClient(protocol, path, [...(args ?? [])]);- }),- setDesktopName: (desktopName) =>- Effect.sync(() => {+ setAsDefaultProtocolClient: Effect.fn("ElectronApp.setAsDefaultProtocolClient")(+ function (protocol, path, args) {+ return Effect.sync(() => {+ if (path === undefined) {+ return Electron.app.setAsDefaultProtocolClient(protocol);+ }+ return Electron.app.setAsDefaultProtocolClient(protocol, path, [...(args ?? [])]);+ });+ },+ ),+ setDesktopName: Effect.fn("ElectronApp.setDesktopName")(function (desktopName) {+ return Effect.sync(() => {const linuxApp = Electron.app as Electron.App & {setDesktopName?: (desktopName: string) => void;};linuxApp.setDesktopName?.(desktopName);- }),- setDockIcon: (iconPath) =>- Effect.sync(() => {+ });+ }),+ setDockIcon: Effect.fn("ElectronApp.setDockIcon")(function (iconPath) {+ return Effect.sync(() => {Electron.app.dock?.setIcon(iconPath);- }),- appendCommandLineSwitch: (switchName, value) =>- Effect.sync(() => {- if (value === undefined) {- Electron.app.commandLine.appendSwitch(switchName);- return;- }- Electron.app.commandLine.appendSwitch(switchName, value);- }),- onBeforeQuitForUpdate: (listener) =>- Effect.acquireRelease(+ });+ }),+ appendCommandLineSwitch: Effect.fn("ElectronApp.appendCommandLineSwitch")(+ function (switchName, value) {+ return Effect.sync(() => {+ if (value === undefined) {+ Electron.app.commandLine.appendSwitch(switchName);+ return;+ }+ Electron.app.commandLine.appendSwitch(switchName, value);+ });+ },+ ),+ onBeforeQuitForUpdate: Effect.fn("ElectronApp.onBeforeQuitForUpdate")(function (listener) {+ return Effect.acquireRelease(Effect.sync(() => {Electron.autoUpdater.on("before-quit-for-update", listener);}),@@ -195,11 +209,13 @@ export const make = ElectronApp.of({Effect.sync(() => {Electron.autoUpdater.removeListener("before-quit-for-update", listener);}),- ).pipe(Effect.asVoid),- removeCommandLineSwitch: (switchName) =>- Effect.sync(() => {+ ).pipe(Effect.asVoid);+ }),+ removeCommandLineSwitch: Effect.fn("ElectronApp.removeCommandLineSwitch")(function (switchName) {+ return Effect.sync(() => {Electron.app.commandLine.removeSwitch(switchName);- }),+ });+ }),on: addScopedAppListener,});diff --git a/apps/desktop/src/electron/ElectronDialog.ts b/apps/desktop/src/electron/ElectronDialog.tsindex 8f0df220161..4f9ab12eddc 100644--- a/apps/desktop/src/electron/ElectronDialog.ts+++ b/apps/desktop/src/electron/ElectronDialog.ts@@ -166,8 +166,8 @@ export const make = ElectronDialog.of({});return result.canceled ? [] : result.filePaths;}),- showMessageBox: (options, owner) =>- Effect.tryPromise({+ showMessageBox: Effect.fn("ElectronDialog.showMessageBox")(function (options, owner) {+ return Effect.tryPromise({try: () =>owner === undefined? Electron.dialog.showMessageBox(options)@@ -181,9 +181,10 @@ export const make = ElectronDialog.of({buttonCount: options.buttons?.length ?? 0,cause,}),- }),- showErrorBox: (title, content) =>- Effect.try({+ });+ }),+ showErrorBox: Effect.fn("ElectronDialog.showErrorBox")(function (title, content) {+ return Effect.try({try: () => Electron.dialog.showErrorBox(title, content),catch: (cause) =>new ElectronDialogShowErrorBoxError({@@ -191,7 +192,8 @@ export const make = ElectronDialog.of({contentLength: content.length,cause,}),- }).pipe(Effect.orDie),+ }).pipe(Effect.orDie);+ }),});export const layer = Layer.succeed(ElectronDialog, make);diff --git a/apps/desktop/src/electron/ElectronMenu.ts b/apps/desktop/src/electron/ElectronMenu.tsindex a58eb0c743f..d4338b45e28 100644--- a/apps/desktop/src/electron/ElectronMenu.ts+++ b/apps/desktop/src/electron/ElectronMenu.ts@@ -187,8 +187,8 @@ export const make = Effect.gen(function* () {};return ElectronMenu.of({- setApplicationMenu: (template) =>- Effect.try({+ setApplicationMenu: Effect.fn("ElectronMenu.setApplicationMenu")(function (template) {+ return Effect.try({try: () => {Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));},@@ -200,9 +200,10 @@ export const make = Effect.gen(function* () {itemCount: template.length,cause,}),- }).pipe(Effect.orDie),- popupTemplate: (input) =>- input.template.length === 0+ }).pipe(Effect.orDie);+ }),+ popupTemplate: Effect.fn("ElectronMenu.popupTemplate")(function (input) {+ return input.template.length === 0? Effect.void: Effect.try({try: () =>@@ -218,9 +219,10 @@ export const make = Effect.gen(function* () {itemCount: input.template.length,cause,}),- }).pipe(Effect.orDie),- showContextMenu: (input) =>- Effect.callback<Option.Option<string>>((resume) => {+ }).pipe(Effect.orDie);+ }),+ showContextMenu: Effect.fn("ElectronMenu.showContextMenu")(function (input) {+ return Effect.callback<Option.Option<string>>((resume) => {const normalizedItems = normalizeContextMenuItems(input.items);if (normalizedItems.length === 0) {resume(Effect.succeedNone);@@ -272,7 +274,8 @@ export const make = Effect.gen(function* () {),);}- }),+ });+ }),});});diff --git a/apps/desktop/src/electron/ElectronPowerMonitor.ts b/apps/desktop/src/electron/ElectronPowerMonitor.tsindex 41c36acf225..5a702b61a81 100644--- a/apps/desktop/src/electron/ElectronPowerMonitor.ts+++ b/apps/desktop/src/electron/ElectronPowerMonitor.ts@@ -79,8 +79,11 @@ const onSpeedLimitChange: ElectronPowerMonitor["Service"]["onSpeedLimitChange"]export const make = ElectronPowerMonitor.of({isOnBatteryPower: Effect.sync(() => Electron.powerMonitor.isOnBatteryPower()),getSystemIdleTime: Effect.sync(() => Electron.powerMonitor.getSystemIdleTime()),- getSystemIdleState: (idleThresholdSeconds) =>- Effect.sync(() => Electron.powerMonitor.getSystemIdleState(idleThresholdSeconds)),+ getSystemIdleState: Effect.fn("ElectronPowerMonitor.getSystemIdleState")(+ function (idleThresholdSeconds) {+ return Effect.sync(() => Electron.powerMonitor.getSystemIdleState(idleThresholdSeconds));+ },+ ),getCurrentThermalState: Effect.sync(() => Electron.powerMonitor.getCurrentThermalState()),onSimpleEvent,onThermalStateChange,diff --git a/apps/desktop/src/electron/ElectronSafeStorage.ts b/apps/desktop/src/electron/ElectronSafeStorage.tsindex 0395d20e9bd..9725fd41e13 100644--- a/apps/desktop/src/electron/ElectronSafeStorage.ts+++ b/apps/desktop/src/electron/ElectronSafeStorage.ts@@ -74,16 +74,18 @@ export const make = Effect.gen(function* () {try: () => Electron.safeStorage.isEncryptionAvailable(),catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),}),- encryptString: (value) =>- Effect.try({+ encryptString: Effect.fn("ElectronSafeStorage.encryptString")(function (value) {+ return Effect.try({try: () => Electron.safeStorage.encryptString(value),catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),- }),- decryptString: (value) =>- Effect.try({+ });+ }),+ decryptString: Effect.fn("ElectronSafeStorage.decryptString")(function (value) {+ return Effect.try({try: () => Electron.safeStorage.decryptString(Buffer.from(value)),catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),- }),+ });+ }),selectedStorageBackend: Effect.sync(() => {if (platform !== "linux") {return Option.none();diff --git a/apps/desktop/src/electron/ElectronShell.ts b/apps/desktop/src/electron/ElectronShell.tsindex a72963c2e25..e32dba36a6d 100644--- a/apps/desktop/src/electron/ElectronShell.ts+++ b/apps/desktop/src/electron/ElectronShell.ts@@ -63,8 +63,8 @@ export class ElectronShell extends Context.Service</** @public */export const make = ElectronShell.of({- openExternal: (rawUrl) =>- Option.match(parseSafeExternalUrl(rawUrl), {+ openExternal: Effect.fn("ElectronShell.openExternal")(function (rawUrl) {+ return Option.match(parseSafeExternalUrl(rawUrl), {onNone: () => Effect.succeed(false),onSome: (externalUrl) =>Effect.promise(() =>@@ -73,16 +73,19 @@ export const make = ElectronShell.of({() => false,),),- }),- openSystemSettings: (pane) =>- Effect.promise(() =>+ });+ }),+ openSystemSettings: Effect.fn("ElectronShell.openSystemSettings")(function (pane) {+ return Effect.promise(() =>Electron.shell.openExternal(MAC_PERMISSION_SETTINGS_URLS[pane]).then(() => true,() => false,),- ),- copyText: (text) =>- Effect.promise(() => Electron.clipboard.writeText(text).catch(() => undefined)),+ );+ }),+ copyText: Effect.fn("ElectronShell.copyText")(function (text) {+ return Effect.promise(() => Electron.clipboard.writeText(text).catch(() => undefined));+ }),});export const layer = Layer.succeed(ElectronShell, make);diff --git a/apps/desktop/src/electron/ElectronTheme.ts b/apps/desktop/src/electron/ElectronTheme.tsindex a84eedda13b..ab0673b817a 100644--- a/apps/desktop/src/electron/ElectronTheme.ts+++ b/apps/desktop/src/electron/ElectronTheme.ts@@ -31,15 +31,16 @@ export class ElectronTheme extends Context.Service</** @public */export const make = ElectronTheme.of({shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),- setSource: (theme) =>- Effect.try({+ setSource: Effect.fn("ElectronTheme.setSource")(function (theme) {+ return Effect.try({try: () => {Electron.nativeTheme.themeSource = theme;},catch: (cause) => new ElectronThemeSetSourceError({ source: theme, cause }),- }),- onUpdated: (listener) =>- Effect.acquireRelease(+ });+ }),+ onUpdated: Effect.fn("ElectronTheme.onUpdated")(function (listener) {+ return Effect.acquireRelease(Effect.suspend(() => {Electron.nativeTheme.on("updated", listener);return Effect.void;@@ -49,7 +50,8 @@ export const make = ElectronTheme.of({Electron.nativeTheme.removeListener("updated", listener);return Effect.void;}),- ),+ );+ }),});export const layer = Layer.succeed(ElectronTheme, make);diff --git a/apps/desktop/src/electron/ElectronUpdater.ts b/apps/desktop/src/electron/ElectronUpdater.tsindex 39704493260..c71b42040db 100644--- a/apps/desktop/src/electron/ElectronUpdater.ts+++ b/apps/desktop/src/electron/ElectronUpdater.ts@@ -82,47 +82,57 @@ export class ElectronUpdater extends Context.Service</** @public */export const make = ElectronUpdater.of({- setFeedURL: (options) =>- Effect.suspend(() => {+ setFeedURL: Effect.fn("ElectronUpdater.setFeedURL")(function (options) {+ return Effect.suspend(() => {autoUpdater.setFeedURL(options);return Effect.void;- }),- setAutoDownload: (value) =>- Effect.suspend(() => {+ });+ }),+ setAutoDownload: Effect.fn("ElectronUpdater.setAutoDownload")(function (value) {+ return Effect.suspend(() => {autoUpdater.autoDownload = value;return Effect.void;- }),- setAutoInstallOnAppQuit: (value) =>- Effect.suspend(() => {+ });+ }),+ setAutoInstallOnAppQuit: Effect.fn("ElectronUpdater.setAutoInstallOnAppQuit")(function (value) {+ return Effect.suspend(() => {autoUpdater.autoInstallOnAppQuit = value;return Effect.void;- }),- setChannel: (channel) =>- Effect.suspend(() => {+ });+ }),+ setChannel: Effect.fn("ElectronUpdater.setChannel")(function (channel) {+ return Effect.suspend(() => {autoUpdater.channel = channel;return Effect.void;- }),- setAllowPrerelease: (value) =>- Effect.suspend(() => {+ });+ }),+ setAllowPrerelease: Effect.fn("ElectronUpdater.setAllowPrerelease")(function (value) {+ return Effect.suspend(() => {autoUpdater.allowPrerelease = value;return Effect.void;- }),+ });+ }),allowDowngrade: Effect.sync(() => autoUpdater.allowDowngrade),- setAllowDowngrade: (value) =>- Effect.suspend(() => {+ setAllowDowngrade: Effect.fn("ElectronUpdater.setAllowDowngrade")(function (value) {+ return Effect.suspend(() => {autoUpdater.allowDowngrade = value;return Effect.void;- }),- setFullChangelog: (value) =>- Effect.suspend(() => {+ });+ }),+ setFullChangelog: Effect.fn("ElectronUpdater.setFullChangelog")(function (value) {+ return Effect.suspend(() => {autoUpdater.fullChangelog = value;return Effect.void;- }),- setDisableDifferentialDownload: (value) =>- Effect.suspend(() => {- autoUpdater.disableDifferentialDownload = value;- return Effect.void;- }),+ });+ }),+ setDisableDifferentialDownload: Effect.fn("ElectronUpdater.setDisableDifferentialDownload")(+ function (value) {+ return Effect.suspend(() => {+ autoUpdater.disableDifferentialDownload = value;+ return Effect.void;+ });+ },+ ),checkForUpdates: Effect.suspend(() => {const channel = autoUpdater.channel;return Effect.tryPromise({@@ -137,8 +147,11 @@ export const make = ElectronUpdater.of({catch: (cause) => new ElectronUpdaterDownloadUpdateError({ channel, cause }),}).pipe(Effect.asVoid);}),- quitAndInstall: ({ isSilent, isForceRunAfter }) =>- Effect.suspend(() => {+ quitAndInstall: Effect.fn("ElectronUpdater.quitAndInstall")(function ({+ isSilent,+ isForceRunAfter,+ }) {+ return Effect.suspend(() => {const channel = autoUpdater.channel;return Effect.try({try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),@@ -150,8 +163,9 @@ export const make = ElectronUpdater.of({cause,}),});- }),- on: (eventName, listener) => {+ });+ }),+ on: Effect.fn("ElectronUpdater.on")(function (eventName, listener) {const eventTarget = autoUpdater as unknown as {on: (eventName: string, listener: (...args: Array<unknown>) => void) => void;removeListener: (eventName: string, listener: (...args: Array<unknown>) => void) => void;@@ -166,7 +180,7 @@ export const make = ElectronUpdater.of({eventTarget.removeListener(eventName, untypedListener);}),).pipe(Effect.asVoid);- },+ }),});export const layer = Layer.succeed(ElectronUpdater, make);diff --git a/apps/desktop/src/electron/ElectronWindow.ts b/apps/desktop/src/electron/ElectronWindow.tsindex 60908ee90dc..35303ed935a 100644--- a/apps/desktop/src/electron/ElectronWindow.ts+++ b/apps/desktop/src/electron/ElectronWindow.ts@@ -207,7 +207,7 @@ export const make = Effect.gen(function* () {});return ElectronWindow.of({- create: (options) => {+ create: Effect.fn("ElectronWindow.create")(function (options) {const webPreferences = options.webPreferences;const diagnosticOptions = {title: options.title ?? null,@@ -235,13 +235,15 @@ export const make = Effect.gen(function* () {try: () => new Electron.BrowserWindow(options),catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),});- },+ }),main: liveMain,currentMainOrFirst,focusedMainOrFirst,- setMain: (window) => Ref.set(mainWindowRef, Option.some(window)),- clearMain: (window) =>- Ref.update(mainWindowRef, (current) => {+ setMain: Effect.fn("ElectronWindow.setMain")(function (window) {+ return Ref.set(mainWindowRef, Option.some(window));+ }),+ clearMain: Effect.fn("ElectronWindow.clearMain")(function (window) {+ return Ref.update(mainWindowRef, (current) => {if (Option.isNone(current)) {return current;}@@ -249,9 +251,10 @@ export const make = Effect.gen(function* () {return current;}return Option.none();- }),- prepareReveal: (window) =>- Effect.promise(async () => {+ });+ }),+ prepareReveal: Effect.fn("ElectronWindow.prepareReveal")(function (window) {+ return Effect.promise(async () => {if (platform !== "win32" || window.isDestroyed()) {return false;}@@ -259,9 +262,10 @@ export const make = Effect.gen(function* () {return ensureWindowsForegroundFocus().prepare(windowsForegroundFocusTarget(window)).catch(() => false);- }),- reveal: (window) =>- Effect.tryPromise({+ });+ }),+ reveal: Effect.fn("ElectronWindow.reveal")(function (window) {+ return Effect.tryPromise({try: async () => {if (window.isDestroyed()) {return;@@ -322,7 +326,8 @@ export const make = Effect.gen(function* () {channel: null,cause,}),- }).pipe(Effect.orDie),+ }).pipe(Effect.orDie);+ }),sendAll:/* Window broadcasts run for streamed updates; avoid a span per broadcast. */Effect.fnUntraced(function* (channel, ...args) {diff --git a/apps/desktop/src/settings/DesktopAppSettings.test.ts b/apps/desktop/src/settings/DesktopAppSettings.test.tsindex 832a7745771..0135225f90c 100644--- a/apps/desktop/src/settings/DesktopAppSettings.test.ts+++ b/apps/desktop/src/settings/DesktopAppSettings.test.ts@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Schema from "effect/Schema";+import * as Tracer from "effect/Tracer";import * as DesktopConfig from "../app/DesktopConfig.ts";import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";@@ -90,6 +91,37 @@ function writeSettingsPatch(patch: typeof DesktopSettingsPatch.Type) {}describe("DesktopSettings", () => {+ it.effect("records one bounds operation span with its input attributes", () =>+ Effect.gen(function* () {+ const spans: Array<Tracer.Span> = [];+ const tracer = Tracer.make({+ span: (options) => {+ const span = new Tracer.NativeSpan(options);+ spans.push(span);+ return span;+ },+ });+ yield* withSettings(+ Effect.gen(function* () {+ const settings = yield* DesktopAppSettings.DesktopAppSettings;+ yield* settings.setMainWindowBounds({ x: 10, y: 20, width: 900, height: 600 }, true);+ }),+ ).pipe(Effect.provideService(Tracer.Tracer, tracer));+ const operationSpans = spans.filter(+ (span) => span.name === "desktop.settings.setMainWindowBounds",+ );+ assert.lengthOf(operationSpans, 1);+ assert.deepEqual(Object.fromEntries(operationSpans[0]!.attributes), {+ x: 10,+ y: 20,+ width: 900,+ height: 600,+ isMaximized: true,+ });+ assert.equal(operationSpans[0]!.status._tag, "Ended");+ }),+ );+it.effect("persists disabling and re-enabling local execution without clearing backend settings",() =>diff --git a/apps/desktop/src/settings/DesktopAppSettings.ts b/apps/desktop/src/settings/DesktopAppSettings.tsindex 433e8127a50..5767057b4a3 100644--- a/apps/desktop/src/settings/DesktopAppSettings.ts+++ b/apps/desktop/src/settings/DesktopAppSettings.ts@@ -521,48 +521,56 @@ export const make = Effect.gen(function* () {);return yield* SynchronizedRef.setAndGet(settingsRef, settings);}).pipe(Effect.withSpan("desktop.settings.load")),- setMainWindowBounds: (bounds, isMaximized) =>- persist((settings) => setMainWindowBounds(settings, bounds, isMaximized)).pipe(- Effect.withSpan("desktop.settings.setMainWindowBounds", {- attributes: {- x: bounds.x,- y: bounds.y,- width: bounds.width,- height: bounds.height,- isMaximized,- },- }),- ),- setServerExposureMode: (mode) =>- persist((settings) => setServerExposureMode(settings, mode)).pipe(- Effect.withSpan("desktop.settings.setServerExposureMode", { attributes: { mode } }),- ),- setTailscaleServe: (input) =>- persist((settings) => setTailscaleServe(settings, input)).pipe(- Effect.withSpan("desktop.settings.setTailscaleServe", { attributes: input }),- ),- setUpdateChannel: (channel) =>- persist((settings) => setUpdateChannel(settings, channel)).pipe(- Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),- ),- setWslBackendEnabled: (enabled) =>- persist((settings) => setWslBackendEnabled(settings, enabled)).pipe(- Effect.withSpan("desktop.settings.setWslBackendEnabled", { attributes: { enabled } }),- ),- setWslDistro: (distro) =>- persist((settings) => setWslDistro(settings, distro)).pipe(- Effect.withSpan("desktop.settings.setWslDistro", {- attributes: { distro: distro ?? null },- }),- ),- setWslOnly: (enabled) =>- persist((settings) => setWslOnly(settings, enabled)).pipe(- Effect.withSpan("desktop.settings.setWslOnly", { attributes: { enabled } }),- ),- setLocalEnvironmentEnabled: (enabled) =>- persist((settings) => setLocalEnvironmentEnabled(settings, enabled)).pipe(- Effect.withSpan("desktop.settings.setLocalEnvironmentEnabled", { attributes: { enabled } }),- ),+ setMainWindowBounds: Effect.fn("desktop.settings.setMainWindowBounds")(+ function* (bounds, isMaximized) {+ yield* Effect.annotateCurrentSpan({+ x: bounds.x,+ y: bounds.y,+ width: bounds.width,+ height: bounds.height,+ isMaximized,+ });++ return yield* persist((settings) => setMainWindowBounds(settings, bounds, isMaximized));+ },+ ),+ setServerExposureMode: Effect.fn("desktop.settings.setServerExposureMode")(function* (mode) {+ yield* Effect.annotateCurrentSpan({ mode });++ return yield* persist((settings) => setServerExposureMode(settings, mode));+ }),+ setTailscaleServe: Effect.fn("desktop.settings.setTailscaleServe")(function* (input) {+ yield* Effect.annotateCurrentSpan(input);++ return yield* persist((settings) => setTailscaleServe(settings, input));+ }),+ setUpdateChannel: Effect.fn("desktop.settings.setUpdateChannel")(function* (channel) {+ yield* Effect.annotateCurrentSpan({ channel });++ return yield* persist((settings) => setUpdateChannel(settings, channel));+ }),+ setWslBackendEnabled: Effect.fn("desktop.settings.setWslBackendEnabled")(function* (enabled) {+ yield* Effect.annotateCurrentSpan({ enabled });++ return yield* persist((settings) => setWslBackendEnabled(settings, enabled));+ }),+ setWslDistro: Effect.fn("desktop.settings.setWslDistro")(function* (distro) {+ yield* Effect.annotateCurrentSpan({ distro: distro ?? null });++ return yield* persist((settings) => setWslDistro(settings, distro));+ }),+ setWslOnly: Effect.fn("desktop.settings.setWslOnly")(function* (enabled) {+ yield* Effect.annotateCurrentSpan({ enabled });++ return yield* persist((settings) => setWslOnly(settings, enabled));+ }),+ setLocalEnvironmentEnabled: Effect.fn("desktop.settings.setLocalEnvironmentEnabled")(+ function* (enabled) {+ yield* Effect.annotateCurrentSpan({ enabled });++ return yield* persist((settings) => setLocalEnvironmentEnabled(settings, enabled));+ },+ ),applyWslWindowsFallback: persist(applyWslWindowsFallback).pipe(Effect.withSpan("desktop.settings.applyWslWindowsFallback"),),@@ -594,18 +602,38 @@ export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SETreturn DesktopAppSettings.of({get: SynchronizedRef.get(settingsRef),load: SynchronizedRef.get(settingsRef),- setMainWindowBounds: (bounds, isMaximized) =>- update((settings) => setMainWindowBounds(settings, bounds, isMaximized)),- setServerExposureMode: (mode) =>- update((settings) => setServerExposureMode(settings, mode)),- setTailscaleServe: (input) => update((settings) => setTailscaleServe(settings, input)),- setUpdateChannel: (channel) => update((settings) => setUpdateChannel(settings, channel)),- setWslBackendEnabled: (enabled) =>- update((settings) => setWslBackendEnabled(settings, enabled)),- setWslDistro: (distro) => update((settings) => setWslDistro(settings, distro)),- setWslOnly: (enabled) => update((settings) => setWslOnly(settings, enabled)),- setLocalEnvironmentEnabled: (enabled) =>- update((settings) => setLocalEnvironmentEnabled(settings, enabled)),+ setMainWindowBounds: Effect.fn("DesktopAppSettings.setMainWindowBounds")(+ function (bounds, isMaximized) {+ return update((settings) => setMainWindowBounds(settings, bounds, isMaximized));+ },+ ),+ setServerExposureMode: Effect.fn("DesktopAppSettings.setServerExposureMode")(+ function (mode) {+ return update((settings) => setServerExposureMode(settings, mode));+ },+ ),+ setTailscaleServe: Effect.fn("DesktopAppSettings.setTailscaleServe")(function (input) {+ return update((settings) => setTailscaleServe(settings, input));+ }),+ setUpdateChannel: Effect.fn("DesktopAppSettings.setUpdateChannel")(function (channel) {+ return update((settings) => setUpdateChannel(settings, channel));+ }),+ setWslBackendEnabled: Effect.fn("DesktopAppSettings.setWslBackendEnabled")(+ function (enabled) {+ return update((settings) => setWslBackendEnabled(settings, enabled));+ },+ ),+ setWslDistro: Effect.fn("DesktopAppSettings.setWslDistro")(function (distro) {+ return update((settings) => setWslDistro(settings, distro));+ }),+ setWslOnly: Effect.fn("DesktopAppSettings.setWslOnly")(function (enabled) {+ return update((settings) => setWslOnly(settings, enabled));+ }),+ setLocalEnvironmentEnabled: Effect.fn("DesktopAppSettings.setLocalEnvironmentEnabled")(+ function (enabled) {+ return update((settings) => setLocalEnvironmentEnabled(settings, enabled));+ },+ ),applyWslWindowsFallback: update(applyWslWindowsFallback),applyWslWindowsFallbackInMemory: update(applyWslWindowsFallback),});diff --git a/apps/desktop/src/settings/DesktopClientSettings.ts b/apps/desktop/src/settings/DesktopClientSettings.tsindex 7c65c35cf04..0836db66782 100644--- a/apps/desktop/src/settings/DesktopClientSettings.ts+++ b/apps/desktop/src/settings/DesktopClientSettings.ts@@ -194,8 +194,8 @@ export const make = Effect.gen(function* () {get: readClientSettings(fileSystem, environment.clientSettingsPath).pipe(Effect.withSpan("desktop.clientSettings.get"),),- set: (settings) =>- crypto.randomUUIDv4().pipe(+ set: Effect.fn("desktop.clientSettings.set")(function (settings) {+ return crypto.randomUUIDv4().pipe(Effect.map((uuid) => uuid.replace(/-/g, "")),Effect.mapError((cause) =>@@ -214,8 +214,8 @@ export const make = Effect.gen(function* () {suffix,}),),- Effect.withSpan("desktop.clientSettings.set"),- ),+ );+ }),});});@@ -228,7 +228,9 @@ export const layerTest = (initialSettings: Option.Option<ClientSettings> = Optioconst settingsRef = yield* Ref.make(initialSettings);return DesktopClientSettings.of({get: Ref.get(settingsRef),- set: (settings) => Ref.set(settingsRef, Option.some(settings)),+ set: Effect.fn("DesktopClientSettings.set")(function (settings) {+ return Ref.set(settingsRef, Option.some(settings));+ }),});}),);diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.ts b/apps/desktop/src/snapShot/DesktopSnapShot.tsindex 9958fad3705..30edacb073c 100644--- a/apps/desktop/src/snapShot/DesktopSnapShot.ts+++ b/apps/desktop/src/snapShot/DesktopSnapShot.ts@@ -1718,24 +1718,28 @@ export const make = Effect.gen(function* () {),),),- setAnimationDestination: (id, destination) =>- Effect.promise(async () => {- if (linuxFeedback?.id === id && destination.relativeFrame) {- await linuxFeedback.feedback- .animateTo(destination.relativeFrame)- .catch(() => closeLinuxFeedback(id));- return;- }- transition.animateTo(id, destination);- await transition.waitForLanding(id);- }),- dismissAnimation: (id) =>- Effect.sync(() => {+ setAnimationDestination: Effect.fn("DesktopSnapShot.setAnimationDestination")(+ function (id, destination) {+ return Effect.promise(async () => {+ if (linuxFeedback?.id === id && destination.relativeFrame) {+ await linuxFeedback.feedback+ .animateTo(destination.relativeFrame)+ .catch(() => closeLinuxFeedback(id));+ return;+ }+ transition.animateTo(id, destination);+ await transition.waitForLanding(id);+ });+ },+ ),+ dismissAnimation: Effect.fn("DesktopSnapShot.dismissAnimation")(function (id) {+ return Effect.sync(() => {closeLinuxFeedback(id);transition.dismiss(id);- }),- acknowledge: (id) =>- Effect.promise(async () => {+ });+ }),+ acknowledge: Effect.fn("DesktopSnapShot.acknowledge")(function (id) {+ return Effect.promise(async () => {await completeLinuxFeedback(id);await transition.complete(id);}).pipe(@@ -1751,7 +1755,8 @@ export const make = Effect.gen(function* () {Effect.mapError((cause) => new DesktopSnapShotError({ operation: "acknowledge", captureId: id, cause }),),- ),+ );+ }),});});diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.tsindex eac148ae4d0..f6c9ee43d75 100644--- a/apps/desktop/src/ssh/DesktopSshEnvironment.ts+++ b/apps/desktop/src/ssh/DesktopSshEnvironment.ts@@ -133,32 +133,26 @@ export const make = Effect.gen(function* () {const passwordPrompt = SshAuth.SshPasswordPrompt.of(makePasswordPrompt(prompts));return DesktopSshEnvironment.of({- discoverHosts: (input) =>- discoverDesktopSshHostsEffect(input).pipe(- Effect.provide(runtimeContext),- Effect.withSpan("desktop.ssh.discoverHosts"),- ),- resolveHost: (alias) =>- resolveSshTarget(alias.trim()).pipe(- Effect.provide(runtimeContext),- Effect.withSpan("desktop.ssh.resolveHost"),- ),- ensureEnvironment: (target, ensureOptions) =>- manager- .ensureEnvironment(target, ensureOptions)- .pipe(- Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),- Effect.provide(runtimeContext),- Effect.withSpan("desktop.ssh.ensureEnvironment"),- ),- disconnectEnvironment: (target) =>- manager- .disconnectEnvironment(target)- .pipe(- Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),- Effect.provide(runtimeContext),- Effect.withSpan("desktop.ssh.disconnectEnvironment"),- ),+ discoverHosts: Effect.fn("desktop.ssh.discoverHosts")(function* (input) {+ return yield* discoverDesktopSshHostsEffect(input);+ }, Effect.provide(runtimeContext)),+ resolveHost: Effect.fn("desktop.ssh.resolveHost")(function* (alias) {+ return yield* resolveSshTarget(alias.trim());+ }, Effect.provide(runtimeContext)),+ ensureEnvironment: Effect.fn("desktop.ssh.ensureEnvironment")(+ function* (target, ensureOptions) {+ return yield* manager.ensureEnvironment(target, ensureOptions);+ },+ Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),+ Effect.provide(runtimeContext),+ ),+ disconnectEnvironment: Effect.fn("desktop.ssh.disconnectEnvironment")(+ function* (target) {+ return yield* manager.disconnectEnvironment(target);+ },+ Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),+ Effect.provide(runtimeContext),+ ),});});diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.tsindex 5265d65523b..3d6556ffae9 100644--- a/apps/desktop/src/updates/DesktopUpdates.ts+++ b/apps/desktop/src/updates/DesktopUpdates.ts@@ -1159,7 +1159,9 @@ export const make = Effect.gen(function* () {install: installWithExpectedVersion().pipe(Effect.map(({ accepted, completed, state }) => ({ accepted, completed, state })),),- installPrepared: (expectedVersion) => installWithExpectedVersion(expectedVersion),+ installPrepared: Effect.fn("DesktopUpdates.installPrepared")(function (expectedVersion) {+ return installWithExpectedVersion(expectedVersion);+ }),});});diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.tsindex 5017793d073..36939729682 100644--- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts+++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts@@ -1070,33 +1070,57 @@ export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {isAvailable: Effect.succeed(stub.isAvailable ?? false),listDistros: probeDistros.pipe(Effect.orElseSucceed(() => [])),probeDistros,- preWarm: () => Effect.void,- windowsToWslPath: (distro, windowsPath) =>- Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none()),- getUserHome: (distro) => Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>()),- getDistroIp: (distro) => Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>()),- prepareRuntime: (distro, archive) =>- Effect.succeed(+ preWarm: Effect.fn("DesktopWslEnvironment.preWarm")(function () {+ return Effect.void;+ }),+ windowsToWslPath: Effect.fn("DesktopWslEnvironment.windowsToWslPath")(+ function (distro, windowsPath) {+ return Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none());+ },+ ),+ getUserHome: Effect.fn("DesktopWslEnvironment.getUserHome")(function (distro) {+ return Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>());+ }),+ getDistroIp: Effect.fn("DesktopWslEnvironment.getDistroIp")(function (distro) {+ return Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>());+ }),+ prepareRuntime: Effect.fn("DesktopWslEnvironment.prepareRuntime")(function (distro, archive) {+ return Effect.succeed(stub.prepareRuntime?.(distro, archive) ?? {ok: false,reason: "prepareRuntime stub not configured",},- ),- pruneRuntimes: (distro, runtimeId) => stub.pruneRuntimes?.(distro, runtimeId) ?? Effect.void,- invalidateRuntime: (distro, runtimeId) =>- stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void,- probeRuntime: (distro, linuxAppRoot) =>- Effect.succeed(- stub.probeRuntime?.(distro, linuxAppRoot) ?? { ok: true, resolvedPath: "/usr/bin:/bin" },- ),- ensureNodePty: (distro, linuxAppRoot, options) =>- Effect.succeed(- stub.ensureNodePty?.(distro, linuxAppRoot, options) ?? {- ok: false,- reason: "ensureNodePty stub not configured",- fatal: true,- },- ),+ );+ }),+ pruneRuntimes: Effect.fn("DesktopWslEnvironment.pruneRuntimes")(function (distro, runtimeId) {+ return stub.pruneRuntimes?.(distro, runtimeId) ?? Effect.void;+ }),+ invalidateRuntime: Effect.fn("DesktopWslEnvironment.invalidateRuntime")(+ function (distro, runtimeId) {+ return stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void;+ },+ ),+ probeRuntime: Effect.fn("DesktopWslEnvironment.probeRuntime")(+ function (distro, linuxAppRoot) {+ return Effect.succeed(+ stub.probeRuntime?.(distro, linuxAppRoot) ?? {+ ok: true,+ resolvedPath: "/usr/bin:/bin",+ },+ );+ },+ ),+ ensureNodePty: Effect.fn("DesktopWslEnvironment.ensureNodePty")(+ function (distro, linuxAppRoot, options) {+ return Effect.succeed(+ stub.ensureNodePty?.(distro, linuxAppRoot, options) ?? {+ ok: false,+ reason: "ensureNodePty stub not configured",+ fatal: true,+ },+ );+ },+ ),}),);};@@ -1151,31 +1175,29 @@ export const layer = Layer.effect(Effect.withSpan("desktop.wsl.listDistros"),),probeDistros,- preWarm: (distro) =>- provideSpawner(preWarmImpl(distro)).pipe(Effect.withSpan("desktop.wsl.preWarm")),+ preWarm: Effect.fn("desktop.wsl.preWarm")(function (distro) {+ return provideSpawner(preWarmImpl(distro));+ }),windowsToWslPath,getUserHome,getDistroIp,- prepareRuntime: (distro, archive) =>- provideSpawner(prepareWslRuntimeImpl(distro, archive, windowsToWslPath)).pipe(- Effect.withSpan("desktop.wsl.prepareRuntime"),- ),- pruneRuntimes: (distro, runtimeId) =>- provideSpawner(pruneWslRuntimesImpl(distro, runtimeId)).pipe(- Effect.withSpan("desktop.wsl.pruneRuntimes"),- ),- invalidateRuntime: (distro, runtimeId) =>- provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId)).pipe(- Effect.withSpan("desktop.wsl.invalidateRuntime"),- ),- probeRuntime: (distro, linuxAppRoot) =>- provideSpawner(probeWslRuntimeImpl(distro, linuxAppRoot)).pipe(- Effect.withSpan("desktop.wsl.probeRuntime"),- ),- ensureNodePty: (distro, linuxAppRoot, options) =>- provideSpawner(ensureNodePtyImpl(distro, linuxAppRoot, options)).pipe(- Effect.withSpan("desktop.wsl.ensureNodePty"),- ),+ prepareRuntime: Effect.fn("desktop.wsl.prepareRuntime")(function (distro, archive) {+ return provideSpawner(prepareWslRuntimeImpl(distro, archive, windowsToWslPath));+ }),+ pruneRuntimes: Effect.fn("desktop.wsl.pruneRuntimes")(function (distro, runtimeId) {+ return provideSpawner(pruneWslRuntimesImpl(distro, runtimeId));+ }),+ invalidateRuntime: Effect.fn("desktop.wsl.invalidateRuntime")(function (distro, runtimeId) {+ return provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId));+ }),+ probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro, linuxAppRoot) {+ return provideSpawner(probeWslRuntimeImpl(distro, linuxAppRoot));+ }),+ ensureNodePty: Effect.fn("desktop.wsl.ensureNodePty")(+ function (distro, linuxAppRoot, options) {+ return provideSpawner(ensureNodePtyImpl(distro, linuxAppRoot, options));+ },+ ),});}),);diff --git a/apps/server/scripts/record-codex-app-server-replay-fixture.ts b/apps/server/scripts/record-codex-app-server-replay-fixture.tsindex 36b8e04b288..41f9982c3d6 100644--- a/apps/server/scripts/record-codex-app-server-replay-fixture.ts+++ b/apps/server/scripts/record-codex-app-server-replay-fixture.ts@@ -1164,7 +1164,7 @@ function layerCodex({ recorder }: { readonly recorder: Recorder }) {const clientOptions: CodexClient.CodexAppServerClientOptions = {logIncoming: true,logOutgoing: true,- logger: (event) => {+ logger: Effect.fn("logger")(function (event) {if (event.stage === "raw") {return Effect.void;}@@ -1215,7 +1215,7 @@ function layerCodex({ recorder }: { readonly recorder: Recorder }) {yield* updateVersion;yield* recorder.writeRecord(record);}).pipe(Effect.ignore);- },+ }),};return Layer.effect(diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.tsindex 8e77f0e88a1..59b0077da04 100644--- a/apps/server/src/auth/EnvironmentAuth.ts+++ b/apps/server/src/auth/EnvironmentAuth.ts@@ -1374,8 +1374,9 @@ export const make = Effect.gen(function* () {);return EnvironmentAuth.of({- getDescriptor: () =>- Effect.succeed(descriptor).pipe(Effect.withSpan("EnvironmentAuth.getDescriptor")),+ getDescriptor: Effect.fn("EnvironmentAuth.getDescriptor")(function () {+ return Effect.succeed(descriptor);+ }),getSessionState,createBrowserSession,exchangeBootstrapCredentialForAccessToken,diff --git a/apps/server/src/auth/EnvironmentAuthPolicy.ts b/apps/server/src/auth/EnvironmentAuthPolicy.tsindex a95c89b537a..141fd86aa52 100644--- a/apps/server/src/auth/EnvironmentAuthPolicy.ts+++ b/apps/server/src/auth/EnvironmentAuthPolicy.ts@@ -52,8 +52,9 @@ export const make = Effect.gen(function* () {};return EnvironmentAuthPolicy.of({- getDescriptor: () =>- Effect.succeed(descriptor).pipe(Effect.withSpan("EnvironmentAuthPolicy.getDescriptor")),+ getDescriptor: Effect.fn("EnvironmentAuthPolicy.getDescriptor")(function () {+ return Effect.succeed(descriptor);+ }),});});diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.tsindex 50adcbcebf5..24cb4f4ddea 100644--- a/apps/server/src/auth/McpOAuth.ts+++ b/apps/server/src/auth/McpOAuth.ts@@ -527,35 +527,38 @@ export const layerMcpClientAuthenticator = Layer.effect(const environment = yield* ServerEnvironment.ServerEnvironment;const environmentId = yield* environment.getEnvironmentId;return McpHttpServer.McpClientAuthenticator.of({- authenticate: (request) =>- environmentAuth.authenticateMcpClient(request).pipe(- Effect.flatMap((client) =>- Clock.currentTimeMillis.pipe(- Effect.map((issuedAt): McpInvocationContext.McpInvocationScope => ({- environmentId,- requestNamespace: `client:${client.sessionId}`,- thread: undefined,- client: {- sessionId: client.sessionId,- label: client.label,- access: client.access,- },- capabilities: new Set<McpInvocationContext.McpCapability>([- "orchestration",- "worktree",- "pull-requests",- ]),- issuedAt,- })),+ authenticate: Effect.fn("McpHttpServer.McpClientAuthenticator.authenticate")(+ function (request) {+ return environmentAuth.authenticateMcpClient(request).pipe(+ Effect.flatMap((client) =>+ Clock.currentTimeMillis.pipe(+ Effect.map((issuedAt): McpInvocationContext.McpInvocationScope => ({+ environmentId,+ requestNamespace: `client:${client.sessionId}`,+ thread: undefined,+ client: {+ sessionId: client.sessionId,+ label: client.label,+ access: client.access,+ },+ capabilities: new Set<McpInvocationContext.McpCapability>([+ "orchestration",+ "worktree",+ "pull-requests",+ ]),+ issuedAt,+ })),+ ),),- ),- Effect.catch((error) =>- (EnvironmentAuth.isServerAuthCredentialError(error)- ? Effect.void- : Effect.logWarning("MCP client authentication failed.", { cause: error })- ).pipe(Effect.as(undefined)),- ),- ),+ Effect.catch((error) =>+ (EnvironmentAuth.isServerAuthCredentialError(error)+ ? Effect.void+ : Effect.logWarning("MCP client authentication failed.", { cause: error })+ ).pipe(Effect.as(undefined)),+ ),+ );+ },+ ),});}),);diff --git a/apps/server/src/cloud/CliTokenManager.ts b/apps/server/src/cloud/CliTokenManager.tsindex 0a196c7741b..d87b1769832 100644--- a/apps/server/src/cloud/CliTokenManager.ts+++ b/apps/server/src/cloud/CliTokenManager.ts@@ -323,44 +323,44 @@ const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (Effect.flatMap((response) => readTokenResponse(response, params)),Effect.timeout(OAUTH_REQUEST_TIMEOUT),Effect.catchTags({- HttpClientError: (cause) =>- Effect.gen(function* () {- const reason = cause.reason;- if (- params.grant_type !== "refresh_token" ||- reason._tag !== "StatusCodeError" ||- !isPermanentRefreshStatus(reason.response.status)- ) {- return yield* cause;- }- // Reading a rejection body shares the exchange budget without losing- // the known status when the body stalls or cannot be decoded.- const elapsed = Duration.toMillis(- Duration.nanos((yield* Clock.monotonicTimeNanos) - startedAt),- );- const body = yield* reason.response.json.pipe(- Effect.timeout(Math.max(0, Duration.toMillis(OAUTH_REQUEST_TIMEOUT) - elapsed)),- Effect.mapError(- (cause) =>- new CloudCliCredentialRefreshError({- status: reason.response.status,- cause: new HttpClientError.HttpClientError({- reason: new HttpClientError.StatusCodeError({- request: reason.request,- response: reason.response,- cause,- }),+ // The enclosing operation owns the span for this inline handler.+ HttpClientError: Effect.fnUntraced(function* (cause) {+ const reason = cause.reason;+ if (+ params.grant_type !== "refresh_token" ||+ reason._tag !== "StatusCodeError" ||+ !isPermanentRefreshStatus(reason.response.status)+ ) {+ return yield* cause;+ }+ // Reading a rejection body shares the exchange budget without losing+ // the known status when the body stalls or cannot be decoded.+ const elapsed = Duration.toMillis(+ Duration.nanos((yield* Clock.monotonicTimeNanos) - startedAt),+ );+ const body = yield* reason.response.json.pipe(+ Effect.timeout(Math.max(0, Duration.toMillis(OAUTH_REQUEST_TIMEOUT) - elapsed)),+ Effect.mapError(+ (cause) =>+ new CloudCliCredentialRefreshError({+ status: reason.response.status,+ cause: new HttpClientError.HttpClientError({+ reason: new HttpClientError.StatusCodeError({+ request: reason.request,+ response: reason.response,+ cause,}),}),- ),- );- const diagnostic = decodeOAuthRefreshErrorResponse(body);- return yield* new CloudCliCredentialRefreshError({- cause,- status: reason.response.status,- ...(Option.isSome(diagnostic) ? { oauthErrorCode: diagnostic.value.error } : {}),- });- }),+ }),+ ),+ );+ const diagnostic = decodeOAuthRefreshErrorResponse(body);+ return yield* new CloudCliCredentialRefreshError({+ cause,+ status: reason.response.status,+ ...(Option.isSome(diagnostic) ? { oauthErrorCode: diagnostic.value.error } : {}),+ });+ }),}),);});diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.ts b/apps/server/src/cloud/ManagedEndpointRuntime.tsindex a269bd4ec25..5ffd31de9ac 100644--- a/apps/server/src/cloud/ManagedEndpointRuntime.ts+++ b/apps/server/src/cloud/ManagedEndpointRuntime.ts@@ -759,7 +759,9 @@ export const make = Effect.gen(function* () {inspectConnector,readinessChanged: Stream.fromQueue(readinessChanges),recoveryRequests: Stream.fromQueue(recoveryRequests),- requestRecovery: (config) => Queue.offer(recoveryRequests, config).pipe(Effect.asVoid),+ requestRecovery: Effect.fn("CloudManagedEndpointRuntime.requestRecovery")(function (config) {+ return Queue.offer(recoveryRequests, config).pipe(Effect.asVoid);+ }),tunnelConnected: Stream.fromQueue(tunnelConnections),withLinkStateLock: linkStateSemaphore.withPermits(1),});diff --git a/apps/server/src/cloud/selfUpdate.ts b/apps/server/src/cloud/selfUpdate.tsindex 33cf6d1cb2e..dca833d8e5b 100644--- a/apps/server/src/cloud/selfUpdate.ts+++ b/apps/server/src/cloud/selfUpdate.ts@@ -368,8 +368,11 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {return ServerSelfUpdate.of({update,- commitDesktopUpdate: (requestId, onHandoffAccepted) =>- desktopAppUpdate.commit(requestId, onHandoffAccepted),+ commitDesktopUpdate: Effect.fn("ServerSelfUpdate.commitDesktopUpdate")(+ function (requestId, onHandoffAccepted) {+ return desktopAppUpdate.commit(requestId, onHandoffAccepted);+ },+ ),});});diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.tsindex 8de76b92aef..d685dc46abf 100644--- a/apps/server/src/device/DeviceService.ts+++ b/apps/server/src/device/DeviceService.ts@@ -804,8 +804,8 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*return {...DeviceService.of({testHost,- updateTool: (tool) =>- lifecycleLock.withPermit(+ updateTool: Effect.fn("DeviceService.updateTool")(function (tool) {+ return lifecycleLock.withPermit(Effect.gen(function* () {if (!installTool)return yield* new DeviceOperationError({@@ -816,15 +816,17 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*yield* installTool(tool);return yield* inspect;}),- ),+ );+ }),retryHost,inspect,- easAccount: () =>- Effect.fail(+ easAccount: Effect.fn("DeviceService.easAccount")(function () {+ return Effect.fail(new DeviceEasAccountError({reason: "EAS accounts are unavailable in this device service.",}),- ),+ );+ }),agentCli: Effect.fail(new DeviceHostUnavailableError({hostId: LOCAL_DEVICE_HOST_ID,diff --git a/apps/server/src/device/EasDeviceHost.ts b/apps/server/src/device/EasDeviceHost.tsindex d29bf9d48ee..72c88de1afe 100644--- a/apps/server/src/device/EasDeviceHost.ts+++ b/apps/server/src/device/EasDeviceHost.ts@@ -862,8 +862,9 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevicesummary,platformAvailability,ensureReady,- ensureAgentReady: (onPhase) =>- ensureReady(onPhase).pipe(Effect.map((value) => ({ ...value, agentDevice: null }))),+ ensureAgentReady: Effect.fn("DeviceHost.ensureAgentReady")(function (onPhase) {+ return ensureReady(onPhase).pipe(Effect.map((value) => ({ ...value, agentDevice: null })));+ }),current: Effect.sync(() => ready),stopAgent: Effect.void,// Unlike machines the user owns, every running session here is billed.diff --git a/apps/server/src/environment/DirectEndpoints.ts b/apps/server/src/environment/DirectEndpoints.tsindex 38fb50ab385..99e33b98f97 100644--- a/apps/server/src/environment/DirectEndpoints.ts+++ b/apps/server/src/environment/DirectEndpoints.ts@@ -155,7 +155,11 @@ export const make = Effect.gen(function* () {return endpoints;});- return DirectEndpoints.of({ resolve: () => resolve });+ return DirectEndpoints.of({+ resolve: Effect.fn("DirectEndpoints.resolve")(function () {+ return resolve;+ }),+ });});export const layer = Layer.effect(DirectEndpoints, make);diff --git a/apps/server/src/environment/RemoteOpenTargets.ts b/apps/server/src/environment/RemoteOpenTargets.tsindex d4ba16c3984..8b4997f695d 100644--- a/apps/server/src/environment/RemoteOpenTargets.ts+++ b/apps/server/src/environment/RemoteOpenTargets.ts@@ -78,7 +78,11 @@ export const make = Effect.gen(function* () {return targets;});- return RemoteOpenTargets.of({ resolveTargets: () => resolveTargets });+ return RemoteOpenTargets.of({+ resolveTargets: Effect.fn("RemoteOpenTargets.resolveTargets")(function () {+ return resolveTargets;+ }),+ });});export const layer = Layer.effect(RemoteOpenTargets, make);diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.tsindex 5c9e9029771..371c841d822 100644--- a/apps/server/src/git/GitWorkflowService.ts+++ b/apps/server/src/git/GitWorkflowService.ts@@ -299,8 +299,8 @@ export const make = Effect.gen(function* () {ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input)));return GitWorkflowService.of({- isRepository: (cwd) =>- registry.detect({ cwd }).pipe(+ isRepository: Effect.fn("GitWorkflowService.isRepository")(function (cwd) {+ return registry.detect({ cwd }).pipe(Effect.map((handle) => handle?.kind === "git"),Effect.mapError((cause) =>@@ -311,9 +311,10 @@ export const make = Effect.gen(function* () {cause,}),),- ),- hasCommit: (input) =>- ensureGitCommand("GitWorkflowService.hasCommit", input.cwd).pipe(+ );+ }),+ hasCommit: Effect.fn("GitWorkflowService.hasCommit")(function (input) {+ return ensureGitCommand("GitWorkflowService.hasCommit", input.cwd).pipe(Effect.andThen(git.execute({operation: "GitWorkflowService.hasCommit",@@ -323,10 +324,11 @@ export const make = Effect.gen(function* () {}),),Effect.map((result) => result.exitCode === 0),- ),- hasRefNamed: (input) =>+ );+ }),+ hasRefNamed: Effect.fn("GitWorkflowService.hasRefNamed")(function (input) {// Pattern characters would widen the ref match.- /[*?[\\]/.test(input.refName)+ return /[*?[\\]/.test(input.refName)? Effect.succeed(false): ensureGitCommand("GitWorkflowService.hasRefNamed", input.cwd).pipe(Effect.andThen(@@ -342,36 +344,41 @@ export const make = Effect.gen(function* () {}),),Effect.map((result) => result.stdout.trim().length > 0),- ),- status: (input) =>- detectGitRepositoryForStatus("GitWorkflowService.status", input.cwd).pipe(+ );+ }),+ status: Effect.fn("GitWorkflowService.status")(function (input) {+ return detectGitRepositoryForStatus("GitWorkflowService.status", input.cwd).pipe(Effect.flatMap((isGitRepository) =>isGitRepository ? gitManager.status(input) : Effect.succeed(nonRepositoryStatus()),),- ),- localStatus: (input) =>- detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe(+ );+ }),+ localStatus: Effect.fn("GitWorkflowService.localStatus")(function (input) {+ return detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe(Effect.flatMap((isGitRepository) =>isGitRepository? gitManager.localStatus(input): Effect.succeed(nonRepositoryLocalStatus()),),- ),- remoteStatus: (input, options) =>- detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(+ );+ }),+ remoteStatus: Effect.fn("GitWorkflowService.remoteStatus")(function (input, options) {+ return detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(Effect.flatMap((isGitRepository) =>isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null),),- ),+ );+ }),invalidateLocalStatus: gitManager.invalidateLocalStatus,invalidateRemoteStatus: gitManager.invalidateRemoteStatus,invalidateStatus: gitManager.invalidateStatus,- pullCurrentBranch: (cwd) =>- ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe(+ pullCurrentBranch: Effect.fn("GitWorkflowService.pullCurrentBranch")(function (cwd) {+ return ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe(Effect.andThen(git.pullCurrentBranch(cwd)),- ),- runStackedAction: (input, options) =>- ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(+ );+ }),+ runStackedAction: Effect.fn("GitWorkflowService.runStackedAction")(function (input, options) {+ return ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(Effect.flatMap((handle) =>input.featureBranch? withCheckoutLease(@@ -380,90 +387,115 @@ export const make = Effect.gen(function* () {): gitManager.runStackedAction(input, options),),- ),+ );+ }),resolvePullRequest: routeGitManager("GitWorkflowService.resolvePullRequest",gitManager.resolvePullRequest,),- preparePullRequestThread: (input) =>- ensureGit("GitWorkflowService.preparePullRequestThread", input.cwd).pipe(- Effect.flatMap((handle) =>- input.mode === "local"- ? withCheckoutLease(- handle.repository.rootPath,- gitManager.preparePullRequestThread(input),- )- : gitManager.preparePullRequestThread(input),- ),- ),- listRefs: (input) =>- detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(+ preparePullRequestThread: Effect.fn("GitWorkflowService.preparePullRequestThread")(+ function (input) {+ return ensureGit("GitWorkflowService.preparePullRequestThread", input.cwd).pipe(+ Effect.flatMap((handle) =>+ input.mode === "local"+ ? withCheckoutLease(+ handle.repository.rootPath,+ gitManager.preparePullRequestThread(input),+ )+ : gitManager.preparePullRequestThread(input),+ ),+ );+ },+ ),+ listRefs: Effect.fn("GitWorkflowService.listRefs")(function (input) {+ return detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(Effect.flatMap((isGitRepository) =>isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()),),- ),- createWorktree: (input, options) =>- ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(+ );+ }),+ createWorktree: Effect.fn("GitWorkflowService.createWorktree")(function (input, options) {+ return ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(Effect.andThen(gitManager.createWorktree(input, options)),- ),- listLocalBranchNames: (cwd) =>- ensureGitCommand("GitWorkflowService.listLocalBranchNames", cwd).pipe(+ );+ }),+ listLocalBranchNames: Effect.fn("GitWorkflowService.listLocalBranchNames")(function (cwd) {+ return ensureGitCommand("GitWorkflowService.listLocalBranchNames", cwd).pipe(Effect.andThen(git.listLocalBranchNames(cwd)),- ),- fetchRemote: (input) =>- ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(+ );+ }),+ fetchRemote: Effect.fn("GitWorkflowService.fetchRemote")(function (input) {+ return ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(Effect.andThen(git.fetchRemote(input)),- ),- remoteExists: (input) =>- ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe(+ );+ }),+ remoteExists: Effect.fn("GitWorkflowService.remoteExists")(function (input) {+ return ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe(Effect.andThen(git.remoteExists(input)),- ),- remoteBranchExists: (input) =>- ensureGitCommand("GitWorkflowService.remoteBranchExists", input.cwd).pipe(+ );+ }),+ remoteBranchExists: Effect.fn("GitWorkflowService.remoteBranchExists")(function (input) {+ return ensureGitCommand("GitWorkflowService.remoteBranchExists", input.cwd).pipe(Effect.andThen(git.remoteBranchExists(input)),- ),- resolveRemoteTrackingCommit: (input) =>- ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(- Effect.andThen(git.resolveRemoteTrackingCommit(input)),- ),- resolveWorktreeBaseRemote: (input) =>- ensureGitCommand("GitWorkflowService.resolveWorktreeBaseRemote", input.cwd).pipe(- Effect.andThen(git.resolveWorktreeBaseRemote(input)),- ),- fetchWorktreeBaseCommit: (input) =>- ensureGitCommand("GitWorkflowService.fetchWorktreeBaseCommit", input.cwd).pipe(- Effect.andThen(git.fetchWorktreeBaseCommit(input)),- ),- removeWorktree: (input) =>- ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(+ );+ }),+ resolveRemoteTrackingCommit: Effect.fn("GitWorkflowService.resolveRemoteTrackingCommit")(+ function (input) {+ return ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(+ Effect.andThen(git.resolveRemoteTrackingCommit(input)),+ );+ },+ ),+ resolveWorktreeBaseRemote: Effect.fn("GitWorkflowService.resolveWorktreeBaseRemote")(+ function (input) {+ return ensureGitCommand("GitWorkflowService.resolveWorktreeBaseRemote", input.cwd).pipe(+ Effect.andThen(git.resolveWorktreeBaseRemote(input)),+ );+ },+ ),+ fetchWorktreeBaseCommit: Effect.fn("GitWorkflowService.fetchWorktreeBaseCommit")(+ function (input) {+ return ensureGitCommand("GitWorkflowService.fetchWorktreeBaseCommit", input.cwd).pipe(+ Effect.andThen(git.fetchWorktreeBaseCommit(input)),+ );+ },+ ),+ removeWorktree: Effect.fn("GitWorkflowService.removeWorktree")(function (input) {+ return ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(Effect.andThen(git.removeWorktree(input)),- ),- pruneWorktrees: (input) =>- ensureGitCommand("GitWorkflowService.pruneWorktrees", input.cwd).pipe(+ );+ }),+ pruneWorktrees: Effect.fn("GitWorkflowService.pruneWorktrees")(function (input) {+ return ensureGitCommand("GitWorkflowService.pruneWorktrees", input.cwd).pipe(Effect.andThen(git.pruneWorktrees(input)),- ),- deleteLocalBranch: (input) =>- ensureGitCommand("GitWorkflowService.deleteLocalBranch", input.cwd).pipe(+ );+ }),+ deleteLocalBranch: Effect.fn("GitWorkflowService.deleteLocalBranch")(function (input) {+ return ensureGitCommand("GitWorkflowService.deleteLocalBranch", input.cwd).pipe(Effect.andThen(git.deleteLocalBranch(input)),- ),- createRef: (input) =>- ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(+ );+ }),+ createRef: Effect.fn("GitWorkflowService.createRef")(function (input) {+ return ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(Effect.flatMap((handle) =>input.switchRef? withCheckoutLease(handle.repository.rootPath, git.createRef(input)): git.createRef(input),),- ),- switchRef: (input) =>- ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(+ );+ }),+ switchRef: Effect.fn("GitWorkflowService.switchRef")(function (input) {+ return ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(Effect.flatMap((handle) =>withCheckoutLease(handle.repository.rootPath, Effect.scoped(git.switchRef(input))),),- ),- renameBranch: (input) =>- ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(+ );+ }),+ renameBranch: Effect.fn("GitWorkflowService.renameBranch")(function (input) {+ return ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(Effect.andThen(git.renameBranch(input)),- ),+ );+ }),});});diff --git a/apps/server/src/htmlRender/headlessChrome.ts b/apps/server/src/htmlRender/headlessChrome.tsindex 5562d43826c..aaf64bdcecc 100644--- a/apps/server/src/htmlRender/headlessChrome.ts+++ b/apps/server/src/htmlRender/headlessChrome.ts@@ -265,13 +265,14 @@ const launchBrowser = Effect.fnUntraced(function* (input: {textEncoder.encode('"}}\0'),]).pipe(Effect.asVoid);- const receive = (raw: string) => {+ // Incoming messages share the session span; frame acknowledgements are frequent.+ const receive = Effect.fnUntraced(function* (raw: string) {const message = Option.getOrUndefined(decodeCdpMessage(raw));if (message?.id !== undefined) {const waiter = pending.get(message.id);pending.delete(message.id);- if (!waiter) return Effect.void;- return message.error+ if (!waiter) return yield* Effect.void;+ return yield* message.error? Deferred.fail(waiter.reply,new HtmlRenderBrowserError({@@ -283,24 +284,24 @@ const launchBrowser = Effect.fnUntraced(function* (input: {}const sessionId = message?.sessionId;const page = sessionId === undefined ? undefined : pages.get(sessionId);- if (sessionId === undefined || !page || !message?.method) return Effect.void;+ if (sessionId === undefined || !page || !message?.method) return yield* Effect.void;if (message.method === "Page.loadEventFired") {- return page.loaded ? Deferred.succeed(page.loaded, undefined) : Effect.void;+ return yield* page.loaded ? Deferred.succeed(page.loaded, undefined) : Effect.void;}if (message.method === "Fetch.requestPaused") {const paused = Option.getOrUndefined(decodeRequestPaused(message.params));- if (!paused) return Effect.void;+ if (!paused) return yield* Effect.void;const body = page.body;const url = paused.request.url.split("#", 1)[0]!;if (url === PAGE_URL && body !== undefined) {- return fulfillPage(sessionId, paused.requestId, body);+ return yield* fulfillPage(sessionId, paused.requestId, body);}// Subframes may show other sites covered by Local Network Access; the main frame stays on T3's page.const otherSiteFrame =paused.resourceType === "Document" &&paused.frameId !== page.mainFrameId &&!url.startsWith(`${PAGE_ORIGIN}/`);- return otherSiteFrame+ return yield* otherSiteFrame? post("Fetch.continueRequest", { requestId: paused.requestId }, sessionId): post("Fetch.failRequest",@@ -309,10 +310,10 @@ const launchBrowser = Effect.fnUntraced(function* (input: {);}const consoleMessage = consoleMessageFromEvent(message.method, message.params);- if (!consoleMessage) return Effect.void;+ if (!consoleMessage) return yield* Effect.void;if (page.consoleMessages.length >= MAX_CONSOLE_MESSAGES) {page.omittedConsoleMessages += 1;- return Effect.void;+ return yield* Effect.void;}const text = consoleMessage.text.replaceAll(PAGE_URL, PAGE_NAME);page.consoleMessages.push({@@ -320,8 +321,8 @@ const launchBrowser = Effect.fnUntraced(function* (input: {text:text.length > MAX_CONSOLE_TEXT_CHARS ? `${text.slice(0, MAX_CONSOLE_TEXT_CHARS)}…` : text,});- return Effect.void;- };+ return yield* Effect.void;+ });// Startup aborts close the pipe; let stderr drain to recover the reason.const disconnect = Effect.gen(function* () {diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.tsindex 5a4e62e3b24..89eb852d1f4 100644--- a/apps/server/src/mcp/McpHttpServer.ts+++ b/apps/server/src/mcp/McpHttpServer.ts@@ -400,7 +400,9 @@ const decodeAsAdvertised = <Tools extends Record<string, Tool.Any>>(const isPreviewAutomationError = Schema.is(PreviewAutomationError);-const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {+const previewSnapshotFailure = Effect.fn("previewSnapshotFailure")(function <E>(+ cause: Cause.Cause<E>,+) {if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {return Effect.failCause(cause).pipe(Effect.orDie);}@@ -433,7 +435,7 @@ const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {errorTag,failureCount: failures.length,}).pipe(Effect.as(result));-};+});const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () {const server = yield* McpServer.McpServer;@@ -903,8 +905,8 @@ const withToolAnalytics =);const recordingServer = McpServer.McpServer.of({...server,- addTool: (options) =>- server.addTool({+ addTool: Effect.fn("McpServer.addTool")(function (options) {+ return server.addTool({...options,handle:/* Request instrumentation already owns the span; keep this helper in that context. */@@ -926,7 +928,8 @@ const withToolAnalytics =}),);}),- }),+ });+ }),});return yield* registration.pipe(Effect.provideService(McpServer.McpServer, recordingServer));});diff --git a/apps/server/src/mcp/PreviewAutomationBroker.ts b/apps/server/src/mcp/PreviewAutomationBroker.tsindex 2aced7dc368..53622f30547 100644--- a/apps/server/src/mcp/PreviewAutomationBroker.ts+++ b/apps/server/src/mcp/PreviewAutomationBroker.ts@@ -647,14 +647,14 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {input.updateCurrentTab === false ? timeoutMs : timeoutMs + HOST_RESPONSE_GRACE_MS;const result = yield* Deferred.await(deferred).pipe(Effect.timeoutOption(responseTimeoutMs));return yield* Option.match(result, {- onNone: () =>- Effect.gen(function* () {- // Never replay possibly applied actions; slow metadata reads must not evict the host.- if (input.updateCurrentTab !== false) {- yield* disconnect(connection.clientId, connection.queue, true);- }- return yield* new PreviewAutomationTimeoutError(requestContext);- }),+ // The enclosing operation owns the span for this inline handler.+ onNone: Effect.fnUntraced(function* () {+ // Never replay possibly applied actions; slow metadata reads must not evict the host.+ if (input.updateCurrentTab !== false) {+ yield* disconnect(connection.clientId, connection.queue, true);+ }+ return yield* new PreviewAutomationTimeoutError(requestContext);+ }),onSome: (value) => Effect.succeed(value as A),});});diff --git a/apps/server/src/mcpApps/McpAppModelContext.ts b/apps/server/src/mcpApps/McpAppModelContext.tsindex 6e563e10b56..8dc16e67564 100644--- a/apps/server/src/mcpApps/McpAppModelContext.ts+++ b/apps/server/src/mcpApps/McpAppModelContext.ts@@ -91,5 +91,12 @@ export const layer = Layer.effect(export const layerEmpty = Layer.succeed(McpAppModelContext,- McpAppModelContext.of({ set: () => Effect.void, forThread: () => Effect.succeed([]) }),+ McpAppModelContext.of({+ set: Effect.fn("McpAppModelContext.set")(function () {+ return Effect.void;+ }),+ forThread: Effect.fn("McpAppModelContext.forThread")(function () {+ return Effect.succeed([]);+ }),+ }),);diff --git a/apps/server/src/observability/BrowserTraceCollector.ts b/apps/server/src/observability/BrowserTraceCollector.tsindex 1802a4a6659..1e3d5f42bc7 100644--- a/apps/server/src/observability/BrowserTraceCollector.ts+++ b/apps/server/src/observability/BrowserTraceCollector.ts@@ -13,12 +13,13 @@ export class BrowserTraceCollector extends Context.Service</** @public */export const make = (sink: TraceSink): BrowserTraceCollector["Service"] =>BrowserTraceCollector.of({- record: (records) =>- Effect.sync(() => {+ record: Effect.fn("BrowserTraceCollector.record")(function (records) {+ return Effect.sync(() => {for (const record of records) {sink.push(record);}- }),+ });+ }),});export const layer = (sink: TraceSink) => Layer.succeed(BrowserTraceCollector, make(sink));diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.tsindex c466cb5ca8a..1a9bf4a2bbb 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts@@ -4393,8 +4393,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (return ProviderAdapter.ProviderAdapterV2.of({instanceId: adapterOptions.instanceId,driver: CLAUDE_PROVIDER,- getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2),- planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),+ getCapabilities: Effect.fn("ClaudeAdapterV2.getCapabilities")(function () {+ return Effect.succeed(ClaudeProviderCapabilitiesV2);+ }),+ planSelectionTransition: Effect.fn("ClaudeAdapterV2.planSelectionTransition")(function () {+ return Effect.succeed(turnScopedSelectionTransition());+ }),openSession: Effect.fn("ClaudeAdapterV2.openSession")(function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) {const sessionScope = yield* Effect.scope;diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.tsindex 7788751b0a6..c98a391de68 100644--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts@@ -1634,8 +1634,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (return ProviderAdapter.ProviderAdapterV2.of({instanceId: adapterOptions.instanceId,driver: CODEX_PROVIDER,- getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),- planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),+ getCapabilities: Effect.fn("CodexAdapterV2.getCapabilities")(function () {+ return Effect.succeed(CodexProviderCapabilitiesV2);+ }),+ planSelectionTransition: Effect.fn("CodexAdapterV2.planSelectionTransition")(function () {+ return Effect.succeed(turnScopedSelectionTransition());+ }),openSession: Effect.fn("CodexAdapterV2.openSession")(function* (input) {const scope = yield* Scope.Scope;diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.tsindex 3727df9e375..8924943fda2 100644--- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts+++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts@@ -232,14 +232,15 @@ export const layer: Layer.Layer<});return CheckpointCaptureServiceV2.of({- execute: (input) =>- execute(input).pipe(+ execute: Effect.fn("CheckpointCaptureServiceV2.execute")(function (input) {+ return execute(input).pipe(Effect.mapError((cause) =>isCheckpointCaptureExecutionError(cause)? cause: new CheckpointCaptureExecutionError({ ...input, cause }),),- ),+ );+ }),});}),);diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.tsindex 112043704c7..6c0feea3526 100644--- a/apps/server/src/orchestration-v2/EffectWorker.ts+++ b/apps/server/src/orchestration-v2/EffectWorker.ts@@ -95,7 +95,7 @@ export const layerExecutor: Layer.Layer<const threads = yield* ThreadManagementService.ThreadManagementService;const settings = yield* ServerSettings.ServerSettingsService;return OrchestrationEffectExecutorV2.of({- execute: (effect, options) => {+ execute: Effect.fn("OrchestrationEffectExecutorV2.execute")(function (effect, options) {const willRetry = options?.willRetry ?? false;switch (effect.request.type) {case "provider-runtime.continue": {@@ -557,7 +557,7 @@ export const layerExecutor: Layer.Layer<),);}- },+ }),});}),);diff --git a/apps/server/src/orchestration-v2/EventStore.ts b/apps/server/src/orchestration-v2/EventStore.tsindex 6a0afd60448..e2125508dee 100644--- a/apps/server/src/orchestration-v2/EventStore.ts+++ b/apps/server/src/orchestration-v2/EventStore.ts@@ -107,8 +107,8 @@ const layerBase: Layer.Layer<EventStoreV2, never, OrchestrationEventStore.Orches);return EventStoreV2.of({- append: (input) =>- applicationEvents.appendAgentEvents(input).pipe(+ append: Effect.fn("EventStoreV2.append")(function (input) {+ return applicationEvents.appendAgentEvents(input).pipe(Effect.mapError((cause) =>new EventStoreAppendEventsError({@@ -116,20 +116,22 @@ const layerBase: Layer.Layer<EventStoreV2, never, OrchestrationEventStore.Orchescause,}),),- ),- appendProjectEvent: (event) =>- applicationEvents+ );+ }),+ appendProjectEvent: Effect.fn("EventStoreV2.appendProjectEvent")(function (event) {+ return applicationEvents.appendProjectEvent(event).pipe(Effect.mapError((cause) => new EventStoreAppendEventsError({ eventCount: 1, cause })),- ),+ );+ }),read,readByCommandId: ({ commandId }) =>applicationEvents.readAgentEvents({ commandId }).pipe(Stream.mapError((cause) => new EventStoreReadEventsError({ cause }))),- latestSequence: (input) =>- applicationEvents.latestAgentSequence(input?.threadId).pipe(+ latestSequence: Effect.fn("EventStoreV2.latestSequence")(function (input) {+ return applicationEvents.latestAgentSequence(input?.threadId).pipe(Effect.mapError((cause) =>new EventStoreReadEventsError({@@ -137,7 +139,8 @@ const layerBase: Layer.Layer<EventStoreV2, never, OrchestrationEventStore.Orchescause,}),),- ),+ );+ }),latestApplicationSequence: applicationEvents.latestApplicationSequence.pipe(Effect.mapError((cause) => new EventStoreReadEventsError({ cause })),),diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.tsindex abfdd9127a7..1541efe578a 100644--- a/apps/server/src/orchestration-v2/Orchestrator.ts+++ b/apps/server/src/orchestration-v2/Orchestrator.ts@@ -12398,13 +12398,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiorecoverDelegatedTasks,recoverDelegatedTask,delegatedTaskResultPending,- restartContinuationPending: (run) =>- awaitsRestartContinuation(run).pipe(Effect.orElseSucceed(() => false)),- awaitRestartContinuation: (run) =>- effectOutbox.awaitSettled(`effect:restart-continuation:${run.id}`).pipe(Effect.ignore),+ restartContinuationPending: Effect.fn("OrchestratorV2.restartContinuationPending")(+ function (run) {+ return awaitsRestartContinuation(run).pipe(Effect.orElseSucceed(() => false));+ },+ ),+ awaitRestartContinuation: Effect.fn("OrchestratorV2.awaitRestartContinuation")(function (run) {+ return effectOutbox.awaitSettled(`effect:restart-continuation:${run.id}`).pipe(Effect.ignore);+ }),dispatch: dispatchWithReceipt,- autoArmLimitRecovery: (input) =>- threadDispatch.withLock(+ autoArmLimitRecovery: Effect.fn("OrchestratorV2.autoArmLimitRecovery")(function (input) {+ return threadDispatch.withLock(input.threadId,Effect.gen(function* () {const thread = yield* projectionStore@@ -12422,7 +12426,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioreturn;yield* dispatchWithReceiptEffect({ type: "thread.metadata.update", ...input });}),- ),+ );+ }),searchThreadStream: (input) =>projectionStore.searchThreadStream(input)@@ -12431,77 +12436,108 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio(cause) => new OrchestratorProjectionError({ threadId: input.threadId, cause }),),),- searchThread: (input) =>- projectionStore+ searchThread: Effect.fn("OrchestratorV2.searchThread")(function (input) {+ return projectionStore.searchThread(input).pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId: input.threadId, cause }),),- ),- getThreadHistoryPage: (threadId, cursor, throughEntryId, conversationOnly) =>- projectionStore- .getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly)- .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),- getTimelinePage: (threadId, options) =>- projectionStore+ );+ }),+ getThreadHistoryPage: Effect.fn("OrchestratorV2.getThreadHistoryPage")(+ function (threadId, cursor, throughEntryId, conversationOnly) {+ return projectionStore+ .getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly)+ .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));+ },+ ),+ getTimelinePage: Effect.fn("OrchestratorV2.getTimelinePage")(function (threadId, options) {+ return projectionStore.getTimelinePage(threadId, options)- .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),- getMessageCount: (threadId) =>- projectionStore+ .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));+ }),+ getMessageCount: Effect.fn("OrchestratorV2.getMessageCount")(function (threadId) {+ return projectionStore.getMessageCount(threadId)- .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),- getTurnItem: (input) =>- projectionStore+ .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));+ }),+ getTurnItem: Effect.fn("OrchestratorV2.getTurnItem")(function (input) {+ return projectionStore.getTurnItem(input).pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId: input.threadId, cause }),),- ),- getThreadRecords: (threadId, fields, filter) =>- projectionStore- .getThreadRecords(threadId, fields, filter)- .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),- getThreadProjection: (threadId) =>- projectionStore+ );+ }),+ getThreadRecords: Effect.fn("OrchestratorV2.getThreadRecords")(+ function (threadId, fields, filter) {+ return projectionStore+ .getThreadRecords(threadId, fields, filter)+ .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));+ },+ ),+ getThreadProjection: Effect.fn("OrchestratorV2.getThreadProjection")(function (threadId) {+ return projectionStore.getThreadProjection(threadId)- .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),- getCheckpointContext: (threadId) =>- projectionStore+ .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));+ }),+ getCheckpointContext: Effect.fn("OrchestratorV2.getCheckpointContext")(function (threadId) {+ return projectionStore.getCheckpointContext(threadId)- .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),- getThreadSnapshot: (threadId) =>- projectionStore+ .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));+ }),+ getThreadSnapshot: Effect.fn("OrchestratorV2.getThreadSnapshot")(function (threadId) {+ return projectionStore.getThreadSnapshot(threadId)- .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),- getThreadSnapshotWindow: (threadId, options) =>- projectionStore- .getThreadSnapshotWindow(threadId, options)- .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),- getShellSnapshot: (options) =>- projectionStore.getShellSnapshot(options).pipe(Effect.mapError(shellProjectionError)),- listActiveSubagentThreadIds: () =>- projectionStore.listActiveSubagentThreadIds().pipe(Effect.mapError(shellProjectionError)),- listOlderSettledThreads: (query) =>- projectionStore.listOlderSettledThreads(query).pipe(Effect.mapError(shellProjectionError)),- readShellSnapshot: (options) =>- projectionStore+ .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));+ }),+ getThreadSnapshotWindow: Effect.fn("OrchestratorV2.getThreadSnapshotWindow")(+ function (threadId, options) {+ return projectionStore+ .getThreadSnapshotWindow(threadId, options)+ .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));+ },+ ),+ getShellSnapshot: Effect.fn("OrchestratorV2.getShellSnapshot")(function (options) {+ return projectionStore.getShellSnapshot(options).pipe(Effect.mapError(shellProjectionError));+ }),+ listActiveSubagentThreadIds: Effect.fn("OrchestratorV2.listActiveSubagentThreadIds")(+ function () {+ return projectionStore+ .listActiveSubagentThreadIds()+ .pipe(Effect.mapError(shellProjectionError));+ },+ ),+ listOlderSettledThreads: Effect.fn("OrchestratorV2.listOlderSettledThreads")(function (query) {+ return projectionStore+ .listOlderSettledThreads(query)+ .pipe(Effect.mapError(shellProjectionError));+ }),+ readShellSnapshot: Effect.fn("OrchestratorV2.readShellSnapshot")(function (options) {+ return projectionStore.readShellSnapshot(options).pipe(Effect.mapError(shellProjectionError),Effect.map(Effect.mapError(shellProjectionError)),- ),- getThreadShell: (threadId) =>- projectionStore+ );+ }),+ getThreadShell: Effect.fn("OrchestratorV2.getThreadShell")(function (threadId) {+ return projectionStore.getThreadShell(threadId)- .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),- findGuestShareThreadId: (shareId) =>- projectionStore.findGuestShareThreadId(shareId).pipe(Effect.mapError(shellProjectionError)),- getThreadEventSequence: (threadId) =>- eventSink+ .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));+ }),+ findGuestShareThreadId: Effect.fn("OrchestratorV2.findGuestShareThreadId")(function (shareId) {+ return projectionStore+ .findGuestShareThreadId(shareId)+ .pipe(Effect.mapError(shellProjectionError));+ }),+ getThreadEventSequence: Effect.fn("OrchestratorV2.getThreadEventSequence")(function (threadId) {+ return eventSink.latestSequence({ threadId })- .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),+ .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));+ }),streamStoredEvents: eventSink.stream().pipe(Stream.mapError((cause) =>diff --git a/apps/server/src/orchestration-v2/ProjectStore.ts b/apps/server/src/orchestration-v2/ProjectStore.tsindex 335522c7542..4a81ee2b625 100644--- a/apps/server/src/orchestration-v2/ProjectStore.ts+++ b/apps/server/src/orchestration-v2/ProjectStore.ts@@ -266,11 +266,14 @@ export const make = Effect.gen(function* () {get,list,findActiveByWorkspaceRoot,- getShell: (projectId) => get(projectId).pipe(Effect.map(Option.map(toShell))),- listShells: (options) =>- list(options?.projectIds === undefined ? undefined : { projectIds: options.projectIds }).pipe(- Effect.map((rows) => rows.map(toShell)),- ),+ getShell: Effect.fn("ProjectStoreV2.getShell")(function (projectId) {+ return get(projectId).pipe(Effect.map(Option.map(toShell)));+ }),+ listShells: Effect.fn("ProjectStoreV2.listShells")(function (options) {+ return list(+ options?.projectIds === undefined ? undefined : { projectIds: options.projectIds },+ ).pipe(Effect.map((rows) => rows.map(toShell)));+ }),});});diff --git a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.tsindex e53ce61bc12..3a34df29f71 100644--- a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts+++ b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts@@ -75,8 +75,8 @@ export const layerFromProviderInstanceRegistry: Layer.Layer<Effect.gen(function* () {const instances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;return ProviderAdapterRegistryV2.of({- get: (instanceId) =>- instances.getInstance(instanceId).pipe(+ get: Effect.fn("ProviderAdapterRegistryV2.get")(function (instanceId) {+ return instances.getInstance(instanceId).pipe(Effect.flatMap((instance) => {if (instance === undefined)return new ProviderAdapterRegistryLookupError({ instanceId });@@ -131,11 +131,13 @@ export const layerFromProviderInstanceRegistry: Layer.Layer<},} satisfies ProviderAdapter.ProviderAdapterV2["Service"]);}),- ),- list: () =>- instances.listInstances.pipe(+ );+ }),+ list: Effect.fn("ProviderAdapterRegistryV2.list")(function () {+ return instances.listInstances.pipe(Effect.map((available) => available.map((instance) => instance.instanceId)),- ),+ );+ }),getMetadata: Effect.fn("ProviderAdapterRegistry.getMetadata")(function* (instanceId) {const instance = yield* instances.getInstance(instanceId);if (instance === undefined) {diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.tsindex e9b45b5418b..6beb4d0e554 100644--- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts+++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts@@ -114,8 +114,11 @@ export const layerAnalytics = Layer.effect(Effect.gen(function* () {const analytics = yield* AnalyticsService.AnalyticsService;return {- record: (properties: Readonly<Record<string, unknown>>) =>- analytics.record("provider.turn.completed", properties),+ record: Effect.fn("ProviderTurnAnalytics.record")(function (+ properties: Readonly<Record<string, unknown>>,+ ) {+ return analytics.record("provider.turn.completed", properties);+ }),};}),);diff --git a/apps/server/src/orchestration-v2/ResourceCleanupService.ts b/apps/server/src/orchestration-v2/ResourceCleanupService.tsindex 30ff48df0d7..ff56b42c492 100644--- a/apps/server/src/orchestration-v2/ResourceCleanupService.ts+++ b/apps/server/src/orchestration-v2/ResourceCleanupService.ts@@ -47,33 +47,44 @@ export const layer = Layer.effect(const config = yield* ServerConfig.ServerConfig;const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService;return {- cleanupScheduledTasks: (threadId: ThreadId) =>- scheduledTasks+ cleanupScheduledTasks: Effect.fn("ResourceCleanupService.cleanupScheduledTasks")(function (+ threadId: ThreadId,+ ) {+ return scheduledTasks.deleteForThread(threadId).pipe(Effect.mapError((cause) =>new ResourceCleanupError({ operation: "scheduled-tasks", threadId, cause }),),- ),- cleanupTerminals: (threadId: string) =>- terminals+ );+ }),+ cleanupTerminals: Effect.fn("ResourceCleanupService.cleanupTerminals")(function (+ threadId: string,+ ) {+ return terminals.close({ threadId, deleteHistory: true }).pipe(Effect.mapError((cause) => new ResourceCleanupError({ operation: "terminal", threadId, cause }),),- ),- cleanupPreviews: (threadId: string) =>- previews+ );+ }),+ cleanupPreviews: Effect.fn("ResourceCleanupService.cleanupPreviews")(function (+ threadId: string,+ ) {+ return previews.close({ threadId: ThreadId.make(threadId) }).pipe(Effect.mapError((cause) => new ResourceCleanupError({ operation: "preview", threadId, cause }),),- ),- cleanupAttachments: (attachmentIds: ReadonlyArray<string>) =>- Effect.forEach(+ );+ }),+ cleanupAttachments: Effect.fn("ResourceCleanupService.cleanupAttachments")(function (+ attachmentIds: ReadonlyArray<string>,+ ) {+ return Effect.forEach(attachmentIds,(attachmentId) => {const extension = parseAttachmentFileExtension(attachmentId);@@ -99,7 +110,8 @@ export const layer = Layer.effect();},{ discard: true, concurrency: 4 },- ),+ );+ }),};}),);diff --git a/apps/server/src/orchestration-v2/RuntimePolicy.ts b/apps/server/src/orchestration-v2/RuntimePolicy.tsindex a2251416b7a..d5f73ebee0e 100644--- a/apps/server/src/orchestration-v2/RuntimePolicy.ts+++ b/apps/server/src/orchestration-v2/RuntimePolicy.ts@@ -51,12 +51,13 @@ export class RuntimePolicyV2 extends Context.Service<RuntimePolicyV2, RuntimePol) {}export const layer: Layer.Layer<RuntimePolicyV2> = Layer.succeed(RuntimePolicyV2, {- resolve: (input) =>- Effect.succeed({+ resolve: Effect.fn("RuntimePolicyV2.resolve")(function (input) {+ return Effect.succeed({runtimeMode: input.thread.runtimeMode,interactionMode: input.thread.interactionMode,cwd: input.thread.worktreePath,- }),+ });+ }),});function providerRuntimeMode(diff --git a/apps/server/src/orchestration-v2/ThreadLifecycleService.ts b/apps/server/src/orchestration-v2/ThreadLifecycleService.tsindex fad7693ba22..dd0c94538ef 100644--- a/apps/server/src/orchestration-v2/ThreadLifecycleService.ts+++ b/apps/server/src/orchestration-v2/ThreadLifecycleService.ts@@ -88,54 +88,61 @@ const make = Effect.gen(function* () {);return ThreadLifecycleService.of({- archive: (input) =>- dispatch("archive", input.threadId, {+ archive: Effect.fn("ThreadLifecycleService.archive")(function (input) {+ return dispatch("archive", input.threadId, {type: "thread.archive",commandId: input.commandId,threadId: input.threadId,- }),- unarchive: (input) =>- dispatch("unarchive", input.threadId, {+ });+ }),+ unarchive: Effect.fn("ThreadLifecycleService.unarchive")(function (input) {+ return dispatch("unarchive", input.threadId, {type: "thread.unarchive",commandId: input.commandId,threadId: input.threadId,- }),- delete: (input) =>- dispatch("delete", input.threadId, {+ });+ }),+ delete: Effect.fn("ThreadLifecycleService.delete")(function (input) {+ return dispatch("delete", input.threadId, {type: "thread.delete",commandId: input.commandId,threadId: input.threadId,- }),- updateMetadata: (input) =>- dispatch("update-metadata", input.threadId, {+ });+ }),+ updateMetadata: Effect.fn("ThreadLifecycleService.updateMetadata")(function (input) {+ return dispatch("update-metadata", input.threadId, {type: "thread.metadata.update",commandId: input.commandId,threadId: input.threadId,...(input.title === undefined ? {} : { title: input.title }),...(input.branch === undefined ? {} : { branch: input.branch }),...(input.worktreePath === undefined ? {} : { worktreePath: input.worktreePath }),- }),- setRuntimeMode: (input) =>- dispatch("set-runtime-mode", input.threadId, {+ });+ }),+ setRuntimeMode: Effect.fn("ThreadLifecycleService.setRuntimeMode")(function (input) {+ return dispatch("set-runtime-mode", input.threadId, {type: "thread.runtime-mode.set",commandId: input.commandId,threadId: input.threadId,runtimeMode: input.runtimeMode,- }),- setInteractionMode: (input) =>- dispatch("set-interaction-mode", input.threadId, {+ });+ }),+ setInteractionMode: Effect.fn("ThreadLifecycleService.setInteractionMode")(function (input) {+ return dispatch("set-interaction-mode", input.threadId, {type: "thread.interaction-mode.set",commandId: input.commandId,threadId: input.threadId,interactionMode: input.interactionMode,- }),- setModelSelection: (input) =>- dispatch("set-model-selection", input.threadId, {+ });+ }),+ setModelSelection: Effect.fn("ThreadLifecycleService.setModelSelection")(function (input) {+ return dispatch("set-model-selection", input.threadId, {type: "thread.model-selection.set",commandId: input.commandId,threadId: input.threadId,modelSelection: input.modelSelection,- }),+ });+ }),});});diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.tsindex 5cda4c23e53..9a80f8d2841 100644--- a/apps/server/src/orchestration-v2/ThreadManagementService.ts+++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts@@ -1204,34 +1204,46 @@ const make = Effect.gen(function* () {Effect.as(orchestrator.searchThreadStream(input)),),),- searchThread: (input) =>- ensureProjectionTranscript(input.threadId).pipe(+ searchThread: Effect.fn("ThreadManagementService.searchThread")(function (input) {+ return ensureProjectionTranscript(input.threadId).pipe(Effect.andThen(orchestrator.searchThread(input)),- ),+ );+ }),dispatch,- getThreadHistoryPage: (threadId, cursor, throughEntryId, conversationOnly) =>- ensureProjectionTranscript(threadId).pipe(- Effect.andThen(- orchestrator.getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly),- ),- ),- getTimelinePage: (threadId, options) =>- ensureProjectionTranscript(threadId).pipe(- Effect.andThen(orchestrator.getTimelinePage(threadId, options)),- ),- getMessageCount: (threadId) =>- ensureProjectionTranscript(threadId).pipe(+ getThreadHistoryPage: Effect.fn("ThreadManagementService.getThreadHistoryPage")(+ function (threadId, cursor, throughEntryId, conversationOnly) {+ return ensureProjectionTranscript(threadId).pipe(+ Effect.andThen(+ orchestrator.getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly),+ ),+ );+ },+ ),+ getTimelinePage: Effect.fn("ThreadManagementService.getTimelinePage")(+ function (threadId, options) {+ return ensureProjectionTranscript(threadId).pipe(+ Effect.andThen(orchestrator.getTimelinePage(threadId, options)),+ );+ },+ ),+ getMessageCount: Effect.fn("ThreadManagementService.getMessageCount")(function (threadId) {+ return ensureProjectionTranscript(threadId).pipe(Effect.andThen(orchestrator.getMessageCount(threadId)),- ),- getTurnItem: (input) =>- ensureProjectionTranscript(input.threadId).pipe(+ );+ }),+ getTurnItem: Effect.fn("ThreadManagementService.getTurnItem")(function (input) {+ return ensureProjectionTranscript(input.threadId).pipe(Effect.andThen(orchestrator.getTurnItem(input)),Effect.map((item) => ({ item: item === null ? null : projectTurnItemForDetail(item) })),- ),- getThreadRecords: (threadId, fields, filter) =>- ensureProjectionTranscript(threadId).pipe(- Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)),- ),+ );+ }),+ getThreadRecords: Effect.fn("ThreadManagementService.getThreadRecords")(+ function (threadId, fields, filter) {+ return ensureProjectionTranscript(threadId).pipe(+ Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)),+ );+ },+ ),getThreadProjection,getCheckpointContext,getThreadSnapshot,@@ -1270,7 +1282,9 @@ const layerLegacyV1ThreadImporterNoop = Layer.succeed(LegacyV1ThreadImporter.LegacyV1ThreadImporter.of({pendingThreadCount: Effect.succeed(0),reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),- ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),+ ensureTranscript: Effect.fn("LegacyV1ThreadImporter.ensureTranscript")(function () {+ return Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 });+ }),importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),}),);diff --git a/apps/server/src/orchestration-v2/TurnItemPositionStore.ts b/apps/server/src/orchestration-v2/TurnItemPositionStore.tsindex a004191e095..03636b34153 100644--- a/apps/server/src/orchestration-v2/TurnItemPositionStore.ts+++ b/apps/server/src/orchestration-v2/TurnItemPositionStore.ts@@ -103,13 +103,15 @@ export const layer: Layer.Layer<TurnItemPositionStoreV2, never, SqlClient.SqlClireturn TurnItemPositionStoreV2.of({allocate,- normalize: (item, runOrdinal) =>- allocate({+ // Per-event normalization shares the enclosing orchestration span.+ normalize: Effect.fnUntraced(function* (item, runOrdinal) {+ return yield* allocate({threadId: item.threadId,turnItemId: item.id,runId: item.runId,...(runOrdinal === undefined ? {} : { runOrdinal }),- }).pipe(Effect.map((ordinal) => (item.ordinal === ordinal ? item : { ...item, ordinal }))),+ }).pipe(Effect.map((ordinal) => (item.ordinal === ordinal ? item : { ...item, ordinal })));+ }),});}),);diff --git a/apps/server/src/orchestration-v2/testkit/CommandOutputRecorder.ts b/apps/server/src/orchestration-v2/testkit/CommandOutputRecorder.tsindex 4ce58753a79..51951bfc3ad 100644--- a/apps/server/src/orchestration-v2/testkit/CommandOutputRecorder.ts+++ b/apps/server/src/orchestration-v2/testkit/CommandOutputRecorder.ts@@ -34,14 +34,15 @@ export const layer: Layer.Layer<CommandOutputHub.CommandOutputHub,CommandOutputHub.CommandOutputHub.of({...hub,- append: (input) =>- Effect.sync(() => {+ append: Effect.fn("CommandOutputHub.append")(function (input) {+ return Effect.sync(() => {const previous = recorded.get(input.itemId);recorded.set(input.itemId, {chunks: (previous?.chunks ?? 0) + 1,output: appendTerminalOutput(previous?.output ?? EMPTY_TERMINAL_OUTPUT, input.chunk),});- }).pipe(Effect.andThen(hub.append(input))),+ }).pipe(Effect.andThen(hub.append(input)));+ }),}),).pipe(Context.add(CommandOutputRecorder, {diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.tsindex 0404496693f..77e8bae8f08 100644--- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts+++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts@@ -279,19 +279,18 @@ export function runOrchestratorV2Scenario(const capturedShellSnapshots = new Map<string, OrchestrationV2ThreadShellSnapshot>();let anonymousBackgroundDispatchIndex = 0;- const awaitDispatch = (key: string) =>- Effect.gen(function* () {- const fiber = backgroundDispatches.get(key);- if (!fiber) {- return yield* new OrchestratorV2ScenarioStepError({- scenario: scenario.name,- step: `await:${key}`,- });- }- const events = yield* Fiber.join(fiber);- backgroundDispatches.delete(key);- storedEventGroups.push(events);- });+ const awaitDispatch = Effect.fn("awaitDispatch")(function* (key: string) {+ const fiber = backgroundDispatches.get(key);+ if (!fiber) {+ return yield* new OrchestratorV2ScenarioStepError({+ scenario: scenario.name,+ step: `await:${key}`,+ });+ }+ const events = yield* Fiber.join(fiber);+ backgroundDispatches.delete(key);+ storedEventGroups.push(events);+ });const waitForPendingRuntimeRequest = (threadId: ThreadId,diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.tsindex be25176dc3f..4da359f74c9 100644--- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts+++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts@@ -444,7 +444,9 @@ export function layerWithRegistry<Error>(const layerThreadTitleRegenerationTest = Layer.succeed(ThreadTitleRegenerationService.ThreadTitleRegenerationService,ThreadTitleRegenerationService.ThreadTitleRegenerationService.of({- execute: () => Effect.void,+ execute: Effect.fn("ThreadTitleRegenerationService.execute")(function () {+ return Effect.void;+ }),}),);const layerOrchestratorProvided = Orchestrator.layer.pipe(diff --git a/apps/server/src/persistence/PullRequestFilesViewed.ts b/apps/server/src/persistence/PullRequestFilesViewed.tsindex f3673ff3fd1..476643c1f0b 100644--- a/apps/server/src/persistence/PullRequestFilesViewed.ts+++ b/apps/server/src/persistence/PullRequestFilesViewed.ts@@ -84,18 +84,19 @@ const make = Effect.gen(function* () {});return PullRequestFilesViewedRepository.of({- list: (input) =>- listRows(input).pipe(+ list: Effect.fn("PullRequestFilesViewedRepository.list")(function (input) {+ return listRows(input).pipe(NodeSqliteClient.readOnly,Effect.map((rows) => ({files: rows.slice(0, MAX_FILES_VIEWED_ROWS),truncated: rows.length > MAX_FILES_VIEWED_ROWS,})),Effect.mapError(toSqlOrDecodeError("listPullRequestFilesViewed", "PullRequestFileViewed")),- ),+ );+ }),- set: (input) =>- sql+ set: Effect.fn("PullRequestFilesViewedRepository.set")(function (input) {+ return sql.withTransaction(Effect.forEach(input.files,@@ -141,7 +142,8 @@ const make = Effect.gen(function* () {Effect.mapError((cause) => new PersistenceSqlError({ operation: "setPullRequestFilesViewed", cause }),),- ),+ );+ }),});});diff --git a/apps/server/src/persistence/PullRequestReviewGuides.ts b/apps/server/src/persistence/PullRequestReviewGuides.tsindex 6dd2780eceb..0a12b3f6f74 100644--- a/apps/server/src/persistence/PullRequestReviewGuides.ts+++ b/apps/server/src/persistence/PullRequestReviewGuides.ts@@ -51,8 +51,8 @@ const make = Effect.gen(function* () {const encodeGuide = Schema.encodeEffect(Schema.fromJsonString(PullRequestReviewGuide));return PullRequestReviewGuideRepository.of({- get: (key) =>- findGuide(key).pipe(+ get: Effect.fn("PullRequestReviewGuideRepository.get")(function (key) {+ return findGuide(key).pipe(NodeSqliteClient.readOnly,Effect.map(Option.map((row) => row.guide)),Effect.mapError((cause) =>@@ -60,9 +60,10 @@ const make = Effect.gen(function* () {? PersistenceDecodeError.fromSchemaError("PullRequestReviewGuide", cause): new PersistenceSqlError({ operation: "getPullRequestReviewGuide", cause }),),- ),- put: (key, guide) =>- encodeGuide(guide).pipe(+ );+ }),+ put: Effect.fn("PullRequestReviewGuideRepository.put")(function (key, guide) {+ return encodeGuide(guide).pipe(Effect.mapError((cause) =>PersistenceDecodeError.fromSchemaError("PullRequestReviewGuide", cause),),@@ -78,7 +79,8 @@ const make = Effect.gen(function* () {),),Effect.asVoid,- ),+ );+ }),});});diff --git a/apps/server/src/preview/DesktopBrowserChannel.ts b/apps/server/src/preview/DesktopBrowserChannel.tsindex d56b2a10a54..d407fc78faf 100644--- a/apps/server/src/preview/DesktopBrowserChannel.ts+++ b/apps/server/src/preview/DesktopBrowserChannel.ts@@ -66,13 +66,23 @@ const make = Effect.gen(function* () {if (inputFd === undefined || controlFd === undefined) {return DesktopBrowserChannel.of({available: false,- awaitAttached: () => Effect.succeed(false),+ awaitAttached: Effect.fn("DesktopBrowserChannel.awaitAttached")(function () {+ return Effect.succeed(false);+ }),detached: Stream.empty,attached: Stream.empty,- isAttached: () => Effect.succeed(false),- endpoint: () => Effect.die("No desktop app is attached to this server."),- pointer: () => Effect.void,- turn: () => Effect.void,+ isAttached: Effect.fn("DesktopBrowserChannel.isAttached")(function () {+ return Effect.succeed(false);+ }),+ endpoint: Effect.fn("DesktopBrowserChannel.endpoint")(function () {+ return Effect.die("No desktop app is attached to this server.");+ }),+ turn: Effect.fn("DesktopBrowserChannel.turn")(function () {+ return Effect.void;+ }),+ pointer: Effect.fn("DesktopBrowserChannel.pointer")(function () {+ return Effect.void;+ }),});}@@ -185,8 +195,8 @@ const make = Effect.gen(function* () {return DesktopBrowserChannel.of({available: true,- awaitAttached: (key, timeout) =>- Effect.scoped(+ awaitAttached: Effect.fn("DesktopBrowserChannel.awaitAttached")(function (key, timeout) {+ return Effect.scoped(Effect.gen(function* () {const subscription = yield* PubSub.subscribe(changes);if (attachedTabs.has(keyOf(key))) return true;@@ -198,7 +208,8 @@ const make = Effect.gen(function* () {Effect.map((result) => Option.getOrElse(result, () => false)),);}),- ),+ );+ }),detached: Stream.fromPubSub(changes).pipe(Stream.filter((change) => !change.attached),Stream.map((change) => change.key),@@ -207,10 +218,16 @@ const make = Effect.gen(function* () {Stream.filter((change) => change.attached),Stream.map((change) => change.key),),- isAttached: (key) => Effect.sync(() => attachedTabs.has(keyOf(key))),+ isAttached: Effect.fn("DesktopBrowserChannel.isAttached")(function (key) {+ return Effect.sync(() => attachedTabs.has(keyOf(key)));+ }),endpoint,- pointer: (key, pointer) => command({ type: "pointer", ...key, ...pointer }),- turn: (threadId, active) => command({ type: "turn", threadId, active }),+ turn: Effect.fn("DesktopBrowserChannel.turn")(function (threadId, active) {+ return command({ type: "turn", threadId, active });+ }),+ pointer: Effect.fn("DesktopBrowserChannel.pointer")(function (key, pointer) {+ return command({ type: "pointer", ...key, ...pointer });+ }),});});diff --git a/apps/server/src/preview/PreviewAgentActivity.ts b/apps/server/src/preview/PreviewAgentActivity.tsindex 2e7d261de9e..1f0e39eb037 100644--- a/apps/server/src/preview/PreviewAgentActivity.ts+++ b/apps/server/src/preview/PreviewAgentActivity.ts@@ -50,7 +50,9 @@ const make = Effect.gen(function* () {return PreviewAgentActivity.of({begin,- active: (threadId) => Effect.sync(() => turns.has(threadId)),+ active: Effect.fn("PreviewAgentActivity.active")(function (threadId) {+ return Effect.sync(() => turns.has(threadId));+ }),changes: PubSub.subscribe(changes),});});diff --git a/apps/server/src/preview/ServerBrowserStream.ts b/apps/server/src/preview/ServerBrowserStream.tsindex 0fc3ab0e970..83d4adde7e2 100644--- a/apps/server/src/preview/ServerBrowserStream.ts+++ b/apps/server/src/preview/ServerBrowserStream.ts@@ -176,12 +176,13 @@ const makeHandler = Effect.fnUntraced(function* (browser: ServerBrowser.ServerBr}}),);- const receive = (chunk: Uint8Array | string) => {+ // Incoming messages share the session span; frame acknowledgements are frequent.+ const receive = Effect.fnUntraced(function* (chunk: Uint8Array | string) {const message = parseMessage(chunk);// Ownership serializes actions in the service. Keep reading so dialog// replies and takeover can unblock an action already waiting on the page.if (!isAck(message))- return canOperate+ return yield* canOperate? viewer.input(message).pipe(Effect.forkScoped, Effect.asVoid): Effect.void;const ack = inFlight;@@ -189,11 +190,11 @@ const makeHandler = Effect.fnUntraced(function* (browser: ServerBrowser.ServerBrinFlight = null;pending = null;// Forked: Chromium acks are paced and must not hold up input.- return Effect.andThen(+ return yield* Effect.andThen(ack ? Effect.forkScoped(ack) : Effect.void,next ? sendFrame(next) : Effect.void,);- };+ });const receiveInput = reader.pull.pipe(Effect.flatMap((chunks) => Effect.forEach(chunks, receive, { discard: true })),);diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.tsindex 45113537ce8..b8c0911a520 100644--- a/apps/server/src/process/externalLauncher.ts+++ b/apps/server/src/process/externalLauncher.ts@@ -817,20 +817,29 @@ export const make = Effect.gen(function* () {}).pipe(Effect.uninterruptible);const cachedAvailableEditors = Effect.flatMap(acquireEditorDiscovery, Deferred.await);+ // Forwarders retain the underlying launcher and discovery spans.return ExternalLauncher.of({- resolveAvailableEditors: () => cachedAvailableEditors,- resolveFileManagerRevealKind: () =>- provideCommandResolutionServices(resolveFileManagerRevealKind()).pipe(- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- ),- launchBrowser: (target) =>- launchBrowser(target).pipe(- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- ),- launchEditor: (input) =>- provideCommandResolutionServices(launchEditor(input)).pipe(- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- ),+ resolveAvailableEditors: Effect.fnUntraced(function* () {+ return yield* cachedAvailableEditors;+ }),+ resolveFileManagerRevealKind: Effect.fnUntraced(+ function* () {+ return yield* provideCommandResolutionServices(resolveFileManagerRevealKind());+ },+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ ),+ launchBrowser: Effect.fnUntraced(+ function* (target) {+ return yield* launchBrowser(target);+ },+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ ),+ launchEditor: Effect.fnUntraced(+ function* (input) {+ return yield* provideCommandResolutionServices(launchEditor(input));+ },+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ ),});});diff --git a/apps/server/src/project/ProjectCloneTracker.ts b/apps/server/src/project/ProjectCloneTracker.tsindex 8cad093efff..4a0c9979515 100644--- a/apps/server/src/project/ProjectCloneTracker.ts+++ b/apps/server/src/project/ProjectCloneTracker.ts@@ -417,11 +417,20 @@ export const make = Effect.gen(function* () {{ bufferSize: 1, strategy: "sliding" },);+ // Forwarders retain the underlying operation spans.return ProjectCloneTracker.of({- start: (input, hooks) => locked(start(input, hooks)),- cancel: (projectId) => locked(cancel(projectId)),- retry: (projectId) => locked(retry(projectId)),- discard: (projectId) => locked(discard(projectId)),+ start: Effect.fnUntraced(function* (input, hooks) {+ return yield* locked(start(input, hooks));+ }),+ cancel: Effect.fnUntraced(function* (projectId) {+ return yield* locked(cancel(projectId));+ }),+ retry: Effect.fnUntraced(function* (projectId) {+ return yield* locked(retry(projectId));+ }),+ discard: Effect.fnUntraced(function* (projectId) {+ return yield* locked(discard(projectId));+ }),get,stream,});diff --git a/apps/server/src/provider/CodexChatGptHandoff.ts b/apps/server/src/provider/CodexChatGptHandoff.tsindex 0b73ae0cf1a..9d00a1b966e 100644--- a/apps/server/src/provider/CodexChatGptHandoff.ts+++ b/apps/server/src/provider/CodexChatGptHandoff.ts@@ -18,17 +18,25 @@ export function subscribeChatGptHandoff(const bytes = new Map<string, Uint8Array>();yield* Effect.addFinalizer(() => Effect.sync(() => bytes.clear()));const store = ServerSecretStore.ServerSecretStore.of({- get: (key) => Effect.sync(() => Option.fromUndefinedOr(bytes.get(key))),- set: (key, value) =>- Effect.sync(() => {+ get: Effect.fn("ServerSecretStore.get")(function (key) {+ return Effect.sync(() => Option.fromUndefinedOr(bytes.get(key)));+ }),+ set: Effect.fn("ServerSecretStore.set")(function (key, value) {+ return Effect.sync(() => {bytes.set(key, value);- }),- remove: (key) =>- Effect.sync(() => {+ });+ }),+ remove: Effect.fn("ServerSecretStore.remove")(function (key) {+ return Effect.sync(() => {bytes.delete(key);- }),- create: () => Effect.die("Handoff does not create persistent secrets."),- getOrCreateRandom: () => Effect.die("Handoff uses the destination environment identity."),+ });+ }),+ create: Effect.fn("ServerSecretStore.create")(function () {+ return Effect.die("Handoff does not create persistent secrets.");+ }),+ getOrCreateRandom: Effect.fn("ServerSecretStore.getOrCreateRandom")(function () {+ return Effect.die("Handoff uses the destination environment identity.");+ }),});const auth = yield* makeCodexChatGptAuth({...endpoints,diff --git a/apps/server/src/provider/ModelManifest.ts b/apps/server/src/provider/ModelManifest.tsindex 3cebfb22c79..10ea764a734 100644--- a/apps/server/src/provider/ModelManifest.ts+++ b/apps/server/src/provider/ModelManifest.ts@@ -267,10 +267,11 @@ export const layerModelCatalog = Layer.effect(Effect.gen(function* () {const manifest = yield* ModelManifest;return ModelCatalog.ModelCatalog.of({- current: (driverKind) =>- manifest.current.pipe(+ current: Effect.fn("ModelCatalog.current")(function (driverKind) {+ return manifest.current.pipe(Effect.map((data) => resolveProviderCatalog(data, driverKind) ?? undefined),- ),+ );+ }),bundled: (driverKind) =>resolveProviderCatalog(BUNDLED_MODEL_MANIFEST, driverKind) ?? undefined,refreshInBackground: manifest.refreshInBackground,diff --git a/apps/server/src/provider/ProviderAuthService.ts b/apps/server/src/provider/ProviderAuthService.tsindex 87772b05228..ed841fde70a 100644--- a/apps/server/src/provider/ProviderAuthService.ts+++ b/apps/server/src/provider/ProviderAuthService.ts@@ -205,8 +205,8 @@ export const makeProviderAuthService = Effect.gen(function* () {});return yield* auth.reconnectProfile(input.methodId);}),- importProfile: (input) =>- credentialChanges.withPermit(+ importProfile: Effect.fn("ProviderAuthService.importProfile")(function (input) {+ return credentialChanges.withPermit(Effect.gen(function* () {const auth = yield* getController(input.instanceId, "import");yield* checkSharedBinding(input.instanceId, "start", auth);@@ -221,7 +221,8 @@ export const makeProviderAuthService = Effect.gen(function* () {stopSessions(input.instanceId, auth.credentialBinding),);}),- ),+ );+ }),start: Effect.fn("ProviderAuthService.start")(function* (input, ownerSessionId) {return yield* credentialChanges.withPermit(Effect.gen(function* () {diff --git a/apps/server/src/provider/ProviderHostLive.ts b/apps/server/src/provider/ProviderHostLive.tsindex 60a70204f93..8d73d697705 100644--- a/apps/server/src/provider/ProviderHostLive.ts+++ b/apps/server/src/provider/ProviderHostLive.ts@@ -39,12 +39,15 @@ export const layer = Layer.effect(shouldRunBackgroundWork: backgroundPolicy.shouldRunScopeWork,resolveAttachmentPath: (attachment) =>resolveAttachmentPath({ attachmentsDir: config.attachmentsDir, attachment }),- resolveExtractedTextPath: (path) =>- DocumentText.resolveExtractedTextPath(path).pipe(- Effect.provideService(FileSystem.FileSystem, fileSystem),- ),- credentials: (namespace, bindingId) =>- ProviderCredentialStore.make(namespace, bindingId).pipe(+ // DocumentText owns the path-resolution span.+ resolveExtractedTextPath: Effect.fnUntraced(+ function* (path) {+ return yield* DocumentText.resolveExtractedTextPath(path);+ },+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ ),+ credentials: Effect.fn("ProviderHost.credentials")(function (namespace, bindingId) {+ return ProviderCredentialStore.make(namespace, bindingId).pipe(Effect.map((store) => ({binding: store.binding,get: store.get.pipe(@@ -66,7 +69,8 @@ export const layer = Layer.effect(})),Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),Effect.provideService(Crypto.Crypto, crypto),- ),+ );+ }),});}),);diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.tsindex 72fb7b13593..6a9c721e3a1 100644--- a/apps/server/src/pullRequest/PullRequestService.ts+++ b/apps/server/src/pullRequest/PullRequestService.ts@@ -3623,10 +3623,13 @@ export const make = Effect.gen(function* () {withRoutingCredential,list,filterOptions,- listStats: (input) =>- Effect.forEach(input.refs, (ref) => canonicalRef(ref).pipe(Effect.option)).pipe(- Effect.flatMap((refs) => listStats({ ...input, refs: refs.flatMap(Option.toArray) })),- ),+ // The local operation owns the span; this wrapper only canonicalizes refs.+ listStats: Effect.fnUntraced(function* (input) {+ const refs = yield* Effect.forEach(input.refs, (ref) =>+ canonicalRef(ref).pipe(Effect.option),+ );+ return yield* listStats({ ...input, refs: refs.flatMap(Option.toArray) });+ }),summary: credentialCached(summary),stack: credentialCached(stack),subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.tsindex e59065400b2..da72320af27 100644--- a/apps/server/src/relay/AgentAwarenessRelay.ts+++ b/apps/server/src/relay/AgentAwarenessRelay.ts@@ -843,7 +843,9 @@ export const make = Effect.gen(function* () {return AgentAwarenessRelay.of({publishThread,drain: worker.drain,- requestCatchUp: () => Queue.offer(catchUpRequests, undefined).pipe(Effect.asVoid),+ requestCatchUp: Effect.fn("AgentAwarenessRelay.requestCatchUp")(function () {+ return Queue.offer(catchUpRequests, undefined).pipe(Effect.asVoid);+ }),start,});});diff --git a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.tsindex 4fec32dd76c..4f3e88e81bd 100644--- a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts+++ b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts@@ -637,16 +637,25 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")health: Ref.get(health),subscribeHealth: subscribeBeforeSnapshotWithoutMutex(healthChanges, Ref.get(health)),setDiagnosticsDemand,- requestDesktopUpdate: (requestId) =>- sendControlMessage({- version: 1,- type: "requestDesktopUpdate",- requestId,- }),- commitDesktopUpdate: (requestId) =>- sendControlMessage({ version: 1, type: "commitDesktopUpdate", requestId }),- cancelDesktopUpdate: (requestId) =>- sendControlMessage({ version: 1, type: "cancelDesktopUpdate", requestId }),+ requestDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.requestDesktopUpdate")(+ function (requestId) {+ return sendControlMessage({+ version: 1,+ type: "requestDesktopUpdate",+ requestId,+ });+ },+ ),+ commitDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.commitDesktopUpdate")(+ function (requestId) {+ return sendControlMessage({ version: 1, type: "commitDesktopUpdate", requestId });+ },+ ),+ cancelDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.cancelDesktopUpdate")(+ function (requestId) {+ return sendControlMessage({ version: 1, type: "cancelDesktopUpdate", requestId });+ },+ ),desktopUpdates: Effect.gen(function* () {const subscription = yield* PubSub.subscribe(updateReportChanges);const initial = yield* Ref.get(latestUpdateReport);@@ -694,10 +703,18 @@ export const layerTest = (changes: Stream.empty,})),),- setDiagnosticsDemand: () => Effect.void,- requestDesktopUpdate: () => Effect.void,- commitDesktopUpdate: () => Effect.void,- cancelDesktopUpdate: () => Effect.void,+ setDiagnosticsDemand: Effect.fn("DesktopTelemetryReceiver.setDiagnosticsDemand")(function () {+ return Effect.void;+ }),+ requestDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.requestDesktopUpdate")(function () {+ return Effect.void;+ }),+ commitDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.commitDesktopUpdate")(function () {+ return Effect.void;+ }),+ cancelDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.cancelDesktopUpdate")(function () {+ return Effect.void;+ }),desktopUpdates:overrides.desktopUpdates ??Effect.succeed({diff --git a/apps/server/src/resourceTelemetry/NativeTelemetryClient.ts b/apps/server/src/resourceTelemetry/NativeTelemetryClient.tsindex 55eeb2f8551..073988ecfd0 100644--- a/apps/server/src/resourceTelemetry/NativeTelemetryClient.ts+++ b/apps/server/src/resourceTelemetry/NativeTelemetryClient.ts@@ -1088,14 +1088,19 @@ export const layerTest = (processTree: true,}),snapshots: Stream.empty,- readHistory: () =>- Effect.fail(+ readHistory: Effect.fn("NativeTelemetryClient.readHistory")(function () {+ return Effect.fail(new NativeTelemetryUnavailable({reason: "No resource monitor history was configured for this test.",}),- ),- setExternalProcesses: () => Effect.void,- setHostPowerState: () => Effect.void,+ );+ }),+ setExternalProcesses: Effect.fn("NativeTelemetryClient.setExternalProcesses")(function () {+ return Effect.void;+ }),+ setHostPowerState: Effect.fn("NativeTelemetryClient.setHostPowerState")(function () {+ return Effect.void;+ }),sampleNow: Effect.fail(new NativeTelemetryUnavailable({reason: "No resource monitor sample was configured for this test.",diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.tsindex 09d89374652..36f5e7642ae 100644--- a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts+++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts@@ -71,6 +71,7 @@ export class SourceControlProviderRegistry extends Context.Service<function unsupportedProvider(kind: SourceControlProviderKind,): SourceControlProvider.SourceControlProvider["Service"] {+ // Binding context does not create a second provider-operation span.return SourceControlProvider.SourceControlProvider.of({kind,// Unknown hosts have no readable change requests; return none to avoid poll warnings on every refresh.@@ -195,37 +196,45 @@ function bindProviderContext(return SourceControlProvider.SourceControlProvider.of({...provider,- listChangeRequests: (input) =>- provider.listChangeRequests({+ listChangeRequests: Effect.fnUntraced(function* (input) {+ return yield* provider.listChangeRequests({...input,context: input.context ?? context,- }),- getChangeRequest: (input) =>- provider.getChangeRequest({+ });+ }),+ getChangeRequest: Effect.fnUntraced(function* (input) {+ return yield* provider.getChangeRequest({...input,context: input.context ?? context,- }),- createChangeRequest: (input) =>- provider.createChangeRequest({+ });+ }),+ createChangeRequest: Effect.fnUntraced(function* (input) {+ return yield* provider.createChangeRequest({...input,context: input.context ?? context,- }),- getRepositoryCloneUrls: (input) =>- provider.getRepositoryCloneUrls({+ });+ }),+ getRepositoryCloneUrls: Effect.fnUntraced(function* (input) {+ return yield* provider.getRepositoryCloneUrls({...input,context: input.context ?? context,- }),- createRepository: (input) => provider.createRepository(input),- getDefaultBranch: (input) =>- provider.getDefaultBranch({+ });+ }),+ createRepository: Effect.fnUntraced(function* (input) {+ return yield* provider.createRepository(input);+ }),+ getDefaultBranch: Effect.fnUntraced(function* (input) {+ return yield* provider.getDefaultBranch({...input,context: input.context ?? context,- }),- checkoutChangeRequest: (input) =>- provider.checkoutChangeRequest({+ });+ }),+ checkoutChangeRequest: Effect.fnUntraced(function* (input) {+ return yield* provider.checkoutChangeRequest({...input,context: input.context ?? context,- }),+ });+ }),});}@@ -336,7 +345,9 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit},get,resolveHandle,- resolve: (input) => resolveHandle(input).pipe(Effect.map((handle) => handle.provider)),+ resolve: Effect.fn("SourceControlProviderRegistry.resolve")(function (input) {+ return resolveHandle(input).pipe(Effect.map((handle) => handle.provider));+ }),discover: Effect.forEach(discoverySpecs,(spec) =>diff --git a/apps/server/src/sourceControl/SourceControlRepositoryService.ts b/apps/server/src/sourceControl/SourceControlRepositoryService.tsindex e211741baf8..7c34e648686 100644--- a/apps/server/src/sourceControl/SourceControlRepositoryService.ts+++ b/apps/server/src/sourceControl/SourceControlRepositoryService.ts@@ -521,29 +521,39 @@ export const make = Effect.gen(function* () {},);+ // Forwarders retain the underlying operation spans.return SourceControlRepositoryService.of({- lookupRepository: (input) =>- lookupRepository(input).pipe(mapRepositoryError("lookupRepository", input.provider)),- prepareClone: (input) =>- prepareClone(input).pipe(+ lookupRepository: Effect.fnUntraced(function* (input) {+ return yield* lookupRepository(input).pipe(+ mapRepositoryError("lookupRepository", input.provider),+ );+ }),+ prepareClone: Effect.fnUntraced(function* (input) {+ return yield* prepareClone(input).pipe(mapRepositoryError("cloneRepository",input.provider ?? SourceControlProviderKind.make("unknown"),),- ),- cloneRepository: (input, options) =>- cloneRepository(input, options).pipe(+ );+ }),+ cloneRepository: Effect.fnUntraced(function* (input, options) {+ return yield* cloneRepository(input, options).pipe(mapRepositoryError("cloneRepository",input.provider ?? SourceControlProviderKind.make("unknown"),),- ),- discardClone: (destinationPath) =>- discardClone(destinationPath).pipe(+ );+ }),+ discardClone: Effect.fnUntraced(function* (destinationPath) {+ return yield* discardClone(destinationPath).pipe(mapRepositoryError("discardClone", SourceControlProviderKind.make("unknown")),- ),- publishRepository: (input) =>- publishRepository(input).pipe(mapRepositoryError("publishRepository", input.provider)),+ );+ }),+ publishRepository: Effect.fnUntraced(function* (input) {+ return yield* publishRepository(input).pipe(+ mapRepositoryError("publishRepository", input.provider),+ );+ }),});});diff --git a/apps/server/src/telemetry/AnalyticsService.ts b/apps/server/src/telemetry/AnalyticsService.tsindex 1e18735681f..64c401c7bb4 100644--- a/apps/server/src/telemetry/AnalyticsService.ts+++ b/apps/server/src/telemetry/AnalyticsService.ts@@ -95,9 +95,13 @@ export class AnalyticsService extends Context.Service<static readonly layerTest = Layer.succeed(AnalyticsService,AnalyticsService.of({- record: () => Effect.void,+ record: Effect.fn("AnalyticsService.record")(function () {+ return Effect.void;+ }),flush: Effect.void,- recordOwners: () => Effect.void,+ recordOwners: Effect.fn("AnalyticsService.recordOwners")(function () {+ return Effect.void;+ }),}),);}diff --git a/apps/server/src/textGeneration/TextGeneration.ts b/apps/server/src/textGeneration/TextGeneration.tsindex aedd2cc4077..96f266c6f89 100644--- a/apps/server/src/textGeneration/TextGeneration.ts+++ b/apps/server/src/textGeneration/TextGeneration.ts@@ -57,24 +57,30 @@ export const make = Effect.gen(function* () {const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;const sourceControl = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;return TextGeneration.of({- generateCommitMessage: (input) =>- resolveInstance(registry, "generateCommitMessage", input.modelSelection.instanceId).pipe(- Effect.flatMap((textGeneration) => textGeneration.generateCommitMessage(input)),- ),- generatePrContent: (input) =>- resolveInstance(registry, "generatePrContent", input.modelSelection.instanceId).pipe(+ generateCommitMessage: Effect.fn("TextGeneration.generateCommitMessage")(function (input) {+ return resolveInstance(+ registry,+ "generateCommitMessage",+ input.modelSelection.instanceId,+ ).pipe(Effect.flatMap((textGeneration) => textGeneration.generateCommitMessage(input)));+ }),+ generatePrContent: Effect.fn("TextGeneration.generatePrContent")(function (input) {+ return resolveInstance(registry, "generatePrContent", input.modelSelection.instanceId).pipe(Effect.flatMap((textGeneration) => textGeneration.generatePrContent(input)),- ),- generateBranchName: (input) =>- resolveInstance(registry, "generateBranchName", input.modelSelection.instanceId).pipe(+ );+ }),+ generateBranchName: Effect.fn("TextGeneration.generateBranchName")(function (input) {+ return resolveInstance(registry, "generateBranchName", input.modelSelection.instanceId).pipe(Effect.flatMap((textGeneration) => textGeneration.generateBranchName(input)),- ),- generateReviewGuide: (input) =>- resolveInstance(registry, "generateReviewGuide", input.modelSelection.instanceId).pipe(+ );+ }),+ generateReviewGuide: Effect.fn("TextGeneration.generateReviewGuide")(function (input) {+ return resolveInstance(registry, "generateReviewGuide", input.modelSelection.instanceId).pipe(Effect.flatMap((textGeneration) => textGeneration.generateReviewGuide(input)),- ),- generateThreadTitle: (input) =>- resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe(+ );+ }),+ generateThreadTitle: Effect.fn("TextGeneration.generateThreadTitle")(function (input) {+ return resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe(Effect.flatMap((textGeneration) =>Effect.gen(function* () {const linkedContext =@@ -88,7 +94,8 @@ export const make = Effect.gen(function* () {return yield* textGeneration.generateThreadTitle({ ...input, linkedContext });}),),- ),+ );+ }),});});diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.tsindex 9b79c2110e2..8c15b808d61 100644--- a/apps/server/src/vcs/GitVcsDriverCore.ts+++ b/apps/server/src/vcs/GitVcsDriverCore.ts@@ -4439,6 +4439,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*),);+ // Forwarders retain the underlying Git operation spans.return GitVcsDriver.GitVcsDriver.of({execute,status,@@ -4446,11 +4447,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*statusDetailsLocal,statusDetailsRemote,prepareCommitContext,- commit: (cwd, subject, body, options) =>- withListRefsInvalidation(cwd, commit(cwd, subject, body, options)),- pushCurrentBranch: (cwd, fallbackBranch, options) =>- withListRefsInvalidation(cwd, pushCurrentBranch(cwd, fallbackBranch, options)),- pullCurrentBranch: (cwd) => withListRefsInvalidation(cwd, pullCurrentBranch(cwd)),+ commit: Effect.fnUntraced(function* (cwd, subject, body, options) {+ return yield* withListRefsInvalidation(cwd, commit(cwd, subject, body, options));+ }),+ pushCurrentBranch: Effect.fnUntraced(function* (cwd, fallbackBranch, options) {+ return yield* withListRefsInvalidation(cwd, pushCurrentBranch(cwd, fallbackBranch, options));+ }),+ pullCurrentBranch: Effect.fnUntraced(function* (cwd) {+ return yield* withListRefsInvalidation(cwd, pullCurrentBranch(cwd));+ }),readRangeContext,getReviewDiffPreview,getReviewDiffFileContents,@@ -4458,18 +4463,24 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*readBranchBase,resolveBranchName,listRefs,- createWorktree: (input, options) =>- withListRefsInvalidation(input.cwd, createWorktree(input, options)),- fetchRefIntoBranch: (input) => withListRefsInvalidation(input.cwd, fetchRefIntoBranch(input)),+ createWorktree: Effect.fnUntraced(function* (input, options) {+ return yield* withListRefsInvalidation(input.cwd, createWorktree(input, options));+ }),+ fetchRefIntoBranch: Effect.fnUntraced(function* (input) {+ return yield* withListRefsInvalidation(input.cwd, fetchRefIntoBranch(input));+ }),fetchRefCommit,resolveCommit,- refreshCheckedOutBranch: (input) =>- withListRefsInvalidation(input.cwd, refreshCheckedOutBranch(input)),- ensureRemote: (input) => withListRefsInvalidation(input.cwd, ensureRemote(input)),+ refreshCheckedOutBranch: Effect.fnUntraced(function* (input) {+ return yield* withListRefsInvalidation(input.cwd, refreshCheckedOutBranch(input));+ }),+ ensureRemote: Effect.fnUntraced(function* (input) {+ return yield* withListRefsInvalidation(input.cwd, ensureRemote(input));+ }),resolvePrimaryRemoteName,resolveDefaultBranchName,- fetchRemote: (input) =>- withListRefsInvalidation(+ fetchRemote: Effect.fnUntraced(function* (input) {+ return yield* withListRefsInvalidation(input.cwd,fetchRemote(input).pipe(Effect.flatMap((fetched) =>@@ -4478,23 +4489,42 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*: fetchRemote({ cwd: input.cwd, remoteName: input.remoteName }).pipe(Effect.asVoid),),),- ),+ );+ }),remoteExists,remoteBranchExists,resolveRemoteTrackingCommit,resolveWorktreeBaseRemote,- fetchWorktreeBaseCommit: (input) =>- withListRefsInvalidation(input.cwd, fetchWorktreeBaseCommit(input)),- fetchRemoteBranch: (input) => withListRefsInvalidation(input.cwd, fetchRemoteBranch(input)),- fetchRemoteTrackingBranch: (input) =>- withListRefsInvalidation(input.cwd, fetchRemoteTrackingBranch(input)),- setBranchUpstream: (input) => withListRefsInvalidation(input.cwd, setBranchUpstream(input)),- removeWorktree: (input) => withListRefsInvalidation(input.cwd, removeWorktree(input)),- pruneWorktrees: (input) => withListRefsInvalidation(input.cwd, pruneWorktrees(input)),- deleteLocalBranch: (input) => withListRefsInvalidation(input.cwd, deleteLocalBranch(input)),- renameBranch: (input) => withListRefsInvalidation(input.cwd, renameBranch(input)),- createRef: (input) => withListRefsInvalidation(input.cwd, createRef(input)),- switchRef: (input) => withListRefsInvalidation(input.cwd, switchRef(input)),+ fetchWorktreeBaseCommit: Effect.fnUntraced(function* (input) {+ return yield* withListRefsInvalidation(input.cwd, fetchWorktreeBaseCommit(input));+ }),+ fetchRemoteBranch: Effect.fnUntraced(function* (input) {+ return yield* withListRefsInvalidation(input.cwd, fetchRemoteBranch(input));+ }),+ fetchRemoteTrackingBranch: Effect.fnUntraced(function* (input) {+ return yield* withListRefsInvalidation(input.cwd, fetchRemoteTrackingBranch(input));+ }),+ setBranchUpstream: Effect.fnUntraced(function* (input) {+ return yield* withListRefsInvalidation(input.cwd, setBranchUpstream(input));+ }),+ removeWorktree: Effect.fnUntraced(function* (input) {+ return yield* withListRefsInvalidation(input.cwd, removeWorktree(input));+ }),+ pruneWorktrees: Effect.fnUntraced(function* (input) {+ return yield* withListRefsInvalidation(input.cwd, pruneWorktrees(input));+ }),+ deleteLocalBranch: Effect.fnUntraced(function* (input) {+ return yield* withListRefsInvalidation(input.cwd, deleteLocalBranch(input));+ }),+ renameBranch: Effect.fnUntraced(function* (input) {+ return yield* withListRefsInvalidation(input.cwd, renameBranch(input));+ }),+ createRef: Effect.fnUntraced(function* (input) {+ return yield* withListRefsInvalidation(input.cwd, createRef(input));+ }),+ switchRef: Effect.fnUntraced(function* (input) {+ return yield* withListRefsInvalidation(input.cwd, switchRef(input));+ }),initRepo: initRepoWithListRefsInvalidation,listLocalBranchNames,listWorktreePaths,diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.tsindex 0fe0129f11a..4ac7fa26e3c 100644--- a/apps/web/src/connection/platform.ts+++ b/apps/web/src/connection/platform.ts@@ -791,25 +791,28 @@ const layerPlatformConnectionSource = Layer.effect(const layerEnvironmentOwnedDataCleanup = Layer.succeed(Persistence.EnvironmentOwnedDataCleanup,Persistence.EnvironmentOwnedDataCleanup.of({- clear: (environmentId) =>- Effect.sync(() => {+ clear: Effect.fn("Persistence.EnvironmentOwnedDataCleanup.clear")(function (environmentId) {+ return Effect.sync(() => {clearComposerDraftsEnvironment(environmentId);- }),+ });+ }),}),);const layerRpcRequestObserver = Layer.succeed(EnvironmentRpcRequestObserver,EnvironmentRpcRequestObserver.of({- observe: ({ environmentId, environmentLabel, method }) =>- Effect.sync(() => {+ // Every RPC passes through this observer; the request owns its span.+ observe: Effect.fnUntraced(function* ({ environmentId, environmentLabel, method }) {+ return yield* Effect.sync(() => {nextObservedRpcRequestId += 1;const requestId = `${environmentId}:${nextObservedRpcRequestId}`;trackRpcRequestSent(requestId, method, `${method} · ${environmentLabel}`);return Effect.sync(() => {acknowledgeRpcRequest(requestId);});- }),+ });+ }),}),);diff --git a/apps/web/src/connection/storage.ts b/apps/web/src/connection/storage.tsindex 621a8020c5a..8cde71f7c20 100644--- a/apps/web/src/connection/storage.ts+++ b/apps/web/src/connection/storage.ts@@ -543,11 +543,12 @@ export function makeBrowserPullRequestRoutingPermissions(catch: (cause) => catalogError("save pull request routing permissions in", cause),});return PullRequestRoutingPermissions.of({- get: (entry) =>- Effect.sync(() => {+ get: Effect.fn("PullRequestRoutingPermissions.get")(function (entry) {+ return Effect.sync(() => {const value = read(`${PULL_REQUEST_ROUTING_KEY_PREFIX}${entry.target.environmentId}`);return pullRequestRoutingPermissionFor(entry, value === null ? [] : [value]);- }),+ });+ }),changes: Stream.callback<ReadonlyArray<StoredPullRequestRoutingPermission>>((queue) =>Effect.acquireRelease(Effect.sync(() => {@@ -570,16 +571,14 @@ export function makeBrowserPullRequestRoutingPermissions(}),).pipe(Effect.asVoid),),- set: (entry, permission) => {+ set: Effect.fn("PullRequestRoutingPermissions.set")(function* (entry, permission) {const connectionKey = pullRequestRoutingConnectionKey(entry);if (connectionKey === null)- return Effect.fail(- new ConnectionBlockedError({- reason: "configuration",- detail: "This environment does not have a saved connection endpoint.",- }),- );- return write(+ return yield* new ConnectionBlockedError({+ reason: "configuration",+ detail: "This environment does not have a saved connection endpoint.",+ });+ return yield* write(entry.target.environmentId,permission === "off"? null@@ -589,8 +588,10 @@ export function makeBrowserPullRequestRoutingPermissions(permission,},);- },- forget: (environmentId) => write(environmentId, null),+ }),+ forget: Effect.fn("PullRequestRoutingPermissions.forget")(function (environmentId) {+ return write(environmentId, null);+ }),});}@@ -635,22 +636,32 @@ export const layer = Layer.effectContext(),});const registrationStore = Persistence.ConnectionRegistrationStore.of({- register: (registration, routes) =>- catalog- .update((document) => registerConnectionInCatalog(document, registration, routes))- .pipe(Effect.mapError((cause) => persistenceError("register-connection", cause))),- setRoutes: (environmentId, routes) =>- catalog- .update((document) => setRoutesInCatalog(document, environmentId, routes))- .pipe(Effect.mapError((cause) => persistenceError("set-connection-routes", cause))),- remove: (environmentId) =>- catalog+ register: Effect.fn("Persistence.ConnectionRegistrationStore.register")(+ function (registration, routes) {+ return catalog+ .update((document) => registerConnectionInCatalog(document, registration, routes))+ .pipe(Effect.mapError((cause) => persistenceError("register-connection", cause)));+ },+ ),+ setRoutes: Effect.fn("Persistence.ConnectionRegistrationStore.setRoutes")(+ function (environmentId, routes) {+ return catalog+ .update((document) => setRoutesInCatalog(document, environmentId, routes))+ .pipe(Effect.mapError((cause) => persistenceError("set-connection-routes", cause)));+ },+ ),+ remove: Effect.fn("Persistence.ConnectionRegistrationStore.remove")(function (environmentId) {+ return catalog.update((document) => removeConnectionFromCatalog(document, environmentId))- .pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause))),- setEnabled: (environmentId, enabled) =>- catalog- .update((document) => setConnectionEnabledInCatalog(document, environmentId, enabled))- .pipe(Effect.mapError((cause) => persistenceError("set-connection-enabled", cause))),+ .pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause)));+ }),+ setEnabled: Effect.fn("Persistence.ConnectionRegistrationStore.setEnabled")(+ function (environmentId, enabled) {+ return catalog+ .update((document) => setConnectionEnabledInCatalog(document, environmentId, enabled))+ .pipe(Effect.mapError((cause) => persistenceError("set-connection-enabled", cause)));+ },+ ),});const profileStore = ProfileStore.make({get: (connectionId) =>@@ -724,8 +735,8 @@ export const layer = Layer.effectContext(})),});const cacheStore = Persistence.EnvironmentCacheStore.of({- loadShell: (environmentId) =>- readDatabaseValue(database, SHELL_STORE_NAME, environmentId).pipe(+ loadShell: Effect.fn("Persistence.EnvironmentCacheStore.loadShell")(function (environmentId) {+ return readDatabaseValue(database, SHELL_STORE_NAME, environmentId).pipe(Effect.tap(() => Effect.promise(() => projectFaviconCache.hydrate())),Effect.flatMap((raw) => {if (typeof raw !== "string") {@@ -744,7 +755,8 @@ export const layer = Layer.effectContext();}),Effect.mapError((cause) => persistenceError("load-shell", cause)),- ),+ );+ }),saveShell: Effect.fn("storage.saveShell")(function* (environmentId, snapshot) {const encoded = yield* encodeStoredShellSnapshot({@@ -760,25 +772,30 @@ export const layer = Layer.effectContext(: persistenceError("save-shell", cause),),),- loadServerConfig: (environmentId) =>- readDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId).pipe(- Effect.flatMap((raw) => {- if (typeof raw !== "string") {- return Effect.succeedNone;- }- return decodeStoredServerConfig(raw).pipe(- Effect.mapError((cause) => persistenceError("load-server-config", cause)),- Effect.map((stored) =>- stored.environmentId === environmentId ? Option.some(stored.config) : Option.none(),- ),- );- }),- Effect.mapError((cause) =>- cause._tag === "ConnectionPersistenceError"- ? cause- : persistenceError("load-server-config", cause),- ),- ),+ loadServerConfig: Effect.fn("Persistence.EnvironmentCacheStore.loadServerConfig")(+ function (environmentId) {+ return readDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId).pipe(+ Effect.flatMap((raw) => {+ if (typeof raw !== "string") {+ return Effect.succeedNone;+ }+ return decodeStoredServerConfig(raw).pipe(+ Effect.mapError((cause) => persistenceError("load-server-config", cause)),+ Effect.map((stored) =>+ stored.environmentId === environmentId+ ? Option.some(stored.config)+ : Option.none(),+ ),+ );+ }),+ Effect.mapError((cause) =>+ cause._tag === "ConnectionPersistenceError"+ ? cause+ : persistenceError("load-server-config", cause),+ ),+ );+ },+ ),saveServerConfig: Effect.fn("storage.saveServerConfig")(function* (environmentId, config) {const encoded = yield* encodeStoredServerConfig({@@ -794,34 +811,37 @@ export const layer = Layer.effectContext(: persistenceError("save-server-config", cause),),),- loadThread: (environmentId, threadId) =>- readDatabaseValue(- database,- THREAD_STORE_NAME,- threadCacheKey(environmentId, threadId),- ).pipe(- Effect.flatMap((raw) => {- if (typeof raw !== "string") {- return Effect.succeedNone;- }- return decodeOrDiscardOrchestrationCache(- decodeStoredThreadSnapshot(raw).pipe(- Effect.mapError((cause) => persistenceError("load-thread", cause)),- Effect.map((stored) =>- stored.environmentId === environmentId && stored.threadId === threadId- ? Option.some(stored.snapshot)- : Option.none(),+ loadThread: Effect.fn("Persistence.EnvironmentCacheStore.loadThread")(+ function (environmentId, threadId) {+ return readDatabaseValue(+ database,+ THREAD_STORE_NAME,+ threadCacheKey(environmentId, threadId),+ ).pipe(+ Effect.flatMap((raw) => {+ if (typeof raw !== "string") {+ return Effect.succeedNone;+ }+ return decodeOrDiscardOrchestrationCache(+ decodeStoredThreadSnapshot(raw).pipe(+ Effect.mapError((cause) => persistenceError("load-thread", cause)),+ Effect.map((stored) =>+ stored.environmentId === environmentId && stored.threadId === threadId+ ? Option.some(stored.snapshot)+ : Option.none(),+ ),),- ),- removeDatabaseValue(- database,- THREAD_STORE_NAME,- threadCacheKey(environmentId, threadId),- ),- );- }),- Effect.mapError((cause) => persistenceError("load-thread", cause)),- ),+ removeDatabaseValue(+ database,+ THREAD_STORE_NAME,+ threadCacheKey(environmentId, threadId),+ ),+ );+ }),+ Effect.mapError((cause) => persistenceError("load-thread", cause)),+ );+ },+ ),saveThread: Effect.fn("storage.saveThread")(function* (environmentId, snapshot) {const encoded = yield* encodeStoredThreadSnapshot({@@ -843,27 +863,34 @@ export const layer = Layer.effectContext(: persistenceError("save-thread", cause),),),- loadVcsRefs: (environmentId, cwd) =>- readDatabaseValue(database, VCS_REFS_STORE_NAME, vcsRefsCacheKey(environmentId, cwd)).pipe(- Effect.flatMap((raw) => {- if (typeof raw !== "string") {- return Effect.succeedNone;- }- return decodeStoredVcsRefs(raw).pipe(- Effect.mapError((cause) => persistenceError("load-vcs-refs", cause)),- Effect.map((stored) =>- stored.environmentId === environmentId && stored.cwd === cwd- ? Option.some(stored.refs)- : Option.none(),- ),- );- }),- Effect.mapError((cause) =>- cause._tag === "ConnectionPersistenceError"- ? cause- : persistenceError("load-vcs-refs", cause),- ),- ),+ loadVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.loadVcsRefs")(+ function (environmentId, cwd) {+ return readDatabaseValue(+ database,+ VCS_REFS_STORE_NAME,+ vcsRefsCacheKey(environmentId, cwd),+ ).pipe(+ Effect.flatMap((raw) => {+ if (typeof raw !== "string") {+ return Effect.succeedNone;+ }+ return decodeStoredVcsRefs(raw).pipe(+ Effect.mapError((cause) => persistenceError("load-vcs-refs", cause)),+ Effect.map((stored) =>+ stored.environmentId === environmentId && stored.cwd === cwd+ ? Option.some(stored.refs)+ : Option.none(),+ ),+ );+ }),+ Effect.mapError((cause) =>+ cause._tag === "ConnectionPersistenceError"+ ? cause+ : persistenceError("load-vcs-refs", cause),+ ),+ );+ },+ ),saveVcsRefs: Effect.fn("storage.saveVcsRefs")(function* (environmentId, cwd, refs) {const encoded = yield* encodeStoredVcsRefs({@@ -885,26 +912,35 @@ export const layer = Layer.effectContext(: persistenceError("save-vcs-refs", cause),),),- removeVcsRefs: (environmentId, cwd) =>- removeDatabaseValue(- database,- VCS_REFS_STORE_NAME,- vcsRefsCacheKey(environmentId, cwd),- ).pipe(Effect.mapError((cause) => persistenceError("remove-vcs-refs", cause))),- clearVcsRefs: (environmentId) =>- removeDatabaseValuesInRange(- database,- VCS_REFS_STORE_NAME,- IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),- ).pipe(Effect.mapError((cause) => persistenceError("clear-vcs-refs", cause))),- removeThread: (environmentId, threadId) =>- removeDatabaseValue(- database,- THREAD_STORE_NAME,- threadCacheKey(environmentId, threadId),- ).pipe(Effect.mapError((cause) => persistenceError("remove-thread", cause))),- clear: (environmentId) =>- Effect.all(+ removeVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.removeVcsRefs")(+ function (environmentId, cwd) {+ return removeDatabaseValue(+ database,+ VCS_REFS_STORE_NAME,+ vcsRefsCacheKey(environmentId, cwd),+ ).pipe(Effect.mapError((cause) => persistenceError("remove-vcs-refs", cause)));+ },+ ),+ clearVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.clearVcsRefs")(+ function (environmentId) {+ return removeDatabaseValuesInRange(+ database,+ VCS_REFS_STORE_NAME,+ IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),+ ).pipe(Effect.mapError((cause) => persistenceError("clear-vcs-refs", cause)));+ },+ ),+ removeThread: Effect.fn("Persistence.EnvironmentCacheStore.removeThread")(+ function (environmentId, threadId) {+ return removeDatabaseValue(+ database,+ THREAD_STORE_NAME,+ threadCacheKey(environmentId, threadId),+ ).pipe(Effect.mapError((cause) => persistenceError("remove-thread", cause)));+ },+ ),+ clear: Effect.fn("Persistence.EnvironmentCacheStore.clear")(function (environmentId) {+ return Effect.all([Effect.promise(() => projectFaviconCache.clearEnvironment(environmentId)),removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),@@ -921,7 +957,8 @@ export const layer = Layer.effectContext(),],{ concurrency: "unbounded", discard: true },- ).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause))),+ ).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause)));+ }),});return Context.make(Persistence.ConnectionTargetStore, targetStore).pipe(diff --git a/docs/internals/effect-services.md b/docs/internals/effect-services.mdindex f2d93b9d8e8..13e05dc926f 100644--- a/docs/internals/effect-services.md+++ b/docs/internals/effect-services.md@@ -94,13 +94,16 @@ export const layer = Layer.effect(Foo, make);Reusable functions use `Effect.fn("Service.operation")`, not an arrow or declaration returning`Effect.gen`. The named form creates a span; `Effect.fn(function* ...)` only captures stack-frames. Keep `Effect.gen` for inline programs, callbacks, and layer construction.+frames. Keep `Effect.gen` for inline programs and layer construction. Use+`Effect.fnUntraced(function* ...)` for inline handlers that share the enclosing operation's span.Default to named spans for service operations and I/O. Use `Effect.fnUntraced` deliberately forper-chunk/per-event work, tight loops, or helpers already covered by the same operation's span.Explain the reason beside the function or a group of related functions. A loop is not by itselfan exemption: its outer operation can still have a useful span without tracing each iteration.-Preserve existing span names and options instead of adding a second span for the same operation.+Move existing span names and options into `Effect.fn` instead of adding a second span for the same+operation; annotate the current span for attributes that depend on function arguments. Keep an+explicit `withSpan` inside an untraced function when an outer tracer override must cover span creation.Pass effect combinators after the generator body. A transform that needs the function's inputreceives it after the effect. Use `Effect.fn.Return<A, E, R>` when the generator needs an explicitdiff --git a/infra/relay/src/agentActivity/ApnsDeliveryQueue.ts b/infra/relay/src/agentActivity/ApnsDeliveryQueue.tsindex ed75b3a877c..6b608802a34 100644--- a/infra/relay/src/agentActivity/ApnsDeliveryQueue.ts+++ b/infra/relay/src/agentActivity/ApnsDeliveryQueue.ts@@ -217,10 +217,12 @@ export const layerCloudflareQueues = (Layer.succeed(ApnsDeliveryQueueSender,ApnsDeliveryQueueSender.of({- send: (body) =>- sender- .send(body)- .pipe(Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext)),+ send: Effect.fn("ApnsDeliveryQueueSender.send")(+ function* (body) {+ return yield* sender.send(body);+ },+ Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),+ ),}),),),diff --git a/infra/relay/src/agentActivity/FcmDeliveryQueueConsumer.ts b/infra/relay/src/agentActivity/FcmDeliveryQueueConsumer.tsindex 862546cf3b0..cd96cd8b623 100644--- a/infra/relay/src/agentActivity/FcmDeliveryQueueConsumer.ts+++ b/infra/relay/src/agentActivity/FcmDeliveryQueueConsumer.ts@@ -9,15 +9,15 @@ export const processMessage = Effect.fn("relay.fcm_delivery_queue.process_messagconst deliveries = yield* FcmDeliveries.FcmDeliveries;yield* deliveries.process(message.body).pipe(Effect.matchEffect({- onFailure: (error) =>- Effect.gen(function* () {- // Cloudflare keeps the first ack/retry decision; decide before Alchemy acknowledges the batch.- message.retry();- yield* Effect.logWarning("FCM queue delivery failed; retrying message", {- messageId: message.id,- errorTag: error._tag,- });- }),+ // The enclosing operation owns the span for this inline handler.+ onFailure: Effect.fnUntraced(function* (error) {+ // Cloudflare keeps the first ack/retry decision; decide before Alchemy acknowledges the batch.+ message.retry();+ yield* Effect.logWarning("FCM queue delivery failed; retrying message", {+ messageId: message.id,+ errorTag: error._tag,+ });+ }),onSuccess: () => Effect.sync(() => message.ack()),}),);diff --git a/infra/relay/src/environments/CloudflareApiPause.ts b/infra/relay/src/environments/CloudflareApiPause.tsindex f3c1d05804a..d69e79e70e7 100644--- a/infra/relay/src/environments/CloudflareApiPause.ts+++ b/infra/relay/src/environments/CloudflareApiPause.ts@@ -56,8 +56,8 @@ export const make = Effect.gen(function* () {outsideTransaction,Effect.withSpan("relay.cloudflare_api_pause.read"),),- pauseUntil: (untilMillis) =>- db+ pauseUntil: Effect.fn("relay.cloudflare_api_pause.record")(function (untilMillis) {+ return db.insert(relayUpstreamApiPauses).values({ api: CLOUDFLARE_API, pausedUntilMs: untilMillis }).onConflictDoUpdate({@@ -72,8 +72,8 @@ export const make = Effect.gen(function* () {Effect.logWarning("Could not record the shared Cloudflare API pause", { cause }),),outsideTransaction,- Effect.withSpan("relay.cloudflare_api_pause.record"),- ),+ );+ }),});});diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.tsindex 709f8c90ff0..41e97ddc071 100644--- a/infra/relay/src/http/Api.ts+++ b/infra/relay/src/http/Api.ts@@ -186,22 +186,22 @@ const relayRequestDeadline = <E, R>(Effect.timeoutOption(Duration.millis(deadlineMs)),Effect.flatMap(Option.match({- onNone: () =>- Effect.gen(function* () {- const request = yield* HttpServerRequest.HttpServerRequest;- yield* Effect.logError("relay request exceeded deadline", {- "http.method": request.method,- "http.url": request.url,- "relay.request.deadline_ms": deadlineMs,- });- yield* Effect.annotateCurrentSpan({- "relay.request.deadline_exceeded": true,- });- return HttpServerResponse.jsonUnsafe(- { error: "relay_request_deadline_exceeded" },- { status: 504 },- );- }),+ // The enclosing operation owns the span for this inline handler.+ onNone: Effect.fnUntraced(function* () {+ const request = yield* HttpServerRequest.HttpServerRequest;+ yield* Effect.logError("relay request exceeded deadline", {+ "http.method": request.method,+ "http.url": request.url,+ "relay.request.deadline_ms": deadlineMs,+ });+ yield* Effect.annotateCurrentSpan({+ "relay.request.deadline_exceeded": true,+ });+ return HttpServerResponse.jsonUnsafe(+ { error: "relay_request_deadline_exceeded" },+ { status: 504 },+ );+ }),onSome: Effect.succeed,}),),diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.tsindex 2b9ea7d152e..ec91b2e27c9 100644--- a/infra/relay/src/worker.ts+++ b/infra/relay/src/worker.ts@@ -89,8 +89,12 @@ const layerHttpPlatformNotSupported = Layer.succeed(HttpPlatform.HttpPlatform, {algorithms: new Set<HttpPlatform.CompressionAlgorithm>(),compressResponse: (response) => Effect.succeed(response),},- fileResponse: () => Effect.die("Relay API does not serve filesystem responses"),- fileWebResponse: () => Effect.die("Relay API does not serve file responses"),+ fileResponse: Effect.fn("HttpPlatform.fileResponse")(function () {+ return Effect.die("Relay API does not serve filesystem responses");+ }),+ fileWebResponse: Effect.fn("HttpPlatform.fileWebResponse")(function () {+ return Effect.die("Relay API does not serve file responses");+ }),});const layerRelayApi = Layer.mergeAll(@@ -235,12 +239,21 @@ export const layer = Api.make(),);const layerHookInbox = Layer.succeed(HookInbox.HookInbox, {- hold: ({ endpointKey, baseUrl, hook }) =>- hookInboxes.getByName(endpointKey).hold(hook, baseUrl).pipe(inboxCall("hold", endpointKey)),- wake: ({ endpointKey, baseUrl }) =>- hookInboxes.getByName(endpointKey).wake(baseUrl).pipe(inboxCall("wake", endpointKey)),- clear: ({ endpointKey }) =>- hookInboxes.getByName(endpointKey).clear().pipe(inboxCall("clear", endpointKey)),+ hold: Effect.fn("HookInbox.hold")(function ({ endpointKey, baseUrl, hook }) {+ return hookInboxes+ .getByName(endpointKey)+ .hold(hook, baseUrl)+ .pipe(inboxCall("hold", endpointKey));+ }),+ wake: Effect.fn("HookInbox.wake")(function ({ endpointKey, baseUrl }) {+ return hookInboxes+ .getByName(endpointKey)+ .wake(baseUrl)+ .pipe(inboxCall("wake", endpointKey));+ }),+ clear: Effect.fn("HookInbox.clear")(function ({ endpointKey }) {+ return hookInboxes.getByName(endpointKey).clear().pipe(inboxCall("clear", endpointKey));+ }),});const layerRuntime = Layer.empty.pipe(@@ -268,10 +281,12 @@ export const layer = Api.make(FcmDeliveries.layer.pipe(Layer.provide(Layer.succeed(FcmDeliveryQueueSender.FcmDeliveryQueueSender, {- send: (body) =>- fcmDeliveryQueueSender- .send(body)- .pipe(Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext)),+ send: Effect.fn("FcmDeliveryQueueSender.send")(+ function* (body) {+ return yield* fcmDeliveryQueueSender.send(body);+ },+ Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),+ ),}),),Layer.provideMerge(diff --git a/infra/task-cache/src/Cache.ts b/infra/task-cache/src/Cache.tsindex 4677de8cd5b..77d18078b61 100644--- a/infra/task-cache/src/Cache.ts+++ b/infra/task-cache/src/Cache.ts@@ -227,12 +227,12 @@ const make = Effect.gen(function* () {);},Effect.catchTags({- CacheError: (error) =>- Effect.gen(function* () {- if (error.status >= 500)- yield* Effect.logWarning("Cache request failed", { reason: error.reason });- return errorResponse(new HttpError(error.status, error.reason));- }),+ // The enclosing operation owns the span for this inline handler.+ CacheError: Effect.fnUntraced(function* (error) {+ if (error.status >= 500)+ yield* Effect.logWarning("Cache request failed", { reason: error.reason });+ return errorResponse(new HttpError(error.status, error.reason));+ }),}),);diff --git a/infra/task-cache/src/NativeClients.ts b/infra/task-cache/src/NativeClients.tsindex 49215de5276..7159845ad39 100644--- a/infra/task-cache/src/NativeClients.ts+++ b/infra/task-cache/src/NativeClients.ts@@ -178,12 +178,12 @@ const make = Effect.gen(function* () {return new Response(null, { status: 204 });},Effect.catchTags({- NativeClientsError: (error) =>- Effect.gen(function* () {- if (error.status >= 500)- yield* Effect.logWarning("Native client request failed", { reason: error.reason });- return Response.json({ error: error.reason }, { status: error.status });- }),+ // The enclosing operation owns the span for this inline handler.+ NativeClientsError: Effect.fnUntraced(function* (error) {+ if (error.status >= 500)+ yield* Effect.logWarning("Native client request failed", { reason: error.reason });+ return Response.json({ error: error.reason }, { status: error.status });+ }),}),);diff --git a/packages/client-runtime/src/authorization/service.ts b/packages/client-runtime/src/authorization/service.tsindex 10a5354327a..d4c5ff93696 100644--- a/packages/client-runtime/src/authorization/service.ts+++ b/packages/client-runtime/src/authorization/service.ts@@ -235,8 +235,9 @@ export const make = Effect.gen(function* () {clientMetadata: presentation.metadata,connectionMethod: "relay",...(timeoutMs === undefined ? {} : { timeoutMs }),- }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient));+ });},+ Effect.provideService(HttpClient.HttpClient, httpClient),);const sessionChanged = () =>@@ -544,14 +545,17 @@ export const make = Effect.gen(function* () {return RemoteEnvironmentAuthorization.of({authorizeBearer,- authorizeDpop: (input) =>- authorizeDpop(input).pipe(Effect.withSpan("environment.authorization")),- authorizeDpopHttp: (input) =>- getDpopToken(input).pipe(+ authorizeDpop: Effect.fn("environment.authorization")(function (input) {+ return authorizeDpop(input);+ }),+ // The relay tracer must wrap span creation, not just the token request.+ authorizeDpopHttp: Effect.fnUntraced(function* (input) {+ return yield* getDpopToken(input).pipe(Effect.map(({ token }) => httpAuthorization(token)),Effect.withSpan("environment.authorization.http"),withRelayClientTracing,- ),+ );+ }),});});diff --git a/packages/client-runtime/src/connection/onboarding.ts b/packages/client-runtime/src/connection/onboarding.tsindex 7c0f193de58..66f14f2eca6 100644--- a/packages/client-runtime/src/connection/onboarding.ts+++ b/packages/client-runtime/src/connection/onboarding.ts@@ -294,23 +294,30 @@ export const make = Effect.gen(function* () {const ssh = yield* ClientCapabilities.SshEnvironmentGateway;const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;+ // Provisioning retains the delegated onboarding operation spans.return ConnectionOnboarding.of({- registerPairing: (input) =>- registerPairingConnection(input).pipe(- Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),- Effect.provideService(ClientCapabilities.ClientPresentation, presentation),- Effect.provideService(HttpClient.HttpClient, httpClient),- ),- registerSsh: (input) =>- registerSshConnection(input).pipe(- Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),- Effect.provideService(ClientCapabilities.SshEnvironmentGateway, ssh),- ),- updateBearer: (input) =>- updateBearerConnection(input).pipe(- Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),- Effect.provideService(ConnectionCredentialStore.ConnectionCredentialStore, credentials),- ),+ registerPairing: Effect.fnUntraced(+ function* (input) {+ return yield* registerPairingConnection(input);+ },+ Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),+ Effect.provideService(ClientCapabilities.ClientPresentation, presentation),+ Effect.provideService(HttpClient.HttpClient, httpClient),+ ),+ registerSsh: Effect.fnUntraced(+ function* (input) {+ return yield* registerSshConnection(input);+ },+ Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),+ Effect.provideService(ClientCapabilities.SshEnvironmentGateway, ssh),+ ),+ updateBearer: Effect.fnUntraced(+ function* (input) {+ return yield* updateBearerConnection(input);+ },+ Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),+ Effect.provideService(ConnectionCredentialStore.ConnectionCredentialStore, credentials),+ ),});});diff --git a/packages/client-runtime/src/connection/pullRequestRoutingPermissions.ts b/packages/client-runtime/src/connection/pullRequestRoutingPermissions.tsindex 23f7eb59844..c72c126d405 100644--- a/packages/client-runtime/src/connection/pullRequestRoutingPermissions.ts+++ b/packages/client-runtime/src/connection/pullRequestRoutingPermissions.ts@@ -135,12 +135,13 @@ export const makePullRequestRoutingPermissions = Effect.fn("makePullRequestRouti}),);return PullRequestRoutingPermissions.of({- get: (entry) =>- SubscriptionRef.get(state).pipe(+ get: Effect.fn("PullRequestRoutingPermissions.get")(function (entry) {+ return SubscriptionRef.get(state).pipe(Effect.map((permissions) => pullRequestRoutingPermissionFor(entry, permissions)),- ),+ );+ }),changes: SubscriptionRef.changes(state),- set: (entry, permission) => {+ set: Effect.fn("PullRequestRoutingPermissions.set")(function (entry, permission) {const connectionKey = pullRequestRoutingConnectionKey(entry);if (connectionKey === null)return Effect.fail(@@ -155,13 +156,14 @@ export const makePullRequestRoutingPermissions = Effect.fn("makePullRequestRouti? []: [{ environmentId: entry.target.environmentId, connectionKey, permission }]),]);- },- forget: (environmentId) =>- update((current) =>+ }),+ forget: Effect.fn("PullRequestRoutingPermissions.forget")(function (environmentId) {+ return update((current) =>current.some((permission) => permission.environmentId === environmentId)? current.filter((permission) => permission.environmentId !== environmentId): current,- ),+ );+ }),});},);diff --git a/packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts b/packages/client-runtime/src/state/boundedThreadSnapshotHttp.tsindex 1d6e4af118d..c7006fd0909 100644--- a/packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts+++ b/packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts@@ -69,7 +69,10 @@ export const layer: Layer.Layer<RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,);return ThreadSnapshotLoader.ThreadSnapshotLoader.of({- load: (prepared: PreparedConnection, threadId: ThreadId) => {+ load: Effect.fn("ThreadSnapshotLoader.load")(function (+ prepared: PreparedConnection,+ threadId: ThreadId,+ ) {const loadFullFallback = ThreadSnapshotLoader.fetchEnvironmentThreadSnapshot({prepared,threadId,@@ -159,7 +162,7 @@ export const layer: Layer.Layer<),),);- },+ }),});}),);diff --git a/packages/client-runtime/src/state/outdatedServerUpdate.ts b/packages/client-runtime/src/state/outdatedServerUpdate.tsindex 9505fcdd175..61e1ead1191 100644--- a/packages/client-runtime/src/state/outdatedServerUpdate.ts+++ b/packages/client-runtime/src/state/outdatedServerUpdate.ts@@ -54,7 +54,10 @@ export function createOutdatedServerUpdateCommand<E>(mode: "singleFlight",key: ({ environmentId }: OutdatedServerUpdateTarget) => environmentId,},- execute: (target: OutdatedServerUpdateTarget, atomRegistry) => {+ execute: Effect.fn("ServerUpdate.updateOutdatedServer")(function (+ target: OutdatedServerUpdateTarget,+ atomRegistry,+ ) {const stateAtom = serverUpdateStateAtom(target.environmentId);const targetVersion = target.input.targetVersion;const fromVersion = target.fromVersion ?? targetVersion;@@ -82,6 +85,6 @@ export function createOutdatedServerUpdateCommand<E>(}),),);- },+ }),});}diff --git a/packages/client-runtime/src/state/pullRequestDiffHttp.ts b/packages/client-runtime/src/state/pullRequestDiffHttp.tsindex 89c56a95c44..9da42b8066d 100644--- a/packages/client-runtime/src/state/pullRequestDiffHttp.ts+++ b/packages/client-runtime/src/state/pullRequestDiffHttp.ts@@ -86,14 +86,19 @@ export const layer: Layer.Layer<PullRequestDiffLoader, never, HttpClient.HttpCliconst remoteAuthorization = yield* Effect.serviceOption(RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,);+ // The HTTP fetch owns the load span.return PullRequestDiffLoader.of({- load: (prepared, input) =>- fetchEnvironmentPullRequestDiff({- prepared,- diff: input,- signer,- remoteAuthorization,- }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),+ load: Effect.fnUntraced(+ function* (prepared, input) {+ return yield* fetchEnvironmentPullRequestDiff({+ prepared,+ diff: input,+ signer,+ remoteAuthorization,+ });+ },+ Effect.provideService(HttpClient.HttpClient, httpClient),+ ),});}),);diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.tsindex 183bb208ffe..f1c8d3c19e8 100644--- a/packages/client-runtime/src/state/server.ts+++ b/packages/client-runtime/src/state/server.ts@@ -830,7 +830,7 @@ export function createServerEnvironmentAtoms<R, E>(label: "environment-data:server:update-server",scheduler: updateScheduler,concurrency: configConcurrency,- execute: (target, atomRegistry) => {+ execute: Effect.fn("ServerUpdate.updateServer")(function (target, atomRegistry) {const stateAtom = serverUpdateStateAtom(target.environmentId);let targetVersion = target.input.targetVersion;let fromVersion =@@ -1045,7 +1045,7 @@ export function createServerEnvironmentAtoms<R, E>(}),),);- },+ }),});const settingsValueAtom = Atom.family((environmentId: EnvironmentId) =>Atom.make((get) => get(configValueAtom(environmentId))?.settings ?? null).pipe(diff --git a/packages/client-runtime/src/state/shellSnapshotHttp.ts b/packages/client-runtime/src/state/shellSnapshotHttp.tsindex f30aa589581..9ff944ad6b2 100644--- a/packages/client-runtime/src/state/shellSnapshotHttp.ts+++ b/packages/client-runtime/src/state/shellSnapshotHttp.ts@@ -105,8 +105,8 @@ export const layer: Layer.Layer<ShellSnapshotLoader, never, HttpClient.HttpClienRemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,);return ShellSnapshotLoader.of({- load: (prepared, options) =>- fetchEnvironmentShellSnapshot({+ load: Effect.fn("ShellSnapshotLoader.load")(function (prepared, options) {+ return fetchEnvironmentShellSnapshot({prepared,signer,remoteAuthorization,@@ -123,7 +123,8 @@ export const layer: Layer.Layer<ShellSnapshotLoader, never, HttpClient.HttpClienEffect.as(Option.none<DeferredShellSnapshot>()),),),- ),+ );+ }),});}),);diff --git a/packages/client-runtime/src/state/threadHistoryController.ts b/packages/client-runtime/src/state/threadHistoryController.tsindex 2c33feeab5a..c9ae1843ff2 100644--- a/packages/client-runtime/src/state/threadHistoryController.ts+++ b/packages/client-runtime/src/state/threadHistoryController.ts@@ -49,20 +49,23 @@ export const layer: Layer.Layer<ThreadHistoryController> = Layer.effect(Effect.gen(function* () {const handlers = yield* Ref.make(new Map<string, ThreadHistoryHandler>());return ThreadHistoryController.of({- register: (environmentId, threadId, handler) =>- Ref.update(handlers, (current) => {- const next = new Map(current);- next.set(threadKey({ environmentId, threadId }), handler);- return next;- }).pipe(- Effect.as({- environmentId,- threadId,- handler,- } satisfies ThreadHistoryRegistration),- ),- unregister: (registration) =>- Ref.update(handlers, (current) => {+ register: Effect.fn("ThreadHistoryController.register")(+ function (environmentId, threadId, handler) {+ return Ref.update(handlers, (current) => {+ const next = new Map(current);+ next.set(threadKey({ environmentId, threadId }), handler);+ return next;+ }).pipe(+ Effect.as({+ environmentId,+ threadId,+ handler,+ } satisfies ThreadHistoryRegistration),+ );+ },+ ),+ unregister: Effect.fn("ThreadHistoryController.unregister")(function (registration) {+ return Ref.update(handlers, (current) => {const key = threadKey({environmentId: registration.environmentId,threadId: registration.threadId,@@ -75,25 +78,32 @@ export const layer: Layer.Layer<ThreadHistoryController> = Layer.effect(const next = new Map(current);next.delete(key);return next;- }),- loadEarlier: (environmentId, threadId, throughEntryId) =>- Ref.get(handlers).pipe(- Effect.flatMap((current) => {- const handler = current.get(threadKey({ environmentId, threadId }));- if (handler === undefined) {- return Effect.succeed({ _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult);- }- return handler.loadEarlier(throughEntryId);- }),- ),- reconcilePendingWork: (environmentId, threadId) =>- Ref.get(handlers).pipe(- Effect.flatMap(- (current) =>- current.get(threadKey({ environmentId, threadId }))?.reconcilePendingWork() ??- Effect.void,- ),- ),+ });+ }),+ loadEarlier: Effect.fn("ThreadHistoryController.loadEarlier")(+ function (environmentId, threadId, throughEntryId) {+ return Ref.get(handlers).pipe(+ Effect.flatMap((current) => {+ const handler = current.get(threadKey({ environmentId, threadId }));+ if (handler === undefined) {+ return Effect.succeed({ _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult);+ }+ return handler.loadEarlier(throughEntryId);+ }),+ );+ },+ ),+ reconcilePendingWork: Effect.fn("ThreadHistoryController.reconcilePendingWork")(+ function (environmentId, threadId) {+ return Ref.get(handlers).pipe(+ Effect.flatMap(+ (current) =>+ current.get(threadKey({ environmentId, threadId }))?.reconcilePendingWork() ??+ Effect.void,+ ),+ );+ },+ ),});}),);diff --git a/packages/client-runtime/src/state/vcsAction.ts b/packages/client-runtime/src/state/vcsAction.tsindex 3a9fc8f0192..5382e611644 100644--- a/packages/client-runtime/src/state/vcsAction.ts+++ b/packages/client-runtime/src/state/vcsAction.ts@@ -444,15 +444,16 @@ export function createVcsActionManager<R, E>(label: `vcs-action:run-stacked:${commandKey}`,scheduler: vcsCommandScheduler,concurrency: { mode: "serial", key: () => commandKey },- execute: (input: RunVcsStackedActionInput, registry) => {+ execute: Effect.fn("VcsAction.runStackedAction")(function* (+ input: RunVcsStackedActionInput,+ registry,+ ) {if (target === null) {- return Effect.fail(- new VcsActionUnavailableError({- operation: "run_change_request",- environmentId: requestedTarget.environmentId,- cwd: requestedTarget.cwd,- }),- );+ return yield* new VcsActionUnavailableError({+ operation: "run_change_request",+ environmentId: requestedTarget.environmentId,+ cwd: requestedTarget.cwd,+ });}const transportActionId = createVcsActionTransportId(target, input.actionId);registry.set(@@ -480,7 +481,7 @@ export function createVcsActionManager<R, E>(registry.set(stateAtom, EMPTY_VCS_ACTION_STATE);}});- return consumeVcsActionProgress(+ return yield* consumeVcsActionProgress(runStreamInEnvironment(target.environmentId,runStreamGuarded(WS_METHODS.gitRunStackedAction, rpcInput),@@ -524,7 +525,7 @@ export function createVcsActionManager<R, E>(),Effect.onInterrupt(() => clearOwnedState),);- },+ }),});runStackedActionCommands.set(commandKey, command);return command;diff --git a/packages/effect-acp/src/agent.ts b/packages/effect-acp/src/agent.tsindex 13518ec56bb..578509f9c85 100644--- a/packages/effect-acp/src/agent.ts+++ b/packages/effect-acp/src/agent.ts@@ -419,109 +419,135 @@ export const make = Effect.fn("effect-acp/AcpAgent.make")(function* (extRequest: transport.request,extNotification: transport.notify,},- handleInitialize: (handler) =>- Effect.suspend(() => {+ handleInitialize: Effect.fn("AcpAgent.handleInitialize")(function (handler) {+ return Effect.suspend(() => {coreHandlers.initialize = handler;return Effect.void;- }),- handleAuthenticate: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleAuthenticate: Effect.fn("AcpAgent.handleAuthenticate")(function (handler) {+ return Effect.suspend(() => {coreHandlers.authenticate = handler;return Effect.void;- }),- handleLogout: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleLogout: Effect.fn("AcpAgent.handleLogout")(function (handler) {+ return Effect.suspend(() => {coreHandlers.logout = handler;return Effect.void;- }),- handleCreateSession: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleCreateSession: Effect.fn("AcpAgent.handleCreateSession")(function (handler) {+ return Effect.suspend(() => {coreHandlers.createSession = handler;return Effect.void;- }),- handleLoadSession: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleLoadSession: Effect.fn("AcpAgent.handleLoadSession")(function (handler) {+ return Effect.suspend(() => {coreHandlers.loadSession = handler;return Effect.void;- }),- handleListSessions: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleListSessions: Effect.fn("AcpAgent.handleListSessions")(function (handler) {+ return Effect.suspend(() => {coreHandlers.listSessions = handler;return Effect.void;- }),- handleForkSession: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleForkSession: Effect.fn("AcpAgent.handleForkSession")(function (handler) {+ return Effect.suspend(() => {coreHandlers.forkSession = handler;return Effect.void;- }),- handleResumeSession: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleResumeSession: Effect.fn("AcpAgent.handleResumeSession")(function (handler) {+ return Effect.suspend(() => {coreHandlers.resumeSession = handler;return Effect.void;- }),- handleCloseSession: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleCloseSession: Effect.fn("AcpAgent.handleCloseSession")(function (handler) {+ return Effect.suspend(() => {coreHandlers.closeSession = handler;return Effect.void;- }),- handleDeleteSession: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleDeleteSession: Effect.fn("AcpAgent.handleDeleteSession")(function (handler) {+ return Effect.suspend(() => {coreHandlers.deleteSession = handler;return Effect.void;- }),- handleListProviders: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleListProviders: Effect.fn("AcpAgent.handleListProviders")(function (handler) {+ return Effect.suspend(() => {coreHandlers.listProviders = handler;return Effect.void;- }),- handleSetProvider: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleSetProvider: Effect.fn("AcpAgent.handleSetProvider")(function (handler) {+ return Effect.suspend(() => {coreHandlers.setProvider = handler;return Effect.void;- }),- handleDisableProvider: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleDisableProvider: Effect.fn("AcpAgent.handleDisableProvider")(function (handler) {+ return Effect.suspend(() => {coreHandlers.disableProvider = handler;return Effect.void;- }),- handleSetSessionConfigOption: (handler) =>- Effect.suspend(() => {- coreHandlers.setSessionConfigOption = handler;- return Effect.void;- }),- handlePrompt: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleSetSessionConfigOption: Effect.fn("AcpAgent.handleSetSessionConfigOption")(+ function (handler) {+ return Effect.suspend(() => {+ coreHandlers.setSessionConfigOption = handler;+ return Effect.void;+ });+ },+ ),+ handlePrompt: Effect.fn("AcpAgent.handlePrompt")(function (handler) {+ return Effect.suspend(() => {coreHandlers.prompt = handler;return Effect.void;- }),- handleCancel: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleCancel: Effect.fn("AcpAgent.handleCancel")(function (handler) {+ return Effect.suspend(() => {cancelHandlers.push(handler);return Effect.void;- }),- handleUnknownExtRequest: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleUnknownExtRequest: Effect.fn("AcpAgent.handleUnknownExtRequest")(function (handler) {+ return Effect.suspend(() => {unknownExtRequestHandler = handler;return Effect.void;- }),- handleUnknownExtNotification: (handler) =>- Effect.suspend(() => {- unknownExtNotificationHandler = handler;- return Effect.void;- }),- handleExtRequest: (method, payload, handler) =>- Effect.suspend(() => {+ });+ }),+ handleUnknownExtNotification: Effect.fn("AcpAgent.handleUnknownExtNotification")(+ function (handler) {+ return Effect.suspend(() => {+ unknownExtNotificationHandler = handler;+ return Effect.void;+ });+ },+ ),+ handleExtRequest: Effect.fn("AcpAgent.handleExtRequest")(function (method, payload, handler) {+ return Effect.suspend(() => {extRequestHandlers.set(method, decodeExtRequestRegistration(method, payload, handler));return Effect.void;- }),- handleExtNotification: (method, payload, handler) =>- Effect.suspend(() => {- extNotificationHandlers.set(- method,- decodeExtNotificationRegistration(method, payload, handler),- );- return Effect.void;- }),+ });+ }),+ handleExtNotification: Effect.fn("AcpAgent.handleExtNotification")(+ function (method, payload, handler) {+ return Effect.suspend(() => {+ extNotificationHandlers.set(+ method,+ decodeExtNotificationRegistration(method, payload, handler),+ );+ return Effect.void;+ });+ },+ ),});});diff --git a/packages/effect-acp/src/client.ts b/packages/effect-acp/src/client.tsindex ca98a73d939..687f9d1da72 100644--- a/packages/effect-acp/src/client.ts+++ b/packages/effect-acp/src/client.ts@@ -1243,98 +1243,121 @@ export const make = Effect.fn("effect-acp/AcpClient.make")(function* (}),cancel: (payload) => transport.notify(AGENT_METHODS.session_cancel, payload),},- handleRequestPermission: (handler) =>- Effect.suspend(() => {+ handleRequestPermission: Effect.fn("AcpClient.handleRequestPermission")(function (handler) {+ return Effect.suspend(() => {coreHandlers.requestPermission = handler;return Effect.void;- }),- handleElicitation: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleElicitation: Effect.fn("AcpClient.handleElicitation")(function (handler) {+ return Effect.suspend(() => {coreHandlers.elicitation = handler;return Effect.void;- }),- handleMcpConnect: (handler) =>- Effect.sync(() => {+ });+ }),+ handleMcpConnect: Effect.fn("AcpClient.handleMcpConnect")(function (handler) {+ return Effect.sync(() => {coreHandlers.mcpConnect = handler;- }),- handleMcpMessage: (handler) =>- Effect.sync(() => {+ });+ }),+ handleMcpMessage: Effect.fn("AcpClient.handleMcpMessage")(function (handler) {+ return Effect.sync(() => {coreHandlers.mcpMessage = handler;- }),- handleMcpDisconnect: (handler) =>- Effect.sync(() => {+ });+ }),+ handleMcpDisconnect: Effect.fn("AcpClient.handleMcpDisconnect")(function (handler) {+ return Effect.sync(() => {coreHandlers.mcpDisconnect = handler;- }),- handleMcpNotification: (handler) =>- Effect.sync(() => {+ });+ }),+ handleMcpNotification: Effect.fn("AcpClient.handleMcpNotification")(function (handler) {+ return Effect.sync(() => {extNotificationHandlers.set(CLIENT_METHODS.mcp_message, (params) =>decodeMessageMcpNotification(params).pipe(Effect.mapError(() => AcpError.AcpRequestError.invalidParams()),Effect.flatMap(handler),),);- }),- handleReadTextFile: (handler) =>- Effect.sync(() => {+ });+ }),+ handleReadTextFile: Effect.fn("AcpClient.handleReadTextFile")(function (handler) {+ return Effect.sync(() => {coreHandlers.readTextFile = handler;- }),- handleWriteTextFile: (handler) =>- Effect.sync(() => {+ });+ }),+ handleWriteTextFile: Effect.fn("AcpClient.handleWriteTextFile")(function (handler) {+ return Effect.sync(() => {coreHandlers.writeTextFile = handler;- }),- handleCreateTerminal: (handler) =>- Effect.sync(() => {+ });+ }),+ handleCreateTerminal: Effect.fn("AcpClient.handleCreateTerminal")(function (handler) {+ return Effect.sync(() => {coreHandlers.createTerminal = handler;- }),- handleTerminalOutput: (handler) =>- Effect.sync(() => {+ });+ }),+ handleTerminalOutput: Effect.fn("AcpClient.handleTerminalOutput")(function (handler) {+ return Effect.sync(() => {coreHandlers.terminalOutput = handler;- }),- handleTerminalWaitForExit: (handler) =>- Effect.sync(() => {+ });+ }),+ handleTerminalWaitForExit: Effect.fn("AcpClient.handleTerminalWaitForExit")(function (handler) {+ return Effect.sync(() => {coreHandlers.terminalWaitForExit = handler;- }),- handleTerminalKill: (handler) =>- Effect.sync(() => {+ });+ }),+ handleTerminalKill: Effect.fn("AcpClient.handleTerminalKill")(function (handler) {+ return Effect.sync(() => {coreHandlers.terminalKill = handler;- }),- handleTerminalRelease: (handler) =>- Effect.sync(() => {+ });+ }),+ handleTerminalRelease: Effect.fn("AcpClient.handleTerminalRelease")(function (handler) {+ return Effect.sync(() => {coreHandlers.terminalRelease = handler;- }),- handleSessionUpdate: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleSessionUpdate: Effect.fn("AcpClient.handleSessionUpdate")(function (handler) {+ return Effect.suspend(() => {notificationHandlers.sessionUpdate.handlers.push(handler);return flushBufferedNotifications(notificationHandlers.sessionUpdate);- }),- handleElicitationComplete: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleElicitationComplete: Effect.fn("AcpClient.handleElicitationComplete")(function (handler) {+ return Effect.suspend(() => {notificationHandlers.elicitationComplete.handlers.push(handler);return flushBufferedNotifications(notificationHandlers.elicitationComplete);- }),- handleUnknownExtRequest: (handler) =>- Effect.suspend(() => {+ });+ }),+ handleUnknownExtRequest: Effect.fn("AcpClient.handleUnknownExtRequest")(function (handler) {+ return Effect.suspend(() => {unknownExtRequestHandler = handler;return Effect.void;- }),- handleUnknownExtNotification: (handler) =>- Effect.suspend(() => {- unknownExtNotificationHandler = handler;- return Effect.void;- }),- handleExtRequest: (method, payload, handler) =>- Effect.suspend(() => {+ });+ }),+ handleUnknownExtNotification: Effect.fn("AcpClient.handleUnknownExtNotification")(+ function (handler) {+ return Effect.suspend(() => {+ unknownExtNotificationHandler = handler;+ return Effect.void;+ });+ },+ ),+ handleExtRequest: Effect.fn("AcpClient.handleExtRequest")(function (method, payload, handler) {+ return Effect.suspend(() => {extRequestHandlers.set(method, decodeExtRequestRegistration(method, payload, handler));return Effect.void;- }),- handleExtNotification: (method, payload, handler) =>- Effect.suspend(() => {- extNotificationHandlers.set(- method,- decodeExtNotificationRegistration(method, payload, handler),- );- return Effect.void;- }),+ });+ }),+ handleExtNotification: Effect.fn("AcpClient.handleExtNotification")(+ function (method, payload, handler) {+ return Effect.suspend(() => {+ extNotificationHandlers.set(+ method,+ decodeExtNotificationRegistration(method, payload, handler),+ );+ return Effect.void;+ });+ },+ ),});});diff --git a/packages/effect-acp/src/protocol.ts b/packages/effect-acp/src/protocol.tsindex 72b4e156436..5c33acb6c02 100644--- a/packages/effect-acp/src/protocol.ts+++ b/packages/effect-acp/src/protocol.ts@@ -868,14 +868,16 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functiEffect.forkScoped,);+ // Protocol loops and per-message sends share the caller's operation span.const clientProtocol = RpcClient.Protocol.of({- run: (_clientId, f) =>- Stream.fromQueue(clientQueue).pipe(+ run: Effect.fnUntraced(function* (_clientId, f) {+ return yield* Stream.fromQueue(clientQueue).pipe(Stream.runForEach((message) => f(message)),Effect.forever,- ),- send: (_clientId, request) =>- offerOutgoing(request).pipe(+ );+ }),+ send: Effect.fnUntraced(function* (_clientId, request) {+ return yield* offerOutgoing(request).pipe(Effect.mapError((error) =>new RpcClientError.RpcClientError({@@ -885,32 +887,36 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi}),}),),- ),+ );+ }),supportsAck: true,supportsTransferables: false,codecFor: parserFactory.codecFor,});const serverProtocol = RpcServer.Protocol.of({- run: (f) =>- Stream.fromQueue(serverQueue).pipe(+ run: Effect.fnUntraced(function* (f) {+ return yield* Stream.fromQueue(serverQueue).pipe(Stream.runForEach((message) => f(0, message)),Effect.forever,- ),+ );+ }),disconnects,- send: (_clientId, response) =>- offerOutgoing(response).pipe(+ send: Effect.fnUntraced(function* (_clientId, response) {+ return yield* offerOutgoing(response).pipe(Effect.tapError((error) =>response._tag === "Exit" && options.onOutgoingResponseFailure !== undefined? options.onOutgoingResponseFailure(acpRequestIdentity(response.requestId), error): Effect.void,),Effect.orDie,- ),- end: (_clientId) =>- Ref.update(outgoingWriterState, (state) => ({ ...state, intentionalEnd: true })).pipe(+ );+ }),+ end: Effect.fn("RpcServer.Protocol.end")(function (_clientId) {+ return Ref.update(outgoingWriterState, (state) => ({ ...state, intentionalEnd: true })).pipe(Effect.andThen(Queue.end(outgoing)),- ),+ );+ }),clientIds: Effect.succeed(new Set([0])),initialMessage: Effect.succeedNone,supportsAck: true,diff --git a/packages/effect-codex-app-server/src/client.ts b/packages/effect-codex-app-server/src/client.tsindex e7c5f50b570..d872b9fa847 100644--- a/packages/effect-codex-app-server/src/client.ts+++ b/packages/effect-codex-app-server/src/client.ts@@ -240,24 +240,36 @@ export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make},request,notify,- handleServerRequest: (method, handler) =>- Effect.sync(() => {- requestHandlers.set(method, handler as ServerRequestHandler);- }),- handleServerNotification: (method, handler) =>- Effect.sync(() => {- const current = notificationHandlers.get(method) ?? [];- current.push(handler as ServerNotificationHandler);- notificationHandlers.set(method, current);- }),- handleUnknownServerRequest: (handler) =>- Effect.sync(() => {- unknownRequestHandler = handler;- }),- handleUnknownServerNotification: (handler) =>- Effect.sync(() => {+ handleServerRequest: Effect.fn("CodexAppServerClient.handleServerRequest")(+ function (method, handler) {+ return Effect.sync(() => {+ requestHandlers.set(method, handler as ServerRequestHandler);+ });+ },+ ),+ handleServerNotification: Effect.fn("CodexAppServerClient.handleServerNotification")(+ function (method, handler) {+ return Effect.sync(() => {+ const current = notificationHandlers.get(method) ?? [];+ current.push(handler as ServerNotificationHandler);+ notificationHandlers.set(method, current);+ });+ },+ ),+ handleUnknownServerRequest: Effect.fn("CodexAppServerClient.handleUnknownServerRequest")(+ function (handler) {+ return Effect.sync(() => {+ unknownRequestHandler = handler;+ });+ },+ ),+ handleUnknownServerNotification: Effect.fn(+ "CodexAppServerClient.handleUnknownServerNotification",+ )(function (handler) {+ return Effect.sync(() => {unknownNotificationHandler = handler;- }),+ });+ }),});});diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.tsindex 0446d2904f5..d44102c2d7f 100644--- a/packages/provider-acp-registry/src/server/driver.ts+++ b/packages/provider-acp-registry/src/server/driver.ts@@ -629,7 +629,11 @@ export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryDhaveSettingsChanged: haveProviderSnapshotSettingsChanged,initialSnapshot: () => checkProvider,checkProvider,- enrichSnapshot: ({ snapshot, getSnapshot, publishSnapshot }) => {+ enrichSnapshot: Effect.fn("enrichSnapshot")(function ({+ snapshot,+ getSnapshot,+ publishSnapshot,+ }) {if (!snapshot.installed) return Effect.void;const publishEnrichment = (Option.isSome(runtimeCoordinator)@@ -711,7 +715,7 @@ export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryDdiscard: true,},);- },+ }),}).pipe(Effect.mapError((cause) =>diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.tsindex eb8bd96c081..b3ce13af0a7 100644--- a/packages/provider-acp/src/server/adapter.ts+++ b/packages/provider-acp/src/server/adapter.ts@@ -1359,8 +1359,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (return ProviderAdapter.ProviderAdapterV2.of({instanceId: options.instanceId,driver,- getCapabilities: () => Effect.succeed(flavor.capabilities),- planSelectionTransition: (input) => Effect.succeed(acpSelectionTransition(input)),+ getCapabilities: Effect.fn("AcpAdapter.getCapabilities")(function () {+ return Effect.succeed(flavor.capabilities);+ }),+ planSelectionTransition: Effect.fn("AcpAdapter.planSelectionTransition")(function (input) {+ return Effect.succeed(acpSelectionTransition(input));+ }),openSession: Effect.fn("AcpAdapterV2.openSession")(function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) {const sessionScope = yield* Effect.scope;@@ -7058,31 +7062,30 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (yield* Deferred.succeed(context.completed, undefined).pipe(Effect.ignore);});- scheduleDeferredFinalize = (context) =>- Effect.gen(function* () {- if (!flavor.deferFinalizeForBackgroundWork) return;- if (!context.promptSettled || context.finalized || context.interrupted) return;+ scheduleDeferredFinalize = Effect.fn("scheduleDeferredFinalize")(function* (context) {+ if (!flavor.deferFinalizeForBackgroundWork) return;+ if (!context.promptSettled || context.finalized || context.interrupted) return;+ if (hasDeferredBackgroundWork(context)) return;+ context.backgroundFinalizeGeneration += 1;+ const generation = context.backgroundFinalizeGeneration;+ yield* Effect.gen(function* () {+ yield* Effect.sleep(ACP_DEFERRED_FINALIZE_DEBOUNCE);+ if (+ context.finalized ||+ context.interrupted ||+ context.backgroundFinalizeGeneration !== generation+ ) {+ return;+ }if (hasDeferredBackgroundWork(context)) return;- context.backgroundFinalizeGeneration += 1;- const generation = context.backgroundFinalizeGeneration;- yield* Effect.gen(function* () {- yield* Effect.sleep(ACP_DEFERRED_FINALIZE_DEBOUNCE);- if (- context.finalized ||- context.interrupted ||- context.backgroundFinalizeGeneration !== generation- ) {- return;- }- if (hasDeferredBackgroundWork(context)) return;- const status = context.promptSettledStatus ?? "completed";- yield* finalizeTurn(context, status);- }).pipe(Effect.forkIn(sessionScope), Effect.asVoid);- yield* (- options.testHooks?.onDeferredFinalizeScheduled?.(ACP_DEFERRED_FINALIZE_DEBOUNCE) ??- Effect.void- );- });+ const status = context.promptSettledStatus ?? "completed";+ yield* finalizeTurn(context, status);+ }).pipe(Effect.forkIn(sessionScope), Effect.asVoid);+ yield* (+ options.testHooks?.onDeferredFinalizeScheduled?.(ACP_DEFERRED_FINALIZE_DEBOUNCE) ??+ Effect.void+ );+ });const resolvePromptParts = Effect.fnUntraced(function* (turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,diff --git a/packages/provider-core/src/server/McpProviderSessions.ts b/packages/provider-core/src/server/McpProviderSessions.tsindex 2da992cfb85..2575cce264c 100644--- a/packages/provider-core/src/server/McpProviderSessions.ts+++ b/packages/provider-core/src/server/McpProviderSessions.ts@@ -92,9 +92,11 @@ const make = Effect.gen(function* () {}yield* Ref.update(sessions, (current) => new Map(current).set(config.threadId, config));}),- read: (threadId) => Ref.get(sessions).pipe(Effect.map((current) => current.get(threadId))),- clear: (threadId) =>- Ref.update(sessions, (current) => {+ read: Effect.fn("McpProviderSessions.read")(function (threadId) {+ return Ref.get(sessions).pipe(Effect.map((current) => current.get(threadId)));+ }),+ clear: Effect.fn("McpProviderSessions.clear")(function (threadId) {+ return Ref.update(sessions, (current) => {const next = new Map(current);next.delete(threadId);return next;@@ -106,46 +108,53 @@ const make = Effect.gen(function* () {return next;}),),- ),- recordHtmlRender: (threadId, input, reference) =>- Ref.update(htmlRenders, (current) =>- new Map(current).set(- threadId,- [- ...(current.get(threadId) ?? []),- {- title: input.title,- height: input.height,- htmlLength: input.html.length,- htmlHash: hashHtml(input.html),- // Copy the tail so its backing storage cannot retain the entire HTML string.- htmlEnd: Buffer.from(input.html.slice(-KEPT_HTML_END_LENGTH), "utf16le").toString(- "utf16le",- ),- reference,- },- ].slice(-MAX_KEPT_HTML_RENDERS),- ),- ),- takeHtmlRender: (threadId, input, reported) =>- Ref.modify(htmlRenders, (current) => {- const kept = current.get(threadId) ?? [];- const index =- reported === undefined- ? matchingPageIndex(kept, input)- : kept.findIndex((page) => page.reference.attachmentId === reported.attachmentId);- if (index === -1) {- return [undefined, current];- }- const rest = kept.filter((_, keptIndex) => keptIndex !== index);- const next = new Map(current);- if (rest.length === 0) {- next.delete(threadId);- } else {- next.set(threadId, rest);- }- return [kept[index]!.reference, next];- }),+ );+ }),+ recordHtmlRender: Effect.fn("McpProviderSessions.recordHtmlRender")(+ function (threadId, input, reference) {+ return Ref.update(htmlRenders, (current) =>+ new Map(current).set(+ threadId,+ [+ ...(current.get(threadId) ?? []),+ {+ title: input.title,+ height: input.height,+ htmlLength: input.html.length,+ htmlHash: hashHtml(input.html),+ // Copy the tail so its backing storage cannot retain the entire HTML string.+ htmlEnd: Buffer.from(input.html.slice(-KEPT_HTML_END_LENGTH), "utf16le").toString(+ "utf16le",+ ),+ reference,+ },+ ].slice(-MAX_KEPT_HTML_RENDERS),+ ),+ );+ },+ ),+ takeHtmlRender: Effect.fn("McpProviderSessions.takeHtmlRender")(+ function (threadId, input, reported) {+ return Ref.modify(htmlRenders, (current) => {+ const kept = current.get(threadId) ?? [];+ const index =+ reported === undefined+ ? matchingPageIndex(kept, input)+ : kept.findIndex((page) => page.reference.attachmentId === reported.attachmentId);+ if (index === -1) {+ return [undefined, current];+ }+ const rest = kept.filter((_, keptIndex) => keptIndex !== index);+ const next = new Map(current);+ if (rest.length === 0) {+ next.delete(threadId);+ } else {+ next.set(threadId, rest);+ }+ return [kept[index]!.reference, next];+ });+ },+ ),});});diff --git a/packages/provider-core/src/server/ProviderContinuationRequests.ts b/packages/provider-core/src/server/ProviderContinuationRequests.tsindex 2117cd4d275..936769c46c3 100644--- a/packages/provider-core/src/server/ProviderContinuationRequests.ts+++ b/packages/provider-core/src/server/ProviderContinuationRequests.ts@@ -45,8 +45,11 @@ export const layer = Layer.effect(Effect.gen(function* () {const queue = yield* Queue.unbounded<ProviderContinuationRequest>();return {- offer: (request: ProviderContinuationRequest) =>- Queue.offer(queue, request).pipe(Effect.asVoid),+ offer: Effect.fn("ProviderContinuationRequests.offer")(function (+ request: ProviderContinuationRequest,+ ) {+ return Queue.offer(queue, request).pipe(Effect.asVoid);+ }),take: Queue.take(queue),};}),diff --git a/packages/provider-core/src/server/ProviderLatestVersions.ts b/packages/provider-core/src/server/ProviderLatestVersions.tsindex a6197233e36..7533b519ae0 100644--- a/packages/provider-core/src/server/ProviderLatestVersions.ts+++ b/packages/provider-core/src/server/ProviderLatestVersions.ts@@ -50,12 +50,13 @@ export const make = Effect.fn("ProviderLatestVersions.make")(function* ();return version;}),- invalidate: (key) =>- Ref.update(entries, (current) => {+ invalidate: Effect.fn("ProviderLatestVersions.invalidate")(function (key) {+ return Ref.update(entries, (current) => {const next = new Map(current);next.delete(key);return next;- }),+ });+ }),});});diff --git a/packages/provider-cursor/src/server/CursorAccountReader.ts b/packages/provider-cursor/src/server/CursorAccountReader.tsindex 79f391166f2..f7601e7873d 100644--- a/packages/provider-cursor/src/server/CursorAccountReader.ts+++ b/packages/provider-cursor/src/server/CursorAccountReader.ts@@ -28,10 +28,14 @@ export const layer = Layer.effect(FileSystem.FileSystem | Crypto.Crypto | HttpClient.HttpClient>();return CursorAccountReader.of({- read: (credentialSource, sinceMs, untilMs) =>- readCursorAccountUsage(credentialSource, sinceMs, untilMs, keychain.accessToken).pipe(- Effect.provideContext(context),- ),+ read: Effect.fn("CursorAccountReader.read")(function (credentialSource, sinceMs, untilMs) {+ return readCursorAccountUsage(+ credentialSource,+ sinceMs,+ untilMs,+ keychain.accessToken,+ ).pipe(Effect.provideContext(context));+ }),});}),);diff --git a/packages/provider-cursor/src/server/CursorSdkCatalog.ts b/packages/provider-cursor/src/server/CursorSdkCatalog.tsindex fae053fe535..39fc003fbbd 100644--- a/packages/provider-cursor/src/server/CursorSdkCatalog.ts+++ b/packages/provider-cursor/src/server/CursorSdkCatalog.ts@@ -79,14 +79,15 @@ export const makeCursorSdkCatalog = Effect.fn("CursorSdkCatalog.make")(function*Exit.isSuccess(exit) && exit.value.length > 0 ? Duration.minutes(30) : Duration.zero,});return CursorSdkCatalog.of({- read: (apiKey) =>- Effect.all(+ read: Effect.fn("CursorSdkCatalog.read")(function (apiKey) {+ return Effect.all({user: probes.readUser(apiKey),models: Cache.get(modelCache, apiKey),},{ concurrency: "unbounded" },- ),+ );+ }),});});diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.tsindex ce966bb1233..186334fe5c9 100644--- a/packages/provider-cursor/src/server/adapter.ts+++ b/packages/provider-cursor/src/server/adapter.ts@@ -894,8 +894,12 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (return ProviderAdapter.ProviderAdapterV2.of({instanceId: adapterOptions.instanceId,driver: CursorAgentSdk.CURSOR_PROVIDER,- getCapabilities: () => Effect.succeed(CursorProviderCapabilitiesV2),- planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),+ getCapabilities: Effect.fn("CursorAdapter.getCapabilities")(function () {+ return Effect.succeed(CursorProviderCapabilitiesV2);+ }),+ planSelectionTransition: Effect.fn("CursorAdapter.planSelectionTransition")(function () {+ return Effect.succeed(turnScopedSelectionTransition());+ }),openSession: Effect.fn("CursorAdapterV2.openSession")(function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) {const sessionScope = yield* Effect.scope;diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.tsindex b568bbd2d8f..40785df6bad 100644--- a/packages/provider-muse/src/server/adapter.ts+++ b/packages/provider-muse/src/server/adapter.ts@@ -276,8 +276,12 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (return ProviderAdapter.ProviderAdapterV2.of({instanceId: options.instanceId,driver: MUSE_PROVIDER,- getCapabilities: () => Effect.succeed(MuseProviderCapabilitiesV2),- planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),+ getCapabilities: Effect.fn("MuseAdapter.getCapabilities")(function () {+ return Effect.succeed(MuseProviderCapabilitiesV2);+ }),+ planSelectionTransition: Effect.fn("MuseAdapter.planSelectionTransition")(function () {+ return Effect.succeed(turnScopedSelectionTransition());+ }),openSession: Effect.fn("MuseAdapterV2.openSession")(function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput,) {@@ -378,11 +382,11 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (}).pipe(Effect.timeout(options.requestTimeoutMs ?? 30_000),Effect.catchTags({- TimeoutError: (cause) =>- Effect.gen(function* () {- yield* eventPermit.withPermits(1)(failHost(cause));- return yield* protocolError(`Muse ${method} timed out; its host was closed`, cause);- }),+ // The enclosing operation owns the span for this inline handler.+ TimeoutError: Effect.fnUntraced(function* (cause) {+ yield* eventPermit.withPermits(1)(failHost(cause));+ return yield* protocolError(`Muse ${method} timed out; its host was closed`, cause);+ }),}),);const updateSession = Effect.fnUntraced(function* (diff --git a/packages/provider-opencode/src/server/OpenCodeServerLedger.ts b/packages/provider-opencode/src/server/OpenCodeServerLedger.tsindex 3e7a7cc9f8a..45a043dde3f 100644--- a/packages/provider-opencode/src/server/OpenCodeServerLedger.ts+++ b/packages/provider-opencode/src/server/OpenCodeServerLedger.ts@@ -307,5 +307,9 @@ export const layer = (input: { readonly stateDir: string }) =>export const layerTest = Layer.succeed(OpenCodeServerLedger,- OpenCodeServerLedger.of({ track: () => Effect.succeed(Effect.void) }),+ OpenCodeServerLedger.of({+ track: Effect.fn("OpenCodeServerLedger.track")(function () {+ return Effect.succeed(Effect.void);+ }),+ }),);diff --git a/packages/provider-opencode/src/server/OpenCodeServerOwner.ts b/packages/provider-opencode/src/server/OpenCodeServerOwner.tsindex dc26f7e1466..839669a4958 100644--- a/packages/provider-opencode/src/server/OpenCodeServerOwner.ts+++ b/packages/provider-opencode/src/server/OpenCodeServerOwner.ts@@ -166,14 +166,15 @@ export const make = Effect.fn("OpenCodeServerOwner.make")(function* (input: {);return OpenCodeServerOwner.of({- withServer: (use) =>- Effect.uninterruptibleMask((restore) =>+ withServer: Effect.fn("OpenCodeServerOwner.withServer")(function (use) {+ return Effect.uninterruptibleMask((restore) =>restore(acquireServer).pipe(Effect.flatMap((server) =>restore(use(server)).pipe(Effect.ensuring(releaseServer(server))),),),- ),+ );+ }),});});diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.tsindex c9f95ba6298..efe90e2e771 100644--- a/packages/provider-opencode/src/server/adapter.ts+++ b/packages/provider-opencode/src/server/adapter.ts@@ -914,8 +914,12 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(functionreturn ProviderAdapter.ProviderAdapterV2.of({instanceId: options.instanceId,driver: OPENCODE_PROVIDER,- getCapabilities: () => Effect.succeed(OpenCodeProviderCapabilitiesV2),- planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),+ getCapabilities: Effect.fn("OpencodeAdapter.getCapabilities")(function () {+ return Effect.succeed(OpenCodeProviderCapabilitiesV2);+ }),+ planSelectionTransition: Effect.fn("OpencodeAdapter.planSelectionTransition")(function () {+ return Effect.succeed(turnScopedSelectionTransition());+ }),openSession: Effect.fn("OpenCodeAdapterV2.openSession")(function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) {const scope = yield* Effect.scope;diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.tsindex 127dc6a7b91..79f6d5f9173 100644--- a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts+++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.ts@@ -146,7 +146,7 @@ const basicAuthorization = (password: string | Redacted.Redacted) => {export const make = Effect.gen(function* () {const httpClient = yield* HttpClient.HttpClient;return OpenCode2Client.of({- connect: ({ baseUrl, password }) => {+ connect: Effect.fn("OpenCode2Client.connect")(function ({ baseUrl, password }) {const authenticated = HttpClient.mapRequest(httpClient,HttpClientRequest.setHeader("Authorization", basicAuthorization(password)),@@ -163,7 +163,7 @@ export const make = Effect.gen(function* () {),})),);- },+ }),});});diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Server.ts b/packages/provider-opencode/src/server/v2/OpenCode2Server.tsindex 2ea8bfff5d8..c8c5dd7b70b 100644--- a/packages/provider-opencode/src/server/v2/OpenCode2Server.ts+++ b/packages/provider-opencode/src/server/v2/OpenCode2Server.ts@@ -139,10 +139,11 @@ export const make = Effect.fn("OpenCode2Server.make")(function* (input: {Effect.tap(remember),);return OpenCode2Server.of({- withConnection: (use) =>- Effect.suspend(() => (latest === undefined ? connect : Effect.succeed(latest))).pipe(+ withConnection: Effect.fn("OpenCode2Server.withConnection")(function (use) {+ return Effect.suspend(() => (latest === undefined ? connect : Effect.succeed(latest))).pipe(Effect.flatMap(use),- ),+ );+ }),});}@@ -154,11 +155,12 @@ export const make = Effect.fn("OpenCode2Server.make")(function* (input: {verify: (url) => connectTo(url, password, false).pipe(Effect.flatMap(remember)),});return OpenCode2Server.of({- withConnection: (use) =>- owner.withServer((server) =>+ withConnection: Effect.fn("OpenCode2Server.withConnection")(function (use) {+ return owner.withServer((server) =>latest?.url === server.url? use(latest): Effect.die(new Error("OpenCode 2 server was lent before verification.")),- ),+ );+ }),});});diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.tsindex 229dc38e66b..9c4ec57c347 100644--- a/packages/provider-opencode/src/server/v2/adapter.ts+++ b/packages/provider-opencode/src/server/v2/adapter.ts@@ -4034,8 +4034,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Prreturn ProviderAdapter.ProviderAdapterV2.of({instanceId,driver,- getCapabilities: () => Effect.succeed(OpenCode2ProviderCapabilities),- planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),+ getCapabilities: Effect.fn("OpencodeAdapter.getCapabilities")(function () {+ return Effect.succeed(OpenCode2ProviderCapabilities);+ }),+ planSelectionTransition: Effect.fn("OpencodeAdapter.planSelectionTransition")(function () {+ return Effect.succeed(turnScopedSelectionTransition());+ }),// The session borrows the instance's server for as long as it is open, so a// spawned server is not idle-stopped under a long tool call.openSession: Effect.fn("OpenCode2Adapter.borrowAndOpenSession")(diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.tsindex cb46d7ae173..aca13e35643 100644--- a/packages/provider-pi/src/server/adapter.ts+++ b/packages/provider-pi/src/server/adapter.ts@@ -429,8 +429,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (return ProviderAdapter.ProviderAdapterV2.of({instanceId: options.instanceId,driver: PI_PROVIDER,- getCapabilities: () => Effect.succeed(PiProviderCapabilitiesV2),- planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),+ getCapabilities: Effect.fn("PiAdapter.getCapabilities")(function () {+ return Effect.succeed(PiProviderCapabilitiesV2);+ }),+ planSelectionTransition: Effect.fn("PiAdapter.planSelectionTransition")(function () {+ return Effect.succeed(turnScopedSelectionTransition());+ }),openSession: Effect.fn("PiAdapterV2.openSession")(function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput,) {diff --git a/packages/provider-pi/src/server/rpc.ts b/packages/provider-pi/src/server/rpc.tsindex 4c468a6d1d2..ed608613ac9 100644--- a/packages/provider-pi/src/server/rpc.ts+++ b/packages/provider-pi/src/server/rpc.ts@@ -315,31 +315,31 @@ export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSp}).pipe(Effect.matchCauseEffect({onFailure: (cause) => failTransport(new PiRpcError({ operation: "read", cause })),- onSuccess: () =>- Effect.gen(function* () {- // Claim stdout-close diagnosis before waiting so broken stdin cannot replace the exit error.- diagnosingStdoutClose = true;- const polled = yield* Deferred.poll(exitDeferred);- const maybeExitCode = Option.isSome(polled)- ? yield* polled.value.pipe(- Effect.asSome,- Effect.orElseSucceed(() => Option.none<number>()),- )- : yield* Deferred.await(exitDeferred).pipe(- Effect.timeoutOption(Duration.millis(250)),- // Stdout-close waits need wall time; TestClock would strand Stop-with-restart without an exit.- Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()),- Effect.orElseSucceed(() => Option.none<number>()),- );- return yield* failTransport(- new PiRpcError({- operation: "read",- detail: describePiStdoutClosure(- Option.isSome(maybeExitCode) ? maybeExitCode.value : undefined,- ),- }),- );- }),+ // The enclosing operation owns the span for this inline handler.+ onSuccess: Effect.fnUntraced(function* () {+ // Claim stdout-close diagnosis before waiting so broken stdin cannot replace the exit error.+ diagnosingStdoutClose = true;+ const polled = yield* Deferred.poll(exitDeferred);+ const maybeExitCode = Option.isSome(polled)+ ? yield* polled.value.pipe(+ Effect.asSome,+ Effect.orElseSucceed(() => Option.none<number>()),+ )+ : yield* Deferred.await(exitDeferred).pipe(+ Effect.timeoutOption(Duration.millis(250)),+ // Stdout-close waits need wall time; TestClock would strand Stop-with-restart without an exit.+ Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()),+ Effect.orElseSucceed(() => Option.none<number>()),+ );+ return yield* failTransport(+ new PiRpcError({+ operation: "read",+ detail: describePiStdoutClosure(+ Option.isSome(maybeExitCode) ? maybeExitCode.value : undefined,+ ),+ }),+ );+ }),}),Effect.forkIn(scope),);diff --git a/packages/provider-testing/src/TestProviderHost.ts b/packages/provider-testing/src/TestProviderHost.tsindex cd2cbbfe0af..6db6186d7f8 100644--- a/packages/provider-testing/src/TestProviderHost.ts+++ b/packages/provider-testing/src/TestProviderHost.ts@@ -56,10 +56,12 @@ export const layer = (changes: Stream.empty,subscribe: Effect.succeed(Stream.empty),},- shouldRunBackgroundWork: () => Effect.succeed(options.runBackgroundWork ?? true),+ shouldRunBackgroundWork: Effect.fn("ProviderHost.shouldRunBackgroundWork")(function () {+ return Effect.succeed(options.runBackgroundWork ?? true);+ }),resolveAttachmentPath: (attachment) => path.join(attachmentsDir, attachment.id),- credentials: (namespace, bindingId) =>- Effect.sync(() => {+ credentials: Effect.fn("ProviderHost.credentials")(function (namespace, bindingId) {+ return Effect.sync(() => {const key = `${namespace}:${bindingId}`;return {binding: { owner: "t3" as const, key },@@ -67,7 +69,8 @@ export const layer = (set: (value: Uint8Array) => Effect.sync(() => void credentials.set(key, value)),remove: Effect.sync(() => void credentials.delete(key)),};- }),+ });+ }),});return Context.make(ProviderHost.ProviderHost, host).pipe(Context.add(TestProviderHostSettings, {diff --git a/packages/shared/src/HostProcess.ts b/packages/shared/src/HostProcess.tsindex 0d4a9d52bc6..f24365cd5c8 100644--- a/packages/shared/src/HostProcess.ts+++ b/packages/shared/src/HostProcess.ts@@ -77,19 +77,19 @@ export const IsExecutable = Context.Reference<boolean>("@t3tools/shared/HostProcexport const Addresses = Context.Reference<Effect.Effect<ReadonlySet<string>>>("@t3tools/shared/HostProcess/Addresses",{- defaultValue: () =>- Effect.gen(function* () {- const interfaces = Object.values(NodeOS.networkInterfaces())- .flat()- .flatMap((entry) => (entry ? [entry.address] : []));- const resolved = yield* Effect.tryPromise(() =>- NodeDns.promises.lookup(NodeOS.hostname(), { all: true }),- ).pipe(- Effect.map((entries) => entries.map((entry) => entry.address)),- Effect.orElseSucceed(() => [] as ReadonlyArray<string>),- );- return new Set([...interfaces, ...resolved]);- }),+ // The enclosing operation owns the span for this inline handler.+ defaultValue: Effect.fnUntraced(function* () {+ const interfaces = Object.values(NodeOS.networkInterfaces())+ .flat()+ .flatMap((entry) => (entry ? [entry.address] : []));+ const resolved = yield* Effect.tryPromise(() =>+ NodeDns.promises.lookup(NodeOS.hostname(), { all: true }),+ ).pipe(+ Effect.map((entries) => entries.map((entry) => entry.address)),+ Effect.orElseSucceed(() => [] as ReadonlyArray<string>),+ );+ return new Set([...interfaces, ...resolved]);+ }),},);diff --git a/packages/shared/src/httpReadiness.ts b/packages/shared/src/httpReadiness.tsindex 811e8fd5e67..d57372f5961 100644--- a/packages/shared/src/httpReadiness.ts+++ b/packages/shared/src/httpReadiness.ts@@ -118,26 +118,26 @@ export const waitForHttpReady = Effect.fn("shared.httpReadiness.waitForHttpReadyrequestUrl,attempts: attempt,}),- onNone: () =>- Effect.gen(function* () {- const lastFailure = yield* Ref.get(lastProbeFailure);- yield* Effect.logWarning("httpReadiness.timedOut", {+ // The enclosing operation owns the span for this inline handler.+ onNone: Effect.fnUntraced(function* () {+ const lastFailure = yield* Ref.get(lastProbeFailure);+ yield* Effect.logWarning("httpReadiness.timedOut", {+ baseUrl: input.baseUrl,+ requestUrl,+ timeoutMs,+ intervalMs,+ probeTimeoutMs,+ attempts: attempt,+ lastFailure,+ });+ return yield* Effect.fail(+ fail({+ kind: "overall-timeout",baseUrl: input.baseUrl,- requestUrl,timeoutMs,- intervalMs,- probeTimeoutMs,- attempts: attempt,lastFailure,- });- return yield* Effect.fail(- fail({- kind: "overall-timeout",- baseUrl: input.baseUrl,- timeoutMs,- lastFailure,- }),- );- }),+ }),+ );+ }),});});diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.tsindex 6c9ef6f5b8f..da50a0013f8 100644--- a/packages/shared/src/nodeSqliteClient.ts+++ b/packages/shared/src/nodeSqliteClient.ts@@ -132,7 +132,7 @@ export class UnsupportedNodeSqliteOperationError extends Schema.TaggedError<Unsu}}-const checkNodeSqliteCompat = () => {+const checkNodeSqliteCompat = Effect.fn("checkNodeSqliteCompat")(function () {const parts = process.versions.node.split(".").map(Number);const major = parts[0] ?? 0;const minor = parts[1] ?? 0;@@ -147,7 +147,7 @@ const checkNodeSqliteCompat = () => {);}return Effect.void;-};+});// node:sqlite supplies errcode; classifySqliteError expects errno.const classifyError = (cause: unknown, message: string, operation: string) => {diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.tsindex 73006ac3053..ec3985fa6a2 100644--- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts+++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts@@ -400,8 +400,8 @@ export const make = Effect.gen(function* () {return AzureDevOpsCli.of({execute,- listPullRequests: (input) =>- executeJson({+ listPullRequests: Effect.fn("AzureDevOpsCli.listPullRequests")(function (input) {+ return executeJson({cwd: input.cwd,args: ["repos",@@ -439,9 +439,10 @@ export const make = Effect.gen(function* () {}),),),- ),- getPullRequest: (input) =>- executeJson({+ );+ }),+ getPullRequest: Effect.fn("AzureDevOpsCli.getPullRequest")(function (input) {+ return executeJson({cwd: input.cwd,args: ["repos",@@ -473,9 +474,10 @@ export const make = Effect.gen(function* () {}),),),- ),- getRepositoryCloneUrls: (input) =>- executeJson({+ );+ }),+ getRepositoryCloneUrls: Effect.fn("AzureDevOpsCli.getRepositoryCloneUrls")(function (input) {+ return executeJson({cwd: input.cwd,args: ["repos", "show", "--detect", "true", "--repository", input.repository],}).pipe(@@ -489,8 +491,9 @@ export const make = Effect.gen(function* () {),),Effect.map(normalizeRepositoryCloneUrls),- ),- createRepository: (input) => {+ );+ }),+ createRepository: Effect.fn("AzureDevOpsCli.createRepository")(function (input) {const repository = parseRepositorySpecifier(input.repository);// Project/organization permissions control visibility; `az repos create` has no flag.return executeJson({@@ -511,9 +514,9 @@ export const make = Effect.gen(function* () {),Effect.map(normalizeRepositoryCloneUrls),);- },- createPullRequest: (input) =>- execute({+ }),+ createPullRequest: Effect.fn("AzureDevOpsCli.createPullRequest")(function (input) {+ return execute({cwd: input.cwd,args: ["repos",@@ -531,9 +534,10 @@ export const make = Effect.gen(function* () {"--description",`@${input.bodyFile}`,],- }).pipe(Effect.asVoid),- getDefaultBranch: (input) =>- executeJson({+ }).pipe(Effect.asVoid);+ }),+ getDefaultBranch: Effect.fn("AzureDevOpsCli.getDefaultBranch")(function (input) {+ return executeJson({cwd: input.cwd,args: ["repos", "show", "--detect", "true"],}).pipe(@@ -542,9 +546,10 @@ export const make = Effect.gen(function* () {decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", input.cwd),),Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),- ),- checkoutPullRequest: (input) =>- execute({+ );+ }),+ checkoutPullRequest: Effect.fn("AzureDevOpsCli.checkoutPullRequest")(function (input) {+ return execute({cwd: input.cwd,args: ["repos",@@ -558,7 +563,8 @@ export const make = Effect.gen(function* () {"--remote-name",input.remoteName ?? "origin",],- }).pipe(Effect.asVoid),+ }).pipe(Effect.asVoid);+ }),});});diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.tsindex 30874e96fce..5856d7c0bea 100644--- a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts+++ b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts@@ -445,8 +445,8 @@ export const make = Effect.gen(function* () {};return AzureDevOpsPullRequestCli.of({- getViewer: (input) =>- executeJson({ cwd: input.cwd, args: ["account", "show", "--query", "user"] }).pipe(+ getViewer: Effect.fn("AzureDevOpsPullRequestCli.getViewer")(function (input) {+ return executeJson({ cwd: input.cwd, args: ["account", "show", "--query", "user"] }).pipe(Effect.flatMap((result): Effect.Effect<string, AzureDevOpsPullRequestCliError> => {const decoded = decodeViewerJson(`{"user":${result.stdout.trim() || "null"}}`);if (!Result.isSuccess(decoded)) {@@ -495,10 +495,11 @@ export const make = Effect.gen(function* () {}),),),- ),+ );+ }),- listPullRequests: (input) =>- listPullRequestPage({+ listPullRequests: Effect.fn("AzureDevOpsPullRequestCli.listPullRequests")(function (input) {+ return listPullRequestPage({cwd: input.cwd,repository: input.repository,state: input.state,@@ -509,10 +510,11 @@ export const make = Effect.gen(function* () {skip: input.cursor?.delivered ?? 0,cursorAdvance: 0,items: [],- }),+ });+ }),- getPullRequest: (input) =>- executeJson({+ getPullRequest: Effect.fn("AzureDevOpsPullRequestCli.getPullRequest")(function (input) {+ return executeJson({cwd: input.cwd,args: ["repos", "pr", "show", ...detectArgs, "--id", String(input.number)],}).pipe(@@ -540,57 +542,62 @@ export const make = Effect.gen(function* () {: Effect.succeed(decoded.success);},),- ),+ );+ }),- listThreads: (input) =>- invoke({+ listThreads: Effect.fn("AzureDevOpsPullRequestCli.listThreads")(function (input) {+ return invoke({cwd: input.cwd,operation: "listThreads",resource: "pullRequestThreads",routeParameters: pullRequestRoute(input),maxOutputBytes: REVIEW_HISTORY_MAX_OUTPUT_BYTES,decode: decodeThreadsJson,- }),+ });+ }),- listIterations: (input) =>- invoke({+ listIterations: Effect.fn("AzureDevOpsPullRequestCli.listIterations")(function (input) {+ return invoke({cwd: input.cwd,operation: "listIterations",resource: "pullRequestIterations",routeParameters: pullRequestRoute(input),maxOutputBytes: REVIEW_HISTORY_MAX_OUTPUT_BYTES,decode: decodeIterationsJson,- }),-- listIterationChanges: (input) => {- const page = (skip: number) =>- invoke({- cwd: input.cwd,- operation: "listIterationChanges",- resource: "pullRequestIterationChanges",- routeParameters: [...pullRequestRoute(input), `iterationId=${input.iterationId}`],- queryParameters: [`$top=${CHANGE_ENTRIES_PER_PAGE}`, `$skip=${skip}`],- maxOutputBytes: CHANGE_ENTRIES_MAX_OUTPUT_BYTES,- decode: decodeIterationChangesJson,- });- const from = (- skip: number,- collected: ReadonlyArray<AzureDevOpsChangeEntry>,- ): Effect.Effect<AzureDevOpsIterationChanges, AzureDevOpsPullRequestCliError> =>- page(skip).pipe(- Effect.flatMap((answer) => {- const changes = [...collected, ...answer.changes];- if (answer.nextSkip === null) return Effect.succeed({ changes, truncated: false });- return answer.nextSkip <= skip || answer.nextSkip >= MAX_CHANGE_ENTRIES- ? Effect.succeed({ changes, truncated: true })- : from(answer.nextSkip, changes);- }),- );- return from(0, []);- },+ });+ }),++ listIterationChanges: Effect.fn("AzureDevOpsPullRequestCli.listIterationChanges")(+ function (input) {+ const page = (skip: number) =>+ invoke({+ cwd: input.cwd,+ operation: "listIterationChanges",+ resource: "pullRequestIterationChanges",+ routeParameters: [...pullRequestRoute(input), `iterationId=${input.iterationId}`],+ queryParameters: [`$top=${CHANGE_ENTRIES_PER_PAGE}`, `$skip=${skip}`],+ maxOutputBytes: CHANGE_ENTRIES_MAX_OUTPUT_BYTES,+ decode: decodeIterationChangesJson,+ });+ const from = (+ skip: number,+ collected: ReadonlyArray<AzureDevOpsChangeEntry>,+ ): Effect.Effect<AzureDevOpsIterationChanges, AzureDevOpsPullRequestCliError> =>+ page(skip).pipe(+ Effect.flatMap((answer) => {+ const changes = [...collected, ...answer.changes];+ if (answer.nextSkip === null) return Effect.succeed({ changes, truncated: false });+ return answer.nextSkip <= skip || answer.nextSkip >= MAX_CHANGE_ENTRIES+ ? Effect.succeed({ changes, truncated: true })+ : from(answer.nextSkip, changes);+ }),+ );+ return from(0, []);+ },+ ),- readItemContent: (input) =>- invoke({+ readItemContent: Effect.fn("AzureDevOpsPullRequestCli.readItemContent")(function (input) {+ return invoke({cwd: input.cwd,operation: "readItemContent",resource: "items",@@ -607,53 +614,61 @@ export const make = Effect.gen(function* () {],maxOutputBytes: ITEM_CONTENT_MAX_OUTPUT_BYTES,decode: decodeItemContentJson,- }),-- setPullRequestReviewers: (input) =>- input.reviewers.some((reviewer) => !isReviewerName(reviewer))- ? Effect.fail(new AzureDevOpsReviewerNameError({ command: "az", cwd: input.cwd }))- : azure- .execute({- cwd: input.cwd,- args: [- "repos",- "pr",- "reviewer",- input.requested ? "add" : "remove",- ...detectArgs,- "--id",- String(input.number),- // Repeating `--reviewers` replaces the earlier list.- "--reviewers",- ...input.reviewers,- "--only-show-errors",- "--output",- "json",- ],- })- .pipe(Effect.asVoid),+ });+ }),- runPullRequestAction: (input) =>- azure- .execute({- cwd: input.cwd,- args: [- "repos",- "pr",- "update",- ...detectArgs,- "--id",- String(input.number),- ...actionArgs(input.action, input.mergeMethod),- "--only-show-errors",- "--output",- "json",- ],- })- .pipe(Effect.asVoid),+ setPullRequestReviewers: Effect.fn("AzureDevOpsPullRequestCli.setPullRequestReviewers")(+ function* (input) {+ if (input.reviewers.some((reviewer) => !isReviewerName(reviewer))) {+ return yield* new AzureDevOpsReviewerNameError({ command: "az", cwd: input.cwd });+ }+ return yield* azure+ .execute({+ cwd: input.cwd,+ args: [+ "repos",+ "pr",+ "reviewer",+ input.requested ? "add" : "remove",+ ...detectArgs,+ "--id",+ String(input.number),+ // Repeating `--reviewers` replaces the earlier list.+ "--reviewers",+ ...input.reviewers,+ "--only-show-errors",+ "--output",+ "json",+ ],+ })+ .pipe(Effect.asVoid);+ },+ ),++ runPullRequestAction: Effect.fn("AzureDevOpsPullRequestCli.runPullRequestAction")(+ function (input) {+ return azure+ .execute({+ cwd: input.cwd,+ args: [+ "repos",+ "pr",+ "update",+ ...detectArgs,+ "--id",+ String(input.number),+ ...actionArgs(input.action, input.mergeMethod),+ "--only-show-errors",+ "--output",+ "json",+ ],+ })+ .pipe(Effect.asVoid);+ },+ ),- updatePullRequest: (input) =>- azure+ updatePullRequest: Effect.fn("AzureDevOpsPullRequestCli.updatePullRequest")(function (input) {+ return azure.execute({cwd: input.cwd,args: [@@ -671,7 +686,8 @@ export const make = Effect.gen(function* () {"json",],})- .pipe(Effect.asVoid),+ .pipe(Effect.asVoid);+ }),});});diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsSourceControlProvider.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsSourceControlProvider.tsindex 109710f881c..64c1ada9bc1 100644--- a/packages/source-control-azure-devops/src/server/AzureDevOpsSourceControlProvider.ts+++ b/packages/source-control-azure-devops/src/server/AzureDevOpsSourceControlProvider.ts@@ -76,151 +76,170 @@ export const make = Effect.gen(function* () {return SourceControlProvider.SourceControlProvider.of({kind: SourceControlProviderKind.make("azure-devops"),- listChangeRequests: (input) => {- const source = SourceControlProvider.sourceControlRefFromInput(input);- return azure- .listPullRequests({- cwd: input.cwd,- headSelector: input.headSelector,- ...(source !== undefined ? { source } : {}),- state: input.state,- ...(input.limit !== undefined ? { limit: input.limit } : {}),- })- .pipe(- Effect.map((items) => items.map(toChangeRequest)),+ listChangeRequests: Effect.fn("AzureDevOpsSourceControlProvider.listChangeRequests")(+ function (input) {+ const source = SourceControlProvider.sourceControlRefFromInput(input);+ return azure+ .listPullRequests({+ cwd: input.cwd,+ headSelector: input.headSelector,+ ...(source !== undefined ? { source } : {}),+ state: input.state,+ ...(input.limit !== undefined ? { limit: input.limit } : {}),+ })+ .pipe(+ Effect.map((items) => items.map(toChangeRequest)),+ Effect.mapError(+ (error) =>+ new SourceControlProviderError({+ provider: SourceControlProviderKind.make("azure-devops"),+ operation: "listChangeRequests",+ command: error.command,+ cwd: input.cwd,+ reference: SourceControlProvider.transportSafeSourceControlErrorValue(+ input.headSelector,+ ),+ detail: error.detail,+ cause: error,+ }),+ ),+ );+ },+ ),+ getChangeRequest: Effect.fn("AzureDevOpsSourceControlProvider.getChangeRequest")(+ function (input) {+ return azure.getPullRequest(input).pipe(+ Effect.map(toChangeRequest),Effect.mapError((error) =>new SourceControlProviderError({provider: SourceControlProviderKind.make("azure-devops"),- operation: "listChangeRequests",+ operation: "getChangeRequest",command: error.command,cwd: input.cwd,reference: SourceControlProvider.transportSafeSourceControlErrorValue(- input.headSelector,+ input.reference,),detail: error.detail,cause: error,}),),);- },- getChangeRequest: (input) =>- azure.getPullRequest(input).pipe(- Effect.map(toChangeRequest),- Effect.mapError(- (error) =>- new SourceControlProviderError({- provider: SourceControlProviderKind.make("azure-devops"),- operation: "getChangeRequest",- command: error.command,- cwd: input.cwd,- reference: SourceControlProvider.transportSafeSourceControlErrorValue(- input.reference,- ),- detail: error.detail,- cause: error,- }),- ),- ),- createChangeRequest: (input) => {- const source = SourceControlProvider.sourceControlRefFromInput(input);- return azure- .createPullRequest({- cwd: input.cwd,- baseBranch: input.baseRefName,- headSelector: input.headSelector,- ...(source !== undefined ? { source } : {}),- ...(input.target !== undefined ? { target: input.target } : {}),- title: input.title,- bodyFile: input.bodyFile,- })- .pipe(+ },+ ),+ createChangeRequest: Effect.fn("AzureDevOpsSourceControlProvider.createChangeRequest")(+ function (input) {+ const source = SourceControlProvider.sourceControlRefFromInput(input);+ return azure+ .createPullRequest({+ cwd: input.cwd,+ baseBranch: input.baseRefName,+ headSelector: input.headSelector,+ ...(source !== undefined ? { source } : {}),+ ...(input.target !== undefined ? { target: input.target } : {}),+ title: input.title,+ bodyFile: input.bodyFile,+ })+ .pipe(+ Effect.mapError(+ (error) =>+ new SourceControlProviderError({+ provider: SourceControlProviderKind.make("azure-devops"),+ operation: "createChangeRequest",+ command: error.command,+ cwd: input.cwd,+ reference: SourceControlProvider.transportSafeSourceControlErrorValue(+ input.headSelector,+ ),+ detail: error.detail,+ cause: error,+ }),+ ),+ );+ },+ ),+ getRepositoryCloneUrls: Effect.fn("AzureDevOpsSourceControlProvider.getRepositoryCloneUrls")(+ function (input) {+ return azure.getRepositoryCloneUrls(input).pipe(Effect.mapError((error) =>new SourceControlProviderError({provider: SourceControlProviderKind.make("azure-devops"),- operation: "createChangeRequest",+ operation: "getRepositoryCloneUrls",command: error.command,cwd: input.cwd,- reference: SourceControlProvider.transportSafeSourceControlErrorValue(- input.headSelector,+ repository: SourceControlProvider.transportSafeSourceControlErrorValue(+ input.repository,),detail: error.detail,cause: error,}),),);- },- getRepositoryCloneUrls: (input) =>- azure.getRepositoryCloneUrls(input).pipe(- Effect.mapError(- (error) =>- new SourceControlProviderError({- provider: SourceControlProviderKind.make("azure-devops"),- operation: "getRepositoryCloneUrls",- command: error.command,- cwd: input.cwd,- repository: SourceControlProvider.transportSafeSourceControlErrorValue(- input.repository,- ),- detail: error.detail,- cause: error,- }),- ),- ),- createRepository: (input) =>- azure.createRepository(input).pipe(- Effect.mapError(- (error) =>- new SourceControlProviderError({- provider: SourceControlProviderKind.make("azure-devops"),- operation: "createRepository",- command: error.command,- cwd: input.cwd,- repository: SourceControlProvider.transportSafeSourceControlErrorValue(- input.repository,- ),- detail: error.detail,- cause: error,- }),- ),- ),- getDefaultBranch: (input) =>- azure.getDefaultBranch({ cwd: input.cwd }).pipe(- Effect.mapError(- (error) =>- new SourceControlProviderError({- provider: SourceControlProviderKind.make("azure-devops"),- operation: "getDefaultBranch",- command: error.command,- cwd: input.cwd,- detail: error.detail,- cause: error,- }),- ),- ),- checkoutChangeRequest: (input) =>- azure- .checkoutPullRequest({- cwd: input.cwd,- reference: input.reference,- ...(input.context !== undefined ? { remoteName: input.context.remoteName } : {}),- })- .pipe(+ },+ ),+ createRepository: Effect.fn("AzureDevOpsSourceControlProvider.createRepository")(+ function (input) {+ return azure.createRepository(input).pipe(Effect.mapError((error) =>new SourceControlProviderError({provider: SourceControlProviderKind.make("azure-devops"),- operation: "checkoutChangeRequest",+ operation: "createRepository",command: error.command,cwd: input.cwd,- reference: SourceControlProvider.transportSafeSourceControlErrorValue(- input.reference,+ repository: SourceControlProvider.transportSafeSourceControlErrorValue(+ input.repository,),detail: error.detail,cause: error,}),),- ),+ );+ },+ ),+ getDefaultBranch: Effect.fn("AzureDevOpsSourceControlProvider.getDefaultBranch")(+ function (input) {+ return azure.getDefaultBranch({ cwd: input.cwd }).pipe(+ Effect.mapError(+ (error) =>+ new SourceControlProviderError({+ provider: SourceControlProviderKind.make("azure-devops"),+ operation: "getDefaultBranch",+ command: error.command,+ cwd: input.cwd,+ detail: error.detail,+ cause: error,+ }),+ ),+ );+ },+ ),+ checkoutChangeRequest: Effect.fn("AzureDevOpsSourceControlProvider.checkoutChangeRequest")(+ function (input) {+ return azure+ .checkoutPullRequest({+ cwd: input.cwd,+ reference: input.reference,+ ...(input.context !== undefined ? { remoteName: input.context.remoteName } : {}),+ })+ .pipe(+ Effect.mapError(+ (error) =>+ new SourceControlProviderError({+ provider: SourceControlProviderKind.make("azure-devops"),+ operation: "checkoutChangeRequest",+ command: error.command,+ cwd: input.cwd,+ reference: SourceControlProvider.transportSafeSourceControlErrorValue(+ input.reference,+ ),+ detail: error.detail,+ cause: error,+ }),+ ),+ );+ },+ ),});});diff --git a/packages/source-control-bitbucket/src/server/BitbucketApi.ts b/packages/source-control-bitbucket/src/server/BitbucketApi.tsindex 878aafa0329..72077040aa8 100644--- a/packages/source-control-bitbucket/src/server/BitbucketApi.ts+++ b/packages/source-control-bitbucket/src/server/BitbucketApi.ts@@ -999,8 +999,8 @@ export const make = Effect.gen(function* () {})),Effect.catch(() => currentCredential.pipe(Effect.map(authFromCredential))),),- listPullRequests: (input) =>- resolveRepository(input).pipe(+ listPullRequests: Effect.fn("BitbucketApi.listPullRequests")(function (input) {+ return resolveRepository(input).pipe(Effect.flatMap((repository) => {const states = toBitbucketStates(input.state);const query: Record<string, string | ReadonlyArray<string>> = {@@ -1025,13 +1025,16 @@ export const make = Effect.gen(function* () {);}),Effect.map((list) => list.values.map(normalizeBitbucketPullRequestRecord)),- ),- getPullRequest: (input) =>- getRawPullRequest(input).pipe(Effect.map(normalizeBitbucketPullRequestRecord)),- getRepositoryCloneUrls: (input) =>- getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),- createRepository: (input) =>- requireRepositoryLocator(input.repository).pipe(+ );+ }),+ getPullRequest: Effect.fn("BitbucketApi.getPullRequest")(function (input) {+ return getRawPullRequest(input).pipe(Effect.map(normalizeBitbucketPullRequestRecord));+ }),+ getRepositoryCloneUrls: Effect.fn("BitbucketApi.getRepositoryCloneUrls")(function (input) {+ return getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls));+ }),+ createRepository: Effect.fn("BitbucketApi.createRepository")(function (input) {+ return requireRepositoryLocator(input.repository).pipe(Effect.flatMap((repository) =>executeJson("createRepository",@@ -1049,7 +1052,8 @@ export const make = Effect.gen(function* () {),),Effect.map(normalizeRepositoryCloneUrls),- ),+ );+ }),createPullRequest: Effect.fn("BitbucketApi.createPullRequest")(function* (input) {const repository = yield* resolveRepository(input);const description = yield* fileSystem.readFileString(input.bodyFile).pipe(@@ -1095,8 +1099,8 @@ export const make = Effect.gen(function* () {BitbucketPullRequestSchema,);}),- getDefaultBranch: (input) =>- resolveRepository(input).pipe(+ getDefaultBranch: Effect.fn("BitbucketApi.getDefaultBranch")(function (input) {+ return resolveRepository(input).pipe(Effect.flatMap((locator) =>Effect.all({@@ -1111,7 +1115,8 @@ export const make = Effect.gen(function* () {),),Effect.map(defaultChangeRequestTargetBranch),- ),+ );+ }),checkoutPullRequest: Effect.fn("BitbucketApi.checkoutPullRequest")(function* (input) {const destinationRepository = yield* resolveRepository(input);diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.tsindex d5ad8491ac8..de4b625bd9c 100644--- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.ts+++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.ts@@ -124,6 +124,9 @@ const DIFF_MAX_BYTES = 8 * 1024 * 1024;/** Must expire before the caller's version cache so refreshes reach Bitbucket. */const REVISION_PATCH_TTL = Duration.seconds(5);const REVISION_PATCH_CAPACITY = 16;+const encodeRevisionKey = Schema.encodeSync(+ Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.Number])),+);export interface BitbucketPullRequestBatch {readonly items: ReadonlyArray<BitbucketPullRequest>;readonly truncated: boolean;@@ -526,8 +529,8 @@ export const make = Effect.gen(function* () {);return BitbucketPullRequestApi.of({- getViewer: () =>- bitbucket.request({ method: "GET", url: "/user" }).pipe(+ getViewer: Effect.fn("BitbucketPullRequestApi.getViewer")(function () {+ return bitbucket.request({ method: "GET", url: "/user" }).pipe(Effect.flatMap((response): Effect.Effect<string, BitbucketPullRequestApiError> => {const decoded = decodeViewerJson(response.body);if (!Result.isSuccess(decoded)) {@@ -539,10 +542,11 @@ export const make = Effect.gen(function* () {? Effect.fail(new BitbucketViewerUnavailableError()): Effect.succeed(decoded.success);}),- ),+ );+ }),- listPullRequests: (input) =>- withRepository(input.repository, (path) => {+ listPullRequests: Effect.fn("BitbucketPullRequestApi.listPullRequests")(function (input) {+ return withRepository(input.repository, (path) => {const search = input.query?.trim() ?? "";// Exclude already-sent IDs at the inclusive timestamp before applying the page limit.const predicates = [@@ -563,77 +567,89 @@ export const make = Effect.gen(function* () {page: 1,collected: [],});- }),+ });+ }),- getPullRequest: (input) =>- withRepository(input.repository, (path) =>+ getPullRequest: Effect.fn("BitbucketPullRequestApi.getPullRequest")(function (input) {+ return withRepository(input.repository, (path) =>readPage({operation: "getPullRequest",// Settlement needs `closed_on`, omitted by default.url: `${path}/pullrequests/${input.number}?fields=%2Bclosed_on`,decode: decodePullRequestJson,}),- ),+ );+ }),// Permission endpoints may return 403/404/410 (CHANGE-2770); let writes enforce access.- getRepositoryPermission: (input) =>- withRepository(input.repository, (_path, workspace, slug) =>- readPage({- operation: "getRepositoryPermission",- url: `/user/workspaces/${encodeURIComponent(workspace)}/permissions/repositories?q=${encodeURIComponent(- `repository.full_name="${filterLiteral(`${workspace}/${slug}`)}"`,- )}`,- decode: decodeRepositoryPermissionJson,- }),- ).pipe(Effect.catchIf(isRepositoryPermissionUnavailableError, () => Effect.succeed(true))),+ getRepositoryPermission: Effect.fn("BitbucketPullRequestApi.getRepositoryPermission")(+ function (input) {+ return withRepository(input.repository, (_path, workspace, slug) =>+ readPage({+ operation: "getRepositoryPermission",+ url: `/user/workspaces/${encodeURIComponent(workspace)}/permissions/repositories?q=${encodeURIComponent(+ `repository.full_name="${filterLiteral(`${workspace}/${slug}`)}"`,+ )}`,+ decode: decodeRepositoryPermissionJson,+ }),+ ).pipe(Effect.catchIf(isRepositoryPermissionUnavailableError, () => Effect.succeed(true)));+ },+ ),getPullRequestDiff: pullRequestDiff,- getFileRevisions: (input) =>- input.paths.length === 0- ? Effect.succeed({ revisions: new Map(), complete: false })- : Cache.get(revisionPatches, JSON.stringify([input.repository, input.number])).pipe(- Effect.map((diff) => {- const revisions = new Map(diff.revisions);- // A truncated patch cannot identify absent paths as deleted.- if (!diff.truncated) {- for (const path of input.paths) {- if (!revisions.has(path)) revisions.set(path, "");- }- }- return { revisions, complete: !diff.truncated };- }),- ),+ getFileRevisions: Effect.fn("BitbucketPullRequestApi.getFileRevisions")(function* (input) {+ if (input.paths.length === 0)+ return { revisions: new Map<string, string>(), complete: false };+ return yield* Cache.get(+ revisionPatches,+ encodeRevisionKey([input.repository, input.number]),+ ).pipe(+ Effect.map((diff) => {+ const revisions = new Map(diff.revisions);+ // A truncated patch cannot identify absent paths as deleted.+ if (!diff.truncated) {+ for (const path of input.paths) {+ if (!revisions.has(path)) revisions.set(path, "");+ }+ }+ return { revisions, complete: !diff.truncated };+ }),+ );+ }),- getDiffStat: (input) =>- withRepository(input.repository, (path) =>+ getDiffStat: Effect.fn("BitbucketPullRequestApi.getDiffStat")(function (input) {+ return withRepository(input.repository, (path) =>diffStatPages({url: `${path}/pullrequests/${input.number}/diffstat?pagelen=${MAX_PAGE_SIZE}`,totals: { additions: 0, deletions: 0, changedFiles: 0 },}),- ),+ );+ }),- getMergeability: (input) =>- withRepository(input.repository, (path) =>+ getMergeability: Effect.fn("BitbucketPullRequestApi.getMergeability")(function (input) {+ return withRepository(input.repository, (path) =>readPage({operation: "getMergeability",url: `${path}/pullrequests/${input.number}/conflicts`,decode: decodeConflictsJson,}),- ),+ );+ }),- listComments: (input) =>- withRepository(input.repository, (path) =>+ listComments: Effect.fn("BitbucketPullRequestApi.listComments")(function (input) {+ return withRepository(input.repository, (path) =>commentsPage({url: `${path}/pullrequests/${input.number}/comments?pagelen=${CONVERSATION_PAGE_SIZE}`,page: 1,comments: [],entries: [],}),- ),+ );+ }),- listCommits: (input) =>- withRepository(input.repository, (path) =>+ listCommits: Effect.fn("BitbucketPullRequestApi.listCommits")(function (input) {+ return withRepository(input.repository, (path) =>itemPages({operation: "listCommits",url: `${path}/pullrequests/${input.number}/commits?pagelen=${CONVERSATION_PAGE_SIZE}`,@@ -641,10 +657,11 @@ export const make = Effect.gen(function* () {items: [],prepend: true,}),- ),+ );+ }),- listChecks: (input) =>- withRepository(input.repository, (path) =>+ listChecks: Effect.fn("BitbucketPullRequestApi.listChecks")(function (input) {+ return withRepository(input.repository, (path) =>itemPages({operation: "listChecks",url: `${path}/pullrequests/${input.number}/statuses?pagelen=${CONVERSATION_PAGE_SIZE}`,@@ -652,43 +669,47 @@ export const make = Effect.gen(function* () {items: [],prepend: false,}).pipe(Effect.map(sortChecks)),- ),-- listReviewerCandidates: (input) =>- withRepository(input.repository, (path, workspace) =>- Effect.all(- [- readPage({- operation: "getPullRequest",- url: `${path}/pullrequests/${input.number}`,- decode: decodePullRequestJson,- }),- readPage({- operation: "listReviewerCandidates",- url: `/workspaces/${encodeURIComponent(workspace)}/members?pagelen=${MAX_PAGE_SIZE}`,- decode: decodeWorkspaceMembersJson,+ );+ }),++ listReviewerCandidates: Effect.fn("BitbucketPullRequestApi.listReviewerCandidates")(+ function (input) {+ return withRepository(input.repository, (path, workspace) =>+ Effect.all(+ [+ readPage({+ operation: "getPullRequest",+ url: `${path}/pullrequests/${input.number}`,+ decode: decodePullRequestJson,+ }),+ readPage({+ operation: "listReviewerCandidates",+ url: `/workspaces/${encodeURIComponent(workspace)}/members?pagelen=${MAX_PAGE_SIZE}`,+ decode: decodeWorkspaceMembersJson,+ }),+ ],+ { concurrency: 2 },+ ).pipe(+ Effect.map(([pullRequest, members]) => {+ const requested = new Set(pullRequest.reviewerIds);+ const author = pullRequest.author?.login;+ return {+ // Bitbucket forbids requesting a review from the PR author.+ candidates: members.items.flatMap((candidate) =>+ candidate.login === author+ ? []+ : [{ ...candidate, isRequested: requested.has(candidate.id) }],+ ),+ truncated: members.next !== null,+ };}),- ],- { concurrency: 2 },- ).pipe(- Effect.map(([pullRequest, members]) => {- const requested = new Set(pullRequest.reviewerIds);- const author = pullRequest.author?.login;- return {- // Bitbucket forbids requesting a review from the PR author.- candidates: members.items.flatMap((candidate) =>- candidate.login === author- ? []- : [{ ...candidate, isRequested: requested.has(candidate.id) }],- ),- truncated: members.next !== null,- };- }),- ),- ),+ ),+ );+ },+ ),- setReviewerRequest: (input) =>- withRepository(input.repository, (path) => {+ setReviewerRequest: Effect.fn("BitbucketPullRequestApi.setReviewerRequest")(function (input) {+ return withRepository(input.repository, (path) => {const pullRequest = `${path}/pullrequests/${input.number}`;return readPage({operation: "getPullRequest",@@ -710,10 +731,11 @@ export const make = Effect.gen(function* () {}),Effect.asVoid,);- }),+ });+ }),- runAction: (input) =>- withRepository(input.repository, (path) => {+ runAction: Effect.fn("BitbucketPullRequestApi.runAction")(function (input) {+ return withRepository(input.repository, (path) => {const pullRequest = `${path}/pullrequests/${input.number}`;if (input.action === "merge") {return bitbucket@@ -727,10 +749,11 @@ export const make = Effect.gen(function* () {return bitbucket.request({ method: "POST", url: `${pullRequest}/decline` }).pipe(Effect.asVoid);- }),+ });+ }),- updateChangeRequest: (input) =>- withRepository(input.repository, (path) =>+ updateChangeRequest: Effect.fn("BitbucketPullRequestApi.updateChangeRequest")(function (input) {+ return withRepository(input.repository, (path) =>// Partial PUTs preserve concurrent edits to unchanged fields.bitbucket.request({@@ -742,10 +765,11 @@ export const make = Effect.gen(function* () {}),}).pipe(Effect.asVoid),- ),+ );+ }),- comment: (input) =>- withRepository(input.repository, (path) =>+ comment: Effect.fn("BitbucketPullRequestApi.comment")(function (input) {+ return withRepository(input.repository, (path) =>bitbucket.request({method: "POST",@@ -753,10 +777,11 @@ export const make = Effect.gen(function* () {body: JSON.stringify({ content: { raw: input.body } }),}).pipe(Effect.asVoid),- ),+ );+ }),- updateComment: (input) =>- withRepository(input.repository, (path) =>+ updateComment: Effect.fn("BitbucketPullRequestApi.updateComment")(function (input) {+ return withRepository(input.repository, (path) =>bitbucket.request({method: "PUT",@@ -766,10 +791,11 @@ export const make = Effect.gen(function* () {body: JSON.stringify({ content: { raw: input.body } }),}).pipe(Effect.asVoid),- ),+ );+ }),- submitReview: (input) =>- withRepository(input.repository, (path) =>+ submitReview: Effect.fn("BitbucketPullRequestApi.submitReview")(function (input) {+ return withRepository(input.repository, (path) =>Effect.gen(function* () {const pullRequest = `${path}/pullrequests/${input.number}`;// A partially failed review must not leave an approval.@@ -804,10 +830,11 @@ export const make = Effect.gen(function* () {yield* bitbucket.request({ method: "POST", url: `${pullRequest}/request-changes` });}}),- ),+ );+ }),- replyToComment: (input) =>- withRepository(input.repository, (path) =>+ replyToComment: Effect.fn("BitbucketPullRequestApi.replyToComment")(function (input) {+ return withRepository(input.repository, (path) =>bitbucket.request({method: "POST",@@ -818,19 +845,23 @@ export const make = Effect.gen(function* () {}),}).pipe(Effect.asVoid),- ),+ );+ }),- setCommentResolution: (input) =>- withRepository(input.repository, (path) =>- bitbucket- .request({- method: input.resolved ? "POST" : "DELETE",- url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(- input.commentId,- )}/resolve`,- })- .pipe(Effect.asVoid),- ),+ setCommentResolution: Effect.fn("BitbucketPullRequestApi.setCommentResolution")(+ function (input) {+ return withRepository(input.repository, (path) =>+ bitbucket+ .request({+ method: input.resolved ? "POST" : "DELETE",+ url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(+ input.commentId,+ )}/resolve`,+ })+ .pipe(Effect.asVoid),+ );+ },+ ),});});diff --git a/packages/source-control-bitbucket/src/server/BitbucketSourceControlProvider.ts b/packages/source-control-bitbucket/src/server/BitbucketSourceControlProvider.tsindex 6154d3e8e96..5e8ef1b4901 100644--- a/packages/source-control-bitbucket/src/server/BitbucketSourceControlProvider.ts+++ b/packages/source-control-bitbucket/src/server/BitbucketSourceControlProvider.ts@@ -44,153 +44,172 @@ export const make = Effect.gen(function* () {return SourceControlProvider.SourceControlProvider.of({kind: SourceControlProviderKind.make("bitbucket"),- listChangeRequests: (input) => {- const source = SourceControlProvider.sourceControlRefFromInput(input);- return bitbucket- .listPullRequests({- cwd: input.cwd,- ...(input.context ? { context: input.context } : {}),- headSelector: input.headSelector,- ...(source ? { source } : {}),- state: input.state,- ...(input.limit !== undefined ? { limit: input.limit } : {}),- })- .pipe(- Effect.map((items) => items.map(toChangeRequest)),+ listChangeRequests: Effect.fn("BitbucketSourceControlProvider.listChangeRequests")(+ function (input) {+ const source = SourceControlProvider.sourceControlRefFromInput(input);+ return bitbucket+ .listPullRequests({+ cwd: input.cwd,+ ...(input.context ? { context: input.context } : {}),+ headSelector: input.headSelector,+ ...(source ? { source } : {}),+ state: input.state,+ ...(input.limit !== undefined ? { limit: input.limit } : {}),+ })+ .pipe(+ Effect.map((items) => items.map(toChangeRequest)),+ Effect.mapError(+ (error) =>+ new SourceControlProviderError({+ provider: SourceControlProviderKind.make("bitbucket"),+ operation: "listChangeRequests",+ cwd: input.cwd,+ reference: SourceControlProvider.transportSafeSourceControlErrorValue(+ input.headSelector,+ ),+ detail: "Failed to list change requests.",+ cause: error,+ }),+ ),+ );+ },+ ),+ getChangeRequest: Effect.fn("BitbucketSourceControlProvider.getChangeRequest")(+ function (input) {+ return bitbucket.getPullRequest(input).pipe(+ Effect.map(toChangeRequest),Effect.mapError((error) =>new SourceControlProviderError({provider: SourceControlProviderKind.make("bitbucket"),- operation: "listChangeRequests",+ operation: "getChangeRequest",cwd: input.cwd,reference: SourceControlProvider.transportSafeSourceControlErrorValue(- input.headSelector,+ input.reference,),- detail: "Failed to list change requests.",+ detail: "Failed to get change request.",cause: error,}),),);- },- getChangeRequest: (input) =>- bitbucket.getPullRequest(input).pipe(- Effect.map(toChangeRequest),- Effect.mapError(- (error) =>- new SourceControlProviderError({- provider: SourceControlProviderKind.make("bitbucket"),- operation: "getChangeRequest",- cwd: input.cwd,- reference: SourceControlProvider.transportSafeSourceControlErrorValue(- input.reference,- ),- detail: "Failed to get change request.",- cause: error,- }),- ),- ),- createChangeRequest: (input) => {- const source = SourceControlProvider.sourceControlRefFromInput(input);- return bitbucket- .createPullRequest({- cwd: input.cwd,- ...(input.context ? { context: input.context } : {}),- baseBranch: input.baseRefName,- headSelector: input.headSelector,- ...(source ? { source } : {}),- ...(input.target ? { target: input.target } : {}),- title: input.title,- bodyFile: input.bodyFile,- })- .pipe(+ },+ ),+ createChangeRequest: Effect.fn("BitbucketSourceControlProvider.createChangeRequest")(+ function (input) {+ const source = SourceControlProvider.sourceControlRefFromInput(input);+ return bitbucket+ .createPullRequest({+ cwd: input.cwd,+ ...(input.context ? { context: input.context } : {}),+ baseBranch: input.baseRefName,+ headSelector: input.headSelector,+ ...(source ? { source } : {}),+ ...(input.target ? { target: input.target } : {}),+ title: input.title,+ bodyFile: input.bodyFile,+ })+ .pipe(+ Effect.mapError(+ (error) =>+ new SourceControlProviderError({+ provider: SourceControlProviderKind.make("bitbucket"),+ operation: "createChangeRequest",+ cwd: input.cwd,+ reference: SourceControlProvider.transportSafeSourceControlErrorValue(+ input.headSelector,+ ),+ detail: "Failed to create change request.",+ cause: error,+ }),+ ),+ );+ },+ ),+ getRepositoryCloneUrls: Effect.fn("BitbucketSourceControlProvider.getRepositoryCloneUrls")(+ function (input) {+ return bitbucket.getRepositoryCloneUrls(input).pipe(Effect.mapError((error) =>new SourceControlProviderError({provider: SourceControlProviderKind.make("bitbucket"),- operation: "createChangeRequest",+ operation: "getRepositoryCloneUrls",cwd: input.cwd,- reference: SourceControlProvider.transportSafeSourceControlErrorValue(- input.headSelector,+ repository: SourceControlProvider.transportSafeSourceControlErrorValue(+ input.repository,),- detail: "Failed to create change request.",+ detail: repositoryDetail(error, "Failed to get repository clone URLs."),cause: error,}),),);- },- getRepositoryCloneUrls: (input) =>- bitbucket.getRepositoryCloneUrls(input).pipe(- Effect.mapError(- (error) =>- new SourceControlProviderError({- provider: SourceControlProviderKind.make("bitbucket"),- operation: "getRepositoryCloneUrls",- cwd: input.cwd,- repository: SourceControlProvider.transportSafeSourceControlErrorValue(- input.repository,- ),- detail: repositoryDetail(error, "Failed to get repository clone URLs."),- cause: error,- }),- ),- ),- createRepository: (input) =>- bitbucket.createRepository(input).pipe(- Effect.mapError(- (error) =>- new SourceControlProviderError({- provider: SourceControlProviderKind.make("bitbucket"),- operation: "createRepository",- cwd: input.cwd,- repository: SourceControlProvider.transportSafeSourceControlErrorValue(- input.repository,- ),- detail: repositoryDetail(error, "Failed to create repository."),- cause: error,- }),- ),- ),- getDefaultBranch: (input) =>- bitbucket- .getDefaultBranch({- cwd: input.cwd,- ...(input.context ? { context: input.context } : {}),- })- .pipe(+ },+ ),+ createRepository: Effect.fn("BitbucketSourceControlProvider.createRepository")(+ function (input) {+ return bitbucket.createRepository(input).pipe(Effect.mapError((error) =>new SourceControlProviderError({provider: SourceControlProviderKind.make("bitbucket"),- operation: "getDefaultBranch",+ operation: "createRepository",cwd: input.cwd,- detail: "Failed to get default branch.",- cause: error,- }),- ),- ),- checkoutChangeRequest: (input) =>- bitbucket- .checkoutPullRequest({- cwd: input.cwd,- ...(input.context ? { context: input.context } : {}),- reference: input.reference,- ...(input.force !== undefined ? { force: input.force } : {}),- })- .pipe(- Effect.mapError(- (error) =>- new SourceControlProviderError({- provider: SourceControlProviderKind.make("bitbucket"),- operation: "checkoutChangeRequest",- cwd: input.cwd,- reference: SourceControlProvider.transportSafeSourceControlErrorValue(- input.reference,+ repository: SourceControlProvider.transportSafeSourceControlErrorValue(+ input.repository,),- detail: "Failed to check out change request.",+ detail: repositoryDetail(error, "Failed to create repository."),cause: error,}),),- ),+ );+ },+ ),+ getDefaultBranch: Effect.fn("BitbucketSourceControlProvider.getDefaultBranch")(+ function (input) {+ return bitbucket+ .getDefaultBranch({+ cwd: input.cwd,+ ...(input.context ? { context: input.context } : {}),+ })+ .pipe(+ Effect.mapError(+ (error) =>+ new SourceControlProviderError({+ provider: SourceControlProviderKind.make("bitbucket"),+ operation: "getDefaultBranch",+ cwd: input.cwd,+ detail: "Failed to get default branch.",+ cause: error,+ }),+ ),+ );+ },+ ),+ checkoutChangeRequest: Effect.fn("BitbucketSourceControlProvider.checkoutChangeRequest")(+ function (input) {+ return bitbucket+ .checkoutPullRequest({+ cwd: input.cwd,+ ...(input.context ? { context: input.context } : {}),+ reference: input.reference,+ ...(input.force !== undefined ? { force: input.force } : {}),+ })+ .pipe(+ Effect.mapError(+ (error) =>+ new SourceControlProviderError({+ provider: SourceControlProviderKind.make("bitbucket"),+ operation: "checkoutChangeRequest",+ cwd: input.cwd,+ reference: SourceControlProvider.transportSafeSourceControlErrorValue(+ input.reference,+ ),+ detail: "Failed to check out change request.",+ cause: error,+ }),+ ),+ );+ },+ ),});});diff --git a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.tsindex 26e90d40b23..3557a5c92eb 100644--- a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts+++ b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts@@ -356,11 +356,12 @@ export const make = Effect.gen(function* () {},(effect, input) => effect.pipe(mapError("listChangeRequests", input.cwd)),),- getChangeRequest: (input) =>- getPull(input).pipe(+ getChangeRequest: Effect.fn("ForgejoSourceControlProvider.getChangeRequest")(function (input) {+ return getPull(input).pipe(Effect.map(toForgejoChangeRequest),mapError("getChangeRequest", input.cwd),- ),+ );+ }),createChangeRequest: Effect.fn("ForgejoSourceControlProvider.createChangeRequest")(function* (input) {const repo = yield* cli.resolveRepository(input);diff --git a/packages/source-control-gitcafe/src/server/GitCafeCredentials.ts b/packages/source-control-gitcafe/src/server/GitCafeCredentials.tsindex de0133d303a..1d482de1ebb 100644--- a/packages/source-control-gitcafe/src/server/GitCafeCredentials.ts+++ b/packages/source-control-gitcafe/src/server/GitCafeCredentials.ts@@ -160,8 +160,8 @@ export const make = Effect.gen(function* () {});return GitCafeCredentials.of({- get: (host) =>- fromSettings(host).pipe(+ get: Effect.fn("GitCafeCredentials.get")(function (host) {+ return fromSettings(host).pipe(Effect.flatMap((saved): Effect.Effect<GitCafeCredential, GitCafeCredentialUnavailableError> =>saved === null@@ -172,10 +172,16 @@ export const make = Effect.gen(function* () {source: "settings",}),),- ),- invalidate: (host) => Cache.invalidate(cache, normalizeHost(host)),- cliEnv: (host) =>- fromSettings(host).pipe(Effect.map((saved) => (saved === null ? {} : { CAFE_TOKEN: saved }))),+ );+ }),+ invalidate: Effect.fn("GitCafeCredentials.invalidate")(function (host) {+ return Cache.invalidate(cache, normalizeHost(host));+ }),+ cliEnv: Effect.fn("GitCafeCredentials.cliEnv")(function (host) {+ return fromSettings(host).pipe(+ Effect.map((saved) => (saved === null ? {} : { CAFE_TOKEN: saved })),+ );+ }),});});diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.tsindex f372c8a2c33..1d4b7338f3c 100644--- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts+++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts@@ -786,7 +786,7 @@ export const make = Effect.gen(function* () {{ ...input, authorNarrowed: actorId !== undefined && input.involvement === "authored" },base,);- const readPage = (rows: number, after: string | null) => {+ const readPage = Effect.fn("readPage")(function (rows: number, after: string | null) {const query = new URLSearchParams({ limit: String(rows), sort: "newest" });if (input.state !== "all") query.set("state", input.state);if (input.query?.trim()) query.set("q", input.query.trim());@@ -803,7 +803,7 @@ export const make = Effect.gen(function* () {{ path: `${base}/pulls?${query}` },Json.GitCafePulls,).pipe(Effect.tap((page) => Effect.sync(() => learnAuthors(input.host, page.items))));- };+ });if (unresolvedAuthor !== null) {// Rows are only ever handed out narrowed by actor, so a continuation always carries on// the same narrowed listing.diff --git a/packages/source-control-github/src/server/GitHubCredentials.ts b/packages/source-control-github/src/server/GitHubCredentials.tsindex 63c7ef29ddc..6f72954c4cf 100644--- a/packages/source-control-github/src/server/GitHubCredentials.ts+++ b/packages/source-control-github/src/server/GitHubCredentials.ts@@ -237,12 +237,12 @@ export const make = Effect.gen(function* () {}return yield* Cache.get(cache, cacheKey(host, choice?.account));}),- invalidate: (rawHost) => {+ invalidate: Effect.fn("GitHubCredentials.invalidate")(function (rawHost) {const host = normalizeHost(rawHost);return hostChoice(host).pipe(Effect.flatMap((choice) => Cache.invalidate(cache, cacheKey(host, choice?.account))),);- },+ }),});});diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.tsindex 49aaaa83318..a35ff2e2d0a 100644--- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts@@ -961,24 +961,24 @@ export const make = Effect.gen(function* () {decodeRoutingIdentity(response.body).pipe(Effect.mapError(unavailable)),),Effect.catchTags({- GitHubApiResponseError: (error) =>- Effect.gen(function* () {- if (error.status !== 403) return yield* error;- const { viewer } = yield* client.RoutingIdentityViewer({}).pipe(- GitHubGraphQlClient.call({- host,- operation: "getRoutingIdentity",- allowReserve: true,- }),- Effect.catchTags({- GraphQLClientError: () => Effect.fail(unavailable()),- }),- );- return yield* decodeViewerIdentity({- id: viewer.databaseId,- login: viewer.login,- }).pipe(Effect.mapError(unavailable));- }),+ // The enclosing operation owns the span for this inline handler.+ GitHubApiResponseError: Effect.fnUntraced(function* (error) {+ if (error.status !== 403) return yield* error;+ const { viewer } = yield* client.RoutingIdentityViewer({}).pipe(+ GitHubGraphQlClient.call({+ host,+ operation: "getRoutingIdentity",+ allowReserve: true,+ }),+ Effect.catchTags({+ GraphQLClientError: () => Effect.fail(unavailable()),+ }),+ );+ return yield* decodeViewerIdentity({+ id: viewer.databaseId,+ login: viewer.login,+ }).pipe(Effect.mapError(unavailable));+ }),}),Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, credential),Effect.provideService(SourceControlRateLimit.CredentialScope, key),@@ -1708,10 +1708,11 @@ export const make = Effect.gen(function* () {withVerifiedCredential,revalidateChecks,getRoutingIdentity,- getViewerLogin: (input) =>- getRoutingIdentity(input).pipe(Effect.map((identity) => identity.viewer)),+ getViewerLogin: Effect.fn("GitHubPullRequestApi.getViewerLogin")(function (input) {+ return getRoutingIdentity(input).pipe(Effect.map((identity) => identity.viewer));+ }),- listPullRequests: (input) => {+ listPullRequests: Effect.fn("GitHubPullRequestApi.listPullRequests")(function (input) {const fallbackMaxRows = Math.max(input.limit + 1, PULL_REQUEST_FALLBACK_MAX_ROWS);const { owner, name } = parseRepositorySelector(input.repository);const query = searchQuery({ ...input, repositories: [input.repository] });@@ -1870,20 +1871,18 @@ export const make = Effect.gen(function* () {),),);- },+ }),- searchPullRequests: (input) => {+ searchPullRequests: Effect.fn("GitHubPullRequestApi.searchPullRequests")(function* (input) {const query = searchQuery(input);if (query === null) {- return Effect.fail(- new GitHubRepositorySelectorError({- cwd: input.cwd,- operation: "searchPullRequests",- }),- );+ return yield* new GitHubRepositorySelectorError({+ cwd: input.cwd,+ operation: "searchPullRequests",+ });}const rows = Math.min(input.limit + 1, PULL_REQUEST_SEARCH_MAX_ROWS);- return client+ return yield* client.PullRequestSearch({q: query,first: rows,@@ -1903,7 +1902,7 @@ export const make = Effect.gen(function* () {};}),);- },+ }),listPullRequestStats: Effect.fn("GitHubPullRequestApi.listPullRequestStats")(function* (input) {@@ -1943,20 +1942,22 @@ export const make = Effect.gen(function* () {getPullRequestWatchFingerprint,getPullRequestDetail,- getPullRequestPreview: (input) => {- const { owner, name } = parseRepositorySelector(input.repository);- const operation = "getPullRequestPreview";- return client- .PullRequestPreview({ owner, name, number: input.number })- .pipe(- graphql({ ...input, operation }),- Effect.map(toPullRequestPreview),- Effect.flatMap(found({ ...input, operation })),- );- },+ getPullRequestPreview: Effect.fn("GitHubPullRequestApi.getPullRequestPreview")(+ function (input) {+ const { owner, name } = parseRepositorySelector(input.repository);+ const operation = "getPullRequestPreview";+ return client+ .PullRequestPreview({ owner, name, number: input.number })+ .pipe(+ graphql({ ...input, operation }),+ Effect.map(toPullRequestPreview),+ Effect.flatMap(found({ ...input, operation })),+ );+ },+ ),listWorkflowRunsRequiringApproval,- getPullRequestStack: (input) => {+ getPullRequestStack: Effect.fn("GitHubPullRequestApi.getPullRequestStack")(function (input) {const { owner, name } = parseRepositorySelector(input.repository);// Polled by the pull request sync for every linked pull request, so revalidate it.return revalidatedRestRead({@@ -1982,7 +1983,7 @@ export const make = Effect.gen(function* () {GitHubApiNotFoundError: () => Effect.succeed(null),}),);- },+ }),getPullRequestActivity: Effect.fn("GitHubPullRequestApi.getPullRequestActivity")(function* (input) {@@ -2043,7 +2044,7 @@ export const make = Effect.gen(function* () {},),- getPullRequestDiff: (input) => {+ getPullRequestDiff: Effect.fn("GitHubPullRequestApi.getPullRequestDiff")(function (input) {const filesPage = (page: number) =>diffFilesPage({cwd: input.cwd,@@ -2086,35 +2087,37 @@ export const make = Effect.gen(function* () {GitHubApiResponseError: (error) => filesPage(1).pipe(Effect.mapError(() => error)),}),);- },+ }),getPullRequestDiffFileContents,- getReviewThreadComments: (input) => {- const { owner, name } = parseRepositorySelector(input.repository);- return client- .ReviewThreadComments({- owner,- name,- number: input.number,- threadId: input.threadId,- after: input.cursor,- })- .pipe(- graphql({ ...input, operation: "getReviewThreadComments" }),- Effect.map(toReviewThreadCommentsPage),- Effect.flatMap(({ belongsToPullRequest, comments, nextCursor }) =>- belongsToPullRequest- ? Effect.succeed({ comments, nextCursor })- : Effect.fail(- new GitHubSubjectScopeError({- cwd: input.cwd,- operation: "getReviewThreadComments",- }),- ),- ),- );- },+ getReviewThreadComments: Effect.fn("GitHubPullRequestApi.getReviewThreadComments")(+ function (input) {+ const { owner, name } = parseRepositorySelector(input.repository);+ return client+ .ReviewThreadComments({+ owner,+ name,+ number: input.number,+ threadId: input.threadId,+ after: input.cursor,+ })+ .pipe(+ graphql({ ...input, operation: "getReviewThreadComments" }),+ Effect.map(toReviewThreadCommentsPage),+ Effect.flatMap(({ belongsToPullRequest, comments, nextCursor }) =>+ belongsToPullRequest+ ? Effect.succeed({ comments, nextCursor })+ : Effect.fail(+ new GitHubSubjectScopeError({+ cwd: input.cwd,+ operation: "getReviewThreadComments",+ }),+ ),+ ),+ );+ },+ ),listReviewThreadComments: Effect.fn("GitHubPullRequestApi.listReviewThreadComments")(function* (input) {@@ -2226,16 +2229,16 @@ export const make = Effect.gen(function* () {},),- listActorAvatars: (input) => {+ listActorAvatars: Effect.fn("GitHubPullRequestApi.listActorAvatars")(function (input) {if (input.ids.length === 0) {return Effect.succeed(new Map<string, string>());}return client.ActorAvatars({ ids: input.ids }).pipe(graphql({ ...input, operation: "listActorAvatars" }), Effect.map(toActorAvatars));- },+ }),- getViewerAccess: (input) => {+ getViewerAccess: Effect.fn("GitHubPullRequestApi.getViewerAccess")(function (input) {const { owner, name } = parseRepositorySelector(input.repository);const operation = "getViewerAccess";return client@@ -2245,21 +2248,23 @@ export const make = Effect.gen(function* () {Effect.map(toViewerPermissions),Effect.flatMap(found({ ...input, operation })),);- },+ }),- listReviewerCandidates: (input) => {- const { owner, name } = parseRepositorySelector(input.repository);- const operation = "listReviewerCandidates";- return client- .ReviewerCandidates({ owner, name, number: input.number })- .pipe(- graphql({ ...input, operation, allowReserve: true }),- Effect.map(toReviewerCandidates),- Effect.flatMap(found({ ...input, operation })),- );- },+ listReviewerCandidates: Effect.fn("GitHubPullRequestApi.listReviewerCandidates")(+ function (input) {+ const { owner, name } = parseRepositorySelector(input.repository);+ const operation = "listReviewerCandidates";+ return client+ .ReviewerCandidates({ owner, name, number: input.number })+ .pipe(+ graphql({ ...input, operation, allowReserve: true }),+ Effect.map(toReviewerCandidates),+ Effect.flatMap(found({ ...input, operation })),+ );+ },+ ),- setReviewerRequest: (input) => {+ setReviewerRequest: Effect.fn("GitHubPullRequestApi.setReviewerRequest")(function (input) {const { owner, name } = parseRepositorySelector(input.repository);return api.rest({@@ -2270,9 +2275,9 @@ export const make = Effect.gen(function* () {body: buildReviewerRequest(input.reviewers),}).pipe(Effect.asVoid);- },+ }),- listLabelCandidates: (input) => {+ listLabelCandidates: Effect.fn("GitHubPullRequestApi.listLabelCandidates")(function (input) {const { owner, name } = parseRepositorySelector(input.repository);const operation = "listLabelCandidates";return client@@ -2282,9 +2287,9 @@ export const make = Effect.gen(function* () {Effect.map(toLabelCandidates),Effect.flatMap(found({ ...input, operation })),);- },+ }),- listRepositoryLabels: (input) => {+ listRepositoryLabels: Effect.fn("GitHubPullRequestApi.listRepositoryLabels")(function (input) {const { owner, name } = parseRepositorySelector(input.repository);const operation = "listRepositoryLabels";return client@@ -2294,21 +2299,23 @@ export const make = Effect.gen(function* () {Effect.map(toRepositoryLabels),Effect.flatMap(found({ ...input, operation })),);- },+ }),- searchRepositoryAuthors: (input) => {- const { owner, name } = parseRepositorySelector(input.repository);- const operation = "searchRepositoryAuthors";- return client- .RepositoryAuthors({ owner, name, query: input.query ?? null })- .pipe(- graphql({ ...input, operation, allowReserve: true }),- Effect.map(toRepositoryAuthors),- Effect.flatMap(found({ ...input, operation })),- );- },+ searchRepositoryAuthors: Effect.fn("GitHubPullRequestApi.searchRepositoryAuthors")(+ function (input) {+ const { owner, name } = parseRepositorySelector(input.repository);+ const operation = "searchRepositoryAuthors";+ return client+ .RepositoryAuthors({ owner, name, query: input.query ?? null })+ .pipe(+ graphql({ ...input, operation, allowReserve: true }),+ Effect.map(toRepositoryAuthors),+ Effect.flatMap(found({ ...input, operation })),+ );+ },+ ),- setLabels: (input) => {+ setLabels: Effect.fn("GitHubPullRequestApi.setLabels")(function (input) {const { owner, name } = parseRepositorySelector(input.repository);const issue = `repos/${owner}/${name}/issues/${input.number}/labels`;if (input.applied) {@@ -2333,9 +2340,9 @@ export const make = Effect.gen(function* () {}),{ concurrency: 1, discard: true },);- },+ }),- runPullRequestAction: (input) => {+ runPullRequestAction: Effect.fn("GitHubPullRequestApi.runPullRequestAction")(function (input) {if (input.action === "delete-branch") {return Effect.gen(function* () {if (input.stackNumber !== undefined) {@@ -2589,19 +2596,20 @@ export const make = Effect.gen(function* () {: client.MergePullRequest({ input: merge }).pipe(Effect.asVoid)).pipe(graphql(target));});- },+ }),- commentOnPullRequest: (input) =>- pullRequestNodeId({ ...input, operation: "commentOnPullRequest" }).pipe(+ commentOnPullRequest: Effect.fn("GitHubPullRequestApi.commentOnPullRequest")(function (input) {+ return pullRequestNodeId({ ...input, operation: "commentOnPullRequest" }).pipe(Effect.flatMap((subjectId) =>client.AddComment({ subjectId, body: input.body }).pipe(graphql({ ...input, operation: "commentOnPullRequest" })),),Effect.asVoid,- ),+ );+ }),- submitReview: (input) => {+ submitReview: Effect.fn("GitHubPullRequestApi.submitReview")(function (input) {const { owner, name } = parseRepositorySelector(input.repository);return api.rest({@@ -2616,96 +2624,107 @@ export const make = Effect.gen(function* () {}),}).pipe(Effect.asVoid);- },+ }),- replyToReviewThread: (input) =>- client+ replyToReviewThread: Effect.fn("GitHubPullRequestApi.replyToReviewThread")(function (input) {+ return client.AddReviewThreadReply({ threadId: input.threadId, body: input.body })- .pipe(graphql({ ...input, operation: "replyToReviewThread" }), Effect.asVoid),+ .pipe(graphql({ ...input, operation: "replyToReviewThread" }), Effect.asVoid);+ }),- getPullRequestFilesViewed: (input) => {- const { owner, name } = parseRepositorySelector(input.repository);- const target = { ...input, operation: "getPullRequestFilesViewed" };- return readPages(- GraphQLClient.pages(client.PullRequestFilesViewed, {- variables: { owner, name, number: input.number },- connection: (result) => {- const page = toPullRequestFilesViewedPage(result);- return {- ...page,- pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },- };+ getPullRequestFilesViewed: Effect.fn("GitHubPullRequestApi.getPullRequestFilesViewed")(+ function (input) {+ const { owner, name } = parseRepositorySelector(input.repository);+ const target = { ...input, operation: "getPullRequestFilesViewed" };+ return readPages(+ GraphQLClient.pages(client.PullRequestFilesViewed, {+ variables: { owner, name, number: input.number },+ connection: (result) => {+ const page = toPullRequestFilesViewedPage(result);+ return {+ ...page,+ pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },+ };+ },+ }),+ {+ ...target,+ maxPages: FILES_VIEWED_MAX_PAGES,+ hasNextPage: (page) => page.nextCursor !== null,},- }),- {- ...target,- maxPages: FILES_VIEWED_MAX_PAGES,- hasNextPage: (page) => page.nextCursor !== null,- },- ).pipe(- graphql(target),- Effect.map(({ pages, truncated }) => ({- files: pages.flatMap((page) => page.files),- truncated,- })),- );- },+ ).pipe(+ graphql(target),+ Effect.map(({ pages, truncated }) => ({+ files: pages.flatMap((page) => page.files),+ truncated,+ })),+ );+ },+ ),- getPullRequestFileStats: (input) => {- const { owner, name } = parseRepositorySelector(input.repository);- const target = { ...input, operation: "getPullRequestFileStats" };- return readPages(- GraphQLClient.pages(client.PullRequestFileStats, {- variables: { owner, name, number: input.number },- connection: (result) => {- const page = toPullRequestFileStatsPage(result);- return {- ...page,- pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },- };+ getPullRequestFileStats: Effect.fn("GitHubPullRequestApi.getPullRequestFileStats")(+ function (input) {+ const { owner, name } = parseRepositorySelector(input.repository);+ const target = { ...input, operation: "getPullRequestFileStats" };+ return readPages(+ GraphQLClient.pages(client.PullRequestFileStats, {+ variables: { owner, name, number: input.number },+ connection: (result) => {+ const page = toPullRequestFileStatsPage(result);+ return {+ ...page,+ pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },+ };+ },+ }),+ {+ ...target,+ maxPages: FILES_VIEWED_MAX_PAGES,+ hasNextPage: (page) => page.nextCursor !== null,},- }),- {- ...target,- maxPages: FILES_VIEWED_MAX_PAGES,- hasNextPage: (page) => page.nextCursor !== null,- },- ).pipe(- graphql(target),- Effect.map(({ pages, truncated }) => ({- files: pages.flatMap((page) => page.files),- truncated,- })),- );- },+ ).pipe(+ graphql(target),+ Effect.map(({ pages, truncated }) => ({+ files: pages.flatMap((page) => page.files),+ truncated,+ })),+ );+ },+ ),- setPullRequestFilesViewed: (input) => {- if (input.files.length === 0) return Effect.void;- const target = { ...input, operation: "setPullRequestFilesViewed" };- return pullRequestNodeId(target).pipe(- Effect.flatMap((pullRequestId) =>- // Top-level mutation fields run in order, so the last toggle for a path wins.- Effect.forEach(- input.files,- (file) =>- GraphQLResolver.request(- { pullRequestId, path: file.path, viewed: file.viewed },- setFileViewedResolver,- ),- { concurrency: "unbounded", discard: true },+ setPullRequestFilesViewed: Effect.fn("GitHubPullRequestApi.setPullRequestFilesViewed")(+ function (input) {+ if (input.files.length === 0) return Effect.void;+ const target = { ...input, operation: "setPullRequestFilesViewed" };+ return pullRequestNodeId(target).pipe(+ Effect.flatMap((pullRequestId) =>+ // Top-level mutation fields run in order, so the last toggle for a path wins.+ Effect.forEach(+ input.files,+ (file) =>+ GraphQLResolver.request(+ { pullRequestId, path: file.path, viewed: file.viewed },+ setFileViewedResolver,+ ),+ { concurrency: "unbounded", discard: true },+ ),),- ),- graphql(target),- );- },+ graphql(target),+ );+ },+ ),- setReviewThreadResolution: (input) =>- (input.resolved- ? client.ResolveReviewThread({ threadId: input.threadId }).pipe(Effect.asVoid)- : client.UnresolveReviewThread({ threadId: input.threadId }).pipe(Effect.asVoid)- ).pipe(graphql({ ...input, operation: "setReviewThreadResolution" })),+ setReviewThreadResolution: Effect.fn("GitHubPullRequestApi.setReviewThreadResolution")(+ function (input) {+ return (+ input.resolved+ ? client.ResolveReviewThread({ threadId: input.threadId }).pipe(Effect.asVoid)+ : client.UnresolveReviewThread({ threadId: input.threadId }).pipe(Effect.asVoid)+ ).pipe(graphql({ ...input, operation: "setReviewThreadResolution" }));+ },+ ),- setReaction: (input) => {+ setReaction: Effect.fn("GitHubPullRequestApi.setReaction")(function (input) {const givenSubjectId = input.subjectId;const subjectId =givenSubjectId === undefined@@ -2736,10 +2755,10 @@ export const make = Effect.gen(function* () {).pipe(graphql({ ...input, operation: "setReaction" }));}),);- },+ }),- updatePullRequest: (input) =>- pullRequestNodeId({ ...input, operation: "updatePullRequest" }).pipe(+ updatePullRequest: Effect.fn("GitHubPullRequestApi.updatePullRequest")(function (input) {+ return pullRequestNodeId({ ...input, operation: "updatePullRequest" }).pipe(Effect.flatMap((pullRequestId) =>client.UpdatePullRequest({@@ -2750,10 +2769,11 @@ export const make = Effect.gen(function* () {.pipe(graphql({ ...input, operation: "updatePullRequest" })),),Effect.asVoid,- ),+ );+ }),- updateComment: (input) =>- subjectBelongsToPullRequest({+ updateComment: Effect.fn("GitHubPullRequestApi.updateComment")(function (input) {+ return subjectBelongsToPullRequest({cwd: input.cwd,repository: input.repository,host: input.host,@@ -2779,7 +2799,8 @@ export const make = Effect.gen(function* () {: client.UpdateReviewComment(variables).pipe(Effect.asVoid)).pipe(graphql({ ...input, operation: "updateComment" }));}),- ),+ );+ }),});});diff --git a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts b/packages/source-control-github/src/server/GitHubSourceControlProvider.tsindex b855e148566..60502a138ea 100644--- a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts+++ b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts@@ -844,8 +844,11 @@ export const make = Effect.gen(function* () {headSelectors: headSelectors.filter((selector) => !selector.includes(":")),limit: 100,}),- readChangeRequestTemplate: ({ cwd, treeish }) =>- GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute),+ readChangeRequestTemplate: Effect.fn("GitHubSourceControlProvider.readChangeRequestTemplate")(+ function ({ cwd, treeish }) {+ return GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute);+ },+ ),// `createChangeRequest` targets what `resolveRepository` picks: GH_REPO when it parses, else// the remote `gh repo set-default` marked (`gh-resolved`). An HTTPS remote keeps a// non-default port in the context's host, and the mark is then ignored.@@ -882,8 +885,12 @@ export const make = Effect.gen(function* () {),// `gh pr create` run in the checkout, as an agent in a T3 worktree often does, takes its base// from this key.- recordBranchBase: ({ cwd, branch, baseBranch }) =>- git+ recordBranchBase: Effect.fn("GitHubSourceControlProvider.recordBranchBase")(function ({+ cwd,+ branch,+ baseBranch,+ }) {+ return git.execute({operation: "GitHubSourceControlProvider.recordBranchBase",cwd,@@ -894,7 +901,8 @@ export const make = Effect.gen(function* () {Effect.catch((cause) =>Effect.logWarning("Could not record the branch base for gh", { cause }),),- ),+ );+ }),resolveLink: (input) => {// Automatic enrichment must not send ambient CLI credentials to a host from message text.if (input.url.host !== "github.com") return undefined;@@ -904,31 +912,37 @@ export const make = Effect.gen(function* () {if (!match) return undefined;return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);},- listChangeRequests: (input) =>- (input.state === "open" ? Effect.succeed(true) : SourceControlRateLimit.Interactive).pipe(- Effect.flatMap((allowReserve) =>- listByHead({- cwd: input.cwd,- headSelector: input.headSelector,- state: input.state,- limit: input.limit ?? (input.state === "open" ? 1 : 20),- host: contextHost(input.context),- context: input.context,- allowReserve,- }),- ),- Effect.map((records) => records.map(toChangeRequest)),- Effect.mapError(- providerError("listChangeRequests", input.cwd, { reference: input.headSelector }),- ),- ),- getChangeRequest: (input) =>- readPullRequest({ ...input, host: contextHost(input.context) }).pipe(+ listChangeRequests: Effect.fn("GitHubSourceControlProvider.listChangeRequests")(+ function (input) {+ return (+ input.state === "open" ? Effect.succeed(true) : SourceControlRateLimit.Interactive+ ).pipe(+ Effect.flatMap((allowReserve) =>+ listByHead({+ cwd: input.cwd,+ headSelector: input.headSelector,+ state: input.state,+ limit: input.limit ?? (input.state === "open" ? 1 : 20),+ host: contextHost(input.context),+ context: input.context,+ allowReserve,+ }),+ ),+ Effect.map((records) => records.map(toChangeRequest)),+ Effect.mapError(+ providerError("listChangeRequests", input.cwd, { reference: input.headSelector }),+ ),+ );+ },+ ),+ getChangeRequest: Effect.fn("GitHubSourceControlProvider.getChangeRequest")(function (input) {+ return readPullRequest({ ...input, host: contextHost(input.context) }).pipe(Effect.map(toChangeRequest),Effect.mapError(providerError("getChangeRequest", input.cwd, { reference: input.reference }),),- ),+ );+ }),createChangeRequest: Effect.fn("GitHubSourceControlProvider.createChangeRequest")(function* (input) {const locator = yield* resolveRepository(input);@@ -1033,11 +1047,14 @@ export const make = Effect.gen(function* () {},(effect, input) => effect.pipe(Effect.mapError(providerError("getDefaultBranch", input.cwd))),),- checkoutChangeRequest: (input) =>- checkoutPullRequest(input).pipe(- Effect.mapError(- providerError("checkoutChangeRequest", input.cwd, { reference: input.reference }),- ),- ),+ checkoutChangeRequest: Effect.fn("GitHubSourceControlProvider.checkoutChangeRequest")(+ function (input) {+ return checkoutPullRequest(input).pipe(+ Effect.mapError(+ providerError("checkoutChangeRequest", input.cwd, { reference: input.reference }),+ ),+ );+ },+ ),});});diff --git a/packages/source-control-gitlab/src/server/GitLabCli.ts b/packages/source-control-gitlab/src/server/GitLabCli.tsindex 27c0650b133..0234b6fcd9f 100644--- a/packages/source-control-gitlab/src/server/GitLabCli.ts+++ b/packages/source-control-gitlab/src/server/GitLabCli.ts@@ -467,8 +467,8 @@ export const make = Effect.gen(function* () {return GitLabCli.of({execute,- listMergeRequests: (input) =>- execute({+ listMergeRequests: Effect.fn("GitLabCli.listMergeRequests")(function (input) {+ return execute({cwd: input.cwd,args: ["mr",@@ -503,9 +503,10 @@ export const make = Effect.gen(function* () {}),),),- ),- getMergeRequest: (input) =>- executeMergeRequest({+ );+ }),+ getMergeRequest: Effect.fn("GitLabCli.getMergeRequest")(function (input) {+ return executeMergeRequest({cwd: input.cwd,reference: input.reference,args: ["mr", "view", "--output", "json", "--", input.reference],@@ -530,9 +531,10 @@ export const make = Effect.gen(function* () {}),),),- ),- getRepositoryCloneUrls: (input) =>- execute({+ );+ }),+ getRepositoryCloneUrls: Effect.fn("GitLabCli.getRepositoryCloneUrls")(function (input) {+ return execute({cwd: input.cwd,args: ["api", `projects/${encodeURIComponent(input.repository)}`],}).pipe(@@ -552,8 +554,9 @@ export const make = Effect.gen(function* () {),),Effect.map(normalizeRepositoryCloneUrls),- ),- createRepository: (input) => {+ );+ }),+ createRepository: Effect.fn("GitLabCli.createRepository")(function (input) {const { namespacePath, projectPath } = parseRepositoryPath(input.repository);const namespaceId: Effect.Effect<number | null, GitLabCliError> = namespacePath? execute({@@ -617,8 +620,8 @@ export const make = Effect.gen(function* () {),Effect.map(normalizeRepositoryCloneUrls),);- },- createMergeRequest: (input) => {+ }),+ createMergeRequest: Effect.fn("GitLabCli.createMergeRequest")(function (input) {const sourceProject = sourceProjectIdentifier(input.source);return execute({cwd: input.cwd,@@ -638,9 +641,9 @@ export const make = Effect.gen(function* () {`description=@${input.bodyFile}`,],}).pipe(Effect.asVoid);- },- getDefaultBranch: (input) =>- execute({+ }),+ getDefaultBranch: Effect.fn("GitLabCli.getDefaultBranch")(function (input) {+ return execute({cwd: input.cwd,args: ["api", "projects/:fullpath"],}).pipe(@@ -659,13 +662,15 @@ export const make = Effect.gen(function* () {),),Effect.map((value) => value.default_branch ?? null),- ),- checkoutMergeRequest: (input) =>- executeMergeRequest({+ );+ }),+ checkoutMergeRequest: Effect.fn("GitLabCli.checkoutMergeRequest")(function (input) {+ return executeMergeRequest({cwd: input.cwd,reference: input.reference,args: ["mr", "checkout", "--", input.reference],- }).pipe(Effect.asVoid),+ }).pipe(Effect.asVoid);+ }),});});diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.tsindex 037bf947955..5ae6ab3b47c 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts@@ -1120,17 +1120,21 @@ export const make = Effect.gen(function* () {return GitLabPullRequestCli.of({getViewerUsername: viewerUsername,- listMergeRequests: (input) => {+ listMergeRequests: Effect.fn("GitLabPullRequestCli.listMergeRequests")(function (input) {const perPage = Math.min(input.limit + 1, MAX_PAGE_SIZE);const page = Math.floor((input.cursor?.delivered ?? 0) / perPage) + 1;return listPage({ ...input, page, collected: [], cursorAdvance: 0 });- },+ }),getMergeRequestDetail: mergeRequestDetail,- listNotes: (input) => notesPage({ ...input, page: 1, collected: [] }),+ listNotes: Effect.fn("GitLabPullRequestCli.listNotes")(function (input) {+ return notesPage({ ...input, page: 1, collected: [] });+ }),- listReactions: (input) => awardsPage({ ...input, cursor: null, page: 1, collected: null }),+ listReactions: Effect.fn("GitLabPullRequestCli.listReactions")(function (input) {+ return awardsPage({ ...input, cursor: null, page: 1, collected: null });+ }),getFileRevisions: fileRevisions,@@ -1168,8 +1172,8 @@ export const make = Effect.gen(function* () {});}),- listCommits: (input) =>- api({+ listCommits: Effect.fn("GitLabPullRequestCli.listCommits")(function (input) {+ return api({cwd: input.cwd,path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/commits?${query([@@ -1191,11 +1195,12 @@ export const make = Effect.gen(function* () {}),);}),- ),+ );+ }),- getMergeRequestDiff: (input) => {+ getMergeRequestDiff: Effect.fn("GitLabPullRequestCli.getMergeRequestDiff")(function* (input) {if (input.commit !== undefined && !isCommitSha(input.commit)) {- return Effect.fail(new GitLabDiffCommitError({ command: "glab", cwd: input.cwd }));+ return yield* new GitLabDiffCommitError({ command: "glab", cwd: input.cwd });}const target = {cwd: input.cwd,@@ -1204,13 +1209,13 @@ export const make = Effect.gen(function* () {...(input.commit === undefined ? {} : { commit: input.commit }),};if (input.cursor === undefined) {- return diffPage({ ...target, page: 1 });+ return yield* diffPage({ ...target, page: 1 });}const page = diffCursorPage(input.cursor);- return page === null- ? Effect.fail(new GitLabDiffCursorError({ command: "glab", cwd: input.cwd }))- : diffPage({ ...target, page });- },+ if (page === null)+ return yield* new GitLabDiffCursorError({ command: "glab", cwd: input.cwd });+ return yield* diffPage({ ...target, page });+ }),getMergeRequestDiffFileContents: Effect.fn("GitLabPullRequestCli.getMergeRequestDiffFileContents",@@ -1264,28 +1269,31 @@ export const make = Effect.gen(function* () {return { oldContents, newContents };}),- getProjectMergeCapabilities: (input) =>- api({- cwd: input.cwd,- path: `projects/${projectPath(input.repository)}?license=false`,- }).pipe(- Effect.flatMap((result) => {- const decoded = decodeProjectMergeCapabilitiesJson(result.stdout.trim());- return Result.isSuccess(decoded)- ? Effect.succeed(decoded.success)- : Effect.fail(- new GitLabMergeRequestReadError({- command: "glab",- cwd: input.cwd,- operation: "getProjectMergeCapabilities",- cause: decoded.failure,- }),- );- }),- ),+ getProjectMergeCapabilities: Effect.fn("GitLabPullRequestCli.getProjectMergeCapabilities")(+ function (input) {+ return api({+ cwd: input.cwd,+ path: `projects/${projectPath(input.repository)}?license=false`,+ }).pipe(+ Effect.flatMap((result) => {+ const decoded = decodeProjectMergeCapabilitiesJson(result.stdout.trim());+ return Result.isSuccess(decoded)+ ? Effect.succeed(decoded.success)+ : Effect.fail(+ new GitLabMergeRequestReadError({+ command: "glab",+ cwd: input.cwd,+ operation: "getProjectMergeCapabilities",+ cause: decoded.failure,+ }),+ );+ }),+ );+ },+ ),- listProjectLabels: (input) =>- api({+ listProjectLabels: Effect.fn("GitLabPullRequestCli.listProjectLabels")(function (input) {+ return api({cwd: input.cwd,path: `projects/${projectPath(input.repository)}/labels?${query([["per_page", String(MAX_PAGE_SIZE)],@@ -1308,35 +1316,42 @@ export const make = Effect.gen(function* () {}),);}),- ),+ );+ }),- listProjectUsers: (input) =>- projectUsers(input).pipe(+ listProjectUsers: Effect.fn("GitLabPullRequestCli.listProjectUsers")(function (input) {+ return projectUsers(input).pipe(Effect.map(({ candidates, rawCount }) => ({items: candidates.map(({ login, name, avatarUrl }) => ({ login, name, avatarUrl })),truncated: rawCount >= MAX_PAGE_SIZE,})),- ),+ );+ }),- listReviewerCandidates: (input) =>- Effect.all([mergeRequestDetail(input), projectUsers(input)], { concurrency: 2 }).pipe(- Effect.map(([mergeRequest, users]) => {- const author = mergeRequest.author?.login;- const requested = new Set(mergeRequest.reviewRequestLogins);- return {- // GitLab forbids requesting a review from the MR author.- candidates: users.candidates.flatMap((candidate) =>- candidate.login === author- ? []- : [{ ...candidate, isRequested: requested.has(candidate.login) }],- ),- truncated: users.rawCount >= MAX_PAGE_SIZE,- };- }),- ),+ listReviewerCandidates: Effect.fn("GitLabPullRequestCli.listReviewerCandidates")(+ function (input) {+ return Effect.all([mergeRequestDetail(input), projectUsers(input)], {+ concurrency: 2,+ }).pipe(+ Effect.map(([mergeRequest, users]) => {+ const author = mergeRequest.author?.login;+ const requested = new Set(mergeRequest.reviewRequestLogins);+ return {+ // GitLab forbids requesting a review from the MR author.+ candidates: users.candidates.flatMap((candidate) =>+ candidate.login === author+ ? []+ : [{ ...candidate, isRequested: requested.has(candidate.login) }],+ ),+ truncated: users.rawCount >= MAX_PAGE_SIZE,+ };+ }),+ );+ },+ ),- setReviewerRequest: (input) =>- mergeRequestDetail(input).pipe(+ setReviewerRequest: Effect.fn("GitLabPullRequestCli.setReviewerRequest")(function (input) {+ return mergeRequestDetail(input).pipe(Effect.flatMap((mergeRequest) => {// GitLab replaces reviewer_ids wholesale.const ids = new Set(mergeRequest.reviewerIds);@@ -1354,7 +1369,8 @@ export const make = Effect.gen(function* () {});}),Effect.asVoid,- ),+ );+ }),runMergeRequestAction: Effect.fn("GitLabPullRequestCli.runMergeRequestAction")(function* (input) {@@ -1386,8 +1402,8 @@ export const make = Effect.gen(function* () {},),- updateMergeRequest: (input) =>- api({+ updateMergeRequest: Effect.fn("GitLabPullRequestCli.updateMergeRequest")(function (input) {+ return api({cwd: input.cwd,path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,method: "PUT",@@ -1396,28 +1412,35 @@ export const make = Effect.gen(function* () {...(input.title === undefined ? {} : { title: input.title }),...(input.description === undefined ? {} : { description: input.description }),}),- }).pipe(Effect.asVoid),+ }).pipe(Effect.asVoid);+ }),- commentOnMergeRequest: (input) =>- api({- cwd: input.cwd,- path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes`,- method: "POST",- // JSON avoids glab's coercion of numeric/boolean comment bodies.- stdin: JSON.stringify({ body: input.body }),- }).pipe(Effect.asVoid),+ commentOnMergeRequest: Effect.fn("GitLabPullRequestCli.commentOnMergeRequest")(+ function (input) {+ return api({+ cwd: input.cwd,+ path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes`,+ method: "POST",+ // JSON avoids glab's coercion of numeric/boolean comment bodies.+ stdin: JSON.stringify({ body: input.body }),+ }).pipe(Effect.asVoid);+ },+ ),- updateNote: (input) =>- api({+ updateNote: Effect.fn("GitLabPullRequestCli.updateNote")(function (input) {+ return api({cwd: input.cwd,path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes/${encodeURIComponent(input.noteId,)}`,method: "PUT",stdin: JSON.stringify({ body: input.body }),- }).pipe(Effect.asVoid),+ }).pipe(Effect.asVoid);+ }),- listDiscussions: (input) => discussionsPage({ ...input, page: 1, collected: [] }),+ listDiscussions: Effect.fn("GitLabPullRequestCli.listDiscussions")(function (input) {+ return discussionsPage({ ...input, page: 1, collected: [] });+ }),submitReview: Effect.fn("GitLabPullRequestCli.submitReview")(function* (input) {const project = projectPath(input.repository);@@ -1468,25 +1491,29 @@ export const make = Effect.gen(function* () {}}),- replyToDiscussion: (input) =>- api({+ replyToDiscussion: Effect.fn("GitLabPullRequestCli.replyToDiscussion")(function (input) {+ return api({cwd: input.cwd,path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions/${encodeURIComponent(input.discussionId,)}/notes`,method: "POST",stdin: JSON.stringify({ body: input.body }),- }).pipe(Effect.asVoid),+ }).pipe(Effect.asVoid);+ }),- setDiscussionResolution: (input) =>- api({- cwd: input.cwd,- path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions/${encodeURIComponent(- input.discussionId,- )}`,- method: "PUT",- stdin: JSON.stringify({ resolved: input.resolved }),- }).pipe(Effect.asVoid),+ setDiscussionResolution: Effect.fn("GitLabPullRequestCli.setDiscussionResolution")(+ function (input) {+ return api({+ cwd: input.cwd,+ path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions/${encodeURIComponent(+ input.discussionId,+ )}`,+ method: "PUT",+ stdin: JSON.stringify({ resolved: input.resolved }),+ }).pipe(Effect.asVoid);+ },+ ),});});diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.tsindex d614db1218a..beeb6b38af1 100644--- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts+++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts@@ -208,8 +208,11 @@ export const make = Effect.gen(function* () {return SourceControlProvider.SourceControlProvider.of({kind: SourceControlProviderKind.make("gitlab"),- readChangeRequestTemplate: ({ cwd, treeish }) =>- GitLabChangeRequestTemplate.detect(cwd, treeish, git.execute),+ readChangeRequestTemplate: Effect.fn("GitLabSourceControlProvider.readChangeRequestTemplate")(+ function ({ cwd, treeish }) {+ return GitLabChangeRequestTemplate.detect(cwd, treeish, git.execute);+ },+ ),refineRepositoryIdentity,resolveLink: (input) => {// Automatic enrichment must not send ambient CLI credentials to a host from message text.@@ -223,36 +226,38 @@ export const make = Effect.gen(function* () {`projects/${encodeURIComponent(match[1]!)}/${match[2]}/${match[3]}`,);},- listChangeRequests: (input) => {- const source = SourceControlProvider.sourceControlRefFromInput(input);- return gitlab- .listMergeRequests({- cwd: input.cwd,- headSelector: input.headSelector,- ...(source ? { source } : {}),- state: input.state,- ...(input.limit !== undefined ? { limit: input.limit } : {}),- })- .pipe(- Effect.map((items) => items.map(toChangeRequest)),- Effect.mapError(- (error) =>- new SourceControlProviderError({- provider: SourceControlProviderKind.make("gitlab"),- operation: "listChangeRequests",- command: error.command,- cwd: input.cwd,- reference: SourceControlProvider.transportSafeSourceControlErrorValue(- input.headSelector,- ),- detail: error.detail,- cause: error,- }),- ),- );- },- getChangeRequest: (input) =>- gitlab.getMergeRequest(input).pipe(+ listChangeRequests: Effect.fn("GitLabSourceControlProvider.listChangeRequests")(+ function (input) {+ const source = SourceControlProvider.sourceControlRefFromInput(input);+ return gitlab+ .listMergeRequests({+ cwd: input.cwd,+ headSelector: input.headSelector,+ ...(source ? { source } : {}),+ state: input.state,+ ...(input.limit !== undefined ? { limit: input.limit } : {}),+ })+ .pipe(+ Effect.map((items) => items.map(toChangeRequest)),+ Effect.mapError(+ (error) =>+ new SourceControlProviderError({+ provider: SourceControlProviderKind.make("gitlab"),+ operation: "listChangeRequests",+ command: error.command,+ cwd: input.cwd,+ reference: SourceControlProvider.transportSafeSourceControlErrorValue(+ input.headSelector,+ ),+ detail: error.detail,+ cause: error,+ }),+ ),+ );+ },+ ),+ getChangeRequest: Effect.fn("GitLabSourceControlProvider.getChangeRequest")(function (input) {+ return gitlab.getMergeRequest(input).pipe(Effect.map(toChangeRequest),Effect.mapError((error) =>@@ -268,55 +273,61 @@ export const make = Effect.gen(function* () {cause: error,}),),- ),- createChangeRequest: (input) => {- const source = SourceControlProvider.sourceControlRefFromInput(input);- return gitlab- .createMergeRequest({- cwd: input.cwd,- baseBranch: input.baseRefName,- headSelector: input.headSelector,- ...(source ? { source } : {}),- ...(input.target ? { target: input.target } : {}),- title: input.title,- bodyFile: input.bodyFile,- })- .pipe(+ );+ }),+ createChangeRequest: Effect.fn("GitLabSourceControlProvider.createChangeRequest")(+ function (input) {+ const source = SourceControlProvider.sourceControlRefFromInput(input);+ return gitlab+ .createMergeRequest({+ cwd: input.cwd,+ baseBranch: input.baseRefName,+ headSelector: input.headSelector,+ ...(source ? { source } : {}),+ ...(input.target ? { target: input.target } : {}),+ title: input.title,+ bodyFile: input.bodyFile,+ })+ .pipe(+ Effect.mapError(+ (error) =>+ new SourceControlProviderError({+ provider: SourceControlProviderKind.make("gitlab"),+ operation: "createChangeRequest",+ command: error.command,+ cwd: input.cwd,+ reference: SourceControlProvider.transportSafeSourceControlErrorValue(+ input.headSelector,+ ),+ detail: error.detail,+ cause: error,+ }),+ ),+ );+ },+ ),+ getRepositoryCloneUrls: Effect.fn("GitLabSourceControlProvider.getRepositoryCloneUrls")(+ function (input) {+ return gitlab.getRepositoryCloneUrls(input).pipe(Effect.mapError((error) =>new SourceControlProviderError({provider: SourceControlProviderKind.make("gitlab"),- operation: "createChangeRequest",+ operation: "getRepositoryCloneUrls",command: error.command,cwd: input.cwd,- reference: SourceControlProvider.transportSafeSourceControlErrorValue(- input.headSelector,+ repository: SourceControlProvider.transportSafeSourceControlErrorValue(+ input.repository,),detail: error.detail,cause: error,}),),);- },- getRepositoryCloneUrls: (input) =>- gitlab.getRepositoryCloneUrls(input).pipe(- Effect.mapError(- (error) =>- new SourceControlProviderError({- provider: SourceControlProviderKind.make("gitlab"),- operation: "getRepositoryCloneUrls",- command: error.command,- cwd: input.cwd,- repository: SourceControlProvider.transportSafeSourceControlErrorValue(- input.repository,- ),- detail: error.detail,- cause: error,- }),- ),- ),- createRepository: (input) =>- gitlab.createRepository(input).pipe(+ },+ ),+ createRepository: Effect.fn("GitLabSourceControlProvider.createRepository")(function (input) {+ return gitlab.createRepository(input).pipe(Effect.mapError((error) =>new SourceControlProviderError({@@ -331,9 +342,10 @@ export const make = Effect.gen(function* () {cause: error,}),),- ),- getDefaultBranch: (input) =>- gitlab.getDefaultBranch(input).pipe(+ );+ }),+ getDefaultBranch: Effect.fn("GitLabSourceControlProvider.getDefaultBranch")(function (input) {+ return gitlab.getDefaultBranch(input).pipe(Effect.mapError((error) =>new SourceControlProviderError({@@ -345,23 +357,27 @@ export const make = Effect.gen(function* () {cause: error,}),),- ),- checkoutChangeRequest: (input) =>- gitlab.checkoutMergeRequest(input).pipe(- Effect.mapError(- (error) =>- new SourceControlProviderError({- provider: SourceControlProviderKind.make("gitlab"),- operation: "checkoutChangeRequest",- command: error.command,- cwd: input.cwd,- reference: SourceControlProvider.transportSafeSourceControlErrorValue(- input.reference,- ),- detail: error.detail,- cause: error,- }),- ),- ),+ );+ }),+ checkoutChangeRequest: Effect.fn("GitLabSourceControlProvider.checkoutChangeRequest")(+ function (input) {+ return gitlab.checkoutMergeRequest(input).pipe(+ Effect.mapError(+ (error) =>+ new SourceControlProviderError({+ provider: SourceControlProviderKind.make("gitlab"),+ operation: "checkoutChangeRequest",+ command: error.command,+ cwd: input.cwd,+ reference: SourceControlProvider.transportSafeSourceControlErrorValue(+ input.reference,+ ),+ detail: error.detail,+ cause: error,+ }),+ ),+ );+ },+ ),});});diff --git a/packages/ssh/src/auth.ts b/packages/ssh/src/auth.tsindex 1fba0ead710..1ea49363b60 100644--- a/packages/ssh/src/auth.ts+++ b/packages/ssh/src/auth.ts@@ -48,7 +48,9 @@ export class SshPasswordPrompt extends Context.Service<SshPasswordPrompt, SshPasSshPasswordPrompt,SshPasswordPrompt.of({isAvailable: false,- request: () => Effect.succeed(null),+ request: Effect.fn("SshPasswordPrompt.request")(function () {+ return Effect.succeed(null);+ }),}),);}diff --git a/packages/ssh/src/command.ts b/packages/ssh/src/command.tsindex 1b295bf6854..c14b775df95 100644--- a/packages/ssh/src/command.ts+++ b/packages/ssh/src/command.ts@@ -308,22 +308,22 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (Effect.flatMap((result) =>Option.match(result, {onSome: Effect.succeed,- onNone: () =>- Effect.gen(function* () {- yield* Effect.logWarning("ssh.command.timedOut", {- ...sshTargetLogFields(target),- timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,- remoteCommandArgs: input.remoteCommandArgs ?? [],- preHostArgs: input.preHostArgs ?? [],- hasStdin: input.stdin !== undefined,- });- return yield* new SshCommandError({- command: ["ssh"],- exitCode: null,- stderr: "",- message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,- });- }),+ // The enclosing operation owns the span for this inline handler.+ onNone: Effect.fnUntraced(function* () {+ yield* Effect.logWarning("ssh.command.timedOut", {+ ...sshTargetLogFields(target),+ timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,+ remoteCommandArgs: input.remoteCommandArgs ?? [],+ preHostArgs: input.preHostArgs ?? [],+ hasStdin: input.stdin !== undefined,+ });+ return yield* new SshCommandError({+ command: ["ssh"],+ exitCode: null,+ stderr: "",+ message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,+ });+ }),}),),);diff --git a/tsconfig.base.json b/tsconfig.base.jsonindex b69040ba5c6..312517cf5f3 100644--- a/tsconfig.base.json+++ b/tsconfig.base.json@@ -47,7 +47,7 @@"mapSomeToAsSome": "error","unnecessaryPipeChain": "error","returnEffectInGen": "off",- "effectFnOpportunity": "suggestion",+ "effectFnOpportunity": "error","anyUnknownInErrorContext": "error","unsafeEffectTypeAssertion": "error","instanceOfSchema": "error",