@devries-cameron20 / t3code-1 / commits / 72dde22b6f
Fork 0

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

chore(lint): enforce effectFnOpportunity (#25099)

Julius Marminge committed Oct 26, 2026 at 01:30 UTC 72dde22b6f092491fac4ddc480bc609bb8092bfd
138 files changed +3338 -2478
apps/desktop/src/app/DesktopAppActivation.ts
+4 -1
@@ -382,7 +382,10 @@ export const make = Effect.gen(function* () {
382 webContents.send(DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL, request);
383 });
384 }),
385 - complete: (response) => Effect.sync(() => broker.complete(response)),
385 + // The IPC handler owns the activation-completion span.
386 + complete: Effect.fnUntraced(function* (response) {
387 + return yield* Effect.sync(() => broker.complete(response));
388 + }),
389 });
390 });
391
apps/desktop/src/app/DesktopObservability.ts
+86 -83
@@ -459,90 +459,91 @@ const makeBackendOutputLogShape = (
459 ): Effect.Effect<DesktopBackendOutputLogShape> =>
460 Option.match(sink, {
461 onNone: () => Effect.succeed(DesktopBackendOutputLogNoop),
462 - onSome: (logFile) =>
463 - Effect.gen(function* () {
464 - const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
465 - const writeFailure = Effect.fn("desktop.observability.backendOutput.writeFailure")(
466 - function* (session: BackendOutputSession, details: string) {
467 - yield* writeBackendChildLogRecord(logFile, {
468 - message: "backend child process failure output start",
469 - level: "ERROR",
470 - annotations: {
471 - component: "desktop-backend-child",
472 - runId: session.runId,
473 - instanceId: id,
474 - phase: "START",
475 - details: session.startDetails,
476 - },
477 - });
478 - for (const output of session.chunks) {
479 - yield* writeBackendChildLogRecord(logFile, {
480 - message: "backend child process output",
481 - level: output.streamName === "stderr" ? "ERROR" : "INFO",
482 - annotations: {
483 - component: "desktop-backend-child",
484 - runId: session.runId,
485 - instanceId: id,
486 - stream: output.streamName,
487 - text: textDecoder.decode(output.chunk.subarray(output.offset)),
488 - },
489 - });
490 - }
491 - yield* writeBackendChildLogRecord(logFile, {
492 - message: "backend child process failure output end",
493 - level: "ERROR",
494 - annotations: {
495 - component: "desktop-backend-child",
496 - runId: session.runId,
497 - instanceId: id,
498 - phase: "END",
499 - details: sanitizeLogValue(details),
500 - },
501 - });
462 + // The enclosing operation owns the span for this inline handler.
463 + onSome: Effect.fnUntraced(function* (logFile) {
464 + const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
465 + const writeFailure = Effect.fn("desktop.observability.backendOutput.writeFailure")(function* (
466 + session: BackendOutputSession,
467 + details: string,
468 + ) {
469 + yield* writeBackendChildLogRecord(logFile, {
470 + message: "backend child process failure output start",
471 + level: "ERROR",
472 + annotations: {
473 + component: "desktop-backend-child",
474 + runId: session.runId,
475 + instanceId: id,
476 + phase: "START",
477 + details: session.startDetails,
478 },
503 - );
504 - return {
505 - beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({
506 - details,
507 - }) {
508 - const runId = yield* currentDesktopRunId;
509 - yield* Ref.set(
510 - sessionRef,
511 - Option.some({
512 - runId,
513 - startDetails: sanitizeLogValue(details),
514 - chunks: [],
515 - byteLength: 0,
516 - }),
517 - );
518 - }),
519 - writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {
520 - if (environment.isDevelopment) {
521 - yield* writeDevelopmentConsoleOutput(streamName, chunk);
522 - }
523 - yield* Ref.update(
524 - sessionRef,
525 - Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),
526 - );
527 - }),
528 - persistFailureSnapshot: Effect.fn(
529 - "desktop.observability.backendOutput.persistFailureSnapshot",
530 - )(function* ({ details }) {
531 - const session = yield* Ref.get(sessionRef);
532 - if (Option.isSome(session)) {
533 - yield* writeFailure(session.value, details);
534 - }
535 - }),
536 - persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(
537 - function* ({ details }) {
538 - const session = yield* Ref.modify(sessionRef, (current) => [current, Option.none()]);
539 - if (Option.isNone(session)) return;
540 - yield* writeFailure(session.value, details);
479 + });
480 + for (const output of session.chunks) {
481 + yield* writeBackendChildLogRecord(logFile, {
482 + message: "backend child process output",
483 + level: output.streamName === "stderr" ? "ERROR" : "INFO",
484 + annotations: {
485 + component: "desktop-backend-child",
486 + runId: session.runId,
487 + instanceId: id,
488 + stream: output.streamName,
489 + text: textDecoder.decode(output.chunk.subarray(output.offset)),
490 },
542 - ),
543 - discardSession: Ref.set(sessionRef, Option.none()),
544 - } satisfies DesktopBackendOutputLogShape;
545 - }),
491 + });
492 + }
493 + yield* writeBackendChildLogRecord(logFile, {
494 + message: "backend child process failure output end",
495 + level: "ERROR",
496 + annotations: {
497 + component: "desktop-backend-child",
498 + runId: session.runId,
499 + instanceId: id,
500 + phase: "END",
501 + details: sanitizeLogValue(details),
502 + },
503 + });
504 + });
505 + return {
506 + beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({
507 + details,
508 + }) {
509 + const runId = yield* currentDesktopRunId;
510 + yield* Ref.set(
511 + sessionRef,
512 + Option.some({
513 + runId,
514 + startDetails: sanitizeLogValue(details),
515 + chunks: [],
516 + byteLength: 0,
517 + }),
518 + );
519 + }),
520 + writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {
521 + if (environment.isDevelopment) {
522 + yield* writeDevelopmentConsoleOutput(streamName, chunk);
523 + }
524 + yield* Ref.update(
525 + sessionRef,
526 + Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),
527 + );
528 + }),
529 + persistFailureSnapshot: Effect.fn(
530 + "desktop.observability.backendOutput.persistFailureSnapshot",
531 + )(function* ({ details }) {
532 + const session = yield* Ref.get(sessionRef);
533 + if (Option.isSome(session)) {
534 + yield* writeFailure(session.value, details);
535 + }
536 + }),
537 + persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(function* ({
538 + details,
539 + }) {
540 + const session = yield* Ref.modify(sessionRef, (current) => [current, Option.none()]);
541 + if (Option.isNone(session)) return;
542 + yield* writeFailure(session.value, details);
543 + }),
544 + discardSession: Ref.set(sessionRef, Option.none()),
545 + } satisfies DesktopBackendOutputLogShape;
546 + }),
547 });
548
549 const layerBackendOutputLogFactory = Layer.effect(
@@ -589,7 +590,9 @@ const layerBackendOutputLogFactory = Layer.effect(
590 });
591
592 return DesktopBackendOutputLogFactory.of({
592 - forInstance: (id) => makeForId(id),
593 + forInstance: Effect.fn("DesktopBackendOutputLogFactory.forInstance")(function (id) {
594 + return makeForId(id);
595 + }),
596 });
597 }),
598 );
apps/desktop/src/app/DesktopWebLinks.ts
+7 -8
@@ -69,16 +69,15 @@ const make = Effect.gen(function* () {
69 });
70
71 return DesktopWebLinks.of({
72 - receive: (url) =>
73 - Effect.suspend(() => {
72 + receive: Effect.fn("DesktopWebLinks.receive")(function (url) {
73 + return Effect.suspend(() => {
74 pending.push(url);
75 return flush;
76 - }).pipe(Effect.withSpan("DesktopWebLinks.receive")),
77 - setRendererReady: (ready) =>
78 - (ready ? startListening : Effect.sync(stopListening)).pipe(
79 - Effect.andThen(flush),
80 - Effect.withSpan("DesktopWebLinks.setRendererReady"),
81 - ),
76 + });
77 + }),
78 + setRendererReady: Effect.fn("DesktopWebLinks.setRendererReady")(function (ready) {
79 + return ready ? startListening : Effect.sync(stopListening);
80 + }, Effect.andThen(flush)),
81 });
82 });
83
apps/desktop/src/backend/DesktopBackendManager.ts
+48 -48
@@ -1043,58 +1043,58 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
1043 });
1044 yield* Option.match(active, {
1045 onNone: () => Effect.void,
1046 - onSome: (run) =>
1047 - Effect.gen(function* () {
1048 - const closed = yield* closeRun(run, parentScope, options);
1049 - if (!closed) {
1050 - return;
1051 - }
1052 - const cleanup = yield* mutex.withPermits(1)(
1053 - Ref.modify(
1054 - state,
1055 - (
1056 - latest,
1057 - ): readonly [
1058 - {
1059 - readonly needsCleanup: boolean;
1060 - readonly shouldStart: boolean;
1061 - },
1062 - BackendManagerState,
1063 - ] => {
1064 - const current = Option.getOrUndefined(latest.active);
1065 - if (current?.id !== run.id) {
1066 - return [
1067 - {
1068 - needsCleanup: false,
1069 - shouldStart:
1070 - latest.desiredRunning &&
1071 - Option.isNone(latest.active) &&
1072 - Option.isNone(latest.restartFiber),
1073 - },
1074 - latest,
1075 - ];
1076 - }
1046 + // The enclosing operation owns the span for this inline handler.
1047 + onSome: Effect.fnUntraced(function* (run) {
1048 + const closed = yield* closeRun(run, parentScope, options);
1049 + if (!closed) {
1050 + return;
1051 + }
1052 + const cleanup = yield* mutex.withPermits(1)(
1053 + Ref.modify(
1054 + state,
1055 + (
1056 + latest,
1057 + ): readonly [
1058 + {
1059 + readonly needsCleanup: boolean;
1060 + readonly shouldStart: boolean;
1061 + },
1062 + BackendManagerState,
1063 + ] => {
1064 + const current = Option.getOrUndefined(latest.active);
1065 + if (current?.id !== run.id) {
1066 return [
1067 {
1079 - needsCleanup: true,
1080 - shouldStart: latest.desiredRunning,
1081 - },
1082 - {
1083 - ...latest,
1084 - active: Option.none<ActiveBackendRun>(),
1068 + needsCleanup: false,
1069 + shouldStart:
1070 + latest.desiredRunning &&
1071 + Option.isNone(latest.active) &&
1072 + Option.isNone(latest.restartFiber),
1073 },
1074 + latest,
1075 ];
1087 - },
1088 - ),
1089 - );
1090 - if (cleanup.needsCleanup) {
1091 - yield* desktopTelemetryPublisher.removeControlSource(spec.id);
1092 - yield* backendOutputLog.discardSession;
1093 - }
1094 - if (cleanup.shouldStart) {
1095 - yield* start;
1096 - }
1097 - }),
1076 + }
1077 + return [
1078 + {
1079 + needsCleanup: true,
1080 + shouldStart: latest.desiredRunning,
1081 + },
1082 + {
1083 + ...latest,
1084 + active: Option.none<ActiveBackendRun>(),
1085 + },
1086 + ];
1087 + },
1088 + ),
1089 + );
1090 + if (cleanup.needsCleanup) {
1091 + yield* desktopTelemetryPublisher.removeControlSource(spec.id);
1092 + yield* backendOutputLog.discardSession;
1093 + }
1094 + if (cleanup.shouldStart) {
1095 + yield* start;
1096 + }
1097 + }),
1098 });
1099 });
1100
apps/desktop/src/backend/DesktopBackendPool.ts
+13 -6
@@ -291,13 +291,14 @@ export const layer = Layer.effect(
291 });
292
293 return DesktopBackendPool.of({
294 - get: (id) =>
295 - SynchronizedRef.get(instancesRef).pipe(
294 + get: Effect.fn("DesktopBackendPool.get")(function (id) {
295 + return SynchronizedRef.get(instancesRef).pipe(
296 Effect.map((instances) => {
297 const entry = instances.get(id);
298 return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none();
299 }),
300 - ),
300 + );
301 + }),
302 list: SynchronizedRef.get(instancesRef).pipe(
303 Effect.map((instances) =>
304 Array.from(instances.values()).flatMap((entry) =>
@@ -326,11 +327,17 @@ export const layerTest = (
327 );
328 const primary = instances[0]!;
329 return DesktopBackendPool.of({
329 - get: (id) => Effect.succeed(Option.fromNullishOr(byId.get(id))),
330 + get: Effect.fn("DesktopBackendPool.get")(function (id) {
331 + return Effect.succeed(Option.fromNullishOr(byId.get(id)));
332 + }),
333 list: Effect.succeed(Array.from(byId.values())),
334 primary: Effect.succeed(primary),
332 - register: () => Effect.die("DesktopBackendPool.layerTest does not support register"),
333 - unregister: () => Effect.die("DesktopBackendPool.layerTest does not support unregister"),
335 + register: Effect.fn("DesktopBackendPool.register")(function () {
336 + return Effect.die("DesktopBackendPool.layerTest does not support register");
337 + }),
338 + unregister: Effect.fn("DesktopBackendPool.unregister")(function () {
339 + return Effect.die("DesktopBackendPool.layerTest does not support unregister");
340 + }),
341 });
342 }),
343 );
apps/desktop/src/electron/ElectronApp.ts
+61 -45
@@ -135,59 +135,73 @@ export const make = ElectronApp.of({
135 quit: Effect.sync(() => {
136 Electron.app.quit();
137 }),
138 - exit: (code) =>
139 - Effect.sync(() => {
138 + exit: Effect.fn("ElectronApp.exit")(function (code) {
139 + return Effect.sync(() => {
140 Electron.app.exit(code);
141 - }),
142 - relaunch: (options) =>
143 - Effect.sync(() => {
141 + });
142 + }),
143 + relaunch: Effect.fn("ElectronApp.relaunch")(function (options) {
144 + return Effect.sync(() => {
145 Electron.app.relaunch(options);
145 - }),
146 - setPath: (name, path) =>
147 - Effect.sync(() => {
146 + });
147 + }),
148 + setPath: Effect.fn("ElectronApp.setPath")(function (name, path) {
149 + return Effect.sync(() => {
150 Electron.app.setPath(name, path);
149 - }),
150 - setName: (name) =>
151 - Effect.sync(() => {
151 + });
152 + }),
153 + setName: Effect.fn("ElectronApp.setName")(function (name) {
154 + return Effect.sync(() => {
155 Electron.app.setName(name);
153 - }),
154 - setAboutPanelOptions: (options) =>
155 - Effect.sync(() => {
156 + });
157 + }),
158 + setAboutPanelOptions: Effect.fn("ElectronApp.setAboutPanelOptions")(function (options) {
159 + return Effect.sync(() => {
160 Electron.app.setAboutPanelOptions(options);
157 - }),
158 - setAppUserModelId: (id) =>
159 - Effect.sync(() => {
161 + });
162 + }),
163 + setAppUserModelId: Effect.fn("ElectronApp.setAppUserModelId")(function (id) {
164 + return Effect.sync(() => {
165 Electron.app.setAppUserModelId(id);
161 - }),
166 + });
167 + }),
168 getAppMetrics: Effect.sync(() => Electron.app.getAppMetrics()),
163 - setAsDefaultProtocolClient: (protocol, path, args) =>
164 - Effect.sync(() => {
165 - if (path === undefined) {
166 - return Electron.app.setAsDefaultProtocolClient(protocol);
167 - }
168 - return Electron.app.setAsDefaultProtocolClient(protocol, path, [...(args ?? [])]);
169 - }),
170 - setDesktopName: (desktopName) =>
171 - Effect.sync(() => {
169 + setAsDefaultProtocolClient: Effect.fn("ElectronApp.setAsDefaultProtocolClient")(
170 + function (protocol, path, args) {
171 + return Effect.sync(() => {
172 + if (path === undefined) {
173 + return Electron.app.setAsDefaultProtocolClient(protocol);
174 + }
175 + return Electron.app.setAsDefaultProtocolClient(protocol, path, [...(args ?? [])]);
176 + });
177 + },
178 + ),
179 + setDesktopName: Effect.fn("ElectronApp.setDesktopName")(function (desktopName) {
180 + return Effect.sync(() => {
181 const linuxApp = Electron.app as Electron.App & {
182 setDesktopName?: (desktopName: string) => void;
183 };
184 linuxApp.setDesktopName?.(desktopName);
176 - }),
177 - setDockIcon: (iconPath) =>
178 - Effect.sync(() => {
185 + });
186 + }),
187 + setDockIcon: Effect.fn("ElectronApp.setDockIcon")(function (iconPath) {
188 + return Effect.sync(() => {
189 Electron.app.dock?.setIcon(iconPath);
180 - }),
181 - appendCommandLineSwitch: (switchName, value) =>
182 - Effect.sync(() => {
183 - if (value === undefined) {
184 - Electron.app.commandLine.appendSwitch(switchName);
185 - return;
186 - }
187 - Electron.app.commandLine.appendSwitch(switchName, value);
188 - }),
189 - onBeforeQuitForUpdate: (listener) =>
190 - Effect.acquireRelease(
190 + });
191 + }),
192 + appendCommandLineSwitch: Effect.fn("ElectronApp.appendCommandLineSwitch")(
193 + function (switchName, value) {
194 + return Effect.sync(() => {
195 + if (value === undefined) {
196 + Electron.app.commandLine.appendSwitch(switchName);
197 + return;
198 + }
199 + Electron.app.commandLine.appendSwitch(switchName, value);
200 + });
201 + },
202 + ),
203 + onBeforeQuitForUpdate: Effect.fn("ElectronApp.onBeforeQuitForUpdate")(function (listener) {
204 + return Effect.acquireRelease(
205 Effect.sync(() => {
206 Electron.autoUpdater.on("before-quit-for-update", listener);
207 }),
@@ -195,11 +209,13 @@ export const make = ElectronApp.of({
209 Effect.sync(() => {
210 Electron.autoUpdater.removeListener("before-quit-for-update", listener);
211 }),
198 - ).pipe(Effect.asVoid),
199 - removeCommandLineSwitch: (switchName) =>
200 - Effect.sync(() => {
212 + ).pipe(Effect.asVoid);
213 + }),
214 + removeCommandLineSwitch: Effect.fn("ElectronApp.removeCommandLineSwitch")(function (switchName) {
215 + return Effect.sync(() => {
216 Electron.app.commandLine.removeSwitch(switchName);
202 - }),
217 + });
218 + }),
219 on: addScopedAppListener,
220 });
221
apps/desktop/src/electron/ElectronDialog.ts
+8 -6
@@ -166,8 +166,8 @@ export const make = ElectronDialog.of({
166 });
167 return result.canceled ? [] : result.filePaths;
168 }),
169 - showMessageBox: (options, owner) =>
170 - Effect.tryPromise({
169 + showMessageBox: Effect.fn("ElectronDialog.showMessageBox")(function (options, owner) {
170 + return Effect.tryPromise({
171 try: () =>
172 owner === undefined
173 ? Electron.dialog.showMessageBox(options)
@@ -181,9 +181,10 @@ export const make = ElectronDialog.of({
181 buttonCount: options.buttons?.length ?? 0,
182 cause,
183 }),
184 - }),
185 - showErrorBox: (title, content) =>
186 - Effect.try({
184 + });
185 + }),
186 + showErrorBox: Effect.fn("ElectronDialog.showErrorBox")(function (title, content) {
187 + return Effect.try({
188 try: () => Electron.dialog.showErrorBox(title, content),
189 catch: (cause) =>
190 new ElectronDialogShowErrorBoxError({
@@ -191,7 +192,8 @@ export const make = ElectronDialog.of({
192 contentLength: content.length,
193 cause,
194 }),
194 - }).pipe(Effect.orDie),
195 + }).pipe(Effect.orDie);
196 + }),
197 });
198
199 export const layer = Layer.succeed(ElectronDialog, make);
apps/desktop/src/electron/ElectronMenu.ts
+12 -9
@@ -187,8 +187,8 @@ export const make = Effect.gen(function* () {
187 };
188
189 return ElectronMenu.of({
190 - setApplicationMenu: (template) =>
191 - Effect.try({
190 + setApplicationMenu: Effect.fn("ElectronMenu.setApplicationMenu")(function (template) {
191 + return Effect.try({
192 try: () => {
193 Electron.Menu.setApplicationMenu(Electron.Menu.buildFromTemplate([...template]));
194 },
@@ -200,9 +200,10 @@ export const make = Effect.gen(function* () {
200 itemCount: template.length,
201 cause,
202 }),
203 - }).pipe(Effect.orDie),
204 - popupTemplate: (input) =>
205 - input.template.length === 0
203 + }).pipe(Effect.orDie);
204 + }),
205 + popupTemplate: Effect.fn("ElectronMenu.popupTemplate")(function (input) {
206 + return input.template.length === 0
207 ? Effect.void
208 : Effect.try({
209 try: () =>
@@ -218,9 +219,10 @@ export const make = Effect.gen(function* () {
219 itemCount: input.template.length,
220 cause,
221 }),
221 - }).pipe(Effect.orDie),
222 - showContextMenu: (input) =>
223 - Effect.callback<Option.Option<string>>((resume) => {
222 + }).pipe(Effect.orDie);
223 + }),
224 + showContextMenu: Effect.fn("ElectronMenu.showContextMenu")(function (input) {
225 + return Effect.callback<Option.Option<string>>((resume) => {
226 const normalizedItems = normalizeContextMenuItems(input.items);
227 if (normalizedItems.length === 0) {
228 resume(Effect.succeedNone);
@@ -272,7 +274,8 @@ export const make = Effect.gen(function* () {
274 ),
275 );
276 }
275 - }),
277 + });
278 + }),
279 });
280 });
281
apps/desktop/src/electron/ElectronPowerMonitor.ts
+5 -2
@@ -79,8 +79,11 @@ const onSpeedLimitChange: ElectronPowerMonitor["Service"]["onSpeedLimitChange"]
79 export const make = ElectronPowerMonitor.of({
80 isOnBatteryPower: Effect.sync(() => Electron.powerMonitor.isOnBatteryPower()),
81 getSystemIdleTime: Effect.sync(() => Electron.powerMonitor.getSystemIdleTime()),
82 - getSystemIdleState: (idleThresholdSeconds) =>
83 - Effect.sync(() => Electron.powerMonitor.getSystemIdleState(idleThresholdSeconds)),
82 + getSystemIdleState: Effect.fn("ElectronPowerMonitor.getSystemIdleState")(
83 + function (idleThresholdSeconds) {
84 + return Effect.sync(() => Electron.powerMonitor.getSystemIdleState(idleThresholdSeconds));
85 + },
86 + ),
87 getCurrentThermalState: Effect.sync(() => Electron.powerMonitor.getCurrentThermalState()),
88 onSimpleEvent,
89 onThermalStateChange,
apps/desktop/src/electron/ElectronSafeStorage.ts
+8 -6
@@ -74,16 +74,18 @@ export const make = Effect.gen(function* () {
74 try: () => Electron.safeStorage.isEncryptionAvailable(),
75 catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
76 }),
77 - encryptString: (value) =>
78 - Effect.try({
77 + encryptString: Effect.fn("ElectronSafeStorage.encryptString")(function (value) {
78 + return Effect.try({
79 try: () => Electron.safeStorage.encryptString(value),
80 catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
81 - }),
82 - decryptString: (value) =>
83 - Effect.try({
81 + });
82 + }),
83 + decryptString: Effect.fn("ElectronSafeStorage.decryptString")(function (value) {
84 + return Effect.try({
85 try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
86 catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
86 - }),
87 + });
88 + }),
89 selectedStorageBackend: Effect.sync(() => {
90 if (platform !== "linux") {
91 return Option.none();
apps/desktop/src/electron/ElectronShell.ts
+11 -8
@@ -63,8 +63,8 @@ export class ElectronShell extends Context.Service<
63
64 /** @public */
65 export const make = ElectronShell.of({
66 - openExternal: (rawUrl) =>
67 - Option.match(parseSafeExternalUrl(rawUrl), {
66 + openExternal: Effect.fn("ElectronShell.openExternal")(function (rawUrl) {
67 + return Option.match(parseSafeExternalUrl(rawUrl), {
68 onNone: () => Effect.succeed(false),
69 onSome: (externalUrl) =>
70 Effect.promise(() =>
@@ -73,16 +73,19 @@ export const make = ElectronShell.of({
73 () => false,
74 ),
75 ),
76 - }),
77 - openSystemSettings: (pane) =>
78 - Effect.promise(() =>
76 + });
77 + }),
78 + openSystemSettings: Effect.fn("ElectronShell.openSystemSettings")(function (pane) {
79 + return Effect.promise(() =>
80 Electron.shell.openExternal(MAC_PERMISSION_SETTINGS_URLS[pane]).then(
81 () => true,
82 () => false,
83 ),
83 - ),
84 - copyText: (text) =>
85 - Effect.promise(() => Electron.clipboard.writeText(text).catch(() => undefined)),
84 + );
85 + }),
86 + copyText: Effect.fn("ElectronShell.copyText")(function (text) {
87 + return Effect.promise(() => Electron.clipboard.writeText(text).catch(() => undefined));
88 + }),
89 });
90
91 export const layer = Layer.succeed(ElectronShell, make);
apps/desktop/src/electron/ElectronTheme.ts
+8 -6
@@ -31,15 +31,16 @@ export class ElectronTheme extends Context.Service<
31 /** @public */
32 export const make = ElectronTheme.of({
33 shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),
34 - setSource: (theme) =>
35 - Effect.try({
34 + setSource: Effect.fn("ElectronTheme.setSource")(function (theme) {
35 + return Effect.try({
36 try: () => {
37 Electron.nativeTheme.themeSource = theme;
38 },
39 catch: (cause) => new ElectronThemeSetSourceError({ source: theme, cause }),
40 - }),
41 - onUpdated: (listener) =>
42 - Effect.acquireRelease(
40 + });
41 + }),
42 + onUpdated: Effect.fn("ElectronTheme.onUpdated")(function (listener) {
43 + return Effect.acquireRelease(
44 Effect.suspend(() => {
45 Electron.nativeTheme.on("updated", listener);
46 return Effect.void;
@@ -49,7 +50,8 @@ export const make = ElectronTheme.of({
50 Electron.nativeTheme.removeListener("updated", listener);
51 return Effect.void;
52 }),
52 - ),
53 + );
54 + }),
55 });
56
57 export const layer = Layer.succeed(ElectronTheme, make);
apps/desktop/src/electron/ElectronUpdater.ts
+45 -31
@@ -82,47 +82,57 @@ export class ElectronUpdater extends Context.Service<
82
83 /** @public */
84 export const make = ElectronUpdater.of({
85 - setFeedURL: (options) =>
86 - Effect.suspend(() => {
85 + setFeedURL: Effect.fn("ElectronUpdater.setFeedURL")(function (options) {
86 + return Effect.suspend(() => {
87 autoUpdater.setFeedURL(options);
88 return Effect.void;
89 - }),
90 - setAutoDownload: (value) =>
91 - Effect.suspend(() => {
89 + });
90 + }),
91 + setAutoDownload: Effect.fn("ElectronUpdater.setAutoDownload")(function (value) {
92 + return Effect.suspend(() => {
93 autoUpdater.autoDownload = value;
94 return Effect.void;
94 - }),
95 - setAutoInstallOnAppQuit: (value) =>
96 - Effect.suspend(() => {
95 + });
96 + }),
97 + setAutoInstallOnAppQuit: Effect.fn("ElectronUpdater.setAutoInstallOnAppQuit")(function (value) {
98 + return Effect.suspend(() => {
99 autoUpdater.autoInstallOnAppQuit = value;
100 return Effect.void;
99 - }),
100 - setChannel: (channel) =>
101 - Effect.suspend(() => {
101 + });
102 + }),
103 + setChannel: Effect.fn("ElectronUpdater.setChannel")(function (channel) {
104 + return Effect.suspend(() => {
105 autoUpdater.channel = channel;
106 return Effect.void;
104 - }),
105 - setAllowPrerelease: (value) =>
106 - Effect.suspend(() => {
107 + });
108 + }),
109 + setAllowPrerelease: Effect.fn("ElectronUpdater.setAllowPrerelease")(function (value) {
110 + return Effect.suspend(() => {
111 autoUpdater.allowPrerelease = value;
112 return Effect.void;
109 - }),
113 + });
114 + }),
115 allowDowngrade: Effect.sync(() => autoUpdater.allowDowngrade),
111 - setAllowDowngrade: (value) =>
112 - Effect.suspend(() => {
116 + setAllowDowngrade: Effect.fn("ElectronUpdater.setAllowDowngrade")(function (value) {
117 + return Effect.suspend(() => {
118 autoUpdater.allowDowngrade = value;
119 return Effect.void;
115 - }),
116 - setFullChangelog: (value) =>
117 - Effect.suspend(() => {
120 + });
121 + }),
122 + setFullChangelog: Effect.fn("ElectronUpdater.setFullChangelog")(function (value) {
123 + return Effect.suspend(() => {
124 autoUpdater.fullChangelog = value;
125 return Effect.void;
120 - }),
121 - setDisableDifferentialDownload: (value) =>
122 - Effect.suspend(() => {
123 - autoUpdater.disableDifferentialDownload = value;
124 - return Effect.void;
125 - }),
126 + });
127 + }),
128 + setDisableDifferentialDownload: Effect.fn("ElectronUpdater.setDisableDifferentialDownload")(
129 + function (value) {
130 + return Effect.suspend(() => {
131 + autoUpdater.disableDifferentialDownload = value;
132 + return Effect.void;
133 + });
134 + },
135 + ),
136 checkForUpdates: Effect.suspend(() => {
137 const channel = autoUpdater.channel;
138 return Effect.tryPromise({
@@ -137,8 +147,11 @@ export const make = ElectronUpdater.of({
147 catch: (cause) => new ElectronUpdaterDownloadUpdateError({ channel, cause }),
148 }).pipe(Effect.asVoid);
149 }),
140 - quitAndInstall: ({ isSilent, isForceRunAfter }) =>
141 - Effect.suspend(() => {
150 + quitAndInstall: Effect.fn("ElectronUpdater.quitAndInstall")(function ({
151 + isSilent,
152 + isForceRunAfter,
153 + }) {
154 + return Effect.suspend(() => {
155 const channel = autoUpdater.channel;
156 return Effect.try({
157 try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter),
@@ -150,8 +163,9 @@ export const make = ElectronUpdater.of({
163 cause,
164 }),
165 });
153 - }),
154 - on: (eventName, listener) => {
166 + });
167 + }),
168 + on: Effect.fn("ElectronUpdater.on")(function (eventName, listener) {
169 const eventTarget = autoUpdater as unknown as {
170 on: (eventName: string, listener: (...args: Array<unknown>) => void) => void;
171 removeListener: (eventName: string, listener: (...args: Array<unknown>) => void) => void;
@@ -166,7 +180,7 @@ export const make = ElectronUpdater.of({
180 eventTarget.removeListener(eventName, untypedListener);
181 }),
182 ).pipe(Effect.asVoid);
169 - },
183 + }),
184 });
185
186 export const layer = Layer.succeed(ElectronUpdater, make);
apps/desktop/src/electron/ElectronWindow.ts
+17 -12
@@ -207,7 +207,7 @@ export const make = Effect.gen(function* () {
207 });
208
209 return ElectronWindow.of({
210 - create: (options) => {
210 + create: Effect.fn("ElectronWindow.create")(function (options) {
211 const webPreferences = options.webPreferences;
212 const diagnosticOptions = {
213 title: options.title ?? null,
@@ -235,13 +235,15 @@ export const make = Effect.gen(function* () {
235 try: () => new Electron.BrowserWindow(options),
236 catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
237 });
238 - },
238 + }),
239 main: liveMain,
240 currentMainOrFirst,
241 focusedMainOrFirst,
242 - setMain: (window) => Ref.set(mainWindowRef, Option.some(window)),
243 - clearMain: (window) =>
244 - Ref.update(mainWindowRef, (current) => {
242 + setMain: Effect.fn("ElectronWindow.setMain")(function (window) {
243 + return Ref.set(mainWindowRef, Option.some(window));
244 + }),
245 + clearMain: Effect.fn("ElectronWindow.clearMain")(function (window) {
246 + return Ref.update(mainWindowRef, (current) => {
247 if (Option.isNone(current)) {
248 return current;
249 }
@@ -249,9 +251,10 @@ export const make = Effect.gen(function* () {
251 return current;
252 }
253 return Option.none();
252 - }),
253 - prepareReveal: (window) =>
254 - Effect.promise(async () => {
254 + });
255 + }),
256 + prepareReveal: Effect.fn("ElectronWindow.prepareReveal")(function (window) {
257 + return Effect.promise(async () => {
258 if (platform !== "win32" || window.isDestroyed()) {
259 return false;
260 }
@@ -259,9 +262,10 @@ export const make = Effect.gen(function* () {
262 return ensureWindowsForegroundFocus()
263 .prepare(windowsForegroundFocusTarget(window))
264 .catch(() => false);
262 - }),
263 - reveal: (window) =>
264 - Effect.tryPromise({
265 + });
266 + }),
267 + reveal: Effect.fn("ElectronWindow.reveal")(function (window) {
268 + return Effect.tryPromise({
269 try: async () => {
270 if (window.isDestroyed()) {
271 return;
@@ -322,7 +326,8 @@ export const make = Effect.gen(function* () {
326 channel: null,
327 cause,
328 }),
325 - }).pipe(Effect.orDie),
329 + }).pipe(Effect.orDie);
330 + }),
331 sendAll:
332 /* Window broadcasts run for streamed updates; avoid a span per broadcast. */
333 Effect.fnUntraced(function* (channel, ...args) {
apps/desktop/src/settings/DesktopAppSettings.test.ts
+32
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5 import * as Layer from "effect/Layer";
6 import * as Schema from "effect/Schema";
7 +import * as Tracer from "effect/Tracer";
8
9 import * as DesktopConfig from "../app/DesktopConfig.ts";
10 import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
@@ -90,6 +91,37 @@ function writeSettingsPatch(patch: typeof DesktopSettingsPatch.Type) {
91 }
92
93 describe("DesktopSettings", () => {
94 + it.effect("records one bounds operation span with its input attributes", () =>
95 + Effect.gen(function* () {
96 + const spans: Array<Tracer.Span> = [];
97 + const tracer = Tracer.make({
98 + span: (options) => {
99 + const span = new Tracer.NativeSpan(options);
100 + spans.push(span);
101 + return span;
102 + },
103 + });
104 + yield* withSettings(
105 + Effect.gen(function* () {
106 + const settings = yield* DesktopAppSettings.DesktopAppSettings;
107 + yield* settings.setMainWindowBounds({ x: 10, y: 20, width: 900, height: 600 }, true);
108 + }),
109 + ).pipe(Effect.provideService(Tracer.Tracer, tracer));
110 + const operationSpans = spans.filter(
111 + (span) => span.name === "desktop.settings.setMainWindowBounds",
112 + );
113 + assert.lengthOf(operationSpans, 1);
114 + assert.deepEqual(Object.fromEntries(operationSpans[0]!.attributes), {
115 + x: 10,
116 + y: 20,
117 + width: 900,
118 + height: 600,
119 + isMaximized: true,
120 + });
121 + assert.equal(operationSpans[0]!.status._tag, "Ended");
122 + }),
123 + );
124 +
125 it.effect(
126 "persists disabling and re-enabling local execution without clearing backend settings",
127 () =>
apps/desktop/src/settings/DesktopAppSettings.ts
+82 -54
@@ -521,48 +521,56 @@ export const make = Effect.gen(function* () {
521 );
522 return yield* SynchronizedRef.setAndGet(settingsRef, settings);
523 }).pipe(Effect.withSpan("desktop.settings.load")),
524 - setMainWindowBounds: (bounds, isMaximized) =>
525 - persist((settings) => setMainWindowBounds(settings, bounds, isMaximized)).pipe(
526 - Effect.withSpan("desktop.settings.setMainWindowBounds", {
527 - attributes: {
528 - x: bounds.x,
529 - y: bounds.y,
530 - width: bounds.width,
531 - height: bounds.height,
532 - isMaximized,
533 - },
534 - }),
535 - ),
536 - setServerExposureMode: (mode) =>
537 - persist((settings) => setServerExposureMode(settings, mode)).pipe(
538 - Effect.withSpan("desktop.settings.setServerExposureMode", { attributes: { mode } }),
539 - ),
540 - setTailscaleServe: (input) =>
541 - persist((settings) => setTailscaleServe(settings, input)).pipe(
542 - Effect.withSpan("desktop.settings.setTailscaleServe", { attributes: input }),
543 - ),
544 - setUpdateChannel: (channel) =>
545 - persist((settings) => setUpdateChannel(settings, channel)).pipe(
546 - Effect.withSpan("desktop.settings.setUpdateChannel", { attributes: { channel } }),
547 - ),
548 - setWslBackendEnabled: (enabled) =>
549 - persist((settings) => setWslBackendEnabled(settings, enabled)).pipe(
550 - Effect.withSpan("desktop.settings.setWslBackendEnabled", { attributes: { enabled } }),
551 - ),
552 - setWslDistro: (distro) =>
553 - persist((settings) => setWslDistro(settings, distro)).pipe(
554 - Effect.withSpan("desktop.settings.setWslDistro", {
555 - attributes: { distro: distro ?? null },
556 - }),
557 - ),
558 - setWslOnly: (enabled) =>
559 - persist((settings) => setWslOnly(settings, enabled)).pipe(
560 - Effect.withSpan("desktop.settings.setWslOnly", { attributes: { enabled } }),
561 - ),
562 - setLocalEnvironmentEnabled: (enabled) =>
563 - persist((settings) => setLocalEnvironmentEnabled(settings, enabled)).pipe(
564 - Effect.withSpan("desktop.settings.setLocalEnvironmentEnabled", { attributes: { enabled } }),
565 - ),
524 + setMainWindowBounds: Effect.fn("desktop.settings.setMainWindowBounds")(
525 + function* (bounds, isMaximized) {
526 + yield* Effect.annotateCurrentSpan({
527 + x: bounds.x,
528 + y: bounds.y,
529 + width: bounds.width,
530 + height: bounds.height,
531 + isMaximized,
532 + });
533 +
534 + return yield* persist((settings) => setMainWindowBounds(settings, bounds, isMaximized));
535 + },
536 + ),
537 + setServerExposureMode: Effect.fn("desktop.settings.setServerExposureMode")(function* (mode) {
538 + yield* Effect.annotateCurrentSpan({ mode });
539 +
540 + return yield* persist((settings) => setServerExposureMode(settings, mode));
541 + }),
542 + setTailscaleServe: Effect.fn("desktop.settings.setTailscaleServe")(function* (input) {
543 + yield* Effect.annotateCurrentSpan(input);
544 +
545 + return yield* persist((settings) => setTailscaleServe(settings, input));
546 + }),
547 + setUpdateChannel: Effect.fn("desktop.settings.setUpdateChannel")(function* (channel) {
548 + yield* Effect.annotateCurrentSpan({ channel });
549 +
550 + return yield* persist((settings) => setUpdateChannel(settings, channel));
551 + }),
552 + setWslBackendEnabled: Effect.fn("desktop.settings.setWslBackendEnabled")(function* (enabled) {
553 + yield* Effect.annotateCurrentSpan({ enabled });
554 +
555 + return yield* persist((settings) => setWslBackendEnabled(settings, enabled));
556 + }),
557 + setWslDistro: Effect.fn("desktop.settings.setWslDistro")(function* (distro) {
558 + yield* Effect.annotateCurrentSpan({ distro: distro ?? null });
559 +
560 + return yield* persist((settings) => setWslDistro(settings, distro));
561 + }),
562 + setWslOnly: Effect.fn("desktop.settings.setWslOnly")(function* (enabled) {
563 + yield* Effect.annotateCurrentSpan({ enabled });
564 +
565 + return yield* persist((settings) => setWslOnly(settings, enabled));
566 + }),
567 + setLocalEnvironmentEnabled: Effect.fn("desktop.settings.setLocalEnvironmentEnabled")(
568 + function* (enabled) {
569 + yield* Effect.annotateCurrentSpan({ enabled });
570 +
571 + return yield* persist((settings) => setLocalEnvironmentEnabled(settings, enabled));
572 + },
573 + ),
574 applyWslWindowsFallback: persist(applyWslWindowsFallback).pipe(
575 Effect.withSpan("desktop.settings.applyWslWindowsFallback"),
576 ),
@@ -594,18 +602,38 @@ export const layerTest = (initialSettings: DesktopSettings = DEFAULT_DESKTOP_SET
602 return DesktopAppSettings.of({
603 get: SynchronizedRef.get(settingsRef),
604 load: SynchronizedRef.get(settingsRef),
597 - setMainWindowBounds: (bounds, isMaximized) =>
598 - update((settings) => setMainWindowBounds(settings, bounds, isMaximized)),
599 - setServerExposureMode: (mode) =>
600 - update((settings) => setServerExposureMode(settings, mode)),
601 - setTailscaleServe: (input) => update((settings) => setTailscaleServe(settings, input)),
602 - setUpdateChannel: (channel) => update((settings) => setUpdateChannel(settings, channel)),
603 - setWslBackendEnabled: (enabled) =>
604 - update((settings) => setWslBackendEnabled(settings, enabled)),
605 - setWslDistro: (distro) => update((settings) => setWslDistro(settings, distro)),
606 - setWslOnly: (enabled) => update((settings) => setWslOnly(settings, enabled)),
607 - setLocalEnvironmentEnabled: (enabled) =>
608 - update((settings) => setLocalEnvironmentEnabled(settings, enabled)),
605 + setMainWindowBounds: Effect.fn("DesktopAppSettings.setMainWindowBounds")(
606 + function (bounds, isMaximized) {
607 + return update((settings) => setMainWindowBounds(settings, bounds, isMaximized));
608 + },
609 + ),
610 + setServerExposureMode: Effect.fn("DesktopAppSettings.setServerExposureMode")(
611 + function (mode) {
612 + return update((settings) => setServerExposureMode(settings, mode));
613 + },
614 + ),
615 + setTailscaleServe: Effect.fn("DesktopAppSettings.setTailscaleServe")(function (input) {
616 + return update((settings) => setTailscaleServe(settings, input));
617 + }),
618 + setUpdateChannel: Effect.fn("DesktopAppSettings.setUpdateChannel")(function (channel) {
619 + return update((settings) => setUpdateChannel(settings, channel));
620 + }),
621 + setWslBackendEnabled: Effect.fn("DesktopAppSettings.setWslBackendEnabled")(
622 + function (enabled) {
623 + return update((settings) => setWslBackendEnabled(settings, enabled));
624 + },
625 + ),
626 + setWslDistro: Effect.fn("DesktopAppSettings.setWslDistro")(function (distro) {
627 + return update((settings) => setWslDistro(settings, distro));
628 + }),
629 + setWslOnly: Effect.fn("DesktopAppSettings.setWslOnly")(function (enabled) {
630 + return update((settings) => setWslOnly(settings, enabled));
631 + }),
632 + setLocalEnvironmentEnabled: Effect.fn("DesktopAppSettings.setLocalEnvironmentEnabled")(
633 + function (enabled) {
634 + return update((settings) => setLocalEnvironmentEnabled(settings, enabled));
635 + },
636 + ),
637 applyWslWindowsFallback: update(applyWslWindowsFallback),
638 applyWslWindowsFallbackInMemory: update(applyWslWindowsFallback),
639 });
apps/desktop/src/settings/DesktopClientSettings.ts
+7 -5
@@ -194,8 +194,8 @@ export const make = Effect.gen(function* () {
194 get: readClientSettings(fileSystem, environment.clientSettingsPath).pipe(
195 Effect.withSpan("desktop.clientSettings.get"),
196 ),
197 - set: (settings) =>
198 - crypto.randomUUIDv4().pipe(
197 + set: Effect.fn("desktop.clientSettings.set")(function (settings) {
198 + return crypto.randomUUIDv4().pipe(
199 Effect.map((uuid) => uuid.replace(/-/g, "")),
200 Effect.mapError(
201 (cause) =>
@@ -214,8 +214,8 @@ export const make = Effect.gen(function* () {
214 suffix,
215 }),
216 ),
217 - Effect.withSpan("desktop.clientSettings.set"),
218 - ),
217 + );
218 + }),
219 });
220 });
221
@@ -228,7 +228,9 @@ export const layerTest = (initialSettings: Option.Option<ClientSettings> = Optio
228 const settingsRef = yield* Ref.make(initialSettings);
229 return DesktopClientSettings.of({
230 get: Ref.get(settingsRef),
231 - set: (settings) => Ref.set(settingsRef, Option.some(settings)),
231 + set: Effect.fn("DesktopClientSettings.set")(function (settings) {
232 + return Ref.set(settingsRef, Option.some(settings));
233 + }),
234 });
235 }),
236 );
apps/desktop/src/snapShot/DesktopSnapShot.ts
+22 -17
@@ -1718,24 +1718,28 @@ export const make = Effect.gen(function* () {
1718 ),
1719 ),
1720 ),
1721 - setAnimationDestination: (id, destination) =>
1722 - Effect.promise(async () => {
1723 - if (linuxFeedback?.id === id && destination.relativeFrame) {
1724 - await linuxFeedback.feedback
1725 - .animateTo(destination.relativeFrame)
1726 - .catch(() => closeLinuxFeedback(id));
1727 - return;
1728 - }
1729 - transition.animateTo(id, destination);
1730 - await transition.waitForLanding(id);
1731 - }),
1732 - dismissAnimation: (id) =>
1733 - Effect.sync(() => {
1721 + setAnimationDestination: Effect.fn("DesktopSnapShot.setAnimationDestination")(
1722 + function (id, destination) {
1723 + return Effect.promise(async () => {
1724 + if (linuxFeedback?.id === id && destination.relativeFrame) {
1725 + await linuxFeedback.feedback
1726 + .animateTo(destination.relativeFrame)
1727 + .catch(() => closeLinuxFeedback(id));
1728 + return;
1729 + }
1730 + transition.animateTo(id, destination);
1731 + await transition.waitForLanding(id);
1732 + });
1733 + },
1734 + ),
1735 + dismissAnimation: Effect.fn("DesktopSnapShot.dismissAnimation")(function (id) {
1736 + return Effect.sync(() => {
1737 closeLinuxFeedback(id);
1738 transition.dismiss(id);
1736 - }),
1737 - acknowledge: (id) =>
1738 - Effect.promise(async () => {
1739 + });
1740 + }),
1741 + acknowledge: Effect.fn("DesktopSnapShot.acknowledge")(function (id) {
1742 + return Effect.promise(async () => {
1743 await completeLinuxFeedback(id);
1744 await transition.complete(id);
1745 }).pipe(
@@ -1751,7 +1755,8 @@ export const make = Effect.gen(function* () {
1755 Effect.mapError(
1756 (cause) => new DesktopSnapShotError({ operation: "acknowledge", captureId: id, cause }),
1757 ),
1754 - ),
1758 + );
1759 + }),
1760 });
1761 });
1762
apps/desktop/src/ssh/DesktopSshEnvironment.ts
+20 -26
@@ -133,32 +133,26 @@ export const make = Effect.gen(function* () {
133 const passwordPrompt = SshAuth.SshPasswordPrompt.of(makePasswordPrompt(prompts));
134
135 return DesktopSshEnvironment.of({
136 - discoverHosts: (input) =>
137 - discoverDesktopSshHostsEffect(input).pipe(
138 - Effect.provide(runtimeContext),
139 - Effect.withSpan("desktop.ssh.discoverHosts"),
140 - ),
141 - resolveHost: (alias) =>
142 - resolveSshTarget(alias.trim()).pipe(
143 - Effect.provide(runtimeContext),
144 - Effect.withSpan("desktop.ssh.resolveHost"),
145 - ),
146 - ensureEnvironment: (target, ensureOptions) =>
147 - manager
148 - .ensureEnvironment(target, ensureOptions)
149 - .pipe(
150 - Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),
151 - Effect.provide(runtimeContext),
152 - Effect.withSpan("desktop.ssh.ensureEnvironment"),
153 - ),
154 - disconnectEnvironment: (target) =>
155 - manager
156 - .disconnectEnvironment(target)
157 - .pipe(
158 - Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),
159 - Effect.provide(runtimeContext),
160 - Effect.withSpan("desktop.ssh.disconnectEnvironment"),
161 - ),
136 + discoverHosts: Effect.fn("desktop.ssh.discoverHosts")(function* (input) {
137 + return yield* discoverDesktopSshHostsEffect(input);
138 + }, Effect.provide(runtimeContext)),
139 + resolveHost: Effect.fn("desktop.ssh.resolveHost")(function* (alias) {
140 + return yield* resolveSshTarget(alias.trim());
141 + }, Effect.provide(runtimeContext)),
142 + ensureEnvironment: Effect.fn("desktop.ssh.ensureEnvironment")(
143 + function* (target, ensureOptions) {
144 + return yield* manager.ensureEnvironment(target, ensureOptions);
145 + },
146 + Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),
147 + Effect.provide(runtimeContext),
148 + ),
149 + disconnectEnvironment: Effect.fn("desktop.ssh.disconnectEnvironment")(
150 + function* (target) {
151 + return yield* manager.disconnectEnvironment(target);
152 + },
153 + Effect.provideService(SshAuth.SshPasswordPrompt, passwordPrompt),
154 + Effect.provide(runtimeContext),
155 + ),
156 });
157 });
158
apps/desktop/src/updates/DesktopUpdates.ts
+3 -1
@@ -1159,7 +1159,9 @@ export const make = Effect.gen(function* () {
1159 install: installWithExpectedVersion().pipe(
1160 Effect.map(({ accepted, completed, state }) => ({ accepted, completed, state })),
1161 ),
1162 - installPrepared: (expectedVersion) => installWithExpectedVersion(expectedVersion),
1162 + installPrepared: Effect.fn("DesktopUpdates.installPrepared")(function (expectedVersion) {
1163 + return installWithExpectedVersion(expectedVersion);
1164 + }),
1165 });
1166 });
1167
apps/desktop/src/wsl/DesktopWslEnvironment.ts
+67 -45
@@ -1070,33 +1070,57 @@ export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => {
1070 isAvailable: Effect.succeed(stub.isAvailable ?? false),
1071 listDistros: probeDistros.pipe(Effect.orElseSucceed(() => [])),
1072 probeDistros,
1073 - preWarm: () => Effect.void,
1074 - windowsToWslPath: (distro, windowsPath) =>
1075 - Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none()),
1076 - getUserHome: (distro) => Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>()),
1077 - getDistroIp: (distro) => Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>()),
1078 - prepareRuntime: (distro, archive) =>
1079 - Effect.succeed(
1073 + preWarm: Effect.fn("DesktopWslEnvironment.preWarm")(function () {
1074 + return Effect.void;
1075 + }),
1076 + windowsToWslPath: Effect.fn("DesktopWslEnvironment.windowsToWslPath")(
1077 + function (distro, windowsPath) {
1078 + return Effect.succeed(stub.windowsToWslPath?.(distro, windowsPath) ?? Option.none());
1079 + },
1080 + ),
1081 + getUserHome: Effect.fn("DesktopWslEnvironment.getUserHome")(function (distro) {
1082 + return Effect.succeed(stub.getUserHome?.(distro) ?? Option.none<string>());
1083 + }),
1084 + getDistroIp: Effect.fn("DesktopWslEnvironment.getDistroIp")(function (distro) {
1085 + return Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none<string>());
1086 + }),
1087 + prepareRuntime: Effect.fn("DesktopWslEnvironment.prepareRuntime")(function (distro, archive) {
1088 + return Effect.succeed(
1089 stub.prepareRuntime?.(distro, archive) ?? {
1090 ok: false,
1091 reason: "prepareRuntime stub not configured",
1092 },
1084 - ),
1085 - pruneRuntimes: (distro, runtimeId) => stub.pruneRuntimes?.(distro, runtimeId) ?? Effect.void,
1086 - invalidateRuntime: (distro, runtimeId) =>
1087 - stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void,
1088 - probeRuntime: (distro, linuxAppRoot) =>
1089 - Effect.succeed(
1090 - stub.probeRuntime?.(distro, linuxAppRoot) ?? { ok: true, resolvedPath: "/usr/bin:/bin" },
1091 - ),
1092 - ensureNodePty: (distro, linuxAppRoot, options) =>
1093 - Effect.succeed(
1094 - stub.ensureNodePty?.(distro, linuxAppRoot, options) ?? {
1095 - ok: false,
1096 - reason: "ensureNodePty stub not configured",
1097 - fatal: true,
1098 - },
1099 - ),
1093 + );
1094 + }),
1095 + pruneRuntimes: Effect.fn("DesktopWslEnvironment.pruneRuntimes")(function (distro, runtimeId) {
1096 + return stub.pruneRuntimes?.(distro, runtimeId) ?? Effect.void;
1097 + }),
1098 + invalidateRuntime: Effect.fn("DesktopWslEnvironment.invalidateRuntime")(
1099 + function (distro, runtimeId) {
1100 + return stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void;
1101 + },
1102 + ),
1103 + probeRuntime: Effect.fn("DesktopWslEnvironment.probeRuntime")(
1104 + function (distro, linuxAppRoot) {
1105 + return Effect.succeed(
1106 + stub.probeRuntime?.(distro, linuxAppRoot) ?? {
1107 + ok: true,
1108 + resolvedPath: "/usr/bin:/bin",
1109 + },
1110 + );
1111 + },
1112 + ),
1113 + ensureNodePty: Effect.fn("DesktopWslEnvironment.ensureNodePty")(
1114 + function (distro, linuxAppRoot, options) {
1115 + return Effect.succeed(
1116 + stub.ensureNodePty?.(distro, linuxAppRoot, options) ?? {
1117 + ok: false,
1118 + reason: "ensureNodePty stub not configured",
1119 + fatal: true,
1120 + },
1121 + );
1122 + },
1123 + ),
1124 }),
1125 );
1126 };
@@ -1151,31 +1175,29 @@ export const layer = Layer.effect(
1175 Effect.withSpan("desktop.wsl.listDistros"),
1176 ),
1177 probeDistros,
1154 - preWarm: (distro) =>
1155 - provideSpawner(preWarmImpl(distro)).pipe(Effect.withSpan("desktop.wsl.preWarm")),
1178 + preWarm: Effect.fn("desktop.wsl.preWarm")(function (distro) {
1179 + return provideSpawner(preWarmImpl(distro));
1180 + }),
1181 windowsToWslPath,
1182 getUserHome,
1183 getDistroIp,
1159 - prepareRuntime: (distro, archive) =>
1160 - provideSpawner(prepareWslRuntimeImpl(distro, archive, windowsToWslPath)).pipe(
1161 - Effect.withSpan("desktop.wsl.prepareRuntime"),
1162 - ),
1163 - pruneRuntimes: (distro, runtimeId) =>
1164 - provideSpawner(pruneWslRuntimesImpl(distro, runtimeId)).pipe(
1165 - Effect.withSpan("desktop.wsl.pruneRuntimes"),
1166 - ),
1167 - invalidateRuntime: (distro, runtimeId) =>
1168 - provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId)).pipe(
1169 - Effect.withSpan("desktop.wsl.invalidateRuntime"),
1170 - ),
1171 - probeRuntime: (distro, linuxAppRoot) =>
1172 - provideSpawner(probeWslRuntimeImpl(distro, linuxAppRoot)).pipe(
1173 - Effect.withSpan("desktop.wsl.probeRuntime"),
1174 - ),
1175 - ensureNodePty: (distro, linuxAppRoot, options) =>
1176 - provideSpawner(ensureNodePtyImpl(distro, linuxAppRoot, options)).pipe(
1177 - Effect.withSpan("desktop.wsl.ensureNodePty"),
1178 - ),
1184 + prepareRuntime: Effect.fn("desktop.wsl.prepareRuntime")(function (distro, archive) {
1185 + return provideSpawner(prepareWslRuntimeImpl(distro, archive, windowsToWslPath));
1186 + }),
1187 + pruneRuntimes: Effect.fn("desktop.wsl.pruneRuntimes")(function (distro, runtimeId) {
1188 + return provideSpawner(pruneWslRuntimesImpl(distro, runtimeId));
1189 + }),
1190 + invalidateRuntime: Effect.fn("desktop.wsl.invalidateRuntime")(function (distro, runtimeId) {
1191 + return provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId));
1192 + }),
1193 + probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro, linuxAppRoot) {
1194 + return provideSpawner(probeWslRuntimeImpl(distro, linuxAppRoot));
1195 + }),
1196 + ensureNodePty: Effect.fn("desktop.wsl.ensureNodePty")(
1197 + function (distro, linuxAppRoot, options) {
1198 + return provideSpawner(ensureNodePtyImpl(distro, linuxAppRoot, options));
1199 + },
1200 + ),
1201 });
1202 }),
1203 );
apps/server/scripts/record-codex-app-server-replay-fixture.ts
+2 -2
@@ -1164,7 +1164,7 @@ function layerCodex({ recorder }: { readonly recorder: Recorder }) {
1164 const clientOptions: CodexClient.CodexAppServerClientOptions = {
1165 logIncoming: true,
1166 logOutgoing: true,
1167 - logger: (event) => {
1167 + logger: Effect.fn("logger")(function (event) {
1168 if (event.stage === "raw") {
1169 return Effect.void;
1170 }
@@ -1215,7 +1215,7 @@ function layerCodex({ recorder }: { readonly recorder: Recorder }) {
1215 yield* updateVersion;
1216 yield* recorder.writeRecord(record);
1217 }).pipe(Effect.ignore);
1218 - },
1218 + }),
1219 };
1220
1221 return Layer.effect(
apps/server/src/auth/EnvironmentAuth.ts
+3 -2
@@ -1374,8 +1374,9 @@ export const make = Effect.gen(function* () {
1374 );
1375
1376 return EnvironmentAuth.of({
1377 - getDescriptor: () =>
1378 - Effect.succeed(descriptor).pipe(Effect.withSpan("EnvironmentAuth.getDescriptor")),
1377 + getDescriptor: Effect.fn("EnvironmentAuth.getDescriptor")(function () {
1378 + return Effect.succeed(descriptor);
1379 + }),
1380 getSessionState,
1381 createBrowserSession,
1382 exchangeBootstrapCredentialForAccessToken,
apps/server/src/auth/EnvironmentAuthPolicy.ts
+3 -2
@@ -52,8 +52,9 @@ export const make = Effect.gen(function* () {
52 };
53
54 return EnvironmentAuthPolicy.of({
55 - getDescriptor: () =>
56 - Effect.succeed(descriptor).pipe(Effect.withSpan("EnvironmentAuthPolicy.getDescriptor")),
55 + getDescriptor: Effect.fn("EnvironmentAuthPolicy.getDescriptor")(function () {
56 + return Effect.succeed(descriptor);
57 + }),
58 });
59 });
60
apps/server/src/auth/McpOAuth.ts
+31 -28
@@ -527,35 +527,38 @@ export const layerMcpClientAuthenticator = Layer.effect(
527 const environment = yield* ServerEnvironment.ServerEnvironment;
528 const environmentId = yield* environment.getEnvironmentId;
529 return McpHttpServer.McpClientAuthenticator.of({
530 - authenticate: (request) =>
531 - environmentAuth.authenticateMcpClient(request).pipe(
532 - Effect.flatMap((client) =>
533 - Clock.currentTimeMillis.pipe(
534 - Effect.map((issuedAt): McpInvocationContext.McpInvocationScope => ({
535 - environmentId,
536 - requestNamespace: `client:${client.sessionId}`,
537 - thread: undefined,
538 - client: {
539 - sessionId: client.sessionId,
540 - label: client.label,
541 - access: client.access,
542 - },
543 - capabilities: new Set<McpInvocationContext.McpCapability>([
544 - "orchestration",
545 - "worktree",
546 - "pull-requests",
547 - ]),
548 - issuedAt,
549 - })),
530 + authenticate: Effect.fn("McpHttpServer.McpClientAuthenticator.authenticate")(
531 + function (request) {
532 + return environmentAuth.authenticateMcpClient(request).pipe(
533 + Effect.flatMap((client) =>
534 + Clock.currentTimeMillis.pipe(
535 + Effect.map((issuedAt): McpInvocationContext.McpInvocationScope => ({
536 + environmentId,
537 + requestNamespace: `client:${client.sessionId}`,
538 + thread: undefined,
539 + client: {
540 + sessionId: client.sessionId,
541 + label: client.label,
542 + access: client.access,
543 + },
544 + capabilities: new Set<McpInvocationContext.McpCapability>([
545 + "orchestration",
546 + "worktree",
547 + "pull-requests",
548 + ]),
549 + issuedAt,
550 + })),
551 + ),
552 ),
551 - ),
552 - Effect.catch((error) =>
553 - (EnvironmentAuth.isServerAuthCredentialError(error)
554 - ? Effect.void
555 - : Effect.logWarning("MCP client authentication failed.", { cause: error })
556 - ).pipe(Effect.as(undefined)),
557 - ),
558 - ),
553 + Effect.catch((error) =>
554 + (EnvironmentAuth.isServerAuthCredentialError(error)
555 + ? Effect.void
556 + : Effect.logWarning("MCP client authentication failed.", { cause: error })
557 + ).pipe(Effect.as(undefined)),
558 + ),
559 + );
560 + },
561 + ),
562 });
563 }),
564 );
apps/server/src/cloud/CliTokenManager.ts
+36 -36
@@ -323,44 +323,44 @@ const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (
323 Effect.flatMap((response) => readTokenResponse(response, params)),
324 Effect.timeout(OAUTH_REQUEST_TIMEOUT),
325 Effect.catchTags({
326 - HttpClientError: (cause) =>
327 - Effect.gen(function* () {
328 - const reason = cause.reason;
329 - if (
330 - params.grant_type !== "refresh_token" ||
331 - reason._tag !== "StatusCodeError" ||
332 - !isPermanentRefreshStatus(reason.response.status)
333 - ) {
334 - return yield* cause;
335 - }
336 - // Reading a rejection body shares the exchange budget without losing
337 - // the known status when the body stalls or cannot be decoded.
338 - const elapsed = Duration.toMillis(
339 - Duration.nanos((yield* Clock.monotonicTimeNanos) - startedAt),
340 - );
341 - const body = yield* reason.response.json.pipe(
342 - Effect.timeout(Math.max(0, Duration.toMillis(OAUTH_REQUEST_TIMEOUT) - elapsed)),
343 - Effect.mapError(
344 - (cause) =>
345 - new CloudCliCredentialRefreshError({
346 - status: reason.response.status,
347 - cause: new HttpClientError.HttpClientError({
348 - reason: new HttpClientError.StatusCodeError({
349 - request: reason.request,
350 - response: reason.response,
351 - cause,
352 - }),
326 + // The enclosing operation owns the span for this inline handler.
327 + HttpClientError: Effect.fnUntraced(function* (cause) {
328 + const reason = cause.reason;
329 + if (
330 + params.grant_type !== "refresh_token" ||
331 + reason._tag !== "StatusCodeError" ||
332 + !isPermanentRefreshStatus(reason.response.status)
333 + ) {
334 + return yield* cause;
335 + }
336 + // Reading a rejection body shares the exchange budget without losing
337 + // the known status when the body stalls or cannot be decoded.
338 + const elapsed = Duration.toMillis(
339 + Duration.nanos((yield* Clock.monotonicTimeNanos) - startedAt),
340 + );
341 + const body = yield* reason.response.json.pipe(
342 + Effect.timeout(Math.max(0, Duration.toMillis(OAUTH_REQUEST_TIMEOUT) - elapsed)),
343 + Effect.mapError(
344 + (cause) =>
345 + new CloudCliCredentialRefreshError({
346 + status: reason.response.status,
347 + cause: new HttpClientError.HttpClientError({
348 + reason: new HttpClientError.StatusCodeError({
349 + request: reason.request,
350 + response: reason.response,
351 + cause,
352 }),
353 }),
355 - ),
356 - );
357 - const diagnostic = decodeOAuthRefreshErrorResponse(body);
358 - return yield* new CloudCliCredentialRefreshError({
359 - cause,
360 - status: reason.response.status,
361 - ...(Option.isSome(diagnostic) ? { oauthErrorCode: diagnostic.value.error } : {}),
362 - });
363 - }),
354 + }),
355 + ),
356 + );
357 + const diagnostic = decodeOAuthRefreshErrorResponse(body);
358 + return yield* new CloudCliCredentialRefreshError({
359 + cause,
360 + status: reason.response.status,
361 + ...(Option.isSome(diagnostic) ? { oauthErrorCode: diagnostic.value.error } : {}),
362 + });
363 + }),
364 }),
365 );
366 });
apps/server/src/cloud/ManagedEndpointRuntime.ts
+3 -1
@@ -759,7 +759,9 @@ export const make = Effect.gen(function* () {
759 inspectConnector,
760 readinessChanged: Stream.fromQueue(readinessChanges),
761 recoveryRequests: Stream.fromQueue(recoveryRequests),
762 - requestRecovery: (config) => Queue.offer(recoveryRequests, config).pipe(Effect.asVoid),
762 + requestRecovery: Effect.fn("CloudManagedEndpointRuntime.requestRecovery")(function (config) {
763 + return Queue.offer(recoveryRequests, config).pipe(Effect.asVoid);
764 + }),
765 tunnelConnected: Stream.fromQueue(tunnelConnections),
766 withLinkStateLock: linkStateSemaphore.withPermits(1),
767 });
apps/server/src/cloud/selfUpdate.ts
+5 -2
@@ -368,8 +368,11 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
368
369 return ServerSelfUpdate.of({
370 update,
371 - commitDesktopUpdate: (requestId, onHandoffAccepted) =>
372 - desktopAppUpdate.commit(requestId, onHandoffAccepted),
371 + commitDesktopUpdate: Effect.fn("ServerSelfUpdate.commitDesktopUpdate")(
372 + function (requestId, onHandoffAccepted) {
373 + return desktopAppUpdate.commit(requestId, onHandoffAccepted);
374 + },
375 + ),
376 });
377 });
378
apps/server/src/device/DeviceService.ts
+8 -6
@@ -804,8 +804,8 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
804 return {
805 ...DeviceService.of({
806 testHost,
807 - updateTool: (tool) =>
808 - lifecycleLock.withPermit(
807 + updateTool: Effect.fn("DeviceService.updateTool")(function (tool) {
808 + return lifecycleLock.withPermit(
809 Effect.gen(function* () {
810 if (!installTool)
811 return yield* new DeviceOperationError({
@@ -816,15 +816,17 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
816 yield* installTool(tool);
817 return yield* inspect;
818 }),
819 - ),
819 + );
820 + }),
821 retryHost,
822 inspect,
822 - easAccount: () =>
823 - Effect.fail(
823 + easAccount: Effect.fn("DeviceService.easAccount")(function () {
824 + return Effect.fail(
825 new DeviceEasAccountError({
826 reason: "EAS accounts are unavailable in this device service.",
827 }),
827 - ),
828 + );
829 + }),
830 agentCli: Effect.fail(
831 new DeviceHostUnavailableError({
832 hostId: LOCAL_DEVICE_HOST_ID,
apps/server/src/device/EasDeviceHost.ts
+3 -2
@@ -862,8 +862,9 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice
862 summary,
863 platformAvailability,
864 ensureReady,
865 - ensureAgentReady: (onPhase) =>
866 - ensureReady(onPhase).pipe(Effect.map((value) => ({ ...value, agentDevice: null }))),
865 + ensureAgentReady: Effect.fn("DeviceHost.ensureAgentReady")(function (onPhase) {
866 + return ensureReady(onPhase).pipe(Effect.map((value) => ({ ...value, agentDevice: null })));
867 + }),
868 current: Effect.sync(() => ready),
869 stopAgent: Effect.void,
870 // Unlike machines the user owns, every running session here is billed.
apps/server/src/environment/DirectEndpoints.ts
+5 -1
@@ -155,7 +155,11 @@ export const make = Effect.gen(function* () {
155 return endpoints;
156 });
157
158 - return DirectEndpoints.of({ resolve: () => resolve });
158 + return DirectEndpoints.of({
159 + resolve: Effect.fn("DirectEndpoints.resolve")(function () {
160 + return resolve;
161 + }),
162 + });
163 });
164
165 export const layer = Layer.effect(DirectEndpoints, make);
apps/server/src/environment/RemoteOpenTargets.ts
+5 -1
@@ -78,7 +78,11 @@ export const make = Effect.gen(function* () {
78 return targets;
79 });
80
81 - return RemoteOpenTargets.of({ resolveTargets: () => resolveTargets });
81 + return RemoteOpenTargets.of({
82 + resolveTargets: Effect.fn("RemoteOpenTargets.resolveTargets")(function () {
83 + return resolveTargets;
84 + }),
85 + });
86 });
87
88 export const layer = Layer.effect(RemoteOpenTargets, make);
apps/server/src/git/GitWorkflowService.ts
+115 -83
@@ -299,8 +299,8 @@ export const make = Effect.gen(function* () {
299 ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input)));
300
301 return GitWorkflowService.of({
302 - isRepository: (cwd) =>
303 - registry.detect({ cwd }).pipe(
302 + isRepository: Effect.fn("GitWorkflowService.isRepository")(function (cwd) {
303 + return registry.detect({ cwd }).pipe(
304 Effect.map((handle) => handle?.kind === "git"),
305 Effect.mapError(
306 (cause) =>
@@ -311,9 +311,10 @@ export const make = Effect.gen(function* () {
311 cause,
312 }),
313 ),
314 - ),
315 - hasCommit: (input) =>
316 - ensureGitCommand("GitWorkflowService.hasCommit", input.cwd).pipe(
314 + );
315 + }),
316 + hasCommit: Effect.fn("GitWorkflowService.hasCommit")(function (input) {
317 + return ensureGitCommand("GitWorkflowService.hasCommit", input.cwd).pipe(
318 Effect.andThen(
319 git.execute({
320 operation: "GitWorkflowService.hasCommit",
@@ -323,10 +324,11 @@ export const make = Effect.gen(function* () {
324 }),
325 ),
326 Effect.map((result) => result.exitCode === 0),
326 - ),
327 - hasRefNamed: (input) =>
327 + );
328 + }),
329 + hasRefNamed: Effect.fn("GitWorkflowService.hasRefNamed")(function (input) {
330 // Pattern characters would widen the ref match.
329 - /[*?[\\]/.test(input.refName)
331 + return /[*?[\\]/.test(input.refName)
332 ? Effect.succeed(false)
333 : ensureGitCommand("GitWorkflowService.hasRefNamed", input.cwd).pipe(
334 Effect.andThen(
@@ -342,36 +344,41 @@ export const make = Effect.gen(function* () {
344 }),
345 ),
346 Effect.map((result) => result.stdout.trim().length > 0),
345 - ),
346 - status: (input) =>
347 - detectGitRepositoryForStatus("GitWorkflowService.status", input.cwd).pipe(
347 + );
348 + }),
349 + status: Effect.fn("GitWorkflowService.status")(function (input) {
350 + return detectGitRepositoryForStatus("GitWorkflowService.status", input.cwd).pipe(
351 Effect.flatMap((isGitRepository) =>
352 isGitRepository ? gitManager.status(input) : Effect.succeed(nonRepositoryStatus()),
353 ),
351 - ),
352 - localStatus: (input) =>
353 - detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe(
354 + );
355 + }),
356 + localStatus: Effect.fn("GitWorkflowService.localStatus")(function (input) {
357 + return detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe(
358 Effect.flatMap((isGitRepository) =>
359 isGitRepository
360 ? gitManager.localStatus(input)
361 : Effect.succeed(nonRepositoryLocalStatus()),
362 ),
359 - ),
360 - remoteStatus: (input, options) =>
361 - detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(
363 + );
364 + }),
365 + remoteStatus: Effect.fn("GitWorkflowService.remoteStatus")(function (input, options) {
366 + return detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(
367 Effect.flatMap((isGitRepository) =>
368 isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null),
369 ),
365 - ),
370 + );
371 + }),
372 invalidateLocalStatus: gitManager.invalidateLocalStatus,
373 invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
374 invalidateStatus: gitManager.invalidateStatus,
369 - pullCurrentBranch: (cwd) =>
370 - ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe(
375 + pullCurrentBranch: Effect.fn("GitWorkflowService.pullCurrentBranch")(function (cwd) {
376 + return ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe(
377 Effect.andThen(git.pullCurrentBranch(cwd)),
372 - ),
373 - runStackedAction: (input, options) =>
374 - ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(
378 + );
379 + }),
380 + runStackedAction: Effect.fn("GitWorkflowService.runStackedAction")(function (input, options) {
381 + return ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(
382 Effect.flatMap((handle) =>
383 input.featureBranch
384 ? withCheckoutLease(
@@ -380,90 +387,115 @@ export const make = Effect.gen(function* () {
387 )
388 : gitManager.runStackedAction(input, options),
389 ),
383 - ),
390 + );
391 + }),
392 resolvePullRequest: routeGitManager(
393 "GitWorkflowService.resolvePullRequest",
394 gitManager.resolvePullRequest,
395 ),
388 - preparePullRequestThread: (input) =>
389 - ensureGit("GitWorkflowService.preparePullRequestThread", input.cwd).pipe(
390 - Effect.flatMap((handle) =>
391 - input.mode === "local"
392 - ? withCheckoutLease(
393 - handle.repository.rootPath,
394 - gitManager.preparePullRequestThread(input),
395 - )
396 - : gitManager.preparePullRequestThread(input),
397 - ),
398 - ),
399 - listRefs: (input) =>
400 - detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(
396 + preparePullRequestThread: Effect.fn("GitWorkflowService.preparePullRequestThread")(
397 + function (input) {
398 + return ensureGit("GitWorkflowService.preparePullRequestThread", input.cwd).pipe(
399 + Effect.flatMap((handle) =>
400 + input.mode === "local"
401 + ? withCheckoutLease(
402 + handle.repository.rootPath,
403 + gitManager.preparePullRequestThread(input),
404 + )
405 + : gitManager.preparePullRequestThread(input),
406 + ),
407 + );
408 + },
409 + ),
410 + listRefs: Effect.fn("GitWorkflowService.listRefs")(function (input) {
411 + return detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(
412 Effect.flatMap((isGitRepository) =>
413 isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()),
414 ),
404 - ),
405 - createWorktree: (input, options) =>
406 - ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
415 + );
416 + }),
417 + createWorktree: Effect.fn("GitWorkflowService.createWorktree")(function (input, options) {
418 + return ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
419 Effect.andThen(gitManager.createWorktree(input, options)),
408 - ),
409 - listLocalBranchNames: (cwd) =>
410 - ensureGitCommand("GitWorkflowService.listLocalBranchNames", cwd).pipe(
420 + );
421 + }),
422 + listLocalBranchNames: Effect.fn("GitWorkflowService.listLocalBranchNames")(function (cwd) {
423 + return ensureGitCommand("GitWorkflowService.listLocalBranchNames", cwd).pipe(
424 Effect.andThen(git.listLocalBranchNames(cwd)),
412 - ),
413 - fetchRemote: (input) =>
414 - ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
425 + );
426 + }),
427 + fetchRemote: Effect.fn("GitWorkflowService.fetchRemote")(function (input) {
428 + return ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
429 Effect.andThen(git.fetchRemote(input)),
416 - ),
417 - remoteExists: (input) =>
418 - ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe(
430 + );
431 + }),
432 + remoteExists: Effect.fn("GitWorkflowService.remoteExists")(function (input) {
433 + return ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe(
434 Effect.andThen(git.remoteExists(input)),
420 - ),
421 - remoteBranchExists: (input) =>
422 - ensureGitCommand("GitWorkflowService.remoteBranchExists", input.cwd).pipe(
435 + );
436 + }),
437 + remoteBranchExists: Effect.fn("GitWorkflowService.remoteBranchExists")(function (input) {
438 + return ensureGitCommand("GitWorkflowService.remoteBranchExists", input.cwd).pipe(
439 Effect.andThen(git.remoteBranchExists(input)),
424 - ),
425 - resolveRemoteTrackingCommit: (input) =>
426 - ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(
427 - Effect.andThen(git.resolveRemoteTrackingCommit(input)),
428 - ),
429 - resolveWorktreeBaseRemote: (input) =>
430 - ensureGitCommand("GitWorkflowService.resolveWorktreeBaseRemote", input.cwd).pipe(
431 - Effect.andThen(git.resolveWorktreeBaseRemote(input)),
432 - ),
433 - fetchWorktreeBaseCommit: (input) =>
434 - ensureGitCommand("GitWorkflowService.fetchWorktreeBaseCommit", input.cwd).pipe(
435 - Effect.andThen(git.fetchWorktreeBaseCommit(input)),
436 - ),
437 - removeWorktree: (input) =>
438 - ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
440 + );
441 + }),
442 + resolveRemoteTrackingCommit: Effect.fn("GitWorkflowService.resolveRemoteTrackingCommit")(
443 + function (input) {
444 + return ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(
445 + Effect.andThen(git.resolveRemoteTrackingCommit(input)),
446 + );
447 + },
448 + ),
449 + resolveWorktreeBaseRemote: Effect.fn("GitWorkflowService.resolveWorktreeBaseRemote")(
450 + function (input) {
451 + return ensureGitCommand("GitWorkflowService.resolveWorktreeBaseRemote", input.cwd).pipe(
452 + Effect.andThen(git.resolveWorktreeBaseRemote(input)),
453 + );
454 + },
455 + ),
456 + fetchWorktreeBaseCommit: Effect.fn("GitWorkflowService.fetchWorktreeBaseCommit")(
457 + function (input) {
458 + return ensureGitCommand("GitWorkflowService.fetchWorktreeBaseCommit", input.cwd).pipe(
459 + Effect.andThen(git.fetchWorktreeBaseCommit(input)),
460 + );
461 + },
462 + ),
463 + removeWorktree: Effect.fn("GitWorkflowService.removeWorktree")(function (input) {
464 + return ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
465 Effect.andThen(git.removeWorktree(input)),
440 - ),
441 - pruneWorktrees: (input) =>
442 - ensureGitCommand("GitWorkflowService.pruneWorktrees", input.cwd).pipe(
466 + );
467 + }),
468 + pruneWorktrees: Effect.fn("GitWorkflowService.pruneWorktrees")(function (input) {
469 + return ensureGitCommand("GitWorkflowService.pruneWorktrees", input.cwd).pipe(
470 Effect.andThen(git.pruneWorktrees(input)),
444 - ),
445 - deleteLocalBranch: (input) =>
446 - ensureGitCommand("GitWorkflowService.deleteLocalBranch", input.cwd).pipe(
471 + );
472 + }),
473 + deleteLocalBranch: Effect.fn("GitWorkflowService.deleteLocalBranch")(function (input) {
474 + return ensureGitCommand("GitWorkflowService.deleteLocalBranch", input.cwd).pipe(
475 Effect.andThen(git.deleteLocalBranch(input)),
448 - ),
449 - createRef: (input) =>
450 - ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(
476 + );
477 + }),
478 + createRef: Effect.fn("GitWorkflowService.createRef")(function (input) {
479 + return ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(
480 Effect.flatMap((handle) =>
481 input.switchRef
482 ? withCheckoutLease(handle.repository.rootPath, git.createRef(input))
483 : git.createRef(input),
484 ),
456 - ),
457 - switchRef: (input) =>
458 - ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
485 + );
486 + }),
487 + switchRef: Effect.fn("GitWorkflowService.switchRef")(function (input) {
488 + return ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
489 Effect.flatMap((handle) =>
490 withCheckoutLease(handle.repository.rootPath, Effect.scoped(git.switchRef(input))),
491 ),
462 - ),
463 - renameBranch: (input) =>
464 - ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
492 + );
493 + }),
494 + renameBranch: Effect.fn("GitWorkflowService.renameBranch")(function (input) {
495 + return ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
496 Effect.andThen(git.renameBranch(input)),
466 - ),
497 + );
498 + }),
499 });
500 });
501
apps/server/src/htmlRender/headlessChrome.ts
+13 -12
@@ -265,13 +265,14 @@ const launchBrowser = Effect.fnUntraced(function* (input: {
265 textEncoder.encode('"}}\0'),
266 ]).pipe(Effect.asVoid);
267
268 - const receive = (raw: string) => {
268 + // Incoming messages share the session span; frame acknowledgements are frequent.
269 + const receive = Effect.fnUntraced(function* (raw: string) {
270 const message = Option.getOrUndefined(decodeCdpMessage(raw));
271 if (message?.id !== undefined) {
272 const waiter = pending.get(message.id);
273 pending.delete(message.id);
273 - if (!waiter) return Effect.void;
274 - return message.error
274 + if (!waiter) return yield* Effect.void;
275 + return yield* message.error
276 ? Deferred.fail(
277 waiter.reply,
278 new HtmlRenderBrowserError({
@@ -283,24 +284,24 @@ const launchBrowser = Effect.fnUntraced(function* (input: {
284 }
285 const sessionId = message?.sessionId;
286 const page = sessionId === undefined ? undefined : pages.get(sessionId);
286 - if (sessionId === undefined || !page || !message?.method) return Effect.void;
287 + if (sessionId === undefined || !page || !message?.method) return yield* Effect.void;
288 if (message.method === "Page.loadEventFired") {
288 - return page.loaded ? Deferred.succeed(page.loaded, undefined) : Effect.void;
289 + return yield* page.loaded ? Deferred.succeed(page.loaded, undefined) : Effect.void;
290 }
291 if (message.method === "Fetch.requestPaused") {
292 const paused = Option.getOrUndefined(decodeRequestPaused(message.params));
292 - if (!paused) return Effect.void;
293 + if (!paused) return yield* Effect.void;
294 const body = page.body;
295 const url = paused.request.url.split("#", 1)[0]!;
296 if (url === PAGE_URL && body !== undefined) {
296 - return fulfillPage(sessionId, paused.requestId, body);
297 + return yield* fulfillPage(sessionId, paused.requestId, body);
298 }
299 // Subframes may show other sites covered by Local Network Access; the main frame stays on T3's page.
300 const otherSiteFrame =
301 paused.resourceType === "Document" &&
302 paused.frameId !== page.mainFrameId &&
303 !url.startsWith(`${PAGE_ORIGIN}/`);
303 - return otherSiteFrame
304 + return yield* otherSiteFrame
305 ? post("Fetch.continueRequest", { requestId: paused.requestId }, sessionId)
306 : post(
307 "Fetch.failRequest",
@@ -309,10 +310,10 @@ const launchBrowser = Effect.fnUntraced(function* (input: {
310 );
311 }
312 const consoleMessage = consoleMessageFromEvent(message.method, message.params);
312 - if (!consoleMessage) return Effect.void;
313 + if (!consoleMessage) return yield* Effect.void;
314 if (page.consoleMessages.length >= MAX_CONSOLE_MESSAGES) {
315 page.omittedConsoleMessages += 1;
315 - return Effect.void;
316 + return yield* Effect.void;
317 }
318 const text = consoleMessage.text.replaceAll(PAGE_URL, PAGE_NAME);
319 page.consoleMessages.push({
@@ -320,8 +321,8 @@ const launchBrowser = Effect.fnUntraced(function* (input: {
321 text:
322 text.length > MAX_CONSOLE_TEXT_CHARS ? `${text.slice(0, MAX_CONSOLE_TEXT_CHARS)}…` : text,
323 });
323 - return Effect.void;
324 - };
324 + return yield* Effect.void;
325 + });
326
327 // Startup aborts close the pipe; let stderr drain to recover the reason.
328 const disconnect = Effect.gen(function* () {
apps/server/src/mcp/McpHttpServer.ts
+8 -5
@@ -400,7 +400,9 @@ const decodeAsAdvertised = <Tools extends Record<string, Tool.Any>>(
400
401 const isPreviewAutomationError = Schema.is(PreviewAutomationError);
402
403 -const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {
403 +const previewSnapshotFailure = Effect.fn("previewSnapshotFailure")(function <E>(
404 + cause: Cause.Cause<E>,
405 +) {
406 if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {
407 return Effect.failCause(cause).pipe(Effect.orDie);
408 }
@@ -433,7 +435,7 @@ const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {
435 errorTag,
436 failureCount: failures.length,
437 }).pipe(Effect.as(result));
436 -};
438 +});
439
440 const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () {
441 const server = yield* McpServer.McpServer;
@@ -903,8 +905,8 @@ const withToolAnalytics =
905 );
906 const recordingServer = McpServer.McpServer.of({
907 ...server,
906 - addTool: (options) =>
907 - server.addTool({
908 + addTool: Effect.fn("McpServer.addTool")(function (options) {
909 + return server.addTool({
910 ...options,
911 handle:
912 /* Request instrumentation already owns the span; keep this helper in that context. */
@@ -926,7 +928,8 @@ const withToolAnalytics =
928 }),
929 );
930 }),
929 - }),
931 + });
932 + }),
933 });
934 return yield* registration.pipe(Effect.provideService(McpServer.McpServer, recordingServer));
935 });
apps/server/src/mcp/PreviewAutomationBroker.ts
+8 -8
@@ -647,14 +647,14 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
647 input.updateCurrentTab === false ? timeoutMs : timeoutMs + HOST_RESPONSE_GRACE_MS;
648 const result = yield* Deferred.await(deferred).pipe(Effect.timeoutOption(responseTimeoutMs));
649 return yield* Option.match(result, {
650 - onNone: () =>
651 - Effect.gen(function* () {
652 - // Never replay possibly applied actions; slow metadata reads must not evict the host.
653 - if (input.updateCurrentTab !== false) {
654 - yield* disconnect(connection.clientId, connection.queue, true);
655 - }
656 - return yield* new PreviewAutomationTimeoutError(requestContext);
657 - }),
650 + // The enclosing operation owns the span for this inline handler.
651 + onNone: Effect.fnUntraced(function* () {
652 + // Never replay possibly applied actions; slow metadata reads must not evict the host.
653 + if (input.updateCurrentTab !== false) {
654 + yield* disconnect(connection.clientId, connection.queue, true);
655 + }
656 + return yield* new PreviewAutomationTimeoutError(requestContext);
657 + }),
658 onSome: (value) => Effect.succeed(value as A),
659 });
660 });
apps/server/src/mcpApps/McpAppModelContext.ts
+8 -1
@@ -91,5 +91,12 @@ export const layer = Layer.effect(
91
92 export const layerEmpty = Layer.succeed(
93 McpAppModelContext,
94 - McpAppModelContext.of({ set: () => Effect.void, forThread: () => Effect.succeed([]) }),
94 + McpAppModelContext.of({
95 + set: Effect.fn("McpAppModelContext.set")(function () {
96 + return Effect.void;
97 + }),
98 + forThread: Effect.fn("McpAppModelContext.forThread")(function () {
99 + return Effect.succeed([]);
100 + }),
101 + }),
102 );
apps/server/src/observability/BrowserTraceCollector.ts
+4 -3
@@ -13,12 +13,13 @@ export class BrowserTraceCollector extends Context.Service<
13 /** @public */
14 export const make = (sink: TraceSink): BrowserTraceCollector["Service"] =>
15 BrowserTraceCollector.of({
16 - record: (records) =>
17 - Effect.sync(() => {
16 + record: Effect.fn("BrowserTraceCollector.record")(function (records) {
17 + return Effect.sync(() => {
18 for (const record of records) {
19 sink.push(record);
20 }
21 - }),
21 + });
22 + }),
23 });
24
25 export const layer = (sink: TraceSink) => Layer.succeed(BrowserTraceCollector, make(sink));
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+6 -2
@@ -4393,8 +4393,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4393 return ProviderAdapter.ProviderAdapterV2.of({
4394 instanceId: adapterOptions.instanceId,
4395 driver: CLAUDE_PROVIDER,
4396 - getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2),
4397 - planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),
4396 + getCapabilities: Effect.fn("ClaudeAdapterV2.getCapabilities")(function () {
4397 + return Effect.succeed(ClaudeProviderCapabilitiesV2);
4398 + }),
4399 + planSelectionTransition: Effect.fn("ClaudeAdapterV2.planSelectionTransition")(function () {
4400 + return Effect.succeed(turnScopedSelectionTransition());
4401 + }),
4402 openSession: Effect.fn("ClaudeAdapterV2.openSession")(
4403 function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) {
4404 const sessionScope = yield* Effect.scope;
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+6 -2
@@ -1634,8 +1634,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
1634 return ProviderAdapter.ProviderAdapterV2.of({
1635 instanceId: adapterOptions.instanceId,
1636 driver: CODEX_PROVIDER,
1637 - getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
1638 - planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),
1637 + getCapabilities: Effect.fn("CodexAdapterV2.getCapabilities")(function () {
1638 + return Effect.succeed(CodexProviderCapabilitiesV2);
1639 + }),
1640 + planSelectionTransition: Effect.fn("CodexAdapterV2.planSelectionTransition")(function () {
1641 + return Effect.succeed(turnScopedSelectionTransition());
1642 + }),
1643 openSession: Effect.fn("CodexAdapterV2.openSession")(
1644 function* (input) {
1645 const scope = yield* Scope.Scope;
apps/server/src/orchestration-v2/CheckpointCaptureService.ts
+4 -3
@@ -232,14 +232,15 @@ export const layer: Layer.Layer<
232 });
233
234 return CheckpointCaptureServiceV2.of({
235 - execute: (input) =>
236 - execute(input).pipe(
235 + execute: Effect.fn("CheckpointCaptureServiceV2.execute")(function (input) {
236 + return execute(input).pipe(
237 Effect.mapError((cause) =>
238 isCheckpointCaptureExecutionError(cause)
239 ? cause
240 : new CheckpointCaptureExecutionError({ ...input, cause }),
241 ),
242 - ),
242 + );
243 + }),
244 });
245 }),
246 );
apps/server/src/orchestration-v2/EffectWorker.ts
+2 -2
@@ -95,7 +95,7 @@ export const layerExecutor: Layer.Layer<
95 const threads = yield* ThreadManagementService.ThreadManagementService;
96 const settings = yield* ServerSettings.ServerSettingsService;
97 return OrchestrationEffectExecutorV2.of({
98 - execute: (effect, options) => {
98 + execute: Effect.fn("OrchestrationEffectExecutorV2.execute")(function (effect, options) {
99 const willRetry = options?.willRetry ?? false;
100 switch (effect.request.type) {
101 case "provider-runtime.continue": {
@@ -557,7 +557,7 @@ export const layerExecutor: Layer.Layer<
557 ),
558 );
559 }
560 - },
560 + }),
561 });
562 }),
563 );
apps/server/src/orchestration-v2/EventStore.ts
+12 -9
@@ -107,8 +107,8 @@ const layerBase: Layer.Layer<EventStoreV2, never, OrchestrationEventStore.Orches
107 );
108
109 return EventStoreV2.of({
110 - append: (input) =>
111 - applicationEvents.appendAgentEvents(input).pipe(
110 + append: Effect.fn("EventStoreV2.append")(function (input) {
111 + return applicationEvents.appendAgentEvents(input).pipe(
112 Effect.mapError(
113 (cause) =>
114 new EventStoreAppendEventsError({
@@ -116,20 +116,22 @@ const layerBase: Layer.Layer<EventStoreV2, never, OrchestrationEventStore.Orches
116 cause,
117 }),
118 ),
119 - ),
120 - appendProjectEvent: (event) =>
121 - applicationEvents
119 + );
120 + }),
121 + appendProjectEvent: Effect.fn("EventStoreV2.appendProjectEvent")(function (event) {
122 + return applicationEvents
123 .appendProjectEvent(event)
124 .pipe(
125 Effect.mapError((cause) => new EventStoreAppendEventsError({ eventCount: 1, cause })),
125 - ),
126 + );
127 + }),
128 read,
129 readByCommandId: ({ commandId }) =>
130 applicationEvents
131 .readAgentEvents({ commandId })
132 .pipe(Stream.mapError((cause) => new EventStoreReadEventsError({ cause }))),
131 - latestSequence: (input) =>
132 - applicationEvents.latestAgentSequence(input?.threadId).pipe(
133 + latestSequence: Effect.fn("EventStoreV2.latestSequence")(function (input) {
134 + return applicationEvents.latestAgentSequence(input?.threadId).pipe(
135 Effect.mapError(
136 (cause) =>
137 new EventStoreReadEventsError({
@@ -137,7 +139,8 @@ const layerBase: Layer.Layer<EventStoreV2, never, OrchestrationEventStore.Orches
139 cause,
140 }),
141 ),
140 - ),
142 + );
143 + }),
144 latestApplicationSequence: applicationEvents.latestApplicationSequence.pipe(
145 Effect.mapError((cause) => new EventStoreReadEventsError({ cause })),
146 ),
apps/server/src/orchestration-v2/Orchestrator.ts
+93 -57
@@ -12398,13 +12398,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
12398 recoverDelegatedTasks,
12399 recoverDelegatedTask,
12400 delegatedTaskResultPending,
12401 - restartContinuationPending: (run) =>
12402 - awaitsRestartContinuation(run).pipe(Effect.orElseSucceed(() => false)),
12403 - awaitRestartContinuation: (run) =>
12404 - effectOutbox.awaitSettled(`effect:restart-continuation:${run.id}`).pipe(Effect.ignore),
12401 + restartContinuationPending: Effect.fn("OrchestratorV2.restartContinuationPending")(
12402 + function (run) {
12403 + return awaitsRestartContinuation(run).pipe(Effect.orElseSucceed(() => false));
12404 + },
12405 + ),
12406 + awaitRestartContinuation: Effect.fn("OrchestratorV2.awaitRestartContinuation")(function (run) {
12407 + return effectOutbox.awaitSettled(`effect:restart-continuation:${run.id}`).pipe(Effect.ignore);
12408 + }),
12409 dispatch: dispatchWithReceipt,
12406 - autoArmLimitRecovery: (input) =>
12407 - threadDispatch.withLock(
12410 + autoArmLimitRecovery: Effect.fn("OrchestratorV2.autoArmLimitRecovery")(function (input) {
12411 + return threadDispatch.withLock(
12412 input.threadId,
12413 Effect.gen(function* () {
12414 const thread = yield* projectionStore
@@ -12422,7 +12426,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
12426 return;
12427 yield* dispatchWithReceiptEffect({ type: "thread.metadata.update", ...input });
12428 }),
12425 - ),
12429 + );
12430 + }),
12431 searchThreadStream: (input) =>
12432 projectionStore
12433 .searchThreadStream(input)
@@ -12431,77 +12436,108 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
12436 (cause) => new OrchestratorProjectionError({ threadId: input.threadId, cause }),
12437 ),
12438 ),
12434 - searchThread: (input) =>
12435 - projectionStore
12439 + searchThread: Effect.fn("OrchestratorV2.searchThread")(function (input) {
12440 + return projectionStore
12441 .searchThread(input)
12442 .pipe(
12443 Effect.mapError(
12444 (cause) => new OrchestratorProjectionError({ threadId: input.threadId, cause }),
12445 ),
12441 - ),
12442 - getThreadHistoryPage: (threadId, cursor, throughEntryId, conversationOnly) =>
12443 - projectionStore
12444 - .getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly)
12445 - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),
12446 - getTimelinePage: (threadId, options) =>
12447 - projectionStore
12446 + );
12447 + }),
12448 + getThreadHistoryPage: Effect.fn("OrchestratorV2.getThreadHistoryPage")(
12449 + function (threadId, cursor, throughEntryId, conversationOnly) {
12450 + return projectionStore
12451 + .getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly)
12452 + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));
12453 + },
12454 + ),
12455 + getTimelinePage: Effect.fn("OrchestratorV2.getTimelinePage")(function (threadId, options) {
12456 + return projectionStore
12457 .getTimelinePage(threadId, options)
12449 - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),
12450 - getMessageCount: (threadId) =>
12451 - projectionStore
12458 + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));
12459 + }),
12460 + getMessageCount: Effect.fn("OrchestratorV2.getMessageCount")(function (threadId) {
12461 + return projectionStore
12462 .getMessageCount(threadId)
12453 - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),
12454 - getTurnItem: (input) =>
12455 - projectionStore
12463 + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));
12464 + }),
12465 + getTurnItem: Effect.fn("OrchestratorV2.getTurnItem")(function (input) {
12466 + return projectionStore
12467 .getTurnItem(input)
12468 .pipe(
12469 Effect.mapError(
12470 (cause) => new OrchestratorProjectionError({ threadId: input.threadId, cause }),
12471 ),
12461 - ),
12462 - getThreadRecords: (threadId, fields, filter) =>
12463 - projectionStore
12464 - .getThreadRecords(threadId, fields, filter)
12465 - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),
12466 - getThreadProjection: (threadId) =>
12467 - projectionStore
12472 + );
12473 + }),
12474 + getThreadRecords: Effect.fn("OrchestratorV2.getThreadRecords")(
12475 + function (threadId, fields, filter) {
12476 + return projectionStore
12477 + .getThreadRecords(threadId, fields, filter)
12478 + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));
12479 + },
12480 + ),
12481 + getThreadProjection: Effect.fn("OrchestratorV2.getThreadProjection")(function (threadId) {
12482 + return projectionStore
12483 .getThreadProjection(threadId)
12469 - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),
12470 - getCheckpointContext: (threadId) =>
12471 - projectionStore
12484 + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));
12485 + }),
12486 + getCheckpointContext: Effect.fn("OrchestratorV2.getCheckpointContext")(function (threadId) {
12487 + return projectionStore
12488 .getCheckpointContext(threadId)
12473 - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),
12474 - getThreadSnapshot: (threadId) =>
12475 - projectionStore
12489 + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));
12490 + }),
12491 + getThreadSnapshot: Effect.fn("OrchestratorV2.getThreadSnapshot")(function (threadId) {
12492 + return projectionStore
12493 .getThreadSnapshot(threadId)
12477 - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),
12478 - getThreadSnapshotWindow: (threadId, options) =>
12479 - projectionStore
12480 - .getThreadSnapshotWindow(threadId, options)
12481 - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),
12482 - getShellSnapshot: (options) =>
12483 - projectionStore.getShellSnapshot(options).pipe(Effect.mapError(shellProjectionError)),
12484 - listActiveSubagentThreadIds: () =>
12485 - projectionStore.listActiveSubagentThreadIds().pipe(Effect.mapError(shellProjectionError)),
12486 - listOlderSettledThreads: (query) =>
12487 - projectionStore.listOlderSettledThreads(query).pipe(Effect.mapError(shellProjectionError)),
12488 - readShellSnapshot: (options) =>
12489 - projectionStore
12494 + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));
12495 + }),
12496 + getThreadSnapshotWindow: Effect.fn("OrchestratorV2.getThreadSnapshotWindow")(
12497 + function (threadId, options) {
12498 + return projectionStore
12499 + .getThreadSnapshotWindow(threadId, options)
12500 + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));
12501 + },
12502 + ),
12503 + getShellSnapshot: Effect.fn("OrchestratorV2.getShellSnapshot")(function (options) {
12504 + return projectionStore.getShellSnapshot(options).pipe(Effect.mapError(shellProjectionError));
12505 + }),
12506 + listActiveSubagentThreadIds: Effect.fn("OrchestratorV2.listActiveSubagentThreadIds")(
12507 + function () {
12508 + return projectionStore
12509 + .listActiveSubagentThreadIds()
12510 + .pipe(Effect.mapError(shellProjectionError));
12511 + },
12512 + ),
12513 + listOlderSettledThreads: Effect.fn("OrchestratorV2.listOlderSettledThreads")(function (query) {
12514 + return projectionStore
12515 + .listOlderSettledThreads(query)
12516 + .pipe(Effect.mapError(shellProjectionError));
12517 + }),
12518 + readShellSnapshot: Effect.fn("OrchestratorV2.readShellSnapshot")(function (options) {
12519 + return projectionStore
12520 .readShellSnapshot(options)
12521 .pipe(
12522 Effect.mapError(shellProjectionError),
12523 Effect.map(Effect.mapError(shellProjectionError)),
12494 - ),
12495 - getThreadShell: (threadId) =>
12496 - projectionStore
12524 + );
12525 + }),
12526 + getThreadShell: Effect.fn("OrchestratorV2.getThreadShell")(function (threadId) {
12527 + return projectionStore
12528 .getThreadShell(threadId)
12498 - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),
12499 - findGuestShareThreadId: (shareId) =>
12500 - projectionStore.findGuestShareThreadId(shareId).pipe(Effect.mapError(shellProjectionError)),
12501 - getThreadEventSequence: (threadId) =>
12502 - eventSink
12529 + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));
12530 + }),
12531 + findGuestShareThreadId: Effect.fn("OrchestratorV2.findGuestShareThreadId")(function (shareId) {
12532 + return projectionStore
12533 + .findGuestShareThreadId(shareId)
12534 + .pipe(Effect.mapError(shellProjectionError));
12535 + }),
12536 + getThreadEventSequence: Effect.fn("OrchestratorV2.getThreadEventSequence")(function (threadId) {
12537 + return eventSink
12538 .latestSequence({ threadId })
12504 - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),
12539 + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));
12540 + }),
12541 streamStoredEvents: eventSink.stream().pipe(
12542 Stream.mapError(
12543 (cause) =>
apps/server/src/orchestration-v2/ProjectStore.ts
+8 -5
@@ -266,11 +266,14 @@ export const make = Effect.gen(function* () {
266 get,
267 list,
268 findActiveByWorkspaceRoot,
269 - getShell: (projectId) => get(projectId).pipe(Effect.map(Option.map(toShell))),
270 - listShells: (options) =>
271 - list(options?.projectIds === undefined ? undefined : { projectIds: options.projectIds }).pipe(
272 - Effect.map((rows) => rows.map(toShell)),
273 - ),
269 + getShell: Effect.fn("ProjectStoreV2.getShell")(function (projectId) {
270 + return get(projectId).pipe(Effect.map(Option.map(toShell)));
271 + }),
272 + listShells: Effect.fn("ProjectStoreV2.listShells")(function (options) {
273 + return list(
274 + options?.projectIds === undefined ? undefined : { projectIds: options.projectIds },
275 + ).pipe(Effect.map((rows) => rows.map(toShell)));
276 + }),
277 });
278 });
279
apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts
+8 -6
@@ -75,8 +75,8 @@ export const layerFromProviderInstanceRegistry: Layer.Layer<
75 Effect.gen(function* () {
76 const instances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
77 return ProviderAdapterRegistryV2.of({
78 - get: (instanceId) =>
79 - instances.getInstance(instanceId).pipe(
78 + get: Effect.fn("ProviderAdapterRegistryV2.get")(function (instanceId) {
79 + return instances.getInstance(instanceId).pipe(
80 Effect.flatMap((instance) => {
81 if (instance === undefined)
82 return new ProviderAdapterRegistryLookupError({ instanceId });
@@ -131,11 +131,13 @@ export const layerFromProviderInstanceRegistry: Layer.Layer<
131 },
132 } satisfies ProviderAdapter.ProviderAdapterV2["Service"]);
133 }),
134 - ),
135 - list: () =>
136 - instances.listInstances.pipe(
134 + );
135 + }),
136 + list: Effect.fn("ProviderAdapterRegistryV2.list")(function () {
137 + return instances.listInstances.pipe(
138 Effect.map((available) => available.map((instance) => instance.instanceId)),
138 - ),
139 + );
140 + }),
141 getMetadata: Effect.fn("ProviderAdapterRegistry.getMetadata")(function* (instanceId) {
142 const instance = yield* instances.getInstance(instanceId);
143 if (instance === undefined) {
apps/server/src/orchestration-v2/ProviderEventIngestor.ts
+5 -2
@@ -114,8 +114,11 @@ export const layerAnalytics = Layer.effect(
114 Effect.gen(function* () {
115 const analytics = yield* AnalyticsService.AnalyticsService;
116 return {
117 - record: (properties: Readonly<Record<string, unknown>>) =>
118 - analytics.record("provider.turn.completed", properties),
117 + record: Effect.fn("ProviderTurnAnalytics.record")(function (
118 + properties: Readonly<Record<string, unknown>>,
119 + ) {
120 + return analytics.record("provider.turn.completed", properties);
121 + }),
122 };
123 }),
124 );
apps/server/src/orchestration-v2/ResourceCleanupService.ts
+24 -12
@@ -47,33 +47,44 @@ export const layer = Layer.effect(
47 const config = yield* ServerConfig.ServerConfig;
48 const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService;
49 return {
50 - cleanupScheduledTasks: (threadId: ThreadId) =>
51 - scheduledTasks
50 + cleanupScheduledTasks: Effect.fn("ResourceCleanupService.cleanupScheduledTasks")(function (
51 + threadId: ThreadId,
52 + ) {
53 + return scheduledTasks
54 .deleteForThread(threadId)
55 .pipe(
56 Effect.mapError(
57 (cause) =>
58 new ResourceCleanupError({ operation: "scheduled-tasks", threadId, cause }),
59 ),
58 - ),
59 - cleanupTerminals: (threadId: string) =>
60 - terminals
60 + );
61 + }),
62 + cleanupTerminals: Effect.fn("ResourceCleanupService.cleanupTerminals")(function (
63 + threadId: string,
64 + ) {
65 + return terminals
66 .close({ threadId, deleteHistory: true })
67 .pipe(
68 Effect.mapError(
69 (cause) => new ResourceCleanupError({ operation: "terminal", threadId, cause }),
70 ),
66 - ),
67 - cleanupPreviews: (threadId: string) =>
68 - previews
71 + );
72 + }),
73 + cleanupPreviews: Effect.fn("ResourceCleanupService.cleanupPreviews")(function (
74 + threadId: string,
75 + ) {
76 + return previews
77 .close({ threadId: ThreadId.make(threadId) })
78 .pipe(
79 Effect.mapError(
80 (cause) => new ResourceCleanupError({ operation: "preview", threadId, cause }),
81 ),
74 - ),
75 - cleanupAttachments: (attachmentIds: ReadonlyArray<string>) =>
76 - Effect.forEach(
82 + );
83 + }),
84 + cleanupAttachments: Effect.fn("ResourceCleanupService.cleanupAttachments")(function (
85 + attachmentIds: ReadonlyArray<string>,
86 + ) {
87 + return Effect.forEach(
88 attachmentIds,
89 (attachmentId) => {
90 const extension = parseAttachmentFileExtension(attachmentId);
@@ -99,7 +110,8 @@ export const layer = Layer.effect(
110 );
111 },
112 { discard: true, concurrency: 4 },
102 - ),
113 + );
114 + }),
115 };
116 }),
117 );
apps/server/src/orchestration-v2/RuntimePolicy.ts
+4 -3
@@ -51,12 +51,13 @@ export class RuntimePolicyV2 extends Context.Service<RuntimePolicyV2, RuntimePol
51 ) {}
52
53 export const layer: Layer.Layer<RuntimePolicyV2> = Layer.succeed(RuntimePolicyV2, {
54 - resolve: (input) =>
55 - Effect.succeed({
54 + resolve: Effect.fn("RuntimePolicyV2.resolve")(function (input) {
55 + return Effect.succeed({
56 runtimeMode: input.thread.runtimeMode,
57 interactionMode: input.thread.interactionMode,
58 cwd: input.thread.worktreePath,
59 - }),
59 + });
60 + }),
61 });
62
63 function providerRuntimeMode(
apps/server/src/orchestration-v2/ThreadLifecycleService.ts
+28 -21
@@ -88,54 +88,61 @@ const make = Effect.gen(function* () {
88 );
89
90 return ThreadLifecycleService.of({
91 - archive: (input) =>
92 - dispatch("archive", input.threadId, {
91 + archive: Effect.fn("ThreadLifecycleService.archive")(function (input) {
92 + return dispatch("archive", input.threadId, {
93 type: "thread.archive",
94 commandId: input.commandId,
95 threadId: input.threadId,
96 - }),
97 - unarchive: (input) =>
98 - dispatch("unarchive", input.threadId, {
96 + });
97 + }),
98 + unarchive: Effect.fn("ThreadLifecycleService.unarchive")(function (input) {
99 + return dispatch("unarchive", input.threadId, {
100 type: "thread.unarchive",
101 commandId: input.commandId,
102 threadId: input.threadId,
102 - }),
103 - delete: (input) =>
104 - dispatch("delete", input.threadId, {
103 + });
104 + }),
105 + delete: Effect.fn("ThreadLifecycleService.delete")(function (input) {
106 + return dispatch("delete", input.threadId, {
107 type: "thread.delete",
108 commandId: input.commandId,
109 threadId: input.threadId,
108 - }),
109 - updateMetadata: (input) =>
110 - dispatch("update-metadata", input.threadId, {
110 + });
111 + }),
112 + updateMetadata: Effect.fn("ThreadLifecycleService.updateMetadata")(function (input) {
113 + return dispatch("update-metadata", input.threadId, {
114 type: "thread.metadata.update",
115 commandId: input.commandId,
116 threadId: input.threadId,
117 ...(input.title === undefined ? {} : { title: input.title }),
118 ...(input.branch === undefined ? {} : { branch: input.branch }),
119 ...(input.worktreePath === undefined ? {} : { worktreePath: input.worktreePath }),
117 - }),
118 - setRuntimeMode: (input) =>
119 - dispatch("set-runtime-mode", input.threadId, {
120 + });
121 + }),
122 + setRuntimeMode: Effect.fn("ThreadLifecycleService.setRuntimeMode")(function (input) {
123 + return dispatch("set-runtime-mode", input.threadId, {
124 type: "thread.runtime-mode.set",
125 commandId: input.commandId,
126 threadId: input.threadId,
127 runtimeMode: input.runtimeMode,
124 - }),
125 - setInteractionMode: (input) =>
126 - dispatch("set-interaction-mode", input.threadId, {
128 + });
129 + }),
130 + setInteractionMode: Effect.fn("ThreadLifecycleService.setInteractionMode")(function (input) {
131 + return dispatch("set-interaction-mode", input.threadId, {
132 type: "thread.interaction-mode.set",
133 commandId: input.commandId,
134 threadId: input.threadId,
135 interactionMode: input.interactionMode,
131 - }),
132 - setModelSelection: (input) =>
133 - dispatch("set-model-selection", input.threadId, {
136 + });
137 + }),
138 + setModelSelection: Effect.fn("ThreadLifecycleService.setModelSelection")(function (input) {
139 + return dispatch("set-model-selection", input.threadId, {
140 type: "thread.model-selection.set",
141 commandId: input.commandId,
142 threadId: input.threadId,
143 modelSelection: input.modelSelection,
138 - }),
144 + });
145 + }),
146 });
147 });
148
apps/server/src/orchestration-v2/ThreadManagementService.ts
+38 -24
@@ -1204,34 +1204,46 @@ const make = Effect.gen(function* () {
1204 Effect.as(orchestrator.searchThreadStream(input)),
1205 ),
1206 ),
1207 - searchThread: (input) =>
1208 - ensureProjectionTranscript(input.threadId).pipe(
1207 + searchThread: Effect.fn("ThreadManagementService.searchThread")(function (input) {
1208 + return ensureProjectionTranscript(input.threadId).pipe(
1209 Effect.andThen(orchestrator.searchThread(input)),
1210 - ),
1210 + );
1211 + }),
1212 dispatch,
1212 - getThreadHistoryPage: (threadId, cursor, throughEntryId, conversationOnly) =>
1213 - ensureProjectionTranscript(threadId).pipe(
1214 - Effect.andThen(
1215 - orchestrator.getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly),
1216 - ),
1217 - ),
1218 - getTimelinePage: (threadId, options) =>
1219 - ensureProjectionTranscript(threadId).pipe(
1220 - Effect.andThen(orchestrator.getTimelinePage(threadId, options)),
1221 - ),
1222 - getMessageCount: (threadId) =>
1223 - ensureProjectionTranscript(threadId).pipe(
1213 + getThreadHistoryPage: Effect.fn("ThreadManagementService.getThreadHistoryPage")(
1214 + function (threadId, cursor, throughEntryId, conversationOnly) {
1215 + return ensureProjectionTranscript(threadId).pipe(
1216 + Effect.andThen(
1217 + orchestrator.getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly),
1218 + ),
1219 + );
1220 + },
1221 + ),
1222 + getTimelinePage: Effect.fn("ThreadManagementService.getTimelinePage")(
1223 + function (threadId, options) {
1224 + return ensureProjectionTranscript(threadId).pipe(
1225 + Effect.andThen(orchestrator.getTimelinePage(threadId, options)),
1226 + );
1227 + },
1228 + ),
1229 + getMessageCount: Effect.fn("ThreadManagementService.getMessageCount")(function (threadId) {
1230 + return ensureProjectionTranscript(threadId).pipe(
1231 Effect.andThen(orchestrator.getMessageCount(threadId)),
1225 - ),
1226 - getTurnItem: (input) =>
1227 - ensureProjectionTranscript(input.threadId).pipe(
1232 + );
1233 + }),
1234 + getTurnItem: Effect.fn("ThreadManagementService.getTurnItem")(function (input) {
1235 + return ensureProjectionTranscript(input.threadId).pipe(
1236 Effect.andThen(orchestrator.getTurnItem(input)),
1237 Effect.map((item) => ({ item: item === null ? null : projectTurnItemForDetail(item) })),
1230 - ),
1231 - getThreadRecords: (threadId, fields, filter) =>
1232 - ensureProjectionTranscript(threadId).pipe(
1233 - Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)),
1234 - ),
1238 + );
1239 + }),
1240 + getThreadRecords: Effect.fn("ThreadManagementService.getThreadRecords")(
1241 + function (threadId, fields, filter) {
1242 + return ensureProjectionTranscript(threadId).pipe(
1243 + Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)),
1244 + );
1245 + },
1246 + ),
1247 getThreadProjection,
1248 getCheckpointContext,
1249 getThreadSnapshot,
@@ -1270,7 +1282,9 @@ const layerLegacyV1ThreadImporterNoop = Layer.succeed(
1282 LegacyV1ThreadImporter.LegacyV1ThreadImporter.of({
1283 pendingThreadCount: Effect.succeed(0),
1284 reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1273 - ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1285 + ensureTranscript: Effect.fn("LegacyV1ThreadImporter.ensureTranscript")(function () {
1286 + return Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 });
1287 + }),
1288 importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
1289 }),
1290 );
apps/server/src/orchestration-v2/TurnItemPositionStore.ts
+5 -3
@@ -103,13 +103,15 @@ export const layer: Layer.Layer<TurnItemPositionStoreV2, never, SqlClient.SqlCli
103
104 return TurnItemPositionStoreV2.of({
105 allocate,
106 - normalize: (item, runOrdinal) =>
107 - allocate({
106 + // Per-event normalization shares the enclosing orchestration span.
107 + normalize: Effect.fnUntraced(function* (item, runOrdinal) {
108 + return yield* allocate({
109 threadId: item.threadId,
110 turnItemId: item.id,
111 runId: item.runId,
112 ...(runOrdinal === undefined ? {} : { runOrdinal }),
112 - }).pipe(Effect.map((ordinal) => (item.ordinal === ordinal ? item : { ...item, ordinal }))),
113 + }).pipe(Effect.map((ordinal) => (item.ordinal === ordinal ? item : { ...item, ordinal })));
114 + }),
115 });
116 }),
117 );
apps/server/src/orchestration-v2/testkit/CommandOutputRecorder.ts
+4 -3
@@ -34,14 +34,15 @@ export const layer: Layer.Layer<
34 CommandOutputHub.CommandOutputHub,
35 CommandOutputHub.CommandOutputHub.of({
36 ...hub,
37 - append: (input) =>
38 - Effect.sync(() => {
37 + append: Effect.fn("CommandOutputHub.append")(function (input) {
38 + return Effect.sync(() => {
39 const previous = recorded.get(input.itemId);
40 recorded.set(input.itemId, {
41 chunks: (previous?.chunks ?? 0) + 1,
42 output: appendTerminalOutput(previous?.output ?? EMPTY_TERMINAL_OUTPUT, input.chunk),
43 });
44 - }).pipe(Effect.andThen(hub.append(input))),
44 + }).pipe(Effect.andThen(hub.append(input)));
45 + }),
46 }),
47 ).pipe(
48 Context.add(CommandOutputRecorder, {
apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts
+12 -13
@@ -279,19 +279,18 @@ export function runOrchestratorV2Scenario(
279 const capturedShellSnapshots = new Map<string, OrchestrationV2ThreadShellSnapshot>();
280 let anonymousBackgroundDispatchIndex = 0;
281
282 - const awaitDispatch = (key: string) =>
283 - Effect.gen(function* () {
284 - const fiber = backgroundDispatches.get(key);
285 - if (!fiber) {
286 - return yield* new OrchestratorV2ScenarioStepError({
287 - scenario: scenario.name,
288 - step: `await:${key}`,
289 - });
290 - }
291 - const events = yield* Fiber.join(fiber);
292 - backgroundDispatches.delete(key);
293 - storedEventGroups.push(events);
294 - });
282 + const awaitDispatch = Effect.fn("awaitDispatch")(function* (key: string) {
283 + const fiber = backgroundDispatches.get(key);
284 + if (!fiber) {
285 + return yield* new OrchestratorV2ScenarioStepError({
286 + scenario: scenario.name,
287 + step: `await:${key}`,
288 + });
289 + }
290 + const events = yield* Fiber.join(fiber);
291 + backgroundDispatches.delete(key);
292 + storedEventGroups.push(events);
293 + });
294
295 const waitForPendingRuntimeRequest = (
296 threadId: ThreadId,
apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts
+3 -1
@@ -444,7 +444,9 @@ export function layerWithRegistry<Error>(
444 const layerThreadTitleRegenerationTest = Layer.succeed(
445 ThreadTitleRegenerationService.ThreadTitleRegenerationService,
446 ThreadTitleRegenerationService.ThreadTitleRegenerationService.of({
447 - execute: () => Effect.void,
447 + execute: Effect.fn("ThreadTitleRegenerationService.execute")(function () {
448 + return Effect.void;
449 + }),
450 }),
451 );
452 const layerOrchestratorProvided = Orchestrator.layer.pipe(
apps/server/src/persistence/PullRequestFilesViewed.ts
+8 -6
@@ -84,18 +84,19 @@ const make = Effect.gen(function* () {
84 });
85
86 return PullRequestFilesViewedRepository.of({
87 - list: (input) =>
88 - listRows(input).pipe(
87 + list: Effect.fn("PullRequestFilesViewedRepository.list")(function (input) {
88 + return listRows(input).pipe(
89 NodeSqliteClient.readOnly,
90 Effect.map((rows) => ({
91 files: rows.slice(0, MAX_FILES_VIEWED_ROWS),
92 truncated: rows.length > MAX_FILES_VIEWED_ROWS,
93 })),
94 Effect.mapError(toSqlOrDecodeError("listPullRequestFilesViewed", "PullRequestFileViewed")),
95 - ),
95 + );
96 + }),
97
97 - set: (input) =>
98 - sql
98 + set: Effect.fn("PullRequestFilesViewedRepository.set")(function (input) {
99 + return sql
100 .withTransaction(
101 Effect.forEach(
102 input.files,
@@ -141,7 +142,8 @@ const make = Effect.gen(function* () {
142 Effect.mapError(
143 (cause) => new PersistenceSqlError({ operation: "setPullRequestFilesViewed", cause }),
144 ),
144 - ),
145 + );
146 + }),
147 });
148 });
149
apps/server/src/persistence/PullRequestReviewGuides.ts
+8 -6
@@ -51,8 +51,8 @@ const make = Effect.gen(function* () {
51 const encodeGuide = Schema.encodeEffect(Schema.fromJsonString(PullRequestReviewGuide));
52
53 return PullRequestReviewGuideRepository.of({
54 - get: (key) =>
55 - findGuide(key).pipe(
54 + get: Effect.fn("PullRequestReviewGuideRepository.get")(function (key) {
55 + return findGuide(key).pipe(
56 NodeSqliteClient.readOnly,
57 Effect.map(Option.map((row) => row.guide)),
58 Effect.mapError((cause) =>
@@ -60,9 +60,10 @@ const make = Effect.gen(function* () {
60 ? PersistenceDecodeError.fromSchemaError("PullRequestReviewGuide", cause)
61 : new PersistenceSqlError({ operation: "getPullRequestReviewGuide", cause }),
62 ),
63 - ),
64 - put: (key, guide) =>
65 - encodeGuide(guide).pipe(
63 + );
64 + }),
65 + put: Effect.fn("PullRequestReviewGuideRepository.put")(function (key, guide) {
66 + return encodeGuide(guide).pipe(
67 Effect.mapError((cause) =>
68 PersistenceDecodeError.fromSchemaError("PullRequestReviewGuide", cause),
69 ),
@@ -78,7 +79,8 @@ const make = Effect.gen(function* () {
79 ),
80 ),
81 Effect.asVoid,
81 - ),
82 + );
83 + }),
84 });
85 });
86
apps/server/src/preview/DesktopBrowserChannel.ts
+28 -11
@@ -66,13 +66,23 @@ const make = Effect.gen(function* () {
66 if (inputFd === undefined || controlFd === undefined) {
67 return DesktopBrowserChannel.of({
68 available: false,
69 - awaitAttached: () => Effect.succeed(false),
69 + awaitAttached: Effect.fn("DesktopBrowserChannel.awaitAttached")(function () {
70 + return Effect.succeed(false);
71 + }),
72 detached: Stream.empty,
73 attached: Stream.empty,
72 - isAttached: () => Effect.succeed(false),
73 - endpoint: () => Effect.die("No desktop app is attached to this server."),
74 - pointer: () => Effect.void,
75 - turn: () => Effect.void,
74 + isAttached: Effect.fn("DesktopBrowserChannel.isAttached")(function () {
75 + return Effect.succeed(false);
76 + }),
77 + endpoint: Effect.fn("DesktopBrowserChannel.endpoint")(function () {
78 + return Effect.die("No desktop app is attached to this server.");
79 + }),
80 + turn: Effect.fn("DesktopBrowserChannel.turn")(function () {
81 + return Effect.void;
82 + }),
83 + pointer: Effect.fn("DesktopBrowserChannel.pointer")(function () {
84 + return Effect.void;
85 + }),
86 });
87 }
88
@@ -185,8 +195,8 @@ const make = Effect.gen(function* () {
195
196 return DesktopBrowserChannel.of({
197 available: true,
188 - awaitAttached: (key, timeout) =>
189 - Effect.scoped(
198 + awaitAttached: Effect.fn("DesktopBrowserChannel.awaitAttached")(function (key, timeout) {
199 + return Effect.scoped(
200 Effect.gen(function* () {
201 const subscription = yield* PubSub.subscribe(changes);
202 if (attachedTabs.has(keyOf(key))) return true;
@@ -198,7 +208,8 @@ const make = Effect.gen(function* () {
208 Effect.map((result) => Option.getOrElse(result, () => false)),
209 );
210 }),
201 - ),
211 + );
212 + }),
213 detached: Stream.fromPubSub(changes).pipe(
214 Stream.filter((change) => !change.attached),
215 Stream.map((change) => change.key),
@@ -207,10 +218,16 @@ const make = Effect.gen(function* () {
218 Stream.filter((change) => change.attached),
219 Stream.map((change) => change.key),
220 ),
210 - isAttached: (key) => Effect.sync(() => attachedTabs.has(keyOf(key))),
221 + isAttached: Effect.fn("DesktopBrowserChannel.isAttached")(function (key) {
222 + return Effect.sync(() => attachedTabs.has(keyOf(key)));
223 + }),
224 endpoint,
212 - pointer: (key, pointer) => command({ type: "pointer", ...key, ...pointer }),
213 - turn: (threadId, active) => command({ type: "turn", threadId, active }),
225 + turn: Effect.fn("DesktopBrowserChannel.turn")(function (threadId, active) {
226 + return command({ type: "turn", threadId, active });
227 + }),
228 + pointer: Effect.fn("DesktopBrowserChannel.pointer")(function (key, pointer) {
229 + return command({ type: "pointer", ...key, ...pointer });
230 + }),
231 });
232 });
233
apps/server/src/preview/PreviewAgentActivity.ts
+3 -1
@@ -50,7 +50,9 @@ const make = Effect.gen(function* () {
50
51 return PreviewAgentActivity.of({
52 begin,
53 - active: (threadId) => Effect.sync(() => turns.has(threadId)),
53 + active: Effect.fn("PreviewAgentActivity.active")(function (threadId) {
54 + return Effect.sync(() => turns.has(threadId));
55 + }),
56 changes: PubSub.subscribe(changes),
57 });
58 });
apps/server/src/preview/ServerBrowserStream.ts
+5 -4
@@ -176,12 +176,13 @@ const makeHandler = Effect.fnUntraced(function* (browser: ServerBrowser.ServerBr
176 }
177 }),
178 );
179 - const receive = (chunk: Uint8Array | string) => {
179 + // Incoming messages share the session span; frame acknowledgements are frequent.
180 + const receive = Effect.fnUntraced(function* (chunk: Uint8Array | string) {
181 const message = parseMessage(chunk);
182 // Ownership serializes actions in the service. Keep reading so dialog
183 // replies and takeover can unblock an action already waiting on the page.
184 if (!isAck(message))
184 - return canOperate
185 + return yield* canOperate
186 ? viewer.input(message).pipe(Effect.forkScoped, Effect.asVoid)
187 : Effect.void;
188 const ack = inFlight;
@@ -189,11 +190,11 @@ const makeHandler = Effect.fnUntraced(function* (browser: ServerBrowser.ServerBr
190 inFlight = null;
191 pending = null;
192 // Forked: Chromium acks are paced and must not hold up input.
192 - return Effect.andThen(
193 + return yield* Effect.andThen(
194 ack ? Effect.forkScoped(ack) : Effect.void,
195 next ? sendFrame(next) : Effect.void,
196 );
196 - };
197 + });
198 const receiveInput = reader.pull.pipe(
199 Effect.flatMap((chunks) => Effect.forEach(chunks, receive, { discard: true })),
200 );
apps/server/src/process/externalLauncher.ts
+22 -13
@@ -817,20 +817,29 @@ export const make = Effect.gen(function* () {
817 }).pipe(Effect.uninterruptible);
818 const cachedAvailableEditors = Effect.flatMap(acquireEditorDiscovery, Deferred.await);
819
820 + // Forwarders retain the underlying launcher and discovery spans.
821 return ExternalLauncher.of({
821 - resolveAvailableEditors: () => cachedAvailableEditors,
822 - resolveFileManagerRevealKind: () =>
823 - provideCommandResolutionServices(resolveFileManagerRevealKind()).pipe(
824 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
825 - ),
826 - launchBrowser: (target) =>
827 - launchBrowser(target).pipe(
828 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
829 - ),
830 - launchEditor: (input) =>
831 - provideCommandResolutionServices(launchEditor(input)).pipe(
832 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
833 - ),
822 + resolveAvailableEditors: Effect.fnUntraced(function* () {
823 + return yield* cachedAvailableEditors;
824 + }),
825 + resolveFileManagerRevealKind: Effect.fnUntraced(
826 + function* () {
827 + return yield* provideCommandResolutionServices(resolveFileManagerRevealKind());
828 + },
829 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
830 + ),
831 + launchBrowser: Effect.fnUntraced(
832 + function* (target) {
833 + return yield* launchBrowser(target);
834 + },
835 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
836 + ),
837 + launchEditor: Effect.fnUntraced(
838 + function* (input) {
839 + return yield* provideCommandResolutionServices(launchEditor(input));
840 + },
841 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
842 + ),
843 });
844 });
845
apps/server/src/project/ProjectCloneTracker.ts
+13 -4
@@ -417,11 +417,20 @@ export const make = Effect.gen(function* () {
417 { bufferSize: 1, strategy: "sliding" },
418 );
419
420 + // Forwarders retain the underlying operation spans.
421 return ProjectCloneTracker.of({
421 - start: (input, hooks) => locked(start(input, hooks)),
422 - cancel: (projectId) => locked(cancel(projectId)),
423 - retry: (projectId) => locked(retry(projectId)),
424 - discard: (projectId) => locked(discard(projectId)),
422 + start: Effect.fnUntraced(function* (input, hooks) {
423 + return yield* locked(start(input, hooks));
424 + }),
425 + cancel: Effect.fnUntraced(function* (projectId) {
426 + return yield* locked(cancel(projectId));
427 + }),
428 + retry: Effect.fnUntraced(function* (projectId) {
429 + return yield* locked(retry(projectId));
430 + }),
431 + discard: Effect.fnUntraced(function* (projectId) {
432 + return yield* locked(discard(projectId));
433 + }),
434 get,
435 stream,
436 });
apps/server/src/provider/CodexChatGptHandoff.ts
+17 -9
@@ -18,17 +18,25 @@ export function subscribeChatGptHandoff(
18 const bytes = new Map<string, Uint8Array>();
19 yield* Effect.addFinalizer(() => Effect.sync(() => bytes.clear()));
20 const store = ServerSecretStore.ServerSecretStore.of({
21 - get: (key) => Effect.sync(() => Option.fromUndefinedOr(bytes.get(key))),
22 - set: (key, value) =>
23 - Effect.sync(() => {
21 + get: Effect.fn("ServerSecretStore.get")(function (key) {
22 + return Effect.sync(() => Option.fromUndefinedOr(bytes.get(key)));
23 + }),
24 + set: Effect.fn("ServerSecretStore.set")(function (key, value) {
25 + return Effect.sync(() => {
26 bytes.set(key, value);
25 - }),
26 - remove: (key) =>
27 - Effect.sync(() => {
27 + });
28 + }),
29 + remove: Effect.fn("ServerSecretStore.remove")(function (key) {
30 + return Effect.sync(() => {
31 bytes.delete(key);
29 - }),
30 - create: () => Effect.die("Handoff does not create persistent secrets."),
31 - getOrCreateRandom: () => Effect.die("Handoff uses the destination environment identity."),
32 + });
33 + }),
34 + create: Effect.fn("ServerSecretStore.create")(function () {
35 + return Effect.die("Handoff does not create persistent secrets.");
36 + }),
37 + getOrCreateRandom: Effect.fn("ServerSecretStore.getOrCreateRandom")(function () {
38 + return Effect.die("Handoff uses the destination environment identity.");
39 + }),
40 });
41 const auth = yield* makeCodexChatGptAuth({
42 ...endpoints,
apps/server/src/provider/ModelManifest.ts
+4 -3
@@ -267,10 +267,11 @@ export const layerModelCatalog = Layer.effect(
267 Effect.gen(function* () {
268 const manifest = yield* ModelManifest;
269 return ModelCatalog.ModelCatalog.of({
270 - current: (driverKind) =>
271 - manifest.current.pipe(
270 + current: Effect.fn("ModelCatalog.current")(function (driverKind) {
271 + return manifest.current.pipe(
272 Effect.map((data) => resolveProviderCatalog(data, driverKind) ?? undefined),
273 - ),
273 + );
274 + }),
275 bundled: (driverKind) =>
276 resolveProviderCatalog(BUNDLED_MODEL_MANIFEST, driverKind) ?? undefined,
277 refreshInBackground: manifest.refreshInBackground,
apps/server/src/provider/ProviderAuthService.ts
+4 -3
@@ -205,8 +205,8 @@ export const makeProviderAuthService = Effect.gen(function* () {
205 });
206 return yield* auth.reconnectProfile(input.methodId);
207 }),
208 - importProfile: (input) =>
209 - credentialChanges.withPermit(
208 + importProfile: Effect.fn("ProviderAuthService.importProfile")(function (input) {
209 + return credentialChanges.withPermit(
210 Effect.gen(function* () {
211 const auth = yield* getController(input.instanceId, "import");
212 yield* checkSharedBinding(input.instanceId, "start", auth);
@@ -221,7 +221,8 @@ export const makeProviderAuthService = Effect.gen(function* () {
221 stopSessions(input.instanceId, auth.credentialBinding),
222 );
223 }),
224 - ),
224 + );
225 + }),
226 start: Effect.fn("ProviderAuthService.start")(function* (input, ownerSessionId) {
227 return yield* credentialChanges.withPermit(
228 Effect.gen(function* () {
apps/server/src/provider/ProviderHostLive.ts
+11 -7
@@ -39,12 +39,15 @@ export const layer = Layer.effect(
39 shouldRunBackgroundWork: backgroundPolicy.shouldRunScopeWork,
40 resolveAttachmentPath: (attachment) =>
41 resolveAttachmentPath({ attachmentsDir: config.attachmentsDir, attachment }),
42 - resolveExtractedTextPath: (path) =>
43 - DocumentText.resolveExtractedTextPath(path).pipe(
44 - Effect.provideService(FileSystem.FileSystem, fileSystem),
45 - ),
46 - credentials: (namespace, bindingId) =>
47 - ProviderCredentialStore.make(namespace, bindingId).pipe(
42 + // DocumentText owns the path-resolution span.
43 + resolveExtractedTextPath: Effect.fnUntraced(
44 + function* (path) {
45 + return yield* DocumentText.resolveExtractedTextPath(path);
46 + },
47 + Effect.provideService(FileSystem.FileSystem, fileSystem),
48 + ),
49 + credentials: Effect.fn("ProviderHost.credentials")(function (namespace, bindingId) {
50 + return ProviderCredentialStore.make(namespace, bindingId).pipe(
51 Effect.map((store) => ({
52 binding: store.binding,
53 get: store.get.pipe(
@@ -66,7 +69,8 @@ export const layer = Layer.effect(
69 })),
70 Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
71 Effect.provideService(Crypto.Crypto, crypto),
69 - ),
72 + );
73 + }),
74 });
75 }),
76 );
apps/server/src/pullRequest/PullRequestService.ts
+7 -4
@@ -3623,10 +3623,13 @@ export const make = Effect.gen(function* () {
3623 withRoutingCredential,
3624 list,
3625 filterOptions,
3626 - listStats: (input) =>
3627 - Effect.forEach(input.refs, (ref) => canonicalRef(ref).pipe(Effect.option)).pipe(
3628 - Effect.flatMap((refs) => listStats({ ...input, refs: refs.flatMap(Option.toArray) })),
3629 - ),
3626 + // The local operation owns the span; this wrapper only canonicalizes refs.
3627 + listStats: Effect.fnUntraced(function* (input) {
3628 + const refs = yield* Effect.forEach(input.refs, (ref) =>
3629 + canonicalRef(ref).pipe(Effect.option),
3630 + );
3631 + return yield* listStats({ ...input, refs: refs.flatMap(Option.toArray) });
3632 + }),
3633 summary: credentialCached(summary),
3634 stack: credentialCached(stack),
3635 subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(
apps/server/src/relay/AgentAwarenessRelay.ts
+3 -1
@@ -843,7 +843,9 @@ export const make = Effect.gen(function* () {
843 return AgentAwarenessRelay.of({
844 publishThread,
845 drain: worker.drain,
846 - requestCatchUp: () => Queue.offer(catchUpRequests, undefined).pipe(Effect.asVoid),
846 + requestCatchUp: Effect.fn("AgentAwarenessRelay.requestCatchUp")(function () {
847 + return Queue.offer(catchUpRequests, undefined).pipe(Effect.asVoid);
848 + }),
849 start,
850 });
851 });
apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts
+31 -14
@@ -637,16 +637,25 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")
637 health: Ref.get(health),
638 subscribeHealth: subscribeBeforeSnapshotWithoutMutex(healthChanges, Ref.get(health)),
639 setDiagnosticsDemand,
640 - requestDesktopUpdate: (requestId) =>
641 - sendControlMessage({
642 - version: 1,
643 - type: "requestDesktopUpdate",
644 - requestId,
645 - }),
646 - commitDesktopUpdate: (requestId) =>
647 - sendControlMessage({ version: 1, type: "commitDesktopUpdate", requestId }),
648 - cancelDesktopUpdate: (requestId) =>
649 - sendControlMessage({ version: 1, type: "cancelDesktopUpdate", requestId }),
640 + requestDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.requestDesktopUpdate")(
641 + function (requestId) {
642 + return sendControlMessage({
643 + version: 1,
644 + type: "requestDesktopUpdate",
645 + requestId,
646 + });
647 + },
648 + ),
649 + commitDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.commitDesktopUpdate")(
650 + function (requestId) {
651 + return sendControlMessage({ version: 1, type: "commitDesktopUpdate", requestId });
652 + },
653 + ),
654 + cancelDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.cancelDesktopUpdate")(
655 + function (requestId) {
656 + return sendControlMessage({ version: 1, type: "cancelDesktopUpdate", requestId });
657 + },
658 + ),
659 desktopUpdates: Effect.gen(function* () {
660 const subscription = yield* PubSub.subscribe(updateReportChanges);
661 const initial = yield* Ref.get(latestUpdateReport);
@@ -694,10 +703,18 @@ export const layerTest = (
703 changes: Stream.empty,
704 })),
705 ),
697 - setDiagnosticsDemand: () => Effect.void,
698 - requestDesktopUpdate: () => Effect.void,
699 - commitDesktopUpdate: () => Effect.void,
700 - cancelDesktopUpdate: () => Effect.void,
706 + setDiagnosticsDemand: Effect.fn("DesktopTelemetryReceiver.setDiagnosticsDemand")(function () {
707 + return Effect.void;
708 + }),
709 + requestDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.requestDesktopUpdate")(function () {
710 + return Effect.void;
711 + }),
712 + commitDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.commitDesktopUpdate")(function () {
713 + return Effect.void;
714 + }),
715 + cancelDesktopUpdate: Effect.fn("DesktopTelemetryReceiver.cancelDesktopUpdate")(function () {
716 + return Effect.void;
717 + }),
718 desktopUpdates:
719 overrides.desktopUpdates ??
720 Effect.succeed({
apps/server/src/resourceTelemetry/NativeTelemetryClient.ts
+10 -5
@@ -1088,14 +1088,19 @@ export const layerTest = (
1088 processTree: true,
1089 }),
1090 snapshots: Stream.empty,
1091 - readHistory: () =>
1092 - Effect.fail(
1091 + readHistory: Effect.fn("NativeTelemetryClient.readHistory")(function () {
1092 + return Effect.fail(
1093 new NativeTelemetryUnavailable({
1094 reason: "No resource monitor history was configured for this test.",
1095 }),
1096 - ),
1097 - setExternalProcesses: () => Effect.void,
1098 - setHostPowerState: () => Effect.void,
1096 + );
1097 + }),
1098 + setExternalProcesses: Effect.fn("NativeTelemetryClient.setExternalProcesses")(function () {
1099 + return Effect.void;
1100 + }),
1101 + setHostPowerState: Effect.fn("NativeTelemetryClient.setHostPowerState")(function () {
1102 + return Effect.void;
1103 + }),
1104 sampleNow: Effect.fail(
1105 new NativeTelemetryUnavailable({
1106 reason: "No resource monitor sample was configured for this test.",
apps/server/src/sourceControl/SourceControlProviderRegistry.ts
+31 -20
@@ -71,6 +71,7 @@ export class SourceControlProviderRegistry extends Context.Service<
71 function unsupportedProvider(
72 kind: SourceControlProviderKind,
73 ): SourceControlProvider.SourceControlProvider["Service"] {
74 + // Binding context does not create a second provider-operation span.
75 return SourceControlProvider.SourceControlProvider.of({
76 kind,
77 // Unknown hosts have no readable change requests; return none to avoid poll warnings on every refresh.
@@ -195,37 +196,45 @@ function bindProviderContext(
196
197 return SourceControlProvider.SourceControlProvider.of({
198 ...provider,
198 - listChangeRequests: (input) =>
199 - provider.listChangeRequests({
199 + listChangeRequests: Effect.fnUntraced(function* (input) {
200 + return yield* provider.listChangeRequests({
201 ...input,
202 context: input.context ?? context,
202 - }),
203 - getChangeRequest: (input) =>
204 - provider.getChangeRequest({
203 + });
204 + }),
205 + getChangeRequest: Effect.fnUntraced(function* (input) {
206 + return yield* provider.getChangeRequest({
207 ...input,
208 context: input.context ?? context,
207 - }),
208 - createChangeRequest: (input) =>
209 - provider.createChangeRequest({
209 + });
210 + }),
211 + createChangeRequest: Effect.fnUntraced(function* (input) {
212 + return yield* provider.createChangeRequest({
213 ...input,
214 context: input.context ?? context,
212 - }),
213 - getRepositoryCloneUrls: (input) =>
214 - provider.getRepositoryCloneUrls({
215 + });
216 + }),
217 + getRepositoryCloneUrls: Effect.fnUntraced(function* (input) {
218 + return yield* provider.getRepositoryCloneUrls({
219 ...input,
220 context: input.context ?? context,
217 - }),
218 - createRepository: (input) => provider.createRepository(input),
219 - getDefaultBranch: (input) =>
220 - provider.getDefaultBranch({
221 + });
222 + }),
223 + createRepository: Effect.fnUntraced(function* (input) {
224 + return yield* provider.createRepository(input);
225 + }),
226 + getDefaultBranch: Effect.fnUntraced(function* (input) {
227 + return yield* provider.getDefaultBranch({
228 ...input,
229 context: input.context ?? context,
223 - }),
224 - checkoutChangeRequest: (input) =>
225 - provider.checkoutChangeRequest({
230 + });
231 + }),
232 + checkoutChangeRequest: Effect.fnUntraced(function* (input) {
233 + return yield* provider.checkoutChangeRequest({
234 ...input,
235 context: input.context ?? context,
228 - }),
236 + });
237 + }),
238 });
239 }
240
@@ -336,7 +345,9 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
345 },
346 get,
347 resolveHandle,
339 - resolve: (input) => resolveHandle(input).pipe(Effect.map((handle) => handle.provider)),
348 + resolve: Effect.fn("SourceControlProviderRegistry.resolve")(function (input) {
349 + return resolveHandle(input).pipe(Effect.map((handle) => handle.provider));
350 + }),
351 discover: Effect.forEach(
352 discoverySpecs,
353 (spec) =>
apps/server/src/sourceControl/SourceControlRepositoryService.ts
+23 -13
@@ -521,29 +521,39 @@ export const make = Effect.gen(function* () {
521 },
522 );
523
524 + // Forwarders retain the underlying operation spans.
525 return SourceControlRepositoryService.of({
525 - lookupRepository: (input) =>
526 - lookupRepository(input).pipe(mapRepositoryError("lookupRepository", input.provider)),
527 - prepareClone: (input) =>
528 - prepareClone(input).pipe(
526 + lookupRepository: Effect.fnUntraced(function* (input) {
527 + return yield* lookupRepository(input).pipe(
528 + mapRepositoryError("lookupRepository", input.provider),
529 + );
530 + }),
531 + prepareClone: Effect.fnUntraced(function* (input) {
532 + return yield* prepareClone(input).pipe(
533 mapRepositoryError(
534 "cloneRepository",
535 input.provider ?? SourceControlProviderKind.make("unknown"),
536 ),
533 - ),
534 - cloneRepository: (input, options) =>
535 - cloneRepository(input, options).pipe(
537 + );
538 + }),
539 + cloneRepository: Effect.fnUntraced(function* (input, options) {
540 + return yield* cloneRepository(input, options).pipe(
541 mapRepositoryError(
542 "cloneRepository",
543 input.provider ?? SourceControlProviderKind.make("unknown"),
544 ),
540 - ),
541 - discardClone: (destinationPath) =>
542 - discardClone(destinationPath).pipe(
545 + );
546 + }),
547 + discardClone: Effect.fnUntraced(function* (destinationPath) {
548 + return yield* discardClone(destinationPath).pipe(
549 mapRepositoryError("discardClone", SourceControlProviderKind.make("unknown")),
544 - ),
545 - publishRepository: (input) =>
546 - publishRepository(input).pipe(mapRepositoryError("publishRepository", input.provider)),
550 + );
551 + }),
552 + publishRepository: Effect.fnUntraced(function* (input) {
553 + return yield* publishRepository(input).pipe(
554 + mapRepositoryError("publishRepository", input.provider),
555 + );
556 + }),
557 });
558 });
559
apps/server/src/telemetry/AnalyticsService.ts
+6 -2
@@ -95,9 +95,13 @@ export class AnalyticsService extends Context.Service<
95 static readonly layerTest = Layer.succeed(
96 AnalyticsService,
97 AnalyticsService.of({
98 - record: () => Effect.void,
98 + record: Effect.fn("AnalyticsService.record")(function () {
99 + return Effect.void;
100 + }),
101 flush: Effect.void,
100 - recordOwners: () => Effect.void,
102 + recordOwners: Effect.fn("AnalyticsService.recordOwners")(function () {
103 + return Effect.void;
104 + }),
105 }),
106 );
107 }
apps/server/src/textGeneration/TextGeneration.ts
+23 -16
@@ -57,24 +57,30 @@ export const make = Effect.gen(function* () {
57 const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
58 const sourceControl = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
59 return TextGeneration.of({
60 - generateCommitMessage: (input) =>
61 - resolveInstance(registry, "generateCommitMessage", input.modelSelection.instanceId).pipe(
62 - Effect.flatMap((textGeneration) => textGeneration.generateCommitMessage(input)),
63 - ),
64 - generatePrContent: (input) =>
65 - resolveInstance(registry, "generatePrContent", input.modelSelection.instanceId).pipe(
60 + generateCommitMessage: Effect.fn("TextGeneration.generateCommitMessage")(function (input) {
61 + return resolveInstance(
62 + registry,
63 + "generateCommitMessage",
64 + input.modelSelection.instanceId,
65 + ).pipe(Effect.flatMap((textGeneration) => textGeneration.generateCommitMessage(input)));
66 + }),
67 + generatePrContent: Effect.fn("TextGeneration.generatePrContent")(function (input) {
68 + return resolveInstance(registry, "generatePrContent", input.modelSelection.instanceId).pipe(
69 Effect.flatMap((textGeneration) => textGeneration.generatePrContent(input)),
67 - ),
68 - generateBranchName: (input) =>
69 - resolveInstance(registry, "generateBranchName", input.modelSelection.instanceId).pipe(
70 + );
71 + }),
72 + generateBranchName: Effect.fn("TextGeneration.generateBranchName")(function (input) {
73 + return resolveInstance(registry, "generateBranchName", input.modelSelection.instanceId).pipe(
74 Effect.flatMap((textGeneration) => textGeneration.generateBranchName(input)),
71 - ),
72 - generateReviewGuide: (input) =>
73 - resolveInstance(registry, "generateReviewGuide", input.modelSelection.instanceId).pipe(
75 + );
76 + }),
77 + generateReviewGuide: Effect.fn("TextGeneration.generateReviewGuide")(function (input) {
78 + return resolveInstance(registry, "generateReviewGuide", input.modelSelection.instanceId).pipe(
79 Effect.flatMap((textGeneration) => textGeneration.generateReviewGuide(input)),
75 - ),
76 - generateThreadTitle: (input) =>
77 - resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe(
80 + );
81 + }),
82 + generateThreadTitle: Effect.fn("TextGeneration.generateThreadTitle")(function (input) {
83 + return resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe(
84 Effect.flatMap((textGeneration) =>
85 Effect.gen(function* () {
86 const linkedContext =
@@ -88,7 +94,8 @@ export const make = Effect.gen(function* () {
94 return yield* textGeneration.generateThreadTitle({ ...input, linkedContext });
95 }),
96 ),
91 - ),
97 + );
98 + }),
99 });
100 });
101
apps/server/src/vcs/GitVcsDriverCore.ts
+56 -26
@@ -4439,6 +4439,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4439 ),
4440 );
4441
4442 + // Forwarders retain the underlying Git operation spans.
4443 return GitVcsDriver.GitVcsDriver.of({
4444 execute,
4445 status,
@@ -4446,11 +4447,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4447 statusDetailsLocal,
4448 statusDetailsRemote,
4449 prepareCommitContext,
4449 - commit: (cwd, subject, body, options) =>
4450 - withListRefsInvalidation(cwd, commit(cwd, subject, body, options)),
4451 - pushCurrentBranch: (cwd, fallbackBranch, options) =>
4452 - withListRefsInvalidation(cwd, pushCurrentBranch(cwd, fallbackBranch, options)),
4453 - pullCurrentBranch: (cwd) => withListRefsInvalidation(cwd, pullCurrentBranch(cwd)),
4450 + commit: Effect.fnUntraced(function* (cwd, subject, body, options) {
4451 + return yield* withListRefsInvalidation(cwd, commit(cwd, subject, body, options));
4452 + }),
4453 + pushCurrentBranch: Effect.fnUntraced(function* (cwd, fallbackBranch, options) {
4454 + return yield* withListRefsInvalidation(cwd, pushCurrentBranch(cwd, fallbackBranch, options));
4455 + }),
4456 + pullCurrentBranch: Effect.fnUntraced(function* (cwd) {
4457 + return yield* withListRefsInvalidation(cwd, pullCurrentBranch(cwd));
4458 + }),
4459 readRangeContext,
4460 getReviewDiffPreview,
4461 getReviewDiffFileContents,
@@ -4458,18 +4463,24 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4463 readBranchBase,
4464 resolveBranchName,
4465 listRefs,
4461 - createWorktree: (input, options) =>
4462 - withListRefsInvalidation(input.cwd, createWorktree(input, options)),
4463 - fetchRefIntoBranch: (input) => withListRefsInvalidation(input.cwd, fetchRefIntoBranch(input)),
4466 + createWorktree: Effect.fnUntraced(function* (input, options) {
4467 + return yield* withListRefsInvalidation(input.cwd, createWorktree(input, options));
4468 + }),
4469 + fetchRefIntoBranch: Effect.fnUntraced(function* (input) {
4470 + return yield* withListRefsInvalidation(input.cwd, fetchRefIntoBranch(input));
4471 + }),
4472 fetchRefCommit,
4473 resolveCommit,
4466 - refreshCheckedOutBranch: (input) =>
4467 - withListRefsInvalidation(input.cwd, refreshCheckedOutBranch(input)),
4468 - ensureRemote: (input) => withListRefsInvalidation(input.cwd, ensureRemote(input)),
4474 + refreshCheckedOutBranch: Effect.fnUntraced(function* (input) {
4475 + return yield* withListRefsInvalidation(input.cwd, refreshCheckedOutBranch(input));
4476 + }),
4477 + ensureRemote: Effect.fnUntraced(function* (input) {
4478 + return yield* withListRefsInvalidation(input.cwd, ensureRemote(input));
4479 + }),
4480 resolvePrimaryRemoteName,
4481 resolveDefaultBranchName,
4471 - fetchRemote: (input) =>
4472 - withListRefsInvalidation(
4482 + fetchRemote: Effect.fnUntraced(function* (input) {
4483 + return yield* withListRefsInvalidation(
4484 input.cwd,
4485 fetchRemote(input).pipe(
4486 Effect.flatMap((fetched) =>
@@ -4478,23 +4489,42 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4489 : fetchRemote({ cwd: input.cwd, remoteName: input.remoteName }).pipe(Effect.asVoid),
4490 ),
4491 ),
4481 - ),
4492 + );
4493 + }),
4494 remoteExists,
4495 remoteBranchExists,
4496 resolveRemoteTrackingCommit,
4497 resolveWorktreeBaseRemote,
4486 - fetchWorktreeBaseCommit: (input) =>
4487 - withListRefsInvalidation(input.cwd, fetchWorktreeBaseCommit(input)),
4488 - fetchRemoteBranch: (input) => withListRefsInvalidation(input.cwd, fetchRemoteBranch(input)),
4489 - fetchRemoteTrackingBranch: (input) =>
4490 - withListRefsInvalidation(input.cwd, fetchRemoteTrackingBranch(input)),
4491 - setBranchUpstream: (input) => withListRefsInvalidation(input.cwd, setBranchUpstream(input)),
4492 - removeWorktree: (input) => withListRefsInvalidation(input.cwd, removeWorktree(input)),
4493 - pruneWorktrees: (input) => withListRefsInvalidation(input.cwd, pruneWorktrees(input)),
4494 - deleteLocalBranch: (input) => withListRefsInvalidation(input.cwd, deleteLocalBranch(input)),
4495 - renameBranch: (input) => withListRefsInvalidation(input.cwd, renameBranch(input)),
4496 - createRef: (input) => withListRefsInvalidation(input.cwd, createRef(input)),
4497 - switchRef: (input) => withListRefsInvalidation(input.cwd, switchRef(input)),
4498 + fetchWorktreeBaseCommit: Effect.fnUntraced(function* (input) {
4499 + return yield* withListRefsInvalidation(input.cwd, fetchWorktreeBaseCommit(input));
4500 + }),
4501 + fetchRemoteBranch: Effect.fnUntraced(function* (input) {
4502 + return yield* withListRefsInvalidation(input.cwd, fetchRemoteBranch(input));
4503 + }),
4504 + fetchRemoteTrackingBranch: Effect.fnUntraced(function* (input) {
4505 + return yield* withListRefsInvalidation(input.cwd, fetchRemoteTrackingBranch(input));
4506 + }),
4507 + setBranchUpstream: Effect.fnUntraced(function* (input) {
4508 + return yield* withListRefsInvalidation(input.cwd, setBranchUpstream(input));
4509 + }),
4510 + removeWorktree: Effect.fnUntraced(function* (input) {
4511 + return yield* withListRefsInvalidation(input.cwd, removeWorktree(input));
4512 + }),
4513 + pruneWorktrees: Effect.fnUntraced(function* (input) {
4514 + return yield* withListRefsInvalidation(input.cwd, pruneWorktrees(input));
4515 + }),
4516 + deleteLocalBranch: Effect.fnUntraced(function* (input) {
4517 + return yield* withListRefsInvalidation(input.cwd, deleteLocalBranch(input));
4518 + }),
4519 + renameBranch: Effect.fnUntraced(function* (input) {
4520 + return yield* withListRefsInvalidation(input.cwd, renameBranch(input));
4521 + }),
4522 + createRef: Effect.fnUntraced(function* (input) {
4523 + return yield* withListRefsInvalidation(input.cwd, createRef(input));
4524 + }),
4525 + switchRef: Effect.fnUntraced(function* (input) {
4526 + return yield* withListRefsInvalidation(input.cwd, switchRef(input));
4527 + }),
4528 initRepo: initRepoWithListRefsInvalidation,
4529 listLocalBranchNames,
4530 listWorktreePaths,
apps/web/src/connection/platform.ts
+9 -6
@@ -791,25 +791,28 @@ const layerPlatformConnectionSource = Layer.effect(
791 const layerEnvironmentOwnedDataCleanup = Layer.succeed(
792 Persistence.EnvironmentOwnedDataCleanup,
793 Persistence.EnvironmentOwnedDataCleanup.of({
794 - clear: (environmentId) =>
795 - Effect.sync(() => {
794 + clear: Effect.fn("Persistence.EnvironmentOwnedDataCleanup.clear")(function (environmentId) {
795 + return Effect.sync(() => {
796 clearComposerDraftsEnvironment(environmentId);
797 - }),
797 + });
798 + }),
799 }),
800 );
801
802 const layerRpcRequestObserver = Layer.succeed(
803 EnvironmentRpcRequestObserver,
804 EnvironmentRpcRequestObserver.of({
804 - observe: ({ environmentId, environmentLabel, method }) =>
805 - Effect.sync(() => {
805 + // Every RPC passes through this observer; the request owns its span.
806 + observe: Effect.fnUntraced(function* ({ environmentId, environmentLabel, method }) {
807 + return yield* Effect.sync(() => {
808 nextObservedRpcRequestId += 1;
809 const requestId = `${environmentId}:${nextObservedRpcRequestId}`;
810 trackRpcRequestSent(requestId, method, `${method} · ${environmentLabel}`);
811 return Effect.sync(() => {
812 acknowledgeRpcRequest(requestId);
813 });
812 - }),
814 + });
815 + }),
816 }),
817 );
818
apps/web/src/connection/storage.ts
+156 -119
@@ -543,11 +543,12 @@ export function makeBrowserPullRequestRoutingPermissions(
543 catch: (cause) => catalogError("save pull request routing permissions in", cause),
544 });
545 return PullRequestRoutingPermissions.of({
546 - get: (entry) =>
547 - Effect.sync(() => {
546 + get: Effect.fn("PullRequestRoutingPermissions.get")(function (entry) {
547 + return Effect.sync(() => {
548 const value = read(`${PULL_REQUEST_ROUTING_KEY_PREFIX}${entry.target.environmentId}`);
549 return pullRequestRoutingPermissionFor(entry, value === null ? [] : [value]);
550 - }),
550 + });
551 + }),
552 changes: Stream.callback<ReadonlyArray<StoredPullRequestRoutingPermission>>((queue) =>
553 Effect.acquireRelease(
554 Effect.sync(() => {
@@ -570,16 +571,14 @@ export function makeBrowserPullRequestRoutingPermissions(
571 }),
572 ).pipe(Effect.asVoid),
573 ),
573 - set: (entry, permission) => {
574 + set: Effect.fn("PullRequestRoutingPermissions.set")(function* (entry, permission) {
575 const connectionKey = pullRequestRoutingConnectionKey(entry);
576 if (connectionKey === null)
576 - return Effect.fail(
577 - new ConnectionBlockedError({
578 - reason: "configuration",
579 - detail: "This environment does not have a saved connection endpoint.",
580 - }),
581 - );
582 - return write(
577 + return yield* new ConnectionBlockedError({
578 + reason: "configuration",
579 + detail: "This environment does not have a saved connection endpoint.",
580 + });
581 + return yield* write(
582 entry.target.environmentId,
583 permission === "off"
584 ? null
@@ -589,8 +588,10 @@ export function makeBrowserPullRequestRoutingPermissions(
588 permission,
589 },
590 );
592 - },
593 - forget: (environmentId) => write(environmentId, null),
591 + }),
592 + forget: Effect.fn("PullRequestRoutingPermissions.forget")(function (environmentId) {
593 + return write(environmentId, null);
594 + }),
595 });
596 }
597
@@ -635,22 +636,32 @@ export const layer = Layer.effectContext(
636 ),
637 });
638 const registrationStore = Persistence.ConnectionRegistrationStore.of({
638 - register: (registration, routes) =>
639 - catalog
640 - .update((document) => registerConnectionInCatalog(document, registration, routes))
641 - .pipe(Effect.mapError((cause) => persistenceError("register-connection", cause))),
642 - setRoutes: (environmentId, routes) =>
643 - catalog
644 - .update((document) => setRoutesInCatalog(document, environmentId, routes))
645 - .pipe(Effect.mapError((cause) => persistenceError("set-connection-routes", cause))),
646 - remove: (environmentId) =>
647 - catalog
639 + register: Effect.fn("Persistence.ConnectionRegistrationStore.register")(
640 + function (registration, routes) {
641 + return catalog
642 + .update((document) => registerConnectionInCatalog(document, registration, routes))
643 + .pipe(Effect.mapError((cause) => persistenceError("register-connection", cause)));
644 + },
645 + ),
646 + setRoutes: Effect.fn("Persistence.ConnectionRegistrationStore.setRoutes")(
647 + function (environmentId, routes) {
648 + return catalog
649 + .update((document) => setRoutesInCatalog(document, environmentId, routes))
650 + .pipe(Effect.mapError((cause) => persistenceError("set-connection-routes", cause)));
651 + },
652 + ),
653 + remove: Effect.fn("Persistence.ConnectionRegistrationStore.remove")(function (environmentId) {
654 + return catalog
655 .update((document) => removeConnectionFromCatalog(document, environmentId))
649 - .pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause))),
650 - setEnabled: (environmentId, enabled) =>
651 - catalog
652 - .update((document) => setConnectionEnabledInCatalog(document, environmentId, enabled))
653 - .pipe(Effect.mapError((cause) => persistenceError("set-connection-enabled", cause))),
656 + .pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause)));
657 + }),
658 + setEnabled: Effect.fn("Persistence.ConnectionRegistrationStore.setEnabled")(
659 + function (environmentId, enabled) {
660 + return catalog
661 + .update((document) => setConnectionEnabledInCatalog(document, environmentId, enabled))
662 + .pipe(Effect.mapError((cause) => persistenceError("set-connection-enabled", cause)));
663 + },
664 + ),
665 });
666 const profileStore = ProfileStore.make({
667 get: (connectionId) =>
@@ -724,8 +735,8 @@ export const layer = Layer.effectContext(
735 })),
736 });
737 const cacheStore = Persistence.EnvironmentCacheStore.of({
727 - loadShell: (environmentId) =>
728 - readDatabaseValue(database, SHELL_STORE_NAME, environmentId).pipe(
738 + loadShell: Effect.fn("Persistence.EnvironmentCacheStore.loadShell")(function (environmentId) {
739 + return readDatabaseValue(database, SHELL_STORE_NAME, environmentId).pipe(
740 Effect.tap(() => Effect.promise(() => projectFaviconCache.hydrate())),
741 Effect.flatMap((raw) => {
742 if (typeof raw !== "string") {
@@ -744,7 +755,8 @@ export const layer = Layer.effectContext(
755 );
756 }),
757 Effect.mapError((cause) => persistenceError("load-shell", cause)),
747 - ),
758 + );
759 + }),
760 saveShell: Effect.fn("storage.saveShell")(
761 function* (environmentId, snapshot) {
762 const encoded = yield* encodeStoredShellSnapshot({
@@ -760,25 +772,30 @@ export const layer = Layer.effectContext(
772 : persistenceError("save-shell", cause),
773 ),
774 ),
763 - loadServerConfig: (environmentId) =>
764 - readDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId).pipe(
765 - Effect.flatMap((raw) => {
766 - if (typeof raw !== "string") {
767 - return Effect.succeedNone;
768 - }
769 - return decodeStoredServerConfig(raw).pipe(
770 - Effect.mapError((cause) => persistenceError("load-server-config", cause)),
771 - Effect.map((stored) =>
772 - stored.environmentId === environmentId ? Option.some(stored.config) : Option.none(),
773 - ),
774 - );
775 - }),
776 - Effect.mapError((cause) =>
777 - cause._tag === "ConnectionPersistenceError"
778 - ? cause
779 - : persistenceError("load-server-config", cause),
780 - ),
781 - ),
775 + loadServerConfig: Effect.fn("Persistence.EnvironmentCacheStore.loadServerConfig")(
776 + function (environmentId) {
777 + return readDatabaseValue(database, SERVER_CONFIG_STORE_NAME, environmentId).pipe(
778 + Effect.flatMap((raw) => {
779 + if (typeof raw !== "string") {
780 + return Effect.succeedNone;
781 + }
782 + return decodeStoredServerConfig(raw).pipe(
783 + Effect.mapError((cause) => persistenceError("load-server-config", cause)),
784 + Effect.map((stored) =>
785 + stored.environmentId === environmentId
786 + ? Option.some(stored.config)
787 + : Option.none(),
788 + ),
789 + );
790 + }),
791 + Effect.mapError((cause) =>
792 + cause._tag === "ConnectionPersistenceError"
793 + ? cause
794 + : persistenceError("load-server-config", cause),
795 + ),
796 + );
797 + },
798 + ),
799 saveServerConfig: Effect.fn("storage.saveServerConfig")(
800 function* (environmentId, config) {
801 const encoded = yield* encodeStoredServerConfig({
@@ -794,34 +811,37 @@ export const layer = Layer.effectContext(
811 : persistenceError("save-server-config", cause),
812 ),
813 ),
797 - loadThread: (environmentId, threadId) =>
798 - readDatabaseValue(
799 - database,
800 - THREAD_STORE_NAME,
801 - threadCacheKey(environmentId, threadId),
802 - ).pipe(
803 - Effect.flatMap((raw) => {
804 - if (typeof raw !== "string") {
805 - return Effect.succeedNone;
806 - }
807 - return decodeOrDiscardOrchestrationCache(
808 - decodeStoredThreadSnapshot(raw).pipe(
809 - Effect.mapError((cause) => persistenceError("load-thread", cause)),
810 - Effect.map((stored) =>
811 - stored.environmentId === environmentId && stored.threadId === threadId
812 - ? Option.some(stored.snapshot)
813 - : Option.none(),
814 + loadThread: Effect.fn("Persistence.EnvironmentCacheStore.loadThread")(
815 + function (environmentId, threadId) {
816 + return readDatabaseValue(
817 + database,
818 + THREAD_STORE_NAME,
819 + threadCacheKey(environmentId, threadId),
820 + ).pipe(
821 + Effect.flatMap((raw) => {
822 + if (typeof raw !== "string") {
823 + return Effect.succeedNone;
824 + }
825 + return decodeOrDiscardOrchestrationCache(
826 + decodeStoredThreadSnapshot(raw).pipe(
827 + Effect.mapError((cause) => persistenceError("load-thread", cause)),
828 + Effect.map((stored) =>
829 + stored.environmentId === environmentId && stored.threadId === threadId
830 + ? Option.some(stored.snapshot)
831 + : Option.none(),
832 + ),
833 ),
815 - ),
816 - removeDatabaseValue(
817 - database,
818 - THREAD_STORE_NAME,
819 - threadCacheKey(environmentId, threadId),
820 - ),
821 - );
822 - }),
823 - Effect.mapError((cause) => persistenceError("load-thread", cause)),
824 - ),
834 + removeDatabaseValue(
835 + database,
836 + THREAD_STORE_NAME,
837 + threadCacheKey(environmentId, threadId),
838 + ),
839 + );
840 + }),
841 + Effect.mapError((cause) => persistenceError("load-thread", cause)),
842 + );
843 + },
844 + ),
845 saveThread: Effect.fn("storage.saveThread")(
846 function* (environmentId, snapshot) {
847 const encoded = yield* encodeStoredThreadSnapshot({
@@ -843,27 +863,34 @@ export const layer = Layer.effectContext(
863 : persistenceError("save-thread", cause),
864 ),
865 ),
846 - loadVcsRefs: (environmentId, cwd) =>
847 - readDatabaseValue(database, VCS_REFS_STORE_NAME, vcsRefsCacheKey(environmentId, cwd)).pipe(
848 - Effect.flatMap((raw) => {
849 - if (typeof raw !== "string") {
850 - return Effect.succeedNone;
851 - }
852 - return decodeStoredVcsRefs(raw).pipe(
853 - Effect.mapError((cause) => persistenceError("load-vcs-refs", cause)),
854 - Effect.map((stored) =>
855 - stored.environmentId === environmentId && stored.cwd === cwd
856 - ? Option.some(stored.refs)
857 - : Option.none(),
858 - ),
859 - );
860 - }),
861 - Effect.mapError((cause) =>
862 - cause._tag === "ConnectionPersistenceError"
863 - ? cause
864 - : persistenceError("load-vcs-refs", cause),
865 - ),
866 - ),
866 + loadVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.loadVcsRefs")(
867 + function (environmentId, cwd) {
868 + return readDatabaseValue(
869 + database,
870 + VCS_REFS_STORE_NAME,
871 + vcsRefsCacheKey(environmentId, cwd),
872 + ).pipe(
873 + Effect.flatMap((raw) => {
874 + if (typeof raw !== "string") {
875 + return Effect.succeedNone;
876 + }
877 + return decodeStoredVcsRefs(raw).pipe(
878 + Effect.mapError((cause) => persistenceError("load-vcs-refs", cause)),
879 + Effect.map((stored) =>
880 + stored.environmentId === environmentId && stored.cwd === cwd
881 + ? Option.some(stored.refs)
882 + : Option.none(),
883 + ),
884 + );
885 + }),
886 + Effect.mapError((cause) =>
887 + cause._tag === "ConnectionPersistenceError"
888 + ? cause
889 + : persistenceError("load-vcs-refs", cause),
890 + ),
891 + );
892 + },
893 + ),
894 saveVcsRefs: Effect.fn("storage.saveVcsRefs")(
895 function* (environmentId, cwd, refs) {
896 const encoded = yield* encodeStoredVcsRefs({
@@ -885,26 +912,35 @@ export const layer = Layer.effectContext(
912 : persistenceError("save-vcs-refs", cause),
913 ),
914 ),
888 - removeVcsRefs: (environmentId, cwd) =>
889 - removeDatabaseValue(
890 - database,
891 - VCS_REFS_STORE_NAME,
892 - vcsRefsCacheKey(environmentId, cwd),
893 - ).pipe(Effect.mapError((cause) => persistenceError("remove-vcs-refs", cause))),
894 - clearVcsRefs: (environmentId) =>
895 - removeDatabaseValuesInRange(
896 - database,
897 - VCS_REFS_STORE_NAME,
898 - IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
899 - ).pipe(Effect.mapError((cause) => persistenceError("clear-vcs-refs", cause))),
900 - removeThread: (environmentId, threadId) =>
901 - removeDatabaseValue(
902 - database,
903 - THREAD_STORE_NAME,
904 - threadCacheKey(environmentId, threadId),
905 - ).pipe(Effect.mapError((cause) => persistenceError("remove-thread", cause))),
906 - clear: (environmentId) =>
907 - Effect.all(
915 + removeVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.removeVcsRefs")(
916 + function (environmentId, cwd) {
917 + return removeDatabaseValue(
918 + database,
919 + VCS_REFS_STORE_NAME,
920 + vcsRefsCacheKey(environmentId, cwd),
921 + ).pipe(Effect.mapError((cause) => persistenceError("remove-vcs-refs", cause)));
922 + },
923 + ),
924 + clearVcsRefs: Effect.fn("Persistence.EnvironmentCacheStore.clearVcsRefs")(
925 + function (environmentId) {
926 + return removeDatabaseValuesInRange(
927 + database,
928 + VCS_REFS_STORE_NAME,
929 + IDBKeyRange.bound(`${environmentId}:`, `${environmentId}:\uffff`),
930 + ).pipe(Effect.mapError((cause) => persistenceError("clear-vcs-refs", cause)));
931 + },
932 + ),
933 + removeThread: Effect.fn("Persistence.EnvironmentCacheStore.removeThread")(
934 + function (environmentId, threadId) {
935 + return removeDatabaseValue(
936 + database,
937 + THREAD_STORE_NAME,
938 + threadCacheKey(environmentId, threadId),
939 + ).pipe(Effect.mapError((cause) => persistenceError("remove-thread", cause)));
940 + },
941 + ),
942 + clear: Effect.fn("Persistence.EnvironmentCacheStore.clear")(function (environmentId) {
943 + return Effect.all(
944 [
945 Effect.promise(() => projectFaviconCache.clearEnvironment(environmentId)),
946 removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
@@ -921,7 +957,8 @@ export const layer = Layer.effectContext(
957 ),
958 ],
959 { concurrency: "unbounded", discard: true },
924 - ).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause))),
960 + ).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause)));
961 + }),
962 });
963
964 return Context.make(Persistence.ConnectionTargetStore, targetStore).pipe(
docs/internals/effect-services.md
+5 -2
@@ -94,13 +94,16 @@ export const layer = Layer.effect(Foo, make);
94
95 Reusable functions use `Effect.fn("Service.operation")`, not an arrow or declaration returning
96 `Effect.gen`. The named form creates a span; `Effect.fn(function* ...)` only captures stack
97 -frames. Keep `Effect.gen` for inline programs, callbacks, and layer construction.
97 +frames. Keep `Effect.gen` for inline programs and layer construction. Use
98 +`Effect.fnUntraced(function* ...)` for inline handlers that share the enclosing operation's span.
99
100 Default to named spans for service operations and I/O. Use `Effect.fnUntraced` deliberately for
101 per-chunk/per-event work, tight loops, or helpers already covered by the same operation's span.
102 Explain the reason beside the function or a group of related functions. A loop is not by itself
103 an exemption: its outer operation can still have a useful span without tracing each iteration.
103 -Preserve existing span names and options instead of adding a second span for the same operation.
104 +Move existing span names and options into `Effect.fn` instead of adding a second span for the same
105 +operation; annotate the current span for attributes that depend on function arguments. Keep an
106 +explicit `withSpan` inside an untraced function when an outer tracer override must cover span creation.
107
108 Pass effect combinators after the generator body. A transform that needs the function's input
109 receives it after the effect. Use `Effect.fn.Return<A, E, R>` when the generator needs an explicit
infra/relay/src/agentActivity/ApnsDeliveryQueue.ts
+6 -4
@@ -217,10 +217,12 @@ export const layerCloudflareQueues = (
217 Layer.succeed(
218 ApnsDeliveryQueueSender,
219 ApnsDeliveryQueueSender.of({
220 - send: (body) =>
221 - sender
222 - .send(body)
223 - .pipe(Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext)),
220 + send: Effect.fn("ApnsDeliveryQueueSender.send")(
221 + function* (body) {
222 + return yield* sender.send(body);
223 + },
224 + Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
225 + ),
226 }),
227 ),
228 ),
infra/relay/src/agentActivity/FcmDeliveryQueueConsumer.ts
+9 -9
@@ -9,15 +9,15 @@ export const processMessage = Effect.fn("relay.fcm_delivery_queue.process_messag
9 const deliveries = yield* FcmDeliveries.FcmDeliveries;
10 yield* deliveries.process(message.body).pipe(
11 Effect.matchEffect({
12 - onFailure: (error) =>
13 - Effect.gen(function* () {
14 - // Cloudflare keeps the first ack/retry decision; decide before Alchemy acknowledges the batch.
15 - message.retry();
16 - yield* Effect.logWarning("FCM queue delivery failed; retrying message", {
17 - messageId: message.id,
18 - errorTag: error._tag,
19 - });
20 - }),
12 + // The enclosing operation owns the span for this inline handler.
13 + onFailure: Effect.fnUntraced(function* (error) {
14 + // Cloudflare keeps the first ack/retry decision; decide before Alchemy acknowledges the batch.
15 + message.retry();
16 + yield* Effect.logWarning("FCM queue delivery failed; retrying message", {
17 + messageId: message.id,
18 + errorTag: error._tag,
19 + });
20 + }),
21 onSuccess: () => Effect.sync(() => message.ack()),
22 }),
23 );
infra/relay/src/environments/CloudflareApiPause.ts
+4 -4
@@ -56,8 +56,8 @@ export const make = Effect.gen(function* () {
56 outsideTransaction,
57 Effect.withSpan("relay.cloudflare_api_pause.read"),
58 ),
59 - pauseUntil: (untilMillis) =>
60 - db
59 + pauseUntil: Effect.fn("relay.cloudflare_api_pause.record")(function (untilMillis) {
60 + return db
61 .insert(relayUpstreamApiPauses)
62 .values({ api: CLOUDFLARE_API, pausedUntilMs: untilMillis })
63 .onConflictDoUpdate({
@@ -72,8 +72,8 @@ export const make = Effect.gen(function* () {
72 Effect.logWarning("Could not record the shared Cloudflare API pause", { cause }),
73 ),
74 outsideTransaction,
75 - Effect.withSpan("relay.cloudflare_api_pause.record"),
76 - ),
75 + );
76 + }),
77 });
78 });
79
infra/relay/src/http/Api.ts
+16 -16
@@ -186,22 +186,22 @@ const relayRequestDeadline = <E, R>(
186 Effect.timeoutOption(Duration.millis(deadlineMs)),
187 Effect.flatMap(
188 Option.match({
189 - onNone: () =>
190 - Effect.gen(function* () {
191 - const request = yield* HttpServerRequest.HttpServerRequest;
192 - yield* Effect.logError("relay request exceeded deadline", {
193 - "http.method": request.method,
194 - "http.url": request.url,
195 - "relay.request.deadline_ms": deadlineMs,
196 - });
197 - yield* Effect.annotateCurrentSpan({
198 - "relay.request.deadline_exceeded": true,
199 - });
200 - return HttpServerResponse.jsonUnsafe(
201 - { error: "relay_request_deadline_exceeded" },
202 - { status: 504 },
203 - );
204 - }),
189 + // The enclosing operation owns the span for this inline handler.
190 + onNone: Effect.fnUntraced(function* () {
191 + const request = yield* HttpServerRequest.HttpServerRequest;
192 + yield* Effect.logError("relay request exceeded deadline", {
193 + "http.method": request.method,
194 + "http.url": request.url,
195 + "relay.request.deadline_ms": deadlineMs,
196 + });
197 + yield* Effect.annotateCurrentSpan({
198 + "relay.request.deadline_exceeded": true,
199 + });
200 + return HttpServerResponse.jsonUnsafe(
201 + { error: "relay_request_deadline_exceeded" },
202 + { status: 504 },
203 + );
204 + }),
205 onSome: Effect.succeed,
206 }),
207 ),
infra/relay/src/worker.ts
+27 -12
@@ -89,8 +89,12 @@ const layerHttpPlatformNotSupported = Layer.succeed(HttpPlatform.HttpPlatform, {
89 algorithms: new Set<HttpPlatform.CompressionAlgorithm>(),
90 compressResponse: (response) => Effect.succeed(response),
91 },
92 - fileResponse: () => Effect.die("Relay API does not serve filesystem responses"),
93 - fileWebResponse: () => Effect.die("Relay API does not serve file responses"),
92 + fileResponse: Effect.fn("HttpPlatform.fileResponse")(function () {
93 + return Effect.die("Relay API does not serve filesystem responses");
94 + }),
95 + fileWebResponse: Effect.fn("HttpPlatform.fileWebResponse")(function () {
96 + return Effect.die("Relay API does not serve file responses");
97 + }),
98 });
99
100 const layerRelayApi = Layer.mergeAll(
@@ -235,12 +239,21 @@ export const layer = Api.make(
239 ),
240 );
241 const layerHookInbox = Layer.succeed(HookInbox.HookInbox, {
238 - hold: ({ endpointKey, baseUrl, hook }) =>
239 - hookInboxes.getByName(endpointKey).hold(hook, baseUrl).pipe(inboxCall("hold", endpointKey)),
240 - wake: ({ endpointKey, baseUrl }) =>
241 - hookInboxes.getByName(endpointKey).wake(baseUrl).pipe(inboxCall("wake", endpointKey)),
242 - clear: ({ endpointKey }) =>
243 - hookInboxes.getByName(endpointKey).clear().pipe(inboxCall("clear", endpointKey)),
242 + hold: Effect.fn("HookInbox.hold")(function ({ endpointKey, baseUrl, hook }) {
243 + return hookInboxes
244 + .getByName(endpointKey)
245 + .hold(hook, baseUrl)
246 + .pipe(inboxCall("hold", endpointKey));
247 + }),
248 + wake: Effect.fn("HookInbox.wake")(function ({ endpointKey, baseUrl }) {
249 + return hookInboxes
250 + .getByName(endpointKey)
251 + .wake(baseUrl)
252 + .pipe(inboxCall("wake", endpointKey));
253 + }),
254 + clear: Effect.fn("HookInbox.clear")(function ({ endpointKey }) {
255 + return hookInboxes.getByName(endpointKey).clear().pipe(inboxCall("clear", endpointKey));
256 + }),
257 });
258
259 const layerRuntime = Layer.empty.pipe(
@@ -268,10 +281,12 @@ export const layer = Api.make(
281 FcmDeliveries.layer.pipe(
282 Layer.provide(
283 Layer.succeed(FcmDeliveryQueueSender.FcmDeliveryQueueSender, {
271 - send: (body) =>
272 - fcmDeliveryQueueSender
273 - .send(body)
274 - .pipe(Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext)),
284 + send: Effect.fn("FcmDeliveryQueueSender.send")(
285 + function* (body) {
286 + return yield* fcmDeliveryQueueSender.send(body);
287 + },
288 + Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
289 + ),
290 }),
291 ),
292 Layer.provideMerge(
infra/task-cache/src/Cache.ts
+6 -6
@@ -227,12 +227,12 @@ const make = Effect.gen(function* () {
227 );
228 },
229 Effect.catchTags({
230 - CacheError: (error) =>
231 - Effect.gen(function* () {
232 - if (error.status >= 500)
233 - yield* Effect.logWarning("Cache request failed", { reason: error.reason });
234 - return errorResponse(new HttpError(error.status, error.reason));
235 - }),
230 + // The enclosing operation owns the span for this inline handler.
231 + CacheError: Effect.fnUntraced(function* (error) {
232 + if (error.status >= 500)
233 + yield* Effect.logWarning("Cache request failed", { reason: error.reason });
234 + return errorResponse(new HttpError(error.status, error.reason));
235 + }),
236 }),
237 );
238
infra/task-cache/src/NativeClients.ts
+6 -6
@@ -178,12 +178,12 @@ const make = Effect.gen(function* () {
178 return new Response(null, { status: 204 });
179 },
180 Effect.catchTags({
181 - NativeClientsError: (error) =>
182 - Effect.gen(function* () {
183 - if (error.status >= 500)
184 - yield* Effect.logWarning("Native client request failed", { reason: error.reason });
185 - return Response.json({ error: error.reason }, { status: error.status });
186 - }),
181 + // The enclosing operation owns the span for this inline handler.
182 + NativeClientsError: Effect.fnUntraced(function* (error) {
183 + if (error.status >= 500)
184 + yield* Effect.logWarning("Native client request failed", { reason: error.reason });
185 + return Response.json({ error: error.reason }, { status: error.status });
186 + }),
187 }),
188 );
189
packages/client-runtime/src/authorization/service.ts
+10 -6
@@ -235,8 +235,9 @@ export const make = Effect.gen(function* () {
235 clientMetadata: presentation.metadata,
236 connectionMethod: "relay",
237 ...(timeoutMs === undefined ? {} : { timeoutMs }),
238 - }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient));
238 + });
239 },
240 + Effect.provideService(HttpClient.HttpClient, httpClient),
241 );
242
243 const sessionChanged = () =>
@@ -544,14 +545,17 @@ export const make = Effect.gen(function* () {
545
546 return RemoteEnvironmentAuthorization.of({
547 authorizeBearer,
547 - authorizeDpop: (input) =>
548 - authorizeDpop(input).pipe(Effect.withSpan("environment.authorization")),
549 - authorizeDpopHttp: (input) =>
550 - getDpopToken(input).pipe(
548 + authorizeDpop: Effect.fn("environment.authorization")(function (input) {
549 + return authorizeDpop(input);
550 + }),
551 + // The relay tracer must wrap span creation, not just the token request.
552 + authorizeDpopHttp: Effect.fnUntraced(function* (input) {
553 + return yield* getDpopToken(input).pipe(
554 Effect.map(({ token }) => httpAuthorization(token)),
555 Effect.withSpan("environment.authorization.http"),
556 withRelayClientTracing,
554 - ),
557 + );
558 + }),
559 });
560 });
561
packages/client-runtime/src/connection/onboarding.ts
+23 -16
@@ -294,23 +294,30 @@ export const make = Effect.gen(function* () {
294 const ssh = yield* ClientCapabilities.SshEnvironmentGateway;
295 const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
296
297 + // Provisioning retains the delegated onboarding operation spans.
298 return ConnectionOnboarding.of({
298 - registerPairing: (input) =>
299 - registerPairingConnection(input).pipe(
300 - Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
301 - Effect.provideService(ClientCapabilities.ClientPresentation, presentation),
302 - Effect.provideService(HttpClient.HttpClient, httpClient),
303 - ),
304 - registerSsh: (input) =>
305 - registerSshConnection(input).pipe(
306 - Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
307 - Effect.provideService(ClientCapabilities.SshEnvironmentGateway, ssh),
308 - ),
309 - updateBearer: (input) =>
310 - updateBearerConnection(input).pipe(
311 - Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
312 - Effect.provideService(ConnectionCredentialStore.ConnectionCredentialStore, credentials),
313 - ),
299 + registerPairing: Effect.fnUntraced(
300 + function* (input) {
301 + return yield* registerPairingConnection(input);
302 + },
303 + Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
304 + Effect.provideService(ClientCapabilities.ClientPresentation, presentation),
305 + Effect.provideService(HttpClient.HttpClient, httpClient),
306 + ),
307 + registerSsh: Effect.fnUntraced(
308 + function* (input) {
309 + return yield* registerSshConnection(input);
310 + },
311 + Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
312 + Effect.provideService(ClientCapabilities.SshEnvironmentGateway, ssh),
313 + ),
314 + updateBearer: Effect.fnUntraced(
315 + function* (input) {
316 + return yield* updateBearerConnection(input);
317 + },
318 + Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
319 + Effect.provideService(ConnectionCredentialStore.ConnectionCredentialStore, credentials),
320 + ),
321 });
322 });
323
packages/client-runtime/src/connection/pullRequestRoutingPermissions.ts
+10 -8
@@ -135,12 +135,13 @@ export const makePullRequestRoutingPermissions = Effect.fn("makePullRequestRouti
135 }),
136 );
137 return PullRequestRoutingPermissions.of({
138 - get: (entry) =>
139 - SubscriptionRef.get(state).pipe(
138 + get: Effect.fn("PullRequestRoutingPermissions.get")(function (entry) {
139 + return SubscriptionRef.get(state).pipe(
140 Effect.map((permissions) => pullRequestRoutingPermissionFor(entry, permissions)),
141 - ),
141 + );
142 + }),
143 changes: SubscriptionRef.changes(state),
143 - set: (entry, permission) => {
144 + set: Effect.fn("PullRequestRoutingPermissions.set")(function (entry, permission) {
145 const connectionKey = pullRequestRoutingConnectionKey(entry);
146 if (connectionKey === null)
147 return Effect.fail(
@@ -155,13 +156,14 @@ export const makePullRequestRoutingPermissions = Effect.fn("makePullRequestRouti
156 ? []
157 : [{ environmentId: entry.target.environmentId, connectionKey, permission }]),
158 ]);
158 - },
159 - forget: (environmentId) =>
160 - update((current) =>
159 + }),
160 + forget: Effect.fn("PullRequestRoutingPermissions.forget")(function (environmentId) {
161 + return update((current) =>
162 current.some((permission) => permission.environmentId === environmentId)
163 ? current.filter((permission) => permission.environmentId !== environmentId)
164 : current,
164 - ),
165 + );
166 + }),
167 });
168 },
169 );
packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts
+5 -2
@@ -69,7 +69,10 @@ export const layer: Layer.Layer<
69 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
70 );
71 return ThreadSnapshotLoader.ThreadSnapshotLoader.of({
72 - load: (prepared: PreparedConnection, threadId: ThreadId) => {
72 + load: Effect.fn("ThreadSnapshotLoader.load")(function (
73 + prepared: PreparedConnection,
74 + threadId: ThreadId,
75 + ) {
76 const loadFullFallback = ThreadSnapshotLoader.fetchEnvironmentThreadSnapshot({
77 prepared,
78 threadId,
@@ -159,7 +162,7 @@ export const layer: Layer.Layer<
162 ),
163 ),
164 );
162 - },
165 + }),
166 });
167 }),
168 );
packages/client-runtime/src/state/outdatedServerUpdate.ts
+5 -2
@@ -54,7 +54,10 @@ export function createOutdatedServerUpdateCommand<E>(
54 mode: "singleFlight",
55 key: ({ environmentId }: OutdatedServerUpdateTarget) => environmentId,
56 },
57 - execute: (target: OutdatedServerUpdateTarget, atomRegistry) => {
57 + execute: Effect.fn("ServerUpdate.updateOutdatedServer")(function (
58 + target: OutdatedServerUpdateTarget,
59 + atomRegistry,
60 + ) {
61 const stateAtom = serverUpdateStateAtom(target.environmentId);
62 const targetVersion = target.input.targetVersion;
63 const fromVersion = target.fromVersion ?? targetVersion;
@@ -82,6 +85,6 @@ export function createOutdatedServerUpdateCommand<E>(
85 }),
86 ),
87 );
85 - },
88 + }),
89 });
90 }
packages/client-runtime/src/state/pullRequestDiffHttp.ts
+12 -7
@@ -86,14 +86,19 @@ export const layer: Layer.Layer<PullRequestDiffLoader, never, HttpClient.HttpCli
86 const remoteAuthorization = yield* Effect.serviceOption(
87 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
88 );
89 + // The HTTP fetch owns the load span.
90 return PullRequestDiffLoader.of({
90 - load: (prepared, input) =>
91 - fetchEnvironmentPullRequestDiff({
92 - prepared,
93 - diff: input,
94 - signer,
95 - remoteAuthorization,
96 - }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),
91 + load: Effect.fnUntraced(
92 + function* (prepared, input) {
93 + return yield* fetchEnvironmentPullRequestDiff({
94 + prepared,
95 + diff: input,
96 + signer,
97 + remoteAuthorization,
98 + });
99 + },
100 + Effect.provideService(HttpClient.HttpClient, httpClient),
101 + ),
102 });
103 }),
104 );
packages/client-runtime/src/state/server.ts
+2 -2
@@ -830,7 +830,7 @@ export function createServerEnvironmentAtoms<R, E>(
830 label: "environment-data:server:update-server",
831 scheduler: updateScheduler,
832 concurrency: configConcurrency,
833 - execute: (target, atomRegistry) => {
833 + execute: Effect.fn("ServerUpdate.updateServer")(function (target, atomRegistry) {
834 const stateAtom = serverUpdateStateAtom(target.environmentId);
835 let targetVersion = target.input.targetVersion;
836 let fromVersion =
@@ -1045,7 +1045,7 @@ export function createServerEnvironmentAtoms<R, E>(
1045 }),
1046 ),
1047 );
1048 - },
1048 + }),
1049 });
1050 const settingsValueAtom = Atom.family((environmentId: EnvironmentId) =>
1051 Atom.make((get) => get(configValueAtom(environmentId))?.settings ?? null).pipe(
packages/client-runtime/src/state/shellSnapshotHttp.ts
+4 -3
@@ -105,8 +105,8 @@ export const layer: Layer.Layer<ShellSnapshotLoader, never, HttpClient.HttpClien
105 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
106 );
107 return ShellSnapshotLoader.of({
108 - load: (prepared, options) =>
109 - fetchEnvironmentShellSnapshot({
108 + load: Effect.fn("ShellSnapshotLoader.load")(function (prepared, options) {
109 + return fetchEnvironmentShellSnapshot({
110 prepared,
111 signer,
112 remoteAuthorization,
@@ -123,7 +123,8 @@ export const layer: Layer.Layer<ShellSnapshotLoader, never, HttpClient.HttpClien
123 Effect.as(Option.none<DeferredShellSnapshot>()),
124 ),
125 ),
126 - ),
126 + );
127 + }),
128 });
129 }),
130 );
packages/client-runtime/src/state/threadHistoryController.ts
+43 -33
@@ -49,20 +49,23 @@ export const layer: Layer.Layer<ThreadHistoryController> = Layer.effect(
49 Effect.gen(function* () {
50 const handlers = yield* Ref.make(new Map<string, ThreadHistoryHandler>());
51 return ThreadHistoryController.of({
52 - register: (environmentId, threadId, handler) =>
53 - Ref.update(handlers, (current) => {
54 - const next = new Map(current);
55 - next.set(threadKey({ environmentId, threadId }), handler);
56 - return next;
57 - }).pipe(
58 - Effect.as({
59 - environmentId,
60 - threadId,
61 - handler,
62 - } satisfies ThreadHistoryRegistration),
63 - ),
64 - unregister: (registration) =>
65 - Ref.update(handlers, (current) => {
52 + register: Effect.fn("ThreadHistoryController.register")(
53 + function (environmentId, threadId, handler) {
54 + return Ref.update(handlers, (current) => {
55 + const next = new Map(current);
56 + next.set(threadKey({ environmentId, threadId }), handler);
57 + return next;
58 + }).pipe(
59 + Effect.as({
60 + environmentId,
61 + threadId,
62 + handler,
63 + } satisfies ThreadHistoryRegistration),
64 + );
65 + },
66 + ),
67 + unregister: Effect.fn("ThreadHistoryController.unregister")(function (registration) {
68 + return Ref.update(handlers, (current) => {
69 const key = threadKey({
70 environmentId: registration.environmentId,
71 threadId: registration.threadId,
@@ -75,25 +78,32 @@ export const layer: Layer.Layer<ThreadHistoryController> = Layer.effect(
78 const next = new Map(current);
79 next.delete(key);
80 return next;
78 - }),
79 - loadEarlier: (environmentId, threadId, throughEntryId) =>
80 - Ref.get(handlers).pipe(
81 - Effect.flatMap((current) => {
82 - const handler = current.get(threadKey({ environmentId, threadId }));
83 - if (handler === undefined) {
84 - return Effect.succeed({ _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult);
85 - }
86 - return handler.loadEarlier(throughEntryId);
87 - }),
88 - ),
89 - reconcilePendingWork: (environmentId, threadId) =>
90 - Ref.get(handlers).pipe(
91 - Effect.flatMap(
92 - (current) =>
93 - current.get(threadKey({ environmentId, threadId }))?.reconcilePendingWork() ??
94 - Effect.void,
95 - ),
96 - ),
81 + });
82 + }),
83 + loadEarlier: Effect.fn("ThreadHistoryController.loadEarlier")(
84 + function (environmentId, threadId, throughEntryId) {
85 + return Ref.get(handlers).pipe(
86 + Effect.flatMap((current) => {
87 + const handler = current.get(threadKey({ environmentId, threadId }));
88 + if (handler === undefined) {
89 + return Effect.succeed({ _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult);
90 + }
91 + return handler.loadEarlier(throughEntryId);
92 + }),
93 + );
94 + },
95 + ),
96 + reconcilePendingWork: Effect.fn("ThreadHistoryController.reconcilePendingWork")(
97 + function (environmentId, threadId) {
98 + return Ref.get(handlers).pipe(
99 + Effect.flatMap(
100 + (current) =>
101 + current.get(threadKey({ environmentId, threadId }))?.reconcilePendingWork() ??
102 + Effect.void,
103 + ),
104 + );
105 + },
106 + ),
107 });
108 }),
109 );
packages/client-runtime/src/state/vcsAction.ts
+11 -10
@@ -444,15 +444,16 @@ export function createVcsActionManager<R, E>(
444 label: `vcs-action:run-stacked:${commandKey}`,
445 scheduler: vcsCommandScheduler,
446 concurrency: { mode: "serial", key: () => commandKey },
447 - execute: (input: RunVcsStackedActionInput, registry) => {
447 + execute: Effect.fn("VcsAction.runStackedAction")(function* (
448 + input: RunVcsStackedActionInput,
449 + registry,
450 + ) {
451 if (target === null) {
449 - return Effect.fail(
450 - new VcsActionUnavailableError({
451 - operation: "run_change_request",
452 - environmentId: requestedTarget.environmentId,
453 - cwd: requestedTarget.cwd,
454 - }),
455 - );
452 + return yield* new VcsActionUnavailableError({
453 + operation: "run_change_request",
454 + environmentId: requestedTarget.environmentId,
455 + cwd: requestedTarget.cwd,
456 + });
457 }
458 const transportActionId = createVcsActionTransportId(target, input.actionId);
459 registry.set(
@@ -480,7 +481,7 @@ export function createVcsActionManager<R, E>(
481 registry.set(stateAtom, EMPTY_VCS_ACTION_STATE);
482 }
483 });
483 - return consumeVcsActionProgress(
484 + return yield* consumeVcsActionProgress(
485 runStreamInEnvironment(
486 target.environmentId,
487 runStreamGuarded(WS_METHODS.gitRunStackedAction, rpcInput),
@@ -524,7 +525,7 @@ export function createVcsActionManager<R, E>(
525 ),
526 Effect.onInterrupt(() => clearOwnedState),
527 );
527 - },
528 + }),
529 });
530 runStackedActionCommands.set(commandKey, command);
531 return command;
packages/effect-acp/src/agent.ts
+95 -69
@@ -419,109 +419,135 @@ export const make = Effect.fn("effect-acp/AcpAgent.make")(function* (
419 extRequest: transport.request,
420 extNotification: transport.notify,
421 },
422 - handleInitialize: (handler) =>
423 - Effect.suspend(() => {
422 + handleInitialize: Effect.fn("AcpAgent.handleInitialize")(function (handler) {
423 + return Effect.suspend(() => {
424 coreHandlers.initialize = handler;
425 return Effect.void;
426 - }),
427 - handleAuthenticate: (handler) =>
428 - Effect.suspend(() => {
426 + });
427 + }),
428 + handleAuthenticate: Effect.fn("AcpAgent.handleAuthenticate")(function (handler) {
429 + return Effect.suspend(() => {
430 coreHandlers.authenticate = handler;
431 return Effect.void;
431 - }),
432 - handleLogout: (handler) =>
433 - Effect.suspend(() => {
432 + });
433 + }),
434 + handleLogout: Effect.fn("AcpAgent.handleLogout")(function (handler) {
435 + return Effect.suspend(() => {
436 coreHandlers.logout = handler;
437 return Effect.void;
436 - }),
437 - handleCreateSession: (handler) =>
438 - Effect.suspend(() => {
438 + });
439 + }),
440 + handleCreateSession: Effect.fn("AcpAgent.handleCreateSession")(function (handler) {
441 + return Effect.suspend(() => {
442 coreHandlers.createSession = handler;
443 return Effect.void;
441 - }),
442 - handleLoadSession: (handler) =>
443 - Effect.suspend(() => {
444 + });
445 + }),
446 + handleLoadSession: Effect.fn("AcpAgent.handleLoadSession")(function (handler) {
447 + return Effect.suspend(() => {
448 coreHandlers.loadSession = handler;
449 return Effect.void;
446 - }),
447 - handleListSessions: (handler) =>
448 - Effect.suspend(() => {
450 + });
451 + }),
452 + handleListSessions: Effect.fn("AcpAgent.handleListSessions")(function (handler) {
453 + return Effect.suspend(() => {
454 coreHandlers.listSessions = handler;
455 return Effect.void;
451 - }),
452 - handleForkSession: (handler) =>
453 - Effect.suspend(() => {
456 + });
457 + }),
458 + handleForkSession: Effect.fn("AcpAgent.handleForkSession")(function (handler) {
459 + return Effect.suspend(() => {
460 coreHandlers.forkSession = handler;
461 return Effect.void;
456 - }),
457 - handleResumeSession: (handler) =>
458 - Effect.suspend(() => {
462 + });
463 + }),
464 + handleResumeSession: Effect.fn("AcpAgent.handleResumeSession")(function (handler) {
465 + return Effect.suspend(() => {
466 coreHandlers.resumeSession = handler;
467 return Effect.void;
461 - }),
462 - handleCloseSession: (handler) =>
463 - Effect.suspend(() => {
468 + });
469 + }),
470 + handleCloseSession: Effect.fn("AcpAgent.handleCloseSession")(function (handler) {
471 + return Effect.suspend(() => {
472 coreHandlers.closeSession = handler;
473 return Effect.void;
466 - }),
467 - handleDeleteSession: (handler) =>
468 - Effect.suspend(() => {
474 + });
475 + }),
476 + handleDeleteSession: Effect.fn("AcpAgent.handleDeleteSession")(function (handler) {
477 + return Effect.suspend(() => {
478 coreHandlers.deleteSession = handler;
479 return Effect.void;
471 - }),
472 - handleListProviders: (handler) =>
473 - Effect.suspend(() => {
480 + });
481 + }),
482 + handleListProviders: Effect.fn("AcpAgent.handleListProviders")(function (handler) {
483 + return Effect.suspend(() => {
484 coreHandlers.listProviders = handler;
485 return Effect.void;
476 - }),
477 - handleSetProvider: (handler) =>
478 - Effect.suspend(() => {
486 + });
487 + }),
488 + handleSetProvider: Effect.fn("AcpAgent.handleSetProvider")(function (handler) {
489 + return Effect.suspend(() => {
490 coreHandlers.setProvider = handler;
491 return Effect.void;
481 - }),
482 - handleDisableProvider: (handler) =>
483 - Effect.suspend(() => {
492 + });
493 + }),
494 + handleDisableProvider: Effect.fn("AcpAgent.handleDisableProvider")(function (handler) {
495 + return Effect.suspend(() => {
496 coreHandlers.disableProvider = handler;
497 return Effect.void;
486 - }),
487 - handleSetSessionConfigOption: (handler) =>
488 - Effect.suspend(() => {
489 - coreHandlers.setSessionConfigOption = handler;
490 - return Effect.void;
491 - }),
492 - handlePrompt: (handler) =>
493 - Effect.suspend(() => {
498 + });
499 + }),
500 + handleSetSessionConfigOption: Effect.fn("AcpAgent.handleSetSessionConfigOption")(
501 + function (handler) {
502 + return Effect.suspend(() => {
503 + coreHandlers.setSessionConfigOption = handler;
504 + return Effect.void;
505 + });
506 + },
507 + ),
508 + handlePrompt: Effect.fn("AcpAgent.handlePrompt")(function (handler) {
509 + return Effect.suspend(() => {
510 coreHandlers.prompt = handler;
511 return Effect.void;
496 - }),
497 - handleCancel: (handler) =>
498 - Effect.suspend(() => {
512 + });
513 + }),
514 + handleCancel: Effect.fn("AcpAgent.handleCancel")(function (handler) {
515 + return Effect.suspend(() => {
516 cancelHandlers.push(handler);
517 return Effect.void;
501 - }),
502 - handleUnknownExtRequest: (handler) =>
503 - Effect.suspend(() => {
518 + });
519 + }),
520 + handleUnknownExtRequest: Effect.fn("AcpAgent.handleUnknownExtRequest")(function (handler) {
521 + return Effect.suspend(() => {
522 unknownExtRequestHandler = handler;
523 return Effect.void;
506 - }),
507 - handleUnknownExtNotification: (handler) =>
508 - Effect.suspend(() => {
509 - unknownExtNotificationHandler = handler;
510 - return Effect.void;
511 - }),
512 - handleExtRequest: (method, payload, handler) =>
513 - Effect.suspend(() => {
524 + });
525 + }),
526 + handleUnknownExtNotification: Effect.fn("AcpAgent.handleUnknownExtNotification")(
527 + function (handler) {
528 + return Effect.suspend(() => {
529 + unknownExtNotificationHandler = handler;
530 + return Effect.void;
531 + });
532 + },
533 + ),
534 + handleExtRequest: Effect.fn("AcpAgent.handleExtRequest")(function (method, payload, handler) {
535 + return Effect.suspend(() => {
536 extRequestHandlers.set(method, decodeExtRequestRegistration(method, payload, handler));
537 return Effect.void;
516 - }),
517 - handleExtNotification: (method, payload, handler) =>
518 - Effect.suspend(() => {
519 - extNotificationHandlers.set(
520 - method,
521 - decodeExtNotificationRegistration(method, payload, handler),
522 - );
523 - return Effect.void;
524 - }),
538 + });
539 + }),
540 + handleExtNotification: Effect.fn("AcpAgent.handleExtNotification")(
541 + function (method, payload, handler) {
542 + return Effect.suspend(() => {
543 + extNotificationHandlers.set(
544 + method,
545 + decodeExtNotificationRegistration(method, payload, handler),
546 + );
547 + return Effect.void;
548 + });
549 + },
550 + ),
551 });
552 });
553
packages/effect-acp/src/client.ts
+87 -64
@@ -1243,98 +1243,121 @@ export const make = Effect.fn("effect-acp/AcpClient.make")(function* (
1243 }),
1244 cancel: (payload) => transport.notify(AGENT_METHODS.session_cancel, payload),
1245 },
1246 - handleRequestPermission: (handler) =>
1247 - Effect.suspend(() => {
1246 + handleRequestPermission: Effect.fn("AcpClient.handleRequestPermission")(function (handler) {
1247 + return Effect.suspend(() => {
1248 coreHandlers.requestPermission = handler;
1249 return Effect.void;
1250 - }),
1251 - handleElicitation: (handler) =>
1252 - Effect.suspend(() => {
1250 + });
1251 + }),
1252 + handleElicitation: Effect.fn("AcpClient.handleElicitation")(function (handler) {
1253 + return Effect.suspend(() => {
1254 coreHandlers.elicitation = handler;
1255 return Effect.void;
1255 - }),
1256 - handleMcpConnect: (handler) =>
1257 - Effect.sync(() => {
1256 + });
1257 + }),
1258 + handleMcpConnect: Effect.fn("AcpClient.handleMcpConnect")(function (handler) {
1259 + return Effect.sync(() => {
1260 coreHandlers.mcpConnect = handler;
1259 - }),
1260 - handleMcpMessage: (handler) =>
1261 - Effect.sync(() => {
1261 + });
1262 + }),
1263 + handleMcpMessage: Effect.fn("AcpClient.handleMcpMessage")(function (handler) {
1264 + return Effect.sync(() => {
1265 coreHandlers.mcpMessage = handler;
1263 - }),
1264 - handleMcpDisconnect: (handler) =>
1265 - Effect.sync(() => {
1266 + });
1267 + }),
1268 + handleMcpDisconnect: Effect.fn("AcpClient.handleMcpDisconnect")(function (handler) {
1269 + return Effect.sync(() => {
1270 coreHandlers.mcpDisconnect = handler;
1267 - }),
1268 - handleMcpNotification: (handler) =>
1269 - Effect.sync(() => {
1271 + });
1272 + }),
1273 + handleMcpNotification: Effect.fn("AcpClient.handleMcpNotification")(function (handler) {
1274 + return Effect.sync(() => {
1275 extNotificationHandlers.set(CLIENT_METHODS.mcp_message, (params) =>
1276 decodeMessageMcpNotification(params).pipe(
1277 Effect.mapError(() => AcpError.AcpRequestError.invalidParams()),
1278 Effect.flatMap(handler),
1279 ),
1280 );
1276 - }),
1277 - handleReadTextFile: (handler) =>
1278 - Effect.sync(() => {
1281 + });
1282 + }),
1283 + handleReadTextFile: Effect.fn("AcpClient.handleReadTextFile")(function (handler) {
1284 + return Effect.sync(() => {
1285 coreHandlers.readTextFile = handler;
1280 - }),
1281 - handleWriteTextFile: (handler) =>
1282 - Effect.sync(() => {
1286 + });
1287 + }),
1288 + handleWriteTextFile: Effect.fn("AcpClient.handleWriteTextFile")(function (handler) {
1289 + return Effect.sync(() => {
1290 coreHandlers.writeTextFile = handler;
1284 - }),
1285 - handleCreateTerminal: (handler) =>
1286 - Effect.sync(() => {
1291 + });
1292 + }),
1293 + handleCreateTerminal: Effect.fn("AcpClient.handleCreateTerminal")(function (handler) {
1294 + return Effect.sync(() => {
1295 coreHandlers.createTerminal = handler;
1288 - }),
1289 - handleTerminalOutput: (handler) =>
1290 - Effect.sync(() => {
1296 + });
1297 + }),
1298 + handleTerminalOutput: Effect.fn("AcpClient.handleTerminalOutput")(function (handler) {
1299 + return Effect.sync(() => {
1300 coreHandlers.terminalOutput = handler;
1292 - }),
1293 - handleTerminalWaitForExit: (handler) =>
1294 - Effect.sync(() => {
1301 + });
1302 + }),
1303 + handleTerminalWaitForExit: Effect.fn("AcpClient.handleTerminalWaitForExit")(function (handler) {
1304 + return Effect.sync(() => {
1305 coreHandlers.terminalWaitForExit = handler;
1296 - }),
1297 - handleTerminalKill: (handler) =>
1298 - Effect.sync(() => {
1306 + });
1307 + }),
1308 + handleTerminalKill: Effect.fn("AcpClient.handleTerminalKill")(function (handler) {
1309 + return Effect.sync(() => {
1310 coreHandlers.terminalKill = handler;
1300 - }),
1301 - handleTerminalRelease: (handler) =>
1302 - Effect.sync(() => {
1311 + });
1312 + }),
1313 + handleTerminalRelease: Effect.fn("AcpClient.handleTerminalRelease")(function (handler) {
1314 + return Effect.sync(() => {
1315 coreHandlers.terminalRelease = handler;
1304 - }),
1305 - handleSessionUpdate: (handler) =>
1306 - Effect.suspend(() => {
1316 + });
1317 + }),
1318 + handleSessionUpdate: Effect.fn("AcpClient.handleSessionUpdate")(function (handler) {
1319 + return Effect.suspend(() => {
1320 notificationHandlers.sessionUpdate.handlers.push(handler);
1321 return flushBufferedNotifications(notificationHandlers.sessionUpdate);
1309 - }),
1310 - handleElicitationComplete: (handler) =>
1311 - Effect.suspend(() => {
1322 + });
1323 + }),
1324 + handleElicitationComplete: Effect.fn("AcpClient.handleElicitationComplete")(function (handler) {
1325 + return Effect.suspend(() => {
1326 notificationHandlers.elicitationComplete.handlers.push(handler);
1327 return flushBufferedNotifications(notificationHandlers.elicitationComplete);
1314 - }),
1315 - handleUnknownExtRequest: (handler) =>
1316 - Effect.suspend(() => {
1328 + });
1329 + }),
1330 + handleUnknownExtRequest: Effect.fn("AcpClient.handleUnknownExtRequest")(function (handler) {
1331 + return Effect.suspend(() => {
1332 unknownExtRequestHandler = handler;
1333 return Effect.void;
1319 - }),
1320 - handleUnknownExtNotification: (handler) =>
1321 - Effect.suspend(() => {
1322 - unknownExtNotificationHandler = handler;
1323 - return Effect.void;
1324 - }),
1325 - handleExtRequest: (method, payload, handler) =>
1326 - Effect.suspend(() => {
1334 + });
1335 + }),
1336 + handleUnknownExtNotification: Effect.fn("AcpClient.handleUnknownExtNotification")(
1337 + function (handler) {
1338 + return Effect.suspend(() => {
1339 + unknownExtNotificationHandler = handler;
1340 + return Effect.void;
1341 + });
1342 + },
1343 + ),
1344 + handleExtRequest: Effect.fn("AcpClient.handleExtRequest")(function (method, payload, handler) {
1345 + return Effect.suspend(() => {
1346 extRequestHandlers.set(method, decodeExtRequestRegistration(method, payload, handler));
1347 return Effect.void;
1329 - }),
1330 - handleExtNotification: (method, payload, handler) =>
1331 - Effect.suspend(() => {
1332 - extNotificationHandlers.set(
1333 - method,
1334 - decodeExtNotificationRegistration(method, payload, handler),
1335 - );
1336 - return Effect.void;
1337 - }),
1348 + });
1349 + }),
1350 + handleExtNotification: Effect.fn("AcpClient.handleExtNotification")(
1351 + function (method, payload, handler) {
1352 + return Effect.suspend(() => {
1353 + extNotificationHandlers.set(
1354 + method,
1355 + decodeExtNotificationRegistration(method, payload, handler),
1356 + );
1357 + return Effect.void;
1358 + });
1359 + },
1360 + ),
1361 });
1362 });
1363
packages/effect-acp/src/protocol.ts
+21 -15
@@ -868,14 +868,16 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
868 Effect.forkScoped,
869 );
870
871 + // Protocol loops and per-message sends share the caller's operation span.
872 const clientProtocol = RpcClient.Protocol.of({
872 - run: (_clientId, f) =>
873 - Stream.fromQueue(clientQueue).pipe(
873 + run: Effect.fnUntraced(function* (_clientId, f) {
874 + return yield* Stream.fromQueue(clientQueue).pipe(
875 Stream.runForEach((message) => f(message)),
876 Effect.forever,
876 - ),
877 - send: (_clientId, request) =>
878 - offerOutgoing(request).pipe(
877 + );
878 + }),
879 + send: Effect.fnUntraced(function* (_clientId, request) {
880 + return yield* offerOutgoing(request).pipe(
881 Effect.mapError(
882 (error) =>
883 new RpcClientError.RpcClientError({
@@ -885,32 +887,36 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
887 }),
888 }),
889 ),
888 - ),
890 + );
891 + }),
892 supportsAck: true,
893 supportsTransferables: false,
894 codecFor: parserFactory.codecFor,
895 });
896
897 const serverProtocol = RpcServer.Protocol.of({
895 - run: (f) =>
896 - Stream.fromQueue(serverQueue).pipe(
898 + run: Effect.fnUntraced(function* (f) {
899 + return yield* Stream.fromQueue(serverQueue).pipe(
900 Stream.runForEach((message) => f(0, message)),
901 Effect.forever,
899 - ),
902 + );
903 + }),
904 disconnects,
901 - send: (_clientId, response) =>
902 - offerOutgoing(response).pipe(
905 + send: Effect.fnUntraced(function* (_clientId, response) {
906 + return yield* offerOutgoing(response).pipe(
907 Effect.tapError((error) =>
908 response._tag === "Exit" && options.onOutgoingResponseFailure !== undefined
909 ? options.onOutgoingResponseFailure(acpRequestIdentity(response.requestId), error)
910 : Effect.void,
911 ),
912 Effect.orDie,
909 - ),
910 - end: (_clientId) =>
911 - Ref.update(outgoingWriterState, (state) => ({ ...state, intentionalEnd: true })).pipe(
913 + );
914 + }),
915 + end: Effect.fn("RpcServer.Protocol.end")(function (_clientId) {
916 + return Ref.update(outgoingWriterState, (state) => ({ ...state, intentionalEnd: true })).pipe(
917 Effect.andThen(Queue.end(outgoing)),
913 - ),
918 + );
919 + }),
920 clientIds: Effect.succeed(new Set([0])),
921 initialMessage: Effect.succeedNone,
922 supportsAck: true,
packages/effect-codex-app-server/src/client.ts
+29 -17
@@ -240,24 +240,36 @@ export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make
240 },
241 request,
242 notify,
243 - handleServerRequest: (method, handler) =>
244 - Effect.sync(() => {
245 - requestHandlers.set(method, handler as ServerRequestHandler);
246 - }),
247 - handleServerNotification: (method, handler) =>
248 - Effect.sync(() => {
249 - const current = notificationHandlers.get(method) ?? [];
250 - current.push(handler as ServerNotificationHandler);
251 - notificationHandlers.set(method, current);
252 - }),
253 - handleUnknownServerRequest: (handler) =>
254 - Effect.sync(() => {
255 - unknownRequestHandler = handler;
256 - }),
257 - handleUnknownServerNotification: (handler) =>
258 - Effect.sync(() => {
243 + handleServerRequest: Effect.fn("CodexAppServerClient.handleServerRequest")(
244 + function (method, handler) {
245 + return Effect.sync(() => {
246 + requestHandlers.set(method, handler as ServerRequestHandler);
247 + });
248 + },
249 + ),
250 + handleServerNotification: Effect.fn("CodexAppServerClient.handleServerNotification")(
251 + function (method, handler) {
252 + return Effect.sync(() => {
253 + const current = notificationHandlers.get(method) ?? [];
254 + current.push(handler as ServerNotificationHandler);
255 + notificationHandlers.set(method, current);
256 + });
257 + },
258 + ),
259 + handleUnknownServerRequest: Effect.fn("CodexAppServerClient.handleUnknownServerRequest")(
260 + function (handler) {
261 + return Effect.sync(() => {
262 + unknownRequestHandler = handler;
263 + });
264 + },
265 + ),
266 + handleUnknownServerNotification: Effect.fn(
267 + "CodexAppServerClient.handleUnknownServerNotification",
268 + )(function (handler) {
269 + return Effect.sync(() => {
270 unknownNotificationHandler = handler;
260 - }),
271 + });
272 + }),
273 });
274 });
275
packages/provider-acp-registry/src/server/driver.ts
+6 -2
@@ -629,7 +629,11 @@ export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryD
629 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
630 initialSnapshot: () => checkProvider,
631 checkProvider,
632 - enrichSnapshot: ({ snapshot, getSnapshot, publishSnapshot }) => {
632 + enrichSnapshot: Effect.fn("enrichSnapshot")(function ({
633 + snapshot,
634 + getSnapshot,
635 + publishSnapshot,
636 + }) {
637 if (!snapshot.installed) return Effect.void;
638 const publishEnrichment = (
639 Option.isSome(runtimeCoordinator)
@@ -711,7 +715,7 @@ export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryD
715 discard: true,
716 },
717 );
714 - },
718 + }),
719 }).pipe(
720 Effect.mapError(
721 (cause) =>
packages/provider-acp/src/server/adapter.ts
+29 -26
@@ -1359,8 +1359,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
1359 return ProviderAdapter.ProviderAdapterV2.of({
1360 instanceId: options.instanceId,
1361 driver,
1362 - getCapabilities: () => Effect.succeed(flavor.capabilities),
1363 - planSelectionTransition: (input) => Effect.succeed(acpSelectionTransition(input)),
1362 + getCapabilities: Effect.fn("AcpAdapter.getCapabilities")(function () {
1363 + return Effect.succeed(flavor.capabilities);
1364 + }),
1365 + planSelectionTransition: Effect.fn("AcpAdapter.planSelectionTransition")(function (input) {
1366 + return Effect.succeed(acpSelectionTransition(input));
1367 + }),
1368 openSession: Effect.fn("AcpAdapterV2.openSession")(
1369 function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) {
1370 const sessionScope = yield* Effect.scope;
@@ -7058,31 +7062,30 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7062 yield* Deferred.succeed(context.completed, undefined).pipe(Effect.ignore);
7063 });
7064
7061 - scheduleDeferredFinalize = (context) =>
7062 - Effect.gen(function* () {
7063 - if (!flavor.deferFinalizeForBackgroundWork) return;
7064 - if (!context.promptSettled || context.finalized || context.interrupted) return;
7065 + scheduleDeferredFinalize = Effect.fn("scheduleDeferredFinalize")(function* (context) {
7066 + if (!flavor.deferFinalizeForBackgroundWork) return;
7067 + if (!context.promptSettled || context.finalized || context.interrupted) return;
7068 + if (hasDeferredBackgroundWork(context)) return;
7069 + context.backgroundFinalizeGeneration += 1;
7070 + const generation = context.backgroundFinalizeGeneration;
7071 + yield* Effect.gen(function* () {
7072 + yield* Effect.sleep(ACP_DEFERRED_FINALIZE_DEBOUNCE);
7073 + if (
7074 + context.finalized ||
7075 + context.interrupted ||
7076 + context.backgroundFinalizeGeneration !== generation
7077 + ) {
7078 + return;
7079 + }
7080 if (hasDeferredBackgroundWork(context)) return;
7066 - context.backgroundFinalizeGeneration += 1;
7067 - const generation = context.backgroundFinalizeGeneration;
7068 - yield* Effect.gen(function* () {
7069 - yield* Effect.sleep(ACP_DEFERRED_FINALIZE_DEBOUNCE);
7070 - if (
7071 - context.finalized ||
7072 - context.interrupted ||
7073 - context.backgroundFinalizeGeneration !== generation
7074 - ) {
7075 - return;
7076 - }
7077 - if (hasDeferredBackgroundWork(context)) return;
7078 - const status = context.promptSettledStatus ?? "completed";
7079 - yield* finalizeTurn(context, status);
7080 - }).pipe(Effect.forkIn(sessionScope), Effect.asVoid);
7081 - yield* (
7082 - options.testHooks?.onDeferredFinalizeScheduled?.(ACP_DEFERRED_FINALIZE_DEBOUNCE) ??
7083 - Effect.void
7084 - );
7085 - });
7081 + const status = context.promptSettledStatus ?? "completed";
7082 + yield* finalizeTurn(context, status);
7083 + }).pipe(Effect.forkIn(sessionScope), Effect.asVoid);
7084 + yield* (
7085 + options.testHooks?.onDeferredFinalizeScheduled?.(ACP_DEFERRED_FINALIZE_DEBOUNCE) ??
7086 + Effect.void
7087 + );
7088 + });
7089
7090 const resolvePromptParts = Effect.fnUntraced(function* (
7091 turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
packages/provider-core/src/server/McpProviderSessions.ts
+52 -43
@@ -92,9 +92,11 @@ const make = Effect.gen(function* () {
92 }
93 yield* Ref.update(sessions, (current) => new Map(current).set(config.threadId, config));
94 }),
95 - read: (threadId) => Ref.get(sessions).pipe(Effect.map((current) => current.get(threadId))),
96 - clear: (threadId) =>
97 - Ref.update(sessions, (current) => {
95 + read: Effect.fn("McpProviderSessions.read")(function (threadId) {
96 + return Ref.get(sessions).pipe(Effect.map((current) => current.get(threadId)));
97 + }),
98 + clear: Effect.fn("McpProviderSessions.clear")(function (threadId) {
99 + return Ref.update(sessions, (current) => {
100 const next = new Map(current);
101 next.delete(threadId);
102 return next;
@@ -106,46 +108,53 @@ const make = Effect.gen(function* () {
108 return next;
109 }),
110 ),
109 - ),
110 - recordHtmlRender: (threadId, input, reference) =>
111 - Ref.update(htmlRenders, (current) =>
112 - new Map(current).set(
113 - threadId,
114 - [
115 - ...(current.get(threadId) ?? []),
116 - {
117 - title: input.title,
118 - height: input.height,
119 - htmlLength: input.html.length,
120 - htmlHash: hashHtml(input.html),
121 - // Copy the tail so its backing storage cannot retain the entire HTML string.
122 - htmlEnd: Buffer.from(input.html.slice(-KEPT_HTML_END_LENGTH), "utf16le").toString(
123 - "utf16le",
124 - ),
125 - reference,
126 - },
127 - ].slice(-MAX_KEPT_HTML_RENDERS),
128 - ),
129 - ),
130 - takeHtmlRender: (threadId, input, reported) =>
131 - Ref.modify(htmlRenders, (current) => {
132 - const kept = current.get(threadId) ?? [];
133 - const index =
134 - reported === undefined
135 - ? matchingPageIndex(kept, input)
136 - : kept.findIndex((page) => page.reference.attachmentId === reported.attachmentId);
137 - if (index === -1) {
138 - return [undefined, current];
139 - }
140 - const rest = kept.filter((_, keptIndex) => keptIndex !== index);
141 - const next = new Map(current);
142 - if (rest.length === 0) {
143 - next.delete(threadId);
144 - } else {
145 - next.set(threadId, rest);
146 - }
147 - return [kept[index]!.reference, next];
148 - }),
111 + );
112 + }),
113 + recordHtmlRender: Effect.fn("McpProviderSessions.recordHtmlRender")(
114 + function (threadId, input, reference) {
115 + return Ref.update(htmlRenders, (current) =>
116 + new Map(current).set(
117 + threadId,
118 + [
119 + ...(current.get(threadId) ?? []),
120 + {
121 + title: input.title,
122 + height: input.height,
123 + htmlLength: input.html.length,
124 + htmlHash: hashHtml(input.html),
125 + // Copy the tail so its backing storage cannot retain the entire HTML string.
126 + htmlEnd: Buffer.from(input.html.slice(-KEPT_HTML_END_LENGTH), "utf16le").toString(
127 + "utf16le",
128 + ),
129 + reference,
130 + },
131 + ].slice(-MAX_KEPT_HTML_RENDERS),
132 + ),
133 + );
134 + },
135 + ),
136 + takeHtmlRender: Effect.fn("McpProviderSessions.takeHtmlRender")(
137 + function (threadId, input, reported) {
138 + return Ref.modify(htmlRenders, (current) => {
139 + const kept = current.get(threadId) ?? [];
140 + const index =
141 + reported === undefined
142 + ? matchingPageIndex(kept, input)
143 + : kept.findIndex((page) => page.reference.attachmentId === reported.attachmentId);
144 + if (index === -1) {
145 + return [undefined, current];
146 + }
147 + const rest = kept.filter((_, keptIndex) => keptIndex !== index);
148 + const next = new Map(current);
149 + if (rest.length === 0) {
150 + next.delete(threadId);
151 + } else {
152 + next.set(threadId, rest);
153 + }
154 + return [kept[index]!.reference, next];
155 + });
156 + },
157 + ),
158 });
159 });
160
packages/provider-core/src/server/ProviderContinuationRequests.ts
+5 -2
@@ -45,8 +45,11 @@ export const layer = Layer.effect(
45 Effect.gen(function* () {
46 const queue = yield* Queue.unbounded<ProviderContinuationRequest>();
47 return {
48 - offer: (request: ProviderContinuationRequest) =>
49 - Queue.offer(queue, request).pipe(Effect.asVoid),
48 + offer: Effect.fn("ProviderContinuationRequests.offer")(function (
49 + request: ProviderContinuationRequest,
50 + ) {
51 + return Queue.offer(queue, request).pipe(Effect.asVoid);
52 + }),
53 take: Queue.take(queue),
54 };
55 }),
packages/provider-core/src/server/ProviderLatestVersions.ts
+4 -3
@@ -50,12 +50,13 @@ export const make = Effect.fn("ProviderLatestVersions.make")(function* (
50 );
51 return version;
52 }),
53 - invalidate: (key) =>
54 - Ref.update(entries, (current) => {
53 + invalidate: Effect.fn("ProviderLatestVersions.invalidate")(function (key) {
54 + return Ref.update(entries, (current) => {
55 const next = new Map(current);
56 next.delete(key);
57 return next;
58 - }),
58 + });
59 + }),
60 });
61 });
62
packages/provider-cursor/src/server/CursorAccountReader.ts
+8 -4
@@ -28,10 +28,14 @@ export const layer = Layer.effect(
28 FileSystem.FileSystem | Crypto.Crypto | HttpClient.HttpClient
29 >();
30 return CursorAccountReader.of({
31 - read: (credentialSource, sinceMs, untilMs) =>
32 - readCursorAccountUsage(credentialSource, sinceMs, untilMs, keychain.accessToken).pipe(
33 - Effect.provideContext(context),
34 - ),
31 + read: Effect.fn("CursorAccountReader.read")(function (credentialSource, sinceMs, untilMs) {
32 + return readCursorAccountUsage(
33 + credentialSource,
34 + sinceMs,
35 + untilMs,
36 + keychain.accessToken,
37 + ).pipe(Effect.provideContext(context));
38 + }),
39 });
40 }),
41 );
packages/provider-cursor/src/server/CursorSdkCatalog.ts
+4 -3
@@ -79,14 +79,15 @@ export const makeCursorSdkCatalog = Effect.fn("CursorSdkCatalog.make")(function*
79 Exit.isSuccess(exit) && exit.value.length > 0 ? Duration.minutes(30) : Duration.zero,
80 });
81 return CursorSdkCatalog.of({
82 - read: (apiKey) =>
83 - Effect.all(
82 + read: Effect.fn("CursorSdkCatalog.read")(function (apiKey) {
83 + return Effect.all(
84 {
85 user: probes.readUser(apiKey),
86 models: Cache.get(modelCache, apiKey),
87 },
88 { concurrency: "unbounded" },
89 - ),
89 + );
90 + }),
91 });
92 });
93
packages/provider-cursor/src/server/adapter.ts
+6 -2
@@ -894,8 +894,12 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
894 return ProviderAdapter.ProviderAdapterV2.of({
895 instanceId: adapterOptions.instanceId,
896 driver: CursorAgentSdk.CURSOR_PROVIDER,
897 - getCapabilities: () => Effect.succeed(CursorProviderCapabilitiesV2),
898 - planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),
897 + getCapabilities: Effect.fn("CursorAdapter.getCapabilities")(function () {
898 + return Effect.succeed(CursorProviderCapabilitiesV2);
899 + }),
900 + planSelectionTransition: Effect.fn("CursorAdapter.planSelectionTransition")(function () {
901 + return Effect.succeed(turnScopedSelectionTransition());
902 + }),
903 openSession: Effect.fn("CursorAdapterV2.openSession")(
904 function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) {
905 const sessionScope = yield* Effect.scope;
packages/provider-muse/src/server/adapter.ts
+11 -7
@@ -276,8 +276,12 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
276 return ProviderAdapter.ProviderAdapterV2.of({
277 instanceId: options.instanceId,
278 driver: MUSE_PROVIDER,
279 - getCapabilities: () => Effect.succeed(MuseProviderCapabilitiesV2),
280 - planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),
279 + getCapabilities: Effect.fn("MuseAdapter.getCapabilities")(function () {
280 + return Effect.succeed(MuseProviderCapabilitiesV2);
281 + }),
282 + planSelectionTransition: Effect.fn("MuseAdapter.planSelectionTransition")(function () {
283 + return Effect.succeed(turnScopedSelectionTransition());
284 + }),
285 openSession: Effect.fn("MuseAdapterV2.openSession")(function* (
286 input: ProviderAdapter.ProviderAdapterV2OpenSessionInput,
287 ) {
@@ -378,11 +382,11 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
382 }).pipe(
383 Effect.timeout(options.requestTimeoutMs ?? 30_000),
384 Effect.catchTags({
381 - TimeoutError: (cause) =>
382 - Effect.gen(function* () {
383 - yield* eventPermit.withPermits(1)(failHost(cause));
384 - return yield* protocolError(`Muse ${method} timed out; its host was closed`, cause);
385 - }),
385 + // The enclosing operation owns the span for this inline handler.
386 + TimeoutError: Effect.fnUntraced(function* (cause) {
387 + yield* eventPermit.withPermits(1)(failHost(cause));
388 + return yield* protocolError(`Muse ${method} timed out; its host was closed`, cause);
389 + }),
390 }),
391 );
392 const updateSession = Effect.fnUntraced(function* (
packages/provider-opencode/src/server/OpenCodeServerLedger.ts
+5 -1
@@ -307,5 +307,9 @@ export const layer = (input: { readonly stateDir: string }) =>
307
308 export const layerTest = Layer.succeed(
309 OpenCodeServerLedger,
310 - OpenCodeServerLedger.of({ track: () => Effect.succeed(Effect.void) }),
310 + OpenCodeServerLedger.of({
311 + track: Effect.fn("OpenCodeServerLedger.track")(function () {
312 + return Effect.succeed(Effect.void);
313 + }),
314 + }),
315 );
packages/provider-opencode/src/server/OpenCodeServerOwner.ts
+4 -3
@@ -166,14 +166,15 @@ export const make = Effect.fn("OpenCodeServerOwner.make")(function* (input: {
166 );
167
168 return OpenCodeServerOwner.of({
169 - withServer: (use) =>
170 - Effect.uninterruptibleMask((restore) =>
169 + withServer: Effect.fn("OpenCodeServerOwner.withServer")(function (use) {
170 + return Effect.uninterruptibleMask((restore) =>
171 restore(acquireServer).pipe(
172 Effect.flatMap((server) =>
173 restore(use(server)).pipe(Effect.ensuring(releaseServer(server))),
174 ),
175 ),
176 - ),
176 + );
177 + }),
178 });
179 });
180
packages/provider-opencode/src/server/adapter.ts
+6 -2
@@ -914,8 +914,12 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
914 return ProviderAdapter.ProviderAdapterV2.of({
915 instanceId: options.instanceId,
916 driver: OPENCODE_PROVIDER,
917 - getCapabilities: () => Effect.succeed(OpenCodeProviderCapabilitiesV2),
918 - planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),
917 + getCapabilities: Effect.fn("OpencodeAdapter.getCapabilities")(function () {
918 + return Effect.succeed(OpenCodeProviderCapabilitiesV2);
919 + }),
920 + planSelectionTransition: Effect.fn("OpencodeAdapter.planSelectionTransition")(function () {
921 + return Effect.succeed(turnScopedSelectionTransition());
922 + }),
923 openSession: Effect.fn("OpenCodeAdapterV2.openSession")(
924 function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) {
925 const scope = yield* Effect.scope;
packages/provider-opencode/src/server/v2/OpenCode2Client.ts
+2 -2
@@ -146,7 +146,7 @@ const basicAuthorization = (password: string | Redacted.Redacted) => {
146 export const make = Effect.gen(function* () {
147 const httpClient = yield* HttpClient.HttpClient;
148 return OpenCode2Client.of({
149 - connect: ({ baseUrl, password }) => {
149 + connect: Effect.fn("OpenCode2Client.connect")(function ({ baseUrl, password }) {
150 const authenticated = HttpClient.mapRequest(
151 httpClient,
152 HttpClientRequest.setHeader("Authorization", basicAuthorization(password)),
@@ -163,7 +163,7 @@ export const make = Effect.gen(function* () {
163 ),
164 })),
165 );
166 - },
166 + }),
167 });
168 });
169
packages/provider-opencode/src/server/v2/OpenCode2Server.ts
+8 -6
@@ -139,10 +139,11 @@ export const make = Effect.fn("OpenCode2Server.make")(function* (input: {
139 Effect.tap(remember),
140 );
141 return OpenCode2Server.of({
142 - withConnection: (use) =>
143 - Effect.suspend(() => (latest === undefined ? connect : Effect.succeed(latest))).pipe(
142 + withConnection: Effect.fn("OpenCode2Server.withConnection")(function (use) {
143 + return Effect.suspend(() => (latest === undefined ? connect : Effect.succeed(latest))).pipe(
144 Effect.flatMap(use),
145 - ),
145 + );
146 + }),
147 });
148 }
149
@@ -154,11 +155,12 @@ export const make = Effect.fn("OpenCode2Server.make")(function* (input: {
155 verify: (url) => connectTo(url, password, false).pipe(Effect.flatMap(remember)),
156 });
157 return OpenCode2Server.of({
157 - withConnection: (use) =>
158 - owner.withServer((server) =>
158 + withConnection: Effect.fn("OpenCode2Server.withConnection")(function (use) {
159 + return owner.withServer((server) =>
160 latest?.url === server.url
161 ? use(latest)
162 : Effect.die(new Error("OpenCode 2 server was lent before verification.")),
162 - ),
163 + );
164 + }),
165 });
166 });
packages/provider-opencode/src/server/v2/adapter.ts
+6 -2
@@ -4034,8 +4034,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
4034 return ProviderAdapter.ProviderAdapterV2.of({
4035 instanceId,
4036 driver,
4037 - getCapabilities: () => Effect.succeed(OpenCode2ProviderCapabilities),
4038 - planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),
4037 + getCapabilities: Effect.fn("OpencodeAdapter.getCapabilities")(function () {
4038 + return Effect.succeed(OpenCode2ProviderCapabilities);
4039 + }),
4040 + planSelectionTransition: Effect.fn("OpencodeAdapter.planSelectionTransition")(function () {
4041 + return Effect.succeed(turnScopedSelectionTransition());
4042 + }),
4043 // The session borrows the instance's server for as long as it is open, so a
4044 // spawned server is not idle-stopped under a long tool call.
4045 openSession: Effect.fn("OpenCode2Adapter.borrowAndOpenSession")(
packages/provider-pi/src/server/adapter.ts
+6 -2
@@ -429,8 +429,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
429 return ProviderAdapter.ProviderAdapterV2.of({
430 instanceId: options.instanceId,
431 driver: PI_PROVIDER,
432 - getCapabilities: () => Effect.succeed(PiProviderCapabilitiesV2),
433 - planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),
432 + getCapabilities: Effect.fn("PiAdapter.getCapabilities")(function () {
433 + return Effect.succeed(PiProviderCapabilitiesV2);
434 + }),
435 + planSelectionTransition: Effect.fn("PiAdapter.planSelectionTransition")(function () {
436 + return Effect.succeed(turnScopedSelectionTransition());
437 + }),
438 openSession: Effect.fn("PiAdapterV2.openSession")(function* (
439 input: ProviderAdapter.ProviderAdapterV2OpenSessionInput,
440 ) {
packages/provider-pi/src/server/rpc.ts
+25 -25
@@ -315,31 +315,31 @@ export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSp
315 }).pipe(
316 Effect.matchCauseEffect({
317 onFailure: (cause) => failTransport(new PiRpcError({ operation: "read", cause })),
318 - onSuccess: () =>
319 - Effect.gen(function* () {
320 - // Claim stdout-close diagnosis before waiting so broken stdin cannot replace the exit error.
321 - diagnosingStdoutClose = true;
322 - const polled = yield* Deferred.poll(exitDeferred);
323 - const maybeExitCode = Option.isSome(polled)
324 - ? yield* polled.value.pipe(
325 - Effect.asSome,
326 - Effect.orElseSucceed(() => Option.none<number>()),
327 - )
328 - : yield* Deferred.await(exitDeferred).pipe(
329 - Effect.timeoutOption(Duration.millis(250)),
330 - // Stdout-close waits need wall time; TestClock would strand Stop-with-restart without an exit.
331 - Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()),
332 - Effect.orElseSucceed(() => Option.none<number>()),
333 - );
334 - return yield* failTransport(
335 - new PiRpcError({
336 - operation: "read",
337 - detail: describePiStdoutClosure(
338 - Option.isSome(maybeExitCode) ? maybeExitCode.value : undefined,
339 - ),
340 - }),
341 - );
342 - }),
318 + // The enclosing operation owns the span for this inline handler.
319 + onSuccess: Effect.fnUntraced(function* () {
320 + // Claim stdout-close diagnosis before waiting so broken stdin cannot replace the exit error.
321 + diagnosingStdoutClose = true;
322 + const polled = yield* Deferred.poll(exitDeferred);
323 + const maybeExitCode = Option.isSome(polled)
324 + ? yield* polled.value.pipe(
325 + Effect.asSome,
326 + Effect.orElseSucceed(() => Option.none<number>()),
327 + )
328 + : yield* Deferred.await(exitDeferred).pipe(
329 + Effect.timeoutOption(Duration.millis(250)),
330 + // Stdout-close waits need wall time; TestClock would strand Stop-with-restart without an exit.
331 + Effect.provideService(Clock.Clock, Clock.Clock.defaultValue()),
332 + Effect.orElseSucceed(() => Option.none<number>()),
333 + );
334 + return yield* failTransport(
335 + new PiRpcError({
336 + operation: "read",
337 + detail: describePiStdoutClosure(
338 + Option.isSome(maybeExitCode) ? maybeExitCode.value : undefined,
339 + ),
340 + }),
341 + );
342 + }),
343 }),
344 Effect.forkIn(scope),
345 );
packages/provider-testing/src/TestProviderHost.ts
+7 -4
@@ -56,10 +56,12 @@ export const layer = (
56 changes: Stream.empty,
57 subscribe: Effect.succeed(Stream.empty),
58 },
59 - shouldRunBackgroundWork: () => Effect.succeed(options.runBackgroundWork ?? true),
59 + shouldRunBackgroundWork: Effect.fn("ProviderHost.shouldRunBackgroundWork")(function () {
60 + return Effect.succeed(options.runBackgroundWork ?? true);
61 + }),
62 resolveAttachmentPath: (attachment) => path.join(attachmentsDir, attachment.id),
61 - credentials: (namespace, bindingId) =>
62 - Effect.sync(() => {
63 + credentials: Effect.fn("ProviderHost.credentials")(function (namespace, bindingId) {
64 + return Effect.sync(() => {
65 const key = `${namespace}:${bindingId}`;
66 return {
67 binding: { owner: "t3" as const, key },
@@ -67,7 +69,8 @@ export const layer = (
69 set: (value: Uint8Array) => Effect.sync(() => void credentials.set(key, value)),
70 remove: Effect.sync(() => void credentials.delete(key)),
71 };
70 - }),
72 + });
73 + }),
74 });
75 return Context.make(ProviderHost.ProviderHost, host).pipe(
76 Context.add(TestProviderHostSettings, {
packages/shared/src/HostProcess.ts
+13 -13
@@ -77,19 +77,19 @@ export const IsExecutable = Context.Reference<boolean>("@t3tools/shared/HostProc
77 export const Addresses = Context.Reference<Effect.Effect<ReadonlySet<string>>>(
78 "@t3tools/shared/HostProcess/Addresses",
79 {
80 - defaultValue: () =>
81 - Effect.gen(function* () {
82 - const interfaces = Object.values(NodeOS.networkInterfaces())
83 - .flat()
84 - .flatMap((entry) => (entry ? [entry.address] : []));
85 - const resolved = yield* Effect.tryPromise(() =>
86 - NodeDns.promises.lookup(NodeOS.hostname(), { all: true }),
87 - ).pipe(
88 - Effect.map((entries) => entries.map((entry) => entry.address)),
89 - Effect.orElseSucceed(() => [] as ReadonlyArray<string>),
90 - );
91 - return new Set([...interfaces, ...resolved]);
92 - }),
80 + // The enclosing operation owns the span for this inline handler.
81 + defaultValue: Effect.fnUntraced(function* () {
82 + const interfaces = Object.values(NodeOS.networkInterfaces())
83 + .flat()
84 + .flatMap((entry) => (entry ? [entry.address] : []));
85 + const resolved = yield* Effect.tryPromise(() =>
86 + NodeDns.promises.lookup(NodeOS.hostname(), { all: true }),
87 + ).pipe(
88 + Effect.map((entries) => entries.map((entry) => entry.address)),
89 + Effect.orElseSucceed(() => [] as ReadonlyArray<string>),
90 + );
91 + return new Set([...interfaces, ...resolved]);
92 + }),
93 },
94 );
95
packages/shared/src/httpReadiness.ts
+18 -18
@@ -118,26 +118,26 @@ export const waitForHttpReady = Effect.fn("shared.httpReadiness.waitForHttpReady
118 requestUrl,
119 attempts: attempt,
120 }),
121 - onNone: () =>
122 - Effect.gen(function* () {
123 - const lastFailure = yield* Ref.get(lastProbeFailure);
124 - yield* Effect.logWarning("httpReadiness.timedOut", {
121 + // The enclosing operation owns the span for this inline handler.
122 + onNone: Effect.fnUntraced(function* () {
123 + const lastFailure = yield* Ref.get(lastProbeFailure);
124 + yield* Effect.logWarning("httpReadiness.timedOut", {
125 + baseUrl: input.baseUrl,
126 + requestUrl,
127 + timeoutMs,
128 + intervalMs,
129 + probeTimeoutMs,
130 + attempts: attempt,
131 + lastFailure,
132 + });
133 + return yield* Effect.fail(
134 + fail({
135 + kind: "overall-timeout",
136 baseUrl: input.baseUrl,
126 - requestUrl,
137 timeoutMs,
128 - intervalMs,
129 - probeTimeoutMs,
130 - attempts: attempt,
138 lastFailure,
132 - });
133 - return yield* Effect.fail(
134 - fail({
135 - kind: "overall-timeout",
136 - baseUrl: input.baseUrl,
137 - timeoutMs,
138 - lastFailure,
139 - }),
140 - );
141 - }),
139 + }),
140 + );
141 + }),
142 });
143 });
packages/shared/src/nodeSqliteClient.ts
+2 -2
@@ -132,7 +132,7 @@ export class UnsupportedNodeSqliteOperationError extends Schema.TaggedError<Unsu
132 }
133 }
134
135 -const checkNodeSqliteCompat = () => {
135 +const checkNodeSqliteCompat = Effect.fn("checkNodeSqliteCompat")(function () {
136 const parts = process.versions.node.split(".").map(Number);
137 const major = parts[0] ?? 0;
138 const minor = parts[1] ?? 0;
@@ -147,7 +147,7 @@ const checkNodeSqliteCompat = () => {
147 );
148 }
149 return Effect.void;
150 -};
150 +});
151
152 // node:sqlite supplies errcode; classifySqliteError expects errno.
153 const classifyError = (cause: unknown, message: string, operation: string) => {
packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts
+26 -20
@@ -400,8 +400,8 @@ export const make = Effect.gen(function* () {
400
401 return AzureDevOpsCli.of({
402 execute,
403 - listPullRequests: (input) =>
404 - executeJson({
403 + listPullRequests: Effect.fn("AzureDevOpsCli.listPullRequests")(function (input) {
404 + return executeJson({
405 cwd: input.cwd,
406 args: [
407 "repos",
@@ -439,9 +439,10 @@ export const make = Effect.gen(function* () {
439 }),
440 ),
441 ),
442 - ),
443 - getPullRequest: (input) =>
444 - executeJson({
442 + );
443 + }),
444 + getPullRequest: Effect.fn("AzureDevOpsCli.getPullRequest")(function (input) {
445 + return executeJson({
446 cwd: input.cwd,
447 args: [
448 "repos",
@@ -473,9 +474,10 @@ export const make = Effect.gen(function* () {
474 }),
475 ),
476 ),
476 - ),
477 - getRepositoryCloneUrls: (input) =>
478 - executeJson({
477 + );
478 + }),
479 + getRepositoryCloneUrls: Effect.fn("AzureDevOpsCli.getRepositoryCloneUrls")(function (input) {
480 + return executeJson({
481 cwd: input.cwd,
482 args: ["repos", "show", "--detect", "true", "--repository", input.repository],
483 }).pipe(
@@ -489,8 +491,9 @@ export const make = Effect.gen(function* () {
491 ),
492 ),
493 Effect.map(normalizeRepositoryCloneUrls),
492 - ),
493 - createRepository: (input) => {
494 + );
495 + }),
496 + createRepository: Effect.fn("AzureDevOpsCli.createRepository")(function (input) {
497 const repository = parseRepositorySpecifier(input.repository);
498 // Project/organization permissions control visibility; `az repos create` has no flag.
499 return executeJson({
@@ -511,9 +514,9 @@ export const make = Effect.gen(function* () {
514 ),
515 Effect.map(normalizeRepositoryCloneUrls),
516 );
514 - },
515 - createPullRequest: (input) =>
516 - execute({
517 + }),
518 + createPullRequest: Effect.fn("AzureDevOpsCli.createPullRequest")(function (input) {
519 + return execute({
520 cwd: input.cwd,
521 args: [
522 "repos",
@@ -531,9 +534,10 @@ export const make = Effect.gen(function* () {
534 "--description",
535 `@${input.bodyFile}`,
536 ],
534 - }).pipe(Effect.asVoid),
535 - getDefaultBranch: (input) =>
536 - executeJson({
537 + }).pipe(Effect.asVoid);
538 + }),
539 + getDefaultBranch: Effect.fn("AzureDevOpsCli.getDefaultBranch")(function (input) {
540 + return executeJson({
541 cwd: input.cwd,
542 args: ["repos", "show", "--detect", "true"],
543 }).pipe(
@@ -542,9 +546,10 @@ export const make = Effect.gen(function* () {
546 decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", input.cwd),
547 ),
548 Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
545 - ),
546 - checkoutPullRequest: (input) =>
547 - execute({
549 + );
550 + }),
551 + checkoutPullRequest: Effect.fn("AzureDevOpsCli.checkoutPullRequest")(function (input) {
552 + return execute({
553 cwd: input.cwd,
554 args: [
555 "repos",
@@ -558,7 +563,8 @@ export const make = Effect.gen(function* () {
563 "--remote-name",
564 input.remoteName ?? "origin",
565 ],
561 - }).pipe(Effect.asVoid),
566 + }).pipe(Effect.asVoid);
567 + }),
568 });
569 });
570
packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts
+106 -90
@@ -445,8 +445,8 @@ export const make = Effect.gen(function* () {
445 };
446
447 return AzureDevOpsPullRequestCli.of({
448 - getViewer: (input) =>
449 - executeJson({ cwd: input.cwd, args: ["account", "show", "--query", "user"] }).pipe(
448 + getViewer: Effect.fn("AzureDevOpsPullRequestCli.getViewer")(function (input) {
449 + return executeJson({ cwd: input.cwd, args: ["account", "show", "--query", "user"] }).pipe(
450 Effect.flatMap((result): Effect.Effect<string, AzureDevOpsPullRequestCliError> => {
451 const decoded = decodeViewerJson(`{"user":${result.stdout.trim() || "null"}}`);
452 if (!Result.isSuccess(decoded)) {
@@ -495,10 +495,11 @@ export const make = Effect.gen(function* () {
495 }),
496 ),
497 ),
498 - ),
498 + );
499 + }),
500
500 - listPullRequests: (input) =>
501 - listPullRequestPage({
501 + listPullRequests: Effect.fn("AzureDevOpsPullRequestCli.listPullRequests")(function (input) {
502 + return listPullRequestPage({
503 cwd: input.cwd,
504 repository: input.repository,
505 state: input.state,
@@ -509,10 +510,11 @@ export const make = Effect.gen(function* () {
510 skip: input.cursor?.delivered ?? 0,
511 cursorAdvance: 0,
512 items: [],
512 - }),
513 + });
514 + }),
515
514 - getPullRequest: (input) =>
515 - executeJson({
516 + getPullRequest: Effect.fn("AzureDevOpsPullRequestCli.getPullRequest")(function (input) {
517 + return executeJson({
518 cwd: input.cwd,
519 args: ["repos", "pr", "show", ...detectArgs, "--id", String(input.number)],
520 }).pipe(
@@ -540,57 +542,62 @@ export const make = Effect.gen(function* () {
542 : Effect.succeed(decoded.success);
543 },
544 ),
543 - ),
545 + );
546 + }),
547
545 - listThreads: (input) =>
546 - invoke({
548 + listThreads: Effect.fn("AzureDevOpsPullRequestCli.listThreads")(function (input) {
549 + return invoke({
550 cwd: input.cwd,
551 operation: "listThreads",
552 resource: "pullRequestThreads",
553 routeParameters: pullRequestRoute(input),
554 maxOutputBytes: REVIEW_HISTORY_MAX_OUTPUT_BYTES,
555 decode: decodeThreadsJson,
553 - }),
556 + });
557 + }),
558
555 - listIterations: (input) =>
556 - invoke({
559 + listIterations: Effect.fn("AzureDevOpsPullRequestCli.listIterations")(function (input) {
560 + return invoke({
561 cwd: input.cwd,
562 operation: "listIterations",
563 resource: "pullRequestIterations",
564 routeParameters: pullRequestRoute(input),
565 maxOutputBytes: REVIEW_HISTORY_MAX_OUTPUT_BYTES,
566 decode: decodeIterationsJson,
563 - }),
564 -
565 - listIterationChanges: (input) => {
566 - const page = (skip: number) =>
567 - invoke({
568 - cwd: input.cwd,
569 - operation: "listIterationChanges",
570 - resource: "pullRequestIterationChanges",
571 - routeParameters: [...pullRequestRoute(input), `iterationId=${input.iterationId}`],
572 - queryParameters: [`$top=${CHANGE_ENTRIES_PER_PAGE}`, `$skip=${skip}`],
573 - maxOutputBytes: CHANGE_ENTRIES_MAX_OUTPUT_BYTES,
574 - decode: decodeIterationChangesJson,
575 - });
576 - const from = (
577 - skip: number,
578 - collected: ReadonlyArray<AzureDevOpsChangeEntry>,
579 - ): Effect.Effect<AzureDevOpsIterationChanges, AzureDevOpsPullRequestCliError> =>
580 - page(skip).pipe(
581 - Effect.flatMap((answer) => {
582 - const changes = [...collected, ...answer.changes];
583 - if (answer.nextSkip === null) return Effect.succeed({ changes, truncated: false });
584 - return answer.nextSkip <= skip || answer.nextSkip >= MAX_CHANGE_ENTRIES
585 - ? Effect.succeed({ changes, truncated: true })
586 - : from(answer.nextSkip, changes);
587 - }),
588 - );
589 - return from(0, []);
590 - },
567 + });
568 + }),
569 +
570 + listIterationChanges: Effect.fn("AzureDevOpsPullRequestCli.listIterationChanges")(
571 + function (input) {
572 + const page = (skip: number) =>
573 + invoke({
574 + cwd: input.cwd,
575 + operation: "listIterationChanges",
576 + resource: "pullRequestIterationChanges",
577 + routeParameters: [...pullRequestRoute(input), `iterationId=${input.iterationId}`],
578 + queryParameters: [`$top=${CHANGE_ENTRIES_PER_PAGE}`, `$skip=${skip}`],
579 + maxOutputBytes: CHANGE_ENTRIES_MAX_OUTPUT_BYTES,
580 + decode: decodeIterationChangesJson,
581 + });
582 + const from = (
583 + skip: number,
584 + collected: ReadonlyArray<AzureDevOpsChangeEntry>,
585 + ): Effect.Effect<AzureDevOpsIterationChanges, AzureDevOpsPullRequestCliError> =>
586 + page(skip).pipe(
587 + Effect.flatMap((answer) => {
588 + const changes = [...collected, ...answer.changes];
589 + if (answer.nextSkip === null) return Effect.succeed({ changes, truncated: false });
590 + return answer.nextSkip <= skip || answer.nextSkip >= MAX_CHANGE_ENTRIES
591 + ? Effect.succeed({ changes, truncated: true })
592 + : from(answer.nextSkip, changes);
593 + }),
594 + );
595 + return from(0, []);
596 + },
597 + ),
598
592 - readItemContent: (input) =>
593 - invoke({
599 + readItemContent: Effect.fn("AzureDevOpsPullRequestCli.readItemContent")(function (input) {
600 + return invoke({
601 cwd: input.cwd,
602 operation: "readItemContent",
603 resource: "items",
@@ -607,53 +614,61 @@ export const make = Effect.gen(function* () {
614 ],
615 maxOutputBytes: ITEM_CONTENT_MAX_OUTPUT_BYTES,
616 decode: decodeItemContentJson,
610 - }),
611 -
612 - setPullRequestReviewers: (input) =>
613 - input.reviewers.some((reviewer) => !isReviewerName(reviewer))
614 - ? Effect.fail(new AzureDevOpsReviewerNameError({ command: "az", cwd: input.cwd }))
615 - : azure
616 - .execute({
617 - cwd: input.cwd,
618 - args: [
619 - "repos",
620 - "pr",
621 - "reviewer",
622 - input.requested ? "add" : "remove",
623 - ...detectArgs,
624 - "--id",
625 - String(input.number),
626 - // Repeating `--reviewers` replaces the earlier list.
627 - "--reviewers",
628 - ...input.reviewers,
629 - "--only-show-errors",
630 - "--output",
631 - "json",
632 - ],
633 - })
634 - .pipe(Effect.asVoid),
617 + });
618 + }),
619
636 - runPullRequestAction: (input) =>
637 - azure
638 - .execute({
639 - cwd: input.cwd,
640 - args: [
641 - "repos",
642 - "pr",
643 - "update",
644 - ...detectArgs,
645 - "--id",
646 - String(input.number),
647 - ...actionArgs(input.action, input.mergeMethod),
648 - "--only-show-errors",
649 - "--output",
650 - "json",
651 - ],
652 - })
653 - .pipe(Effect.asVoid),
620 + setPullRequestReviewers: Effect.fn("AzureDevOpsPullRequestCli.setPullRequestReviewers")(
621 + function* (input) {
622 + if (input.reviewers.some((reviewer) => !isReviewerName(reviewer))) {
623 + return yield* new AzureDevOpsReviewerNameError({ command: "az", cwd: input.cwd });
624 + }
625 + return yield* azure
626 + .execute({
627 + cwd: input.cwd,
628 + args: [
629 + "repos",
630 + "pr",
631 + "reviewer",
632 + input.requested ? "add" : "remove",
633 + ...detectArgs,
634 + "--id",
635 + String(input.number),
636 + // Repeating `--reviewers` replaces the earlier list.
637 + "--reviewers",
638 + ...input.reviewers,
639 + "--only-show-errors",
640 + "--output",
641 + "json",
642 + ],
643 + })
644 + .pipe(Effect.asVoid);
645 + },
646 + ),
647 +
648 + runPullRequestAction: Effect.fn("AzureDevOpsPullRequestCli.runPullRequestAction")(
649 + function (input) {
650 + return azure
651 + .execute({
652 + cwd: input.cwd,
653 + args: [
654 + "repos",
655 + "pr",
656 + "update",
657 + ...detectArgs,
658 + "--id",
659 + String(input.number),
660 + ...actionArgs(input.action, input.mergeMethod),
661 + "--only-show-errors",
662 + "--output",
663 + "json",
664 + ],
665 + })
666 + .pipe(Effect.asVoid);
667 + },
668 + ),
669
655 - updatePullRequest: (input) =>
656 - azure
670 + updatePullRequest: Effect.fn("AzureDevOpsPullRequestCli.updatePullRequest")(function (input) {
671 + return azure
672 .execute({
673 cwd: input.cwd,
674 args: [
@@ -671,7 +686,8 @@ export const make = Effect.gen(function* () {
686 "json",
687 ],
688 })
674 - .pipe(Effect.asVoid),
689 + .pipe(Effect.asVoid);
690 + }),
691 });
692 });
693
packages/source-control-azure-devops/src/server/AzureDevOpsSourceControlProvider.ts
+129 -110
@@ -76,151 +76,170 @@ export const make = Effect.gen(function* () {
76
77 return SourceControlProvider.SourceControlProvider.of({
78 kind: SourceControlProviderKind.make("azure-devops"),
79 - listChangeRequests: (input) => {
80 - const source = SourceControlProvider.sourceControlRefFromInput(input);
81 - return azure
82 - .listPullRequests({
83 - cwd: input.cwd,
84 - headSelector: input.headSelector,
85 - ...(source !== undefined ? { source } : {}),
86 - state: input.state,
87 - ...(input.limit !== undefined ? { limit: input.limit } : {}),
88 - })
89 - .pipe(
90 - Effect.map((items) => items.map(toChangeRequest)),
79 + listChangeRequests: Effect.fn("AzureDevOpsSourceControlProvider.listChangeRequests")(
80 + function (input) {
81 + const source = SourceControlProvider.sourceControlRefFromInput(input);
82 + return azure
83 + .listPullRequests({
84 + cwd: input.cwd,
85 + headSelector: input.headSelector,
86 + ...(source !== undefined ? { source } : {}),
87 + state: input.state,
88 + ...(input.limit !== undefined ? { limit: input.limit } : {}),
89 + })
90 + .pipe(
91 + Effect.map((items) => items.map(toChangeRequest)),
92 + Effect.mapError(
93 + (error) =>
94 + new SourceControlProviderError({
95 + provider: SourceControlProviderKind.make("azure-devops"),
96 + operation: "listChangeRequests",
97 + command: error.command,
98 + cwd: input.cwd,
99 + reference: SourceControlProvider.transportSafeSourceControlErrorValue(
100 + input.headSelector,
101 + ),
102 + detail: error.detail,
103 + cause: error,
104 + }),
105 + ),
106 + );
107 + },
108 + ),
109 + getChangeRequest: Effect.fn("AzureDevOpsSourceControlProvider.getChangeRequest")(
110 + function (input) {
111 + return azure.getPullRequest(input).pipe(
112 + Effect.map(toChangeRequest),
113 Effect.mapError(
114 (error) =>
115 new SourceControlProviderError({
116 provider: SourceControlProviderKind.make("azure-devops"),
95 - operation: "listChangeRequests",
117 + operation: "getChangeRequest",
118 command: error.command,
119 cwd: input.cwd,
120 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
99 - input.headSelector,
121 + input.reference,
122 ),
123 detail: error.detail,
124 cause: error,
125 }),
126 ),
127 );
106 - },
107 - getChangeRequest: (input) =>
108 - azure.getPullRequest(input).pipe(
109 - Effect.map(toChangeRequest),
110 - Effect.mapError(
111 - (error) =>
112 - new SourceControlProviderError({
113 - provider: SourceControlProviderKind.make("azure-devops"),
114 - operation: "getChangeRequest",
115 - command: error.command,
116 - cwd: input.cwd,
117 - reference: SourceControlProvider.transportSafeSourceControlErrorValue(
118 - input.reference,
119 - ),
120 - detail: error.detail,
121 - cause: error,
122 - }),
123 - ),
124 - ),
125 - createChangeRequest: (input) => {
126 - const source = SourceControlProvider.sourceControlRefFromInput(input);
127 - return azure
128 - .createPullRequest({
129 - cwd: input.cwd,
130 - baseBranch: input.baseRefName,
131 - headSelector: input.headSelector,
132 - ...(source !== undefined ? { source } : {}),
133 - ...(input.target !== undefined ? { target: input.target } : {}),
134 - title: input.title,
135 - bodyFile: input.bodyFile,
136 - })
137 - .pipe(
128 + },
129 + ),
130 + createChangeRequest: Effect.fn("AzureDevOpsSourceControlProvider.createChangeRequest")(
131 + function (input) {
132 + const source = SourceControlProvider.sourceControlRefFromInput(input);
133 + return azure
134 + .createPullRequest({
135 + cwd: input.cwd,
136 + baseBranch: input.baseRefName,
137 + headSelector: input.headSelector,
138 + ...(source !== undefined ? { source } : {}),
139 + ...(input.target !== undefined ? { target: input.target } : {}),
140 + title: input.title,
141 + bodyFile: input.bodyFile,
142 + })
143 + .pipe(
144 + Effect.mapError(
145 + (error) =>
146 + new SourceControlProviderError({
147 + provider: SourceControlProviderKind.make("azure-devops"),
148 + operation: "createChangeRequest",
149 + command: error.command,
150 + cwd: input.cwd,
151 + reference: SourceControlProvider.transportSafeSourceControlErrorValue(
152 + input.headSelector,
153 + ),
154 + detail: error.detail,
155 + cause: error,
156 + }),
157 + ),
158 + );
159 + },
160 + ),
161 + getRepositoryCloneUrls: Effect.fn("AzureDevOpsSourceControlProvider.getRepositoryCloneUrls")(
162 + function (input) {
163 + return azure.getRepositoryCloneUrls(input).pipe(
164 Effect.mapError(
165 (error) =>
166 new SourceControlProviderError({
167 provider: SourceControlProviderKind.make("azure-devops"),
142 - operation: "createChangeRequest",
168 + operation: "getRepositoryCloneUrls",
169 command: error.command,
170 cwd: input.cwd,
145 - reference: SourceControlProvider.transportSafeSourceControlErrorValue(
146 - input.headSelector,
171 + repository: SourceControlProvider.transportSafeSourceControlErrorValue(
172 + input.repository,
173 ),
174 detail: error.detail,
175 cause: error,
176 }),
177 ),
178 );
153 - },
154 - getRepositoryCloneUrls: (input) =>
155 - azure.getRepositoryCloneUrls(input).pipe(
156 - Effect.mapError(
157 - (error) =>
158 - new SourceControlProviderError({
159 - provider: SourceControlProviderKind.make("azure-devops"),
160 - operation: "getRepositoryCloneUrls",
161 - command: error.command,
162 - cwd: input.cwd,
163 - repository: SourceControlProvider.transportSafeSourceControlErrorValue(
164 - input.repository,
165 - ),
166 - detail: error.detail,
167 - cause: error,
168 - }),
169 - ),
170 - ),
171 - createRepository: (input) =>
172 - azure.createRepository(input).pipe(
173 - Effect.mapError(
174 - (error) =>
175 - new SourceControlProviderError({
176 - provider: SourceControlProviderKind.make("azure-devops"),
177 - operation: "createRepository",
178 - command: error.command,
179 - cwd: input.cwd,
180 - repository: SourceControlProvider.transportSafeSourceControlErrorValue(
181 - input.repository,
182 - ),
183 - detail: error.detail,
184 - cause: error,
185 - }),
186 - ),
187 - ),
188 - getDefaultBranch: (input) =>
189 - azure.getDefaultBranch({ cwd: input.cwd }).pipe(
190 - Effect.mapError(
191 - (error) =>
192 - new SourceControlProviderError({
193 - provider: SourceControlProviderKind.make("azure-devops"),
194 - operation: "getDefaultBranch",
195 - command: error.command,
196 - cwd: input.cwd,
197 - detail: error.detail,
198 - cause: error,
199 - }),
200 - ),
201 - ),
202 - checkoutChangeRequest: (input) =>
203 - azure
204 - .checkoutPullRequest({
205 - cwd: input.cwd,
206 - reference: input.reference,
207 - ...(input.context !== undefined ? { remoteName: input.context.remoteName } : {}),
208 - })
209 - .pipe(
179 + },
180 + ),
181 + createRepository: Effect.fn("AzureDevOpsSourceControlProvider.createRepository")(
182 + function (input) {
183 + return azure.createRepository(input).pipe(
184 Effect.mapError(
185 (error) =>
186 new SourceControlProviderError({
187 provider: SourceControlProviderKind.make("azure-devops"),
214 - operation: "checkoutChangeRequest",
188 + operation: "createRepository",
189 command: error.command,
190 cwd: input.cwd,
217 - reference: SourceControlProvider.transportSafeSourceControlErrorValue(
218 - input.reference,
191 + repository: SourceControlProvider.transportSafeSourceControlErrorValue(
192 + input.repository,
193 ),
194 detail: error.detail,
195 cause: error,
196 }),
197 ),
224 - ),
198 + );
199 + },
200 + ),
201 + getDefaultBranch: Effect.fn("AzureDevOpsSourceControlProvider.getDefaultBranch")(
202 + function (input) {
203 + return azure.getDefaultBranch({ cwd: input.cwd }).pipe(
204 + Effect.mapError(
205 + (error) =>
206 + new SourceControlProviderError({
207 + provider: SourceControlProviderKind.make("azure-devops"),
208 + operation: "getDefaultBranch",
209 + command: error.command,
210 + cwd: input.cwd,
211 + detail: error.detail,
212 + cause: error,
213 + }),
214 + ),
215 + );
216 + },
217 + ),
218 + checkoutChangeRequest: Effect.fn("AzureDevOpsSourceControlProvider.checkoutChangeRequest")(
219 + function (input) {
220 + return azure
221 + .checkoutPullRequest({
222 + cwd: input.cwd,
223 + reference: input.reference,
224 + ...(input.context !== undefined ? { remoteName: input.context.remoteName } : {}),
225 + })
226 + .pipe(
227 + Effect.mapError(
228 + (error) =>
229 + new SourceControlProviderError({
230 + provider: SourceControlProviderKind.make("azure-devops"),
231 + operation: "checkoutChangeRequest",
232 + command: error.command,
233 + cwd: input.cwd,
234 + reference: SourceControlProvider.transportSafeSourceControlErrorValue(
235 + input.reference,
236 + ),
237 + detail: error.detail,
238 + cause: error,
239 + }),
240 + ),
241 + );
242 + },
243 + ),
244 });
245 });
packages/source-control-bitbucket/src/server/BitbucketApi.ts
+18 -13
@@ -999,8 +999,8 @@ export const make = Effect.gen(function* () {
999 })),
1000 Effect.catch(() => currentCredential.pipe(Effect.map(authFromCredential))),
1001 ),
1002 - listPullRequests: (input) =>
1003 - resolveRepository(input).pipe(
1002 + listPullRequests: Effect.fn("BitbucketApi.listPullRequests")(function (input) {
1003 + return resolveRepository(input).pipe(
1004 Effect.flatMap((repository) => {
1005 const states = toBitbucketStates(input.state);
1006 const query: Record<string, string | ReadonlyArray<string>> = {
@@ -1025,13 +1025,16 @@ export const make = Effect.gen(function* () {
1025 );
1026 }),
1027 Effect.map((list) => list.values.map(normalizeBitbucketPullRequestRecord)),
1028 - ),
1029 - getPullRequest: (input) =>
1030 - getRawPullRequest(input).pipe(Effect.map(normalizeBitbucketPullRequestRecord)),
1031 - getRepositoryCloneUrls: (input) =>
1032 - getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),
1033 - createRepository: (input) =>
1034 - requireRepositoryLocator(input.repository).pipe(
1028 + );
1029 + }),
1030 + getPullRequest: Effect.fn("BitbucketApi.getPullRequest")(function (input) {
1031 + return getRawPullRequest(input).pipe(Effect.map(normalizeBitbucketPullRequestRecord));
1032 + }),
1033 + getRepositoryCloneUrls: Effect.fn("BitbucketApi.getRepositoryCloneUrls")(function (input) {
1034 + return getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls));
1035 + }),
1036 + createRepository: Effect.fn("BitbucketApi.createRepository")(function (input) {
1037 + return requireRepositoryLocator(input.repository).pipe(
1038 Effect.flatMap((repository) =>
1039 executeJson(
1040 "createRepository",
@@ -1049,7 +1052,8 @@ export const make = Effect.gen(function* () {
1052 ),
1053 ),
1054 Effect.map(normalizeRepositoryCloneUrls),
1052 - ),
1055 + );
1056 + }),
1057 createPullRequest: Effect.fn("BitbucketApi.createPullRequest")(function* (input) {
1058 const repository = yield* resolveRepository(input);
1059 const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
@@ -1095,8 +1099,8 @@ export const make = Effect.gen(function* () {
1099 BitbucketPullRequestSchema,
1100 );
1101 }),
1098 - getDefaultBranch: (input) =>
1099 - resolveRepository(input).pipe(
1102 + getDefaultBranch: Effect.fn("BitbucketApi.getDefaultBranch")(function (input) {
1103 + return resolveRepository(input).pipe(
1104 Effect.flatMap((locator) =>
1105 Effect.all(
1106 {
@@ -1111,7 +1115,8 @@ export const make = Effect.gen(function* () {
1115 ),
1116 ),
1117 Effect.map(defaultChangeRequestTargetBranch),
1114 - ),
1118 + );
1119 + }),
1120 checkoutPullRequest: Effect.fn("BitbucketApi.checkoutPullRequest")(
1121 function* (input) {
1122 const destinationRepository = yield* resolveRepository(input);
packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.ts
+144 -113
@@ -124,6 +124,9 @@ const DIFF_MAX_BYTES = 8 * 1024 * 1024;
124 /** Must expire before the caller's version cache so refreshes reach Bitbucket. */
125 const REVISION_PATCH_TTL = Duration.seconds(5);
126 const REVISION_PATCH_CAPACITY = 16;
127 +const encodeRevisionKey = Schema.encodeSync(
128 + Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.Number])),
129 +);
130 export interface BitbucketPullRequestBatch {
131 readonly items: ReadonlyArray<BitbucketPullRequest>;
132 readonly truncated: boolean;
@@ -526,8 +529,8 @@ export const make = Effect.gen(function* () {
529 );
530
531 return BitbucketPullRequestApi.of({
529 - getViewer: () =>
530 - bitbucket.request({ method: "GET", url: "/user" }).pipe(
532 + getViewer: Effect.fn("BitbucketPullRequestApi.getViewer")(function () {
533 + return bitbucket.request({ method: "GET", url: "/user" }).pipe(
534 Effect.flatMap((response): Effect.Effect<string, BitbucketPullRequestApiError> => {
535 const decoded = decodeViewerJson(response.body);
536 if (!Result.isSuccess(decoded)) {
@@ -539,10 +542,11 @@ export const make = Effect.gen(function* () {
542 ? Effect.fail(new BitbucketViewerUnavailableError())
543 : Effect.succeed(decoded.success);
544 }),
542 - ),
545 + );
546 + }),
547
544 - listPullRequests: (input) =>
545 - withRepository(input.repository, (path) => {
548 + listPullRequests: Effect.fn("BitbucketPullRequestApi.listPullRequests")(function (input) {
549 + return withRepository(input.repository, (path) => {
550 const search = input.query?.trim() ?? "";
551 // Exclude already-sent IDs at the inclusive timestamp before applying the page limit.
552 const predicates = [
@@ -563,77 +567,89 @@ export const make = Effect.gen(function* () {
567 page: 1,
568 collected: [],
569 });
566 - }),
570 + });
571 + }),
572
568 - getPullRequest: (input) =>
569 - withRepository(input.repository, (path) =>
573 + getPullRequest: Effect.fn("BitbucketPullRequestApi.getPullRequest")(function (input) {
574 + return withRepository(input.repository, (path) =>
575 readPage({
576 operation: "getPullRequest",
577 // Settlement needs `closed_on`, omitted by default.
578 url: `${path}/pullrequests/${input.number}?fields=%2Bclosed_on`,
579 decode: decodePullRequestJson,
580 }),
576 - ),
581 + );
582 + }),
583
584 // Permission endpoints may return 403/404/410 (CHANGE-2770); let writes enforce access.
579 - getRepositoryPermission: (input) =>
580 - withRepository(input.repository, (_path, workspace, slug) =>
581 - readPage({
582 - operation: "getRepositoryPermission",
583 - url: `/user/workspaces/${encodeURIComponent(workspace)}/permissions/repositories?q=${encodeURIComponent(
584 - `repository.full_name="${filterLiteral(`${workspace}/${slug}`)}"`,
585 - )}`,
586 - decode: decodeRepositoryPermissionJson,
587 - }),
588 - ).pipe(Effect.catchIf(isRepositoryPermissionUnavailableError, () => Effect.succeed(true))),
585 + getRepositoryPermission: Effect.fn("BitbucketPullRequestApi.getRepositoryPermission")(
586 + function (input) {
587 + return withRepository(input.repository, (_path, workspace, slug) =>
588 + readPage({
589 + operation: "getRepositoryPermission",
590 + url: `/user/workspaces/${encodeURIComponent(workspace)}/permissions/repositories?q=${encodeURIComponent(
591 + `repository.full_name="${filterLiteral(`${workspace}/${slug}`)}"`,
592 + )}`,
593 + decode: decodeRepositoryPermissionJson,
594 + }),
595 + ).pipe(Effect.catchIf(isRepositoryPermissionUnavailableError, () => Effect.succeed(true)));
596 + },
597 + ),
598
599 getPullRequestDiff: pullRequestDiff,
600
592 - getFileRevisions: (input) =>
593 - input.paths.length === 0
594 - ? Effect.succeed({ revisions: new Map(), complete: false })
595 - : Cache.get(revisionPatches, JSON.stringify([input.repository, input.number])).pipe(
596 - Effect.map((diff) => {
597 - const revisions = new Map(diff.revisions);
598 - // A truncated patch cannot identify absent paths as deleted.
599 - if (!diff.truncated) {
600 - for (const path of input.paths) {
601 - if (!revisions.has(path)) revisions.set(path, "");
602 - }
603 - }
604 - return { revisions, complete: !diff.truncated };
605 - }),
606 - ),
601 + getFileRevisions: Effect.fn("BitbucketPullRequestApi.getFileRevisions")(function* (input) {
602 + if (input.paths.length === 0)
603 + return { revisions: new Map<string, string>(), complete: false };
604 + return yield* Cache.get(
605 + revisionPatches,
606 + encodeRevisionKey([input.repository, input.number]),
607 + ).pipe(
608 + Effect.map((diff) => {
609 + const revisions = new Map(diff.revisions);
610 + // A truncated patch cannot identify absent paths as deleted.
611 + if (!diff.truncated) {
612 + for (const path of input.paths) {
613 + if (!revisions.has(path)) revisions.set(path, "");
614 + }
615 + }
616 + return { revisions, complete: !diff.truncated };
617 + }),
618 + );
619 + }),
620
608 - getDiffStat: (input) =>
609 - withRepository(input.repository, (path) =>
621 + getDiffStat: Effect.fn("BitbucketPullRequestApi.getDiffStat")(function (input) {
622 + return withRepository(input.repository, (path) =>
623 diffStatPages({
624 url: `${path}/pullrequests/${input.number}/diffstat?pagelen=${MAX_PAGE_SIZE}`,
625 totals: { additions: 0, deletions: 0, changedFiles: 0 },
626 }),
614 - ),
627 + );
628 + }),
629
616 - getMergeability: (input) =>
617 - withRepository(input.repository, (path) =>
630 + getMergeability: Effect.fn("BitbucketPullRequestApi.getMergeability")(function (input) {
631 + return withRepository(input.repository, (path) =>
632 readPage({
633 operation: "getMergeability",
634 url: `${path}/pullrequests/${input.number}/conflicts`,
635 decode: decodeConflictsJson,
636 }),
623 - ),
637 + );
638 + }),
639
625 - listComments: (input) =>
626 - withRepository(input.repository, (path) =>
640 + listComments: Effect.fn("BitbucketPullRequestApi.listComments")(function (input) {
641 + return withRepository(input.repository, (path) =>
642 commentsPage({
643 url: `${path}/pullrequests/${input.number}/comments?pagelen=${CONVERSATION_PAGE_SIZE}`,
644 page: 1,
645 comments: [],
646 entries: [],
647 }),
633 - ),
648 + );
649 + }),
650
635 - listCommits: (input) =>
636 - withRepository(input.repository, (path) =>
651 + listCommits: Effect.fn("BitbucketPullRequestApi.listCommits")(function (input) {
652 + return withRepository(input.repository, (path) =>
653 itemPages({
654 operation: "listCommits",
655 url: `${path}/pullrequests/${input.number}/commits?pagelen=${CONVERSATION_PAGE_SIZE}`,
@@ -641,10 +657,11 @@ export const make = Effect.gen(function* () {
657 items: [],
658 prepend: true,
659 }),
644 - ),
660 + );
661 + }),
662
646 - listChecks: (input) =>
647 - withRepository(input.repository, (path) =>
663 + listChecks: Effect.fn("BitbucketPullRequestApi.listChecks")(function (input) {
664 + return withRepository(input.repository, (path) =>
665 itemPages({
666 operation: "listChecks",
667 url: `${path}/pullrequests/${input.number}/statuses?pagelen=${CONVERSATION_PAGE_SIZE}`,
@@ -652,43 +669,47 @@ export const make = Effect.gen(function* () {
669 items: [],
670 prepend: false,
671 }).pipe(Effect.map(sortChecks)),
655 - ),
656 -
657 - listReviewerCandidates: (input) =>
658 - withRepository(input.repository, (path, workspace) =>
659 - Effect.all(
660 - [
661 - readPage({
662 - operation: "getPullRequest",
663 - url: `${path}/pullrequests/${input.number}`,
664 - decode: decodePullRequestJson,
665 - }),
666 - readPage({
667 - operation: "listReviewerCandidates",
668 - url: `/workspaces/${encodeURIComponent(workspace)}/members?pagelen=${MAX_PAGE_SIZE}`,
669 - decode: decodeWorkspaceMembersJson,
672 + );
673 + }),
674 +
675 + listReviewerCandidates: Effect.fn("BitbucketPullRequestApi.listReviewerCandidates")(
676 + function (input) {
677 + return withRepository(input.repository, (path, workspace) =>
678 + Effect.all(
679 + [
680 + readPage({
681 + operation: "getPullRequest",
682 + url: `${path}/pullrequests/${input.number}`,
683 + decode: decodePullRequestJson,
684 + }),
685 + readPage({
686 + operation: "listReviewerCandidates",
687 + url: `/workspaces/${encodeURIComponent(workspace)}/members?pagelen=${MAX_PAGE_SIZE}`,
688 + decode: decodeWorkspaceMembersJson,
689 + }),
690 + ],
691 + { concurrency: 2 },
692 + ).pipe(
693 + Effect.map(([pullRequest, members]) => {
694 + const requested = new Set(pullRequest.reviewerIds);
695 + const author = pullRequest.author?.login;
696 + return {
697 + // Bitbucket forbids requesting a review from the PR author.
698 + candidates: members.items.flatMap((candidate) =>
699 + candidate.login === author
700 + ? []
701 + : [{ ...candidate, isRequested: requested.has(candidate.id) }],
702 + ),
703 + truncated: members.next !== null,
704 + };
705 }),
671 - ],
672 - { concurrency: 2 },
673 - ).pipe(
674 - Effect.map(([pullRequest, members]) => {
675 - const requested = new Set(pullRequest.reviewerIds);
676 - const author = pullRequest.author?.login;
677 - return {
678 - // Bitbucket forbids requesting a review from the PR author.
679 - candidates: members.items.flatMap((candidate) =>
680 - candidate.login === author
681 - ? []
682 - : [{ ...candidate, isRequested: requested.has(candidate.id) }],
683 - ),
684 - truncated: members.next !== null,
685 - };
686 - }),
687 - ),
688 - ),
706 + ),
707 + );
708 + },
709 + ),
710
690 - setReviewerRequest: (input) =>
691 - withRepository(input.repository, (path) => {
711 + setReviewerRequest: Effect.fn("BitbucketPullRequestApi.setReviewerRequest")(function (input) {
712 + return withRepository(input.repository, (path) => {
713 const pullRequest = `${path}/pullrequests/${input.number}`;
714 return readPage({
715 operation: "getPullRequest",
@@ -710,10 +731,11 @@ export const make = Effect.gen(function* () {
731 }),
732 Effect.asVoid,
733 );
713 - }),
734 + });
735 + }),
736
715 - runAction: (input) =>
716 - withRepository(input.repository, (path) => {
737 + runAction: Effect.fn("BitbucketPullRequestApi.runAction")(function (input) {
738 + return withRepository(input.repository, (path) => {
739 const pullRequest = `${path}/pullrequests/${input.number}`;
740 if (input.action === "merge") {
741 return bitbucket
@@ -727,10 +749,11 @@ export const make = Effect.gen(function* () {
749 return bitbucket
750 .request({ method: "POST", url: `${pullRequest}/decline` })
751 .pipe(Effect.asVoid);
730 - }),
752 + });
753 + }),
754
732 - updateChangeRequest: (input) =>
733 - withRepository(input.repository, (path) =>
755 + updateChangeRequest: Effect.fn("BitbucketPullRequestApi.updateChangeRequest")(function (input) {
756 + return withRepository(input.repository, (path) =>
757 // Partial PUTs preserve concurrent edits to unchanged fields.
758 bitbucket
759 .request({
@@ -742,10 +765,11 @@ export const make = Effect.gen(function* () {
765 }),
766 })
767 .pipe(Effect.asVoid),
745 - ),
768 + );
769 + }),
770
747 - comment: (input) =>
748 - withRepository(input.repository, (path) =>
771 + comment: Effect.fn("BitbucketPullRequestApi.comment")(function (input) {
772 + return withRepository(input.repository, (path) =>
773 bitbucket
774 .request({
775 method: "POST",
@@ -753,10 +777,11 @@ export const make = Effect.gen(function* () {
777 body: JSON.stringify({ content: { raw: input.body } }),
778 })
779 .pipe(Effect.asVoid),
756 - ),
780 + );
781 + }),
782
758 - updateComment: (input) =>
759 - withRepository(input.repository, (path) =>
783 + updateComment: Effect.fn("BitbucketPullRequestApi.updateComment")(function (input) {
784 + return withRepository(input.repository, (path) =>
785 bitbucket
786 .request({
787 method: "PUT",
@@ -766,10 +791,11 @@ export const make = Effect.gen(function* () {
791 body: JSON.stringify({ content: { raw: input.body } }),
792 })
793 .pipe(Effect.asVoid),
769 - ),
794 + );
795 + }),
796
771 - submitReview: (input) =>
772 - withRepository(input.repository, (path) =>
797 + submitReview: Effect.fn("BitbucketPullRequestApi.submitReview")(function (input) {
798 + return withRepository(input.repository, (path) =>
799 Effect.gen(function* () {
800 const pullRequest = `${path}/pullrequests/${input.number}`;
801 // A partially failed review must not leave an approval.
@@ -804,10 +830,11 @@ export const make = Effect.gen(function* () {
830 yield* bitbucket.request({ method: "POST", url: `${pullRequest}/request-changes` });
831 }
832 }),
807 - ),
833 + );
834 + }),
835
809 - replyToComment: (input) =>
810 - withRepository(input.repository, (path) =>
836 + replyToComment: Effect.fn("BitbucketPullRequestApi.replyToComment")(function (input) {
837 + return withRepository(input.repository, (path) =>
838 bitbucket
839 .request({
840 method: "POST",
@@ -818,19 +845,23 @@ export const make = Effect.gen(function* () {
845 }),
846 })
847 .pipe(Effect.asVoid),
821 - ),
848 + );
849 + }),
850
823 - setCommentResolution: (input) =>
824 - withRepository(input.repository, (path) =>
825 - bitbucket
826 - .request({
827 - method: input.resolved ? "POST" : "DELETE",
828 - url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
829 - input.commentId,
830 - )}/resolve`,
831 - })
832 - .pipe(Effect.asVoid),
833 - ),
851 + setCommentResolution: Effect.fn("BitbucketPullRequestApi.setCommentResolution")(
852 + function (input) {
853 + return withRepository(input.repository, (path) =>
854 + bitbucket
855 + .request({
856 + method: input.resolved ? "POST" : "DELETE",
857 + url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
858 + input.commentId,
859 + )}/resolve`,
860 + })
861 + .pipe(Effect.asVoid),
862 + );
863 + },
864 + ),
865 });
866 });
867
packages/source-control-bitbucket/src/server/BitbucketSourceControlProvider.ts
+136 -117
@@ -44,153 +44,172 @@ export const make = Effect.gen(function* () {
44
45 return SourceControlProvider.SourceControlProvider.of({
46 kind: SourceControlProviderKind.make("bitbucket"),
47 - listChangeRequests: (input) => {
48 - const source = SourceControlProvider.sourceControlRefFromInput(input);
49 - return bitbucket
50 - .listPullRequests({
51 - cwd: input.cwd,
52 - ...(input.context ? { context: input.context } : {}),
53 - headSelector: input.headSelector,
54 - ...(source ? { source } : {}),
55 - state: input.state,
56 - ...(input.limit !== undefined ? { limit: input.limit } : {}),
57 - })
58 - .pipe(
59 - Effect.map((items) => items.map(toChangeRequest)),
47 + listChangeRequests: Effect.fn("BitbucketSourceControlProvider.listChangeRequests")(
48 + function (input) {
49 + const source = SourceControlProvider.sourceControlRefFromInput(input);
50 + return bitbucket
51 + .listPullRequests({
52 + cwd: input.cwd,
53 + ...(input.context ? { context: input.context } : {}),
54 + headSelector: input.headSelector,
55 + ...(source ? { source } : {}),
56 + state: input.state,
57 + ...(input.limit !== undefined ? { limit: input.limit } : {}),
58 + })
59 + .pipe(
60 + Effect.map((items) => items.map(toChangeRequest)),
61 + Effect.mapError(
62 + (error) =>
63 + new SourceControlProviderError({
64 + provider: SourceControlProviderKind.make("bitbucket"),
65 + operation: "listChangeRequests",
66 + cwd: input.cwd,
67 + reference: SourceControlProvider.transportSafeSourceControlErrorValue(
68 + input.headSelector,
69 + ),
70 + detail: "Failed to list change requests.",
71 + cause: error,
72 + }),
73 + ),
74 + );
75 + },
76 + ),
77 + getChangeRequest: Effect.fn("BitbucketSourceControlProvider.getChangeRequest")(
78 + function (input) {
79 + return bitbucket.getPullRequest(input).pipe(
80 + Effect.map(toChangeRequest),
81 Effect.mapError(
82 (error) =>
83 new SourceControlProviderError({
84 provider: SourceControlProviderKind.make("bitbucket"),
64 - operation: "listChangeRequests",
85 + operation: "getChangeRequest",
86 cwd: input.cwd,
87 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
67 - input.headSelector,
88 + input.reference,
89 ),
69 - detail: "Failed to list change requests.",
90 + detail: "Failed to get change request.",
91 cause: error,
92 }),
93 ),
94 );
74 - },
75 - getChangeRequest: (input) =>
76 - bitbucket.getPullRequest(input).pipe(
77 - Effect.map(toChangeRequest),
78 - Effect.mapError(
79 - (error) =>
80 - new SourceControlProviderError({
81 - provider: SourceControlProviderKind.make("bitbucket"),
82 - operation: "getChangeRequest",
83 - cwd: input.cwd,
84 - reference: SourceControlProvider.transportSafeSourceControlErrorValue(
85 - input.reference,
86 - ),
87 - detail: "Failed to get change request.",
88 - cause: error,
89 - }),
90 - ),
91 - ),
92 - createChangeRequest: (input) => {
93 - const source = SourceControlProvider.sourceControlRefFromInput(input);
94 - return bitbucket
95 - .createPullRequest({
96 - cwd: input.cwd,
97 - ...(input.context ? { context: input.context } : {}),
98 - baseBranch: input.baseRefName,
99 - headSelector: input.headSelector,
100 - ...(source ? { source } : {}),
101 - ...(input.target ? { target: input.target } : {}),
102 - title: input.title,
103 - bodyFile: input.bodyFile,
104 - })
105 - .pipe(
95 + },
96 + ),
97 + createChangeRequest: Effect.fn("BitbucketSourceControlProvider.createChangeRequest")(
98 + function (input) {
99 + const source = SourceControlProvider.sourceControlRefFromInput(input);
100 + return bitbucket
101 + .createPullRequest({
102 + cwd: input.cwd,
103 + ...(input.context ? { context: input.context } : {}),
104 + baseBranch: input.baseRefName,
105 + headSelector: input.headSelector,
106 + ...(source ? { source } : {}),
107 + ...(input.target ? { target: input.target } : {}),
108 + title: input.title,
109 + bodyFile: input.bodyFile,
110 + })
111 + .pipe(
112 + Effect.mapError(
113 + (error) =>
114 + new SourceControlProviderError({
115 + provider: SourceControlProviderKind.make("bitbucket"),
116 + operation: "createChangeRequest",
117 + cwd: input.cwd,
118 + reference: SourceControlProvider.transportSafeSourceControlErrorValue(
119 + input.headSelector,
120 + ),
121 + detail: "Failed to create change request.",
122 + cause: error,
123 + }),
124 + ),
125 + );
126 + },
127 + ),
128 + getRepositoryCloneUrls: Effect.fn("BitbucketSourceControlProvider.getRepositoryCloneUrls")(
129 + function (input) {
130 + return bitbucket.getRepositoryCloneUrls(input).pipe(
131 Effect.mapError(
132 (error) =>
133 new SourceControlProviderError({
134 provider: SourceControlProviderKind.make("bitbucket"),
110 - operation: "createChangeRequest",
135 + operation: "getRepositoryCloneUrls",
136 cwd: input.cwd,
112 - reference: SourceControlProvider.transportSafeSourceControlErrorValue(
113 - input.headSelector,
137 + repository: SourceControlProvider.transportSafeSourceControlErrorValue(
138 + input.repository,
139 ),
115 - detail: "Failed to create change request.",
140 + detail: repositoryDetail(error, "Failed to get repository clone URLs."),
141 cause: error,
142 }),
143 ),
144 );
120 - },
121 - getRepositoryCloneUrls: (input) =>
122 - bitbucket.getRepositoryCloneUrls(input).pipe(
123 - Effect.mapError(
124 - (error) =>
125 - new SourceControlProviderError({
126 - provider: SourceControlProviderKind.make("bitbucket"),
127 - operation: "getRepositoryCloneUrls",
128 - cwd: input.cwd,
129 - repository: SourceControlProvider.transportSafeSourceControlErrorValue(
130 - input.repository,
131 - ),
132 - detail: repositoryDetail(error, "Failed to get repository clone URLs."),
133 - cause: error,
134 - }),
135 - ),
136 - ),
137 - createRepository: (input) =>
138 - bitbucket.createRepository(input).pipe(
139 - Effect.mapError(
140 - (error) =>
141 - new SourceControlProviderError({
142 - provider: SourceControlProviderKind.make("bitbucket"),
143 - operation: "createRepository",
144 - cwd: input.cwd,
145 - repository: SourceControlProvider.transportSafeSourceControlErrorValue(
146 - input.repository,
147 - ),
148 - detail: repositoryDetail(error, "Failed to create repository."),
149 - cause: error,
150 - }),
151 - ),
152 - ),
153 - getDefaultBranch: (input) =>
154 - bitbucket
155 - .getDefaultBranch({
156 - cwd: input.cwd,
157 - ...(input.context ? { context: input.context } : {}),
158 - })
159 - .pipe(
145 + },
146 + ),
147 + createRepository: Effect.fn("BitbucketSourceControlProvider.createRepository")(
148 + function (input) {
149 + return bitbucket.createRepository(input).pipe(
150 Effect.mapError(
151 (error) =>
152 new SourceControlProviderError({
153 provider: SourceControlProviderKind.make("bitbucket"),
164 - operation: "getDefaultBranch",
154 + operation: "createRepository",
155 cwd: input.cwd,
166 - detail: "Failed to get default branch.",
167 - cause: error,
168 - }),
169 - ),
170 - ),
171 - checkoutChangeRequest: (input) =>
172 - bitbucket
173 - .checkoutPullRequest({
174 - cwd: input.cwd,
175 - ...(input.context ? { context: input.context } : {}),
176 - reference: input.reference,
177 - ...(input.force !== undefined ? { force: input.force } : {}),
178 - })
179 - .pipe(
180 - Effect.mapError(
181 - (error) =>
182 - new SourceControlProviderError({
183 - provider: SourceControlProviderKind.make("bitbucket"),
184 - operation: "checkoutChangeRequest",
185 - cwd: input.cwd,
186 - reference: SourceControlProvider.transportSafeSourceControlErrorValue(
187 - input.reference,
156 + repository: SourceControlProvider.transportSafeSourceControlErrorValue(
157 + input.repository,
158 ),
189 - detail: "Failed to check out change request.",
159 + detail: repositoryDetail(error, "Failed to create repository."),
160 cause: error,
161 }),
162 ),
193 - ),
163 + );
164 + },
165 + ),
166 + getDefaultBranch: Effect.fn("BitbucketSourceControlProvider.getDefaultBranch")(
167 + function (input) {
168 + return bitbucket
169 + .getDefaultBranch({
170 + cwd: input.cwd,
171 + ...(input.context ? { context: input.context } : {}),
172 + })
173 + .pipe(
174 + Effect.mapError(
175 + (error) =>
176 + new SourceControlProviderError({
177 + provider: SourceControlProviderKind.make("bitbucket"),
178 + operation: "getDefaultBranch",
179 + cwd: input.cwd,
180 + detail: "Failed to get default branch.",
181 + cause: error,
182 + }),
183 + ),
184 + );
185 + },
186 + ),
187 + checkoutChangeRequest: Effect.fn("BitbucketSourceControlProvider.checkoutChangeRequest")(
188 + function (input) {
189 + return bitbucket
190 + .checkoutPullRequest({
191 + cwd: input.cwd,
192 + ...(input.context ? { context: input.context } : {}),
193 + reference: input.reference,
194 + ...(input.force !== undefined ? { force: input.force } : {}),
195 + })
196 + .pipe(
197 + Effect.mapError(
198 + (error) =>
199 + new SourceControlProviderError({
200 + provider: SourceControlProviderKind.make("bitbucket"),
201 + operation: "checkoutChangeRequest",
202 + cwd: input.cwd,
203 + reference: SourceControlProvider.transportSafeSourceControlErrorValue(
204 + input.reference,
205 + ),
206 + detail: "Failed to check out change request.",
207 + cause: error,
208 + }),
209 + ),
210 + );
211 + },
212 + ),
213 });
214 });
215
packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts
+4 -3
@@ -356,11 +356,12 @@ export const make = Effect.gen(function* () {
356 },
357 (effect, input) => effect.pipe(mapError("listChangeRequests", input.cwd)),
358 ),
359 - getChangeRequest: (input) =>
360 - getPull(input).pipe(
359 + getChangeRequest: Effect.fn("ForgejoSourceControlProvider.getChangeRequest")(function (input) {
360 + return getPull(input).pipe(
361 Effect.map(toForgejoChangeRequest),
362 mapError("getChangeRequest", input.cwd),
363 - ),
363 + );
364 + }),
365 createChangeRequest: Effect.fn("ForgejoSourceControlProvider.createChangeRequest")(
366 function* (input) {
367 const repo = yield* cli.resolveRepository(input);
packages/source-control-gitcafe/src/server/GitCafeCredentials.ts
+12 -6
@@ -160,8 +160,8 @@ export const make = Effect.gen(function* () {
160 });
161
162 return GitCafeCredentials.of({
163 - get: (host) =>
164 - fromSettings(host).pipe(
163 + get: Effect.fn("GitCafeCredentials.get")(function (host) {
164 + return fromSettings(host).pipe(
165 Effect.flatMap(
166 (saved): Effect.Effect<GitCafeCredential, GitCafeCredentialUnavailableError> =>
167 saved === null
@@ -172,10 +172,16 @@ export const make = Effect.gen(function* () {
172 source: "settings",
173 }),
174 ),
175 - ),
176 - invalidate: (host) => Cache.invalidate(cache, normalizeHost(host)),
177 - cliEnv: (host) =>
178 - fromSettings(host).pipe(Effect.map((saved) => (saved === null ? {} : { CAFE_TOKEN: saved }))),
175 + );
176 + }),
177 + invalidate: Effect.fn("GitCafeCredentials.invalidate")(function (host) {
178 + return Cache.invalidate(cache, normalizeHost(host));
179 + }),
180 + cliEnv: Effect.fn("GitCafeCredentials.cliEnv")(function (host) {
181 + return fromSettings(host).pipe(
182 + Effect.map((saved) => (saved === null ? {} : { CAFE_TOKEN: saved })),
183 + );
184 + }),
185 });
186 });
187
packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
+2 -2
@@ -786,7 +786,7 @@ export const make = Effect.gen(function* () {
786 { ...input, authorNarrowed: actorId !== undefined && input.involvement === "authored" },
787 base,
788 );
789 - const readPage = (rows: number, after: string | null) => {
789 + const readPage = Effect.fn("readPage")(function (rows: number, after: string | null) {
790 const query = new URLSearchParams({ limit: String(rows), sort: "newest" });
791 if (input.state !== "all") query.set("state", input.state);
792 if (input.query?.trim()) query.set("q", input.query.trim());
@@ -803,7 +803,7 @@ export const make = Effect.gen(function* () {
803 { path: `${base}/pulls?${query}` },
804 Json.GitCafePulls,
805 ).pipe(Effect.tap((page) => Effect.sync(() => learnAuthors(input.host, page.items))));
806 - };
806 + });
807 if (unresolvedAuthor !== null) {
808 // Rows are only ever handed out narrowed by actor, so a continuation always carries on
809 // the same narrowed listing.
packages/source-control-github/src/server/GitHubCredentials.ts
+2 -2
@@ -237,12 +237,12 @@ export const make = Effect.gen(function* () {
237 }
238 return yield* Cache.get(cache, cacheKey(host, choice?.account));
239 }),
240 - invalidate: (rawHost) => {
240 + invalidate: Effect.fn("GitHubCredentials.invalidate")(function (rawHost) {
241 const host = normalizeHost(rawHost);
242 return hostChoice(host).pipe(
243 Effect.flatMap((choice) => Cache.invalidate(cache, cacheKey(host, choice?.account))),
244 );
245 - },
245 + }),
246 });
247 });
248
packages/source-control-github/src/server/GitHubPullRequestApi.ts
+219 -198
@@ -961,24 +961,24 @@ export const make = Effect.gen(function* () {
961 decodeRoutingIdentity(response.body).pipe(Effect.mapError(unavailable)),
962 ),
963 Effect.catchTags({
964 - GitHubApiResponseError: (error) =>
965 - Effect.gen(function* () {
966 - if (error.status !== 403) return yield* error;
967 - const { viewer } = yield* client.RoutingIdentityViewer({}).pipe(
968 - GitHubGraphQlClient.call({
969 - host,
970 - operation: "getRoutingIdentity",
971 - allowReserve: true,
972 - }),
973 - Effect.catchTags({
974 - GraphQLClientError: () => Effect.fail(unavailable()),
975 - }),
976 - );
977 - return yield* decodeViewerIdentity({
978 - id: viewer.databaseId,
979 - login: viewer.login,
980 - }).pipe(Effect.mapError(unavailable));
981 - }),
964 + // The enclosing operation owns the span for this inline handler.
965 + GitHubApiResponseError: Effect.fnUntraced(function* (error) {
966 + if (error.status !== 403) return yield* error;
967 + const { viewer } = yield* client.RoutingIdentityViewer({}).pipe(
968 + GitHubGraphQlClient.call({
969 + host,
970 + operation: "getRoutingIdentity",
971 + allowReserve: true,
972 + }),
973 + Effect.catchTags({
974 + GraphQLClientError: () => Effect.fail(unavailable()),
975 + }),
976 + );
977 + return yield* decodeViewerIdentity({
978 + id: viewer.databaseId,
979 + login: viewer.login,
980 + }).pipe(Effect.mapError(unavailable));
981 + }),
982 }),
983 Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, credential),
984 Effect.provideService(SourceControlRateLimit.CredentialScope, key),
@@ -1708,10 +1708,11 @@ export const make = Effect.gen(function* () {
1708 withVerifiedCredential,
1709 revalidateChecks,
1710 getRoutingIdentity,
1711 - getViewerLogin: (input) =>
1712 - getRoutingIdentity(input).pipe(Effect.map((identity) => identity.viewer)),
1711 + getViewerLogin: Effect.fn("GitHubPullRequestApi.getViewerLogin")(function (input) {
1712 + return getRoutingIdentity(input).pipe(Effect.map((identity) => identity.viewer));
1713 + }),
1714
1714 - listPullRequests: (input) => {
1715 + listPullRequests: Effect.fn("GitHubPullRequestApi.listPullRequests")(function (input) {
1716 const fallbackMaxRows = Math.max(input.limit + 1, PULL_REQUEST_FALLBACK_MAX_ROWS);
1717 const { owner, name } = parseRepositorySelector(input.repository);
1718 const query = searchQuery({ ...input, repositories: [input.repository] });
@@ -1870,20 +1871,18 @@ export const make = Effect.gen(function* () {
1871 ),
1872 ),
1873 );
1873 - },
1874 + }),
1875
1875 - searchPullRequests: (input) => {
1876 + searchPullRequests: Effect.fn("GitHubPullRequestApi.searchPullRequests")(function* (input) {
1877 const query = searchQuery(input);
1878 if (query === null) {
1878 - return Effect.fail(
1879 - new GitHubRepositorySelectorError({
1880 - cwd: input.cwd,
1881 - operation: "searchPullRequests",
1882 - }),
1883 - );
1879 + return yield* new GitHubRepositorySelectorError({
1880 + cwd: input.cwd,
1881 + operation: "searchPullRequests",
1882 + });
1883 }
1884 const rows = Math.min(input.limit + 1, PULL_REQUEST_SEARCH_MAX_ROWS);
1886 - return client
1885 + return yield* client
1886 .PullRequestSearch({
1887 q: query,
1888 first: rows,
@@ -1903,7 +1902,7 @@ export const make = Effect.gen(function* () {
1902 };
1903 }),
1904 );
1906 - },
1905 + }),
1906
1907 listPullRequestStats: Effect.fn("GitHubPullRequestApi.listPullRequestStats")(
1908 function* (input) {
@@ -1943,20 +1942,22 @@ export const make = Effect.gen(function* () {
1942 getPullRequestWatchFingerprint,
1943
1944 getPullRequestDetail,
1946 - getPullRequestPreview: (input) => {
1947 - const { owner, name } = parseRepositorySelector(input.repository);
1948 - const operation = "getPullRequestPreview";
1949 - return client
1950 - .PullRequestPreview({ owner, name, number: input.number })
1951 - .pipe(
1952 - graphql({ ...input, operation }),
1953 - Effect.map(toPullRequestPreview),
1954 - Effect.flatMap(found({ ...input, operation })),
1955 - );
1956 - },
1945 + getPullRequestPreview: Effect.fn("GitHubPullRequestApi.getPullRequestPreview")(
1946 + function (input) {
1947 + const { owner, name } = parseRepositorySelector(input.repository);
1948 + const operation = "getPullRequestPreview";
1949 + return client
1950 + .PullRequestPreview({ owner, name, number: input.number })
1951 + .pipe(
1952 + graphql({ ...input, operation }),
1953 + Effect.map(toPullRequestPreview),
1954 + Effect.flatMap(found({ ...input, operation })),
1955 + );
1956 + },
1957 + ),
1958 listWorkflowRunsRequiringApproval,
1959
1959 - getPullRequestStack: (input) => {
1960 + getPullRequestStack: Effect.fn("GitHubPullRequestApi.getPullRequestStack")(function (input) {
1961 const { owner, name } = parseRepositorySelector(input.repository);
1962 // Polled by the pull request sync for every linked pull request, so revalidate it.
1963 return revalidatedRestRead({
@@ -1982,7 +1983,7 @@ export const make = Effect.gen(function* () {
1983 GitHubApiNotFoundError: () => Effect.succeed(null),
1984 }),
1985 );
1985 - },
1986 + }),
1987
1988 getPullRequestActivity: Effect.fn("GitHubPullRequestApi.getPullRequestActivity")(
1989 function* (input) {
@@ -2043,7 +2044,7 @@ export const make = Effect.gen(function* () {
2044 },
2045 ),
2046
2046 - getPullRequestDiff: (input) => {
2047 + getPullRequestDiff: Effect.fn("GitHubPullRequestApi.getPullRequestDiff")(function (input) {
2048 const filesPage = (page: number) =>
2049 diffFilesPage({
2050 cwd: input.cwd,
@@ -2086,35 +2087,37 @@ export const make = Effect.gen(function* () {
2087 GitHubApiResponseError: (error) => filesPage(1).pipe(Effect.mapError(() => error)),
2088 }),
2089 );
2089 - },
2090 + }),
2091
2092 getPullRequestDiffFileContents,
2093
2093 - getReviewThreadComments: (input) => {
2094 - const { owner, name } = parseRepositorySelector(input.repository);
2095 - return client
2096 - .ReviewThreadComments({
2097 - owner,
2098 - name,
2099 - number: input.number,
2100 - threadId: input.threadId,
2101 - after: input.cursor,
2102 - })
2103 - .pipe(
2104 - graphql({ ...input, operation: "getReviewThreadComments" }),
2105 - Effect.map(toReviewThreadCommentsPage),
2106 - Effect.flatMap(({ belongsToPullRequest, comments, nextCursor }) =>
2107 - belongsToPullRequest
2108 - ? Effect.succeed({ comments, nextCursor })
2109 - : Effect.fail(
2110 - new GitHubSubjectScopeError({
2111 - cwd: input.cwd,
2112 - operation: "getReviewThreadComments",
2113 - }),
2114 - ),
2115 - ),
2116 - );
2117 - },
2094 + getReviewThreadComments: Effect.fn("GitHubPullRequestApi.getReviewThreadComments")(
2095 + function (input) {
2096 + const { owner, name } = parseRepositorySelector(input.repository);
2097 + return client
2098 + .ReviewThreadComments({
2099 + owner,
2100 + name,
2101 + number: input.number,
2102 + threadId: input.threadId,
2103 + after: input.cursor,
2104 + })
2105 + .pipe(
2106 + graphql({ ...input, operation: "getReviewThreadComments" }),
2107 + Effect.map(toReviewThreadCommentsPage),
2108 + Effect.flatMap(({ belongsToPullRequest, comments, nextCursor }) =>
2109 + belongsToPullRequest
2110 + ? Effect.succeed({ comments, nextCursor })
2111 + : Effect.fail(
2112 + new GitHubSubjectScopeError({
2113 + cwd: input.cwd,
2114 + operation: "getReviewThreadComments",
2115 + }),
2116 + ),
2117 + ),
2118 + );
2119 + },
2120 + ),
2121
2122 listReviewThreadComments: Effect.fn("GitHubPullRequestApi.listReviewThreadComments")(
2123 function* (input) {
@@ -2226,16 +2229,16 @@ export const make = Effect.gen(function* () {
2229 },
2230 ),
2231
2229 - listActorAvatars: (input) => {
2232 + listActorAvatars: Effect.fn("GitHubPullRequestApi.listActorAvatars")(function (input) {
2233 if (input.ids.length === 0) {
2234 return Effect.succeed(new Map<string, string>());
2235 }
2236 return client
2237 .ActorAvatars({ ids: input.ids })
2238 .pipe(graphql({ ...input, operation: "listActorAvatars" }), Effect.map(toActorAvatars));
2236 - },
2239 + }),
2240
2238 - getViewerAccess: (input) => {
2241 + getViewerAccess: Effect.fn("GitHubPullRequestApi.getViewerAccess")(function (input) {
2242 const { owner, name } = parseRepositorySelector(input.repository);
2243 const operation = "getViewerAccess";
2244 return client
@@ -2245,21 +2248,23 @@ export const make = Effect.gen(function* () {
2248 Effect.map(toViewerPermissions),
2249 Effect.flatMap(found({ ...input, operation })),
2250 );
2248 - },
2251 + }),
2252
2250 - listReviewerCandidates: (input) => {
2251 - const { owner, name } = parseRepositorySelector(input.repository);
2252 - const operation = "listReviewerCandidates";
2253 - return client
2254 - .ReviewerCandidates({ owner, name, number: input.number })
2255 - .pipe(
2256 - graphql({ ...input, operation, allowReserve: true }),
2257 - Effect.map(toReviewerCandidates),
2258 - Effect.flatMap(found({ ...input, operation })),
2259 - );
2260 - },
2253 + listReviewerCandidates: Effect.fn("GitHubPullRequestApi.listReviewerCandidates")(
2254 + function (input) {
2255 + const { owner, name } = parseRepositorySelector(input.repository);
2256 + const operation = "listReviewerCandidates";
2257 + return client
2258 + .ReviewerCandidates({ owner, name, number: input.number })
2259 + .pipe(
2260 + graphql({ ...input, operation, allowReserve: true }),
2261 + Effect.map(toReviewerCandidates),
2262 + Effect.flatMap(found({ ...input, operation })),
2263 + );
2264 + },
2265 + ),
2266
2262 - setReviewerRequest: (input) => {
2267 + setReviewerRequest: Effect.fn("GitHubPullRequestApi.setReviewerRequest")(function (input) {
2268 const { owner, name } = parseRepositorySelector(input.repository);
2269 return api
2270 .rest({
@@ -2270,9 +2275,9 @@ export const make = Effect.gen(function* () {
2275 body: buildReviewerRequest(input.reviewers),
2276 })
2277 .pipe(Effect.asVoid);
2273 - },
2278 + }),
2279
2275 - listLabelCandidates: (input) => {
2280 + listLabelCandidates: Effect.fn("GitHubPullRequestApi.listLabelCandidates")(function (input) {
2281 const { owner, name } = parseRepositorySelector(input.repository);
2282 const operation = "listLabelCandidates";
2283 return client
@@ -2282,9 +2287,9 @@ export const make = Effect.gen(function* () {
2287 Effect.map(toLabelCandidates),
2288 Effect.flatMap(found({ ...input, operation })),
2289 );
2285 - },
2290 + }),
2291
2287 - listRepositoryLabels: (input) => {
2292 + listRepositoryLabels: Effect.fn("GitHubPullRequestApi.listRepositoryLabels")(function (input) {
2293 const { owner, name } = parseRepositorySelector(input.repository);
2294 const operation = "listRepositoryLabels";
2295 return client
@@ -2294,21 +2299,23 @@ export const make = Effect.gen(function* () {
2299 Effect.map(toRepositoryLabels),
2300 Effect.flatMap(found({ ...input, operation })),
2301 );
2297 - },
2302 + }),
2303
2299 - searchRepositoryAuthors: (input) => {
2300 - const { owner, name } = parseRepositorySelector(input.repository);
2301 - const operation = "searchRepositoryAuthors";
2302 - return client
2303 - .RepositoryAuthors({ owner, name, query: input.query ?? null })
2304 - .pipe(
2305 - graphql({ ...input, operation, allowReserve: true }),
2306 - Effect.map(toRepositoryAuthors),
2307 - Effect.flatMap(found({ ...input, operation })),
2308 - );
2309 - },
2304 + searchRepositoryAuthors: Effect.fn("GitHubPullRequestApi.searchRepositoryAuthors")(
2305 + function (input) {
2306 + const { owner, name } = parseRepositorySelector(input.repository);
2307 + const operation = "searchRepositoryAuthors";
2308 + return client
2309 + .RepositoryAuthors({ owner, name, query: input.query ?? null })
2310 + .pipe(
2311 + graphql({ ...input, operation, allowReserve: true }),
2312 + Effect.map(toRepositoryAuthors),
2313 + Effect.flatMap(found({ ...input, operation })),
2314 + );
2315 + },
2316 + ),
2317
2311 - setLabels: (input) => {
2318 + setLabels: Effect.fn("GitHubPullRequestApi.setLabels")(function (input) {
2319 const { owner, name } = parseRepositorySelector(input.repository);
2320 const issue = `repos/${owner}/${name}/issues/${input.number}/labels`;
2321 if (input.applied) {
@@ -2333,9 +2340,9 @@ export const make = Effect.gen(function* () {
2340 }),
2341 { concurrency: 1, discard: true },
2342 );
2336 - },
2343 + }),
2344
2338 - runPullRequestAction: (input) => {
2345 + runPullRequestAction: Effect.fn("GitHubPullRequestApi.runPullRequestAction")(function (input) {
2346 if (input.action === "delete-branch") {
2347 return Effect.gen(function* () {
2348 if (input.stackNumber !== undefined) {
@@ -2589,19 +2596,20 @@ export const make = Effect.gen(function* () {
2596 : client.MergePullRequest({ input: merge }).pipe(Effect.asVoid)
2597 ).pipe(graphql(target));
2598 });
2592 - },
2599 + }),
2600
2594 - commentOnPullRequest: (input) =>
2595 - pullRequestNodeId({ ...input, operation: "commentOnPullRequest" }).pipe(
2601 + commentOnPullRequest: Effect.fn("GitHubPullRequestApi.commentOnPullRequest")(function (input) {
2602 + return pullRequestNodeId({ ...input, operation: "commentOnPullRequest" }).pipe(
2603 Effect.flatMap((subjectId) =>
2604 client
2605 .AddComment({ subjectId, body: input.body })
2606 .pipe(graphql({ ...input, operation: "commentOnPullRequest" })),
2607 ),
2608 Effect.asVoid,
2602 - ),
2609 + );
2610 + }),
2611
2604 - submitReview: (input) => {
2612 + submitReview: Effect.fn("GitHubPullRequestApi.submitReview")(function (input) {
2613 const { owner, name } = parseRepositorySelector(input.repository);
2614 return api
2615 .rest({
@@ -2616,96 +2624,107 @@ export const make = Effect.gen(function* () {
2624 }),
2625 })
2626 .pipe(Effect.asVoid);
2619 - },
2627 + }),
2628
2621 - replyToReviewThread: (input) =>
2622 - client
2629 + replyToReviewThread: Effect.fn("GitHubPullRequestApi.replyToReviewThread")(function (input) {
2630 + return client
2631 .AddReviewThreadReply({ threadId: input.threadId, body: input.body })
2624 - .pipe(graphql({ ...input, operation: "replyToReviewThread" }), Effect.asVoid),
2632 + .pipe(graphql({ ...input, operation: "replyToReviewThread" }), Effect.asVoid);
2633 + }),
2634
2626 - getPullRequestFilesViewed: (input) => {
2627 - const { owner, name } = parseRepositorySelector(input.repository);
2628 - const target = { ...input, operation: "getPullRequestFilesViewed" };
2629 - return readPages(
2630 - GraphQLClient.pages(client.PullRequestFilesViewed, {
2631 - variables: { owner, name, number: input.number },
2632 - connection: (result) => {
2633 - const page = toPullRequestFilesViewedPage(result);
2634 - return {
2635 - ...page,
2636 - pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },
2637 - };
2635 + getPullRequestFilesViewed: Effect.fn("GitHubPullRequestApi.getPullRequestFilesViewed")(
2636 + function (input) {
2637 + const { owner, name } = parseRepositorySelector(input.repository);
2638 + const target = { ...input, operation: "getPullRequestFilesViewed" };
2639 + return readPages(
2640 + GraphQLClient.pages(client.PullRequestFilesViewed, {
2641 + variables: { owner, name, number: input.number },
2642 + connection: (result) => {
2643 + const page = toPullRequestFilesViewedPage(result);
2644 + return {
2645 + ...page,
2646 + pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },
2647 + };
2648 + },
2649 + }),
2650 + {
2651 + ...target,
2652 + maxPages: FILES_VIEWED_MAX_PAGES,
2653 + hasNextPage: (page) => page.nextCursor !== null,
2654 },
2639 - }),
2640 - {
2641 - ...target,
2642 - maxPages: FILES_VIEWED_MAX_PAGES,
2643 - hasNextPage: (page) => page.nextCursor !== null,
2644 - },
2645 - ).pipe(
2646 - graphql(target),
2647 - Effect.map(({ pages, truncated }) => ({
2648 - files: pages.flatMap((page) => page.files),
2649 - truncated,
2650 - })),
2651 - );
2652 - },
2655 + ).pipe(
2656 + graphql(target),
2657 + Effect.map(({ pages, truncated }) => ({
2658 + files: pages.flatMap((page) => page.files),
2659 + truncated,
2660 + })),
2661 + );
2662 + },
2663 + ),
2664
2654 - getPullRequestFileStats: (input) => {
2655 - const { owner, name } = parseRepositorySelector(input.repository);
2656 - const target = { ...input, operation: "getPullRequestFileStats" };
2657 - return readPages(
2658 - GraphQLClient.pages(client.PullRequestFileStats, {
2659 - variables: { owner, name, number: input.number },
2660 - connection: (result) => {
2661 - const page = toPullRequestFileStatsPage(result);
2662 - return {
2663 - ...page,
2664 - pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },
2665 - };
2665 + getPullRequestFileStats: Effect.fn("GitHubPullRequestApi.getPullRequestFileStats")(
2666 + function (input) {
2667 + const { owner, name } = parseRepositorySelector(input.repository);
2668 + const target = { ...input, operation: "getPullRequestFileStats" };
2669 + return readPages(
2670 + GraphQLClient.pages(client.PullRequestFileStats, {
2671 + variables: { owner, name, number: input.number },
2672 + connection: (result) => {
2673 + const page = toPullRequestFileStatsPage(result);
2674 + return {
2675 + ...page,
2676 + pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },
2677 + };
2678 + },
2679 + }),
2680 + {
2681 + ...target,
2682 + maxPages: FILES_VIEWED_MAX_PAGES,
2683 + hasNextPage: (page) => page.nextCursor !== null,
2684 },
2667 - }),
2668 - {
2669 - ...target,
2670 - maxPages: FILES_VIEWED_MAX_PAGES,
2671 - hasNextPage: (page) => page.nextCursor !== null,
2672 - },
2673 - ).pipe(
2674 - graphql(target),
2675 - Effect.map(({ pages, truncated }) => ({
2676 - files: pages.flatMap((page) => page.files),
2677 - truncated,
2678 - })),
2679 - );
2680 - },
2685 + ).pipe(
2686 + graphql(target),
2687 + Effect.map(({ pages, truncated }) => ({
2688 + files: pages.flatMap((page) => page.files),
2689 + truncated,
2690 + })),
2691 + );
2692 + },
2693 + ),
2694
2682 - setPullRequestFilesViewed: (input) => {
2683 - if (input.files.length === 0) return Effect.void;
2684 - const target = { ...input, operation: "setPullRequestFilesViewed" };
2685 - return pullRequestNodeId(target).pipe(
2686 - Effect.flatMap((pullRequestId) =>
2687 - // Top-level mutation fields run in order, so the last toggle for a path wins.
2688 - Effect.forEach(
2689 - input.files,
2690 - (file) =>
2691 - GraphQLResolver.request(
2692 - { pullRequestId, path: file.path, viewed: file.viewed },
2693 - setFileViewedResolver,
2694 - ),
2695 - { concurrency: "unbounded", discard: true },
2695 + setPullRequestFilesViewed: Effect.fn("GitHubPullRequestApi.setPullRequestFilesViewed")(
2696 + function (input) {
2697 + if (input.files.length === 0) return Effect.void;
2698 + const target = { ...input, operation: "setPullRequestFilesViewed" };
2699 + return pullRequestNodeId(target).pipe(
2700 + Effect.flatMap((pullRequestId) =>
2701 + // Top-level mutation fields run in order, so the last toggle for a path wins.
2702 + Effect.forEach(
2703 + input.files,
2704 + (file) =>
2705 + GraphQLResolver.request(
2706 + { pullRequestId, path: file.path, viewed: file.viewed },
2707 + setFileViewedResolver,
2708 + ),
2709 + { concurrency: "unbounded", discard: true },
2710 + ),
2711 ),
2697 - ),
2698 - graphql(target),
2699 - );
2700 - },
2712 + graphql(target),
2713 + );
2714 + },
2715 + ),
2716
2702 - setReviewThreadResolution: (input) =>
2703 - (input.resolved
2704 - ? client.ResolveReviewThread({ threadId: input.threadId }).pipe(Effect.asVoid)
2705 - : client.UnresolveReviewThread({ threadId: input.threadId }).pipe(Effect.asVoid)
2706 - ).pipe(graphql({ ...input, operation: "setReviewThreadResolution" })),
2717 + setReviewThreadResolution: Effect.fn("GitHubPullRequestApi.setReviewThreadResolution")(
2718 + function (input) {
2719 + return (
2720 + input.resolved
2721 + ? client.ResolveReviewThread({ threadId: input.threadId }).pipe(Effect.asVoid)
2722 + : client.UnresolveReviewThread({ threadId: input.threadId }).pipe(Effect.asVoid)
2723 + ).pipe(graphql({ ...input, operation: "setReviewThreadResolution" }));
2724 + },
2725 + ),
2726
2708 - setReaction: (input) => {
2727 + setReaction: Effect.fn("GitHubPullRequestApi.setReaction")(function (input) {
2728 const givenSubjectId = input.subjectId;
2729 const subjectId =
2730 givenSubjectId === undefined
@@ -2736,10 +2755,10 @@ export const make = Effect.gen(function* () {
2755 ).pipe(graphql({ ...input, operation: "setReaction" }));
2756 }),
2757 );
2739 - },
2758 + }),
2759
2741 - updatePullRequest: (input) =>
2742 - pullRequestNodeId({ ...input, operation: "updatePullRequest" }).pipe(
2760 + updatePullRequest: Effect.fn("GitHubPullRequestApi.updatePullRequest")(function (input) {
2761 + return pullRequestNodeId({ ...input, operation: "updatePullRequest" }).pipe(
2762 Effect.flatMap((pullRequestId) =>
2763 client
2764 .UpdatePullRequest({
@@ -2750,10 +2769,11 @@ export const make = Effect.gen(function* () {
2769 .pipe(graphql({ ...input, operation: "updatePullRequest" })),
2770 ),
2771 Effect.asVoid,
2753 - ),
2772 + );
2773 + }),
2774
2755 - updateComment: (input) =>
2756 - subjectBelongsToPullRequest({
2775 + updateComment: Effect.fn("GitHubPullRequestApi.updateComment")(function (input) {
2776 + return subjectBelongsToPullRequest({
2777 cwd: input.cwd,
2778 repository: input.repository,
2779 host: input.host,
@@ -2779,7 +2799,8 @@ export const make = Effect.gen(function* () {
2799 : client.UpdateReviewComment(variables).pipe(Effect.asVoid)
2800 ).pipe(graphql({ ...input, operation: "updateComment" }));
2801 }),
2782 - ),
2802 + );
2803 + }),
2804 });
2805 });
2806
packages/source-control-github/src/server/GitHubSourceControlProvider.ts
+49 -32
@@ -844,8 +844,11 @@ export const make = Effect.gen(function* () {
844 headSelectors: headSelectors.filter((selector) => !selector.includes(":")),
845 limit: 100,
846 }),
847 - readChangeRequestTemplate: ({ cwd, treeish }) =>
848 - GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute),
847 + readChangeRequestTemplate: Effect.fn("GitHubSourceControlProvider.readChangeRequestTemplate")(
848 + function ({ cwd, treeish }) {
849 + return GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute);
850 + },
851 + ),
852 // `createChangeRequest` targets what `resolveRepository` picks: GH_REPO when it parses, else
853 // the remote `gh repo set-default` marked (`gh-resolved`). An HTTPS remote keeps a
854 // non-default port in the context's host, and the mark is then ignored.
@@ -882,8 +885,12 @@ export const make = Effect.gen(function* () {
885 ),
886 // `gh pr create` run in the checkout, as an agent in a T3 worktree often does, takes its base
887 // from this key.
885 - recordBranchBase: ({ cwd, branch, baseBranch }) =>
886 - git
888 + recordBranchBase: Effect.fn("GitHubSourceControlProvider.recordBranchBase")(function ({
889 + cwd,
890 + branch,
891 + baseBranch,
892 + }) {
893 + return git
894 .execute({
895 operation: "GitHubSourceControlProvider.recordBranchBase",
896 cwd,
@@ -894,7 +901,8 @@ export const make = Effect.gen(function* () {
901 Effect.catch((cause) =>
902 Effect.logWarning("Could not record the branch base for gh", { cause }),
903 ),
897 - ),
904 + );
905 + }),
906 resolveLink: (input) => {
907 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
908 if (input.url.host !== "github.com") return undefined;
@@ -904,31 +912,37 @@ export const make = Effect.gen(function* () {
912 if (!match) return undefined;
913 return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
914 },
907 - listChangeRequests: (input) =>
908 - (input.state === "open" ? Effect.succeed(true) : SourceControlRateLimit.Interactive).pipe(
909 - Effect.flatMap((allowReserve) =>
910 - listByHead({
911 - cwd: input.cwd,
912 - headSelector: input.headSelector,
913 - state: input.state,
914 - limit: input.limit ?? (input.state === "open" ? 1 : 20),
915 - host: contextHost(input.context),
916 - context: input.context,
917 - allowReserve,
918 - }),
919 - ),
920 - Effect.map((records) => records.map(toChangeRequest)),
921 - Effect.mapError(
922 - providerError("listChangeRequests", input.cwd, { reference: input.headSelector }),
923 - ),
924 - ),
925 - getChangeRequest: (input) =>
926 - readPullRequest({ ...input, host: contextHost(input.context) }).pipe(
915 + listChangeRequests: Effect.fn("GitHubSourceControlProvider.listChangeRequests")(
916 + function (input) {
917 + return (
918 + input.state === "open" ? Effect.succeed(true) : SourceControlRateLimit.Interactive
919 + ).pipe(
920 + Effect.flatMap((allowReserve) =>
921 + listByHead({
922 + cwd: input.cwd,
923 + headSelector: input.headSelector,
924 + state: input.state,
925 + limit: input.limit ?? (input.state === "open" ? 1 : 20),
926 + host: contextHost(input.context),
927 + context: input.context,
928 + allowReserve,
929 + }),
930 + ),
931 + Effect.map((records) => records.map(toChangeRequest)),
932 + Effect.mapError(
933 + providerError("listChangeRequests", input.cwd, { reference: input.headSelector }),
934 + ),
935 + );
936 + },
937 + ),
938 + getChangeRequest: Effect.fn("GitHubSourceControlProvider.getChangeRequest")(function (input) {
939 + return readPullRequest({ ...input, host: contextHost(input.context) }).pipe(
940 Effect.map(toChangeRequest),
941 Effect.mapError(
942 providerError("getChangeRequest", input.cwd, { reference: input.reference }),
943 ),
931 - ),
944 + );
945 + }),
946 createChangeRequest: Effect.fn("GitHubSourceControlProvider.createChangeRequest")(
947 function* (input) {
948 const locator = yield* resolveRepository(input);
@@ -1033,11 +1047,14 @@ export const make = Effect.gen(function* () {
1047 },
1048 (effect, input) => effect.pipe(Effect.mapError(providerError("getDefaultBranch", input.cwd))),
1049 ),
1036 - checkoutChangeRequest: (input) =>
1037 - checkoutPullRequest(input).pipe(
1038 - Effect.mapError(
1039 - providerError("checkoutChangeRequest", input.cwd, { reference: input.reference }),
1040 - ),
1041 - ),
1050 + checkoutChangeRequest: Effect.fn("GitHubSourceControlProvider.checkoutChangeRequest")(
1051 + function (input) {
1052 + return checkoutPullRequest(input).pipe(
1053 + Effect.mapError(
1054 + providerError("checkoutChangeRequest", input.cwd, { reference: input.reference }),
1055 + ),
1056 + );
1057 + },
1058 + ),
1059 });
1060 });
packages/source-control-gitlab/src/server/GitLabCli.ts
+24 -19
@@ -467,8 +467,8 @@ export const make = Effect.gen(function* () {
467
468 return GitLabCli.of({
469 execute,
470 - listMergeRequests: (input) =>
471 - execute({
470 + listMergeRequests: Effect.fn("GitLabCli.listMergeRequests")(function (input) {
471 + return execute({
472 cwd: input.cwd,
473 args: [
474 "mr",
@@ -503,9 +503,10 @@ export const make = Effect.gen(function* () {
503 }),
504 ),
505 ),
506 - ),
507 - getMergeRequest: (input) =>
508 - executeMergeRequest({
506 + );
507 + }),
508 + getMergeRequest: Effect.fn("GitLabCli.getMergeRequest")(function (input) {
509 + return executeMergeRequest({
510 cwd: input.cwd,
511 reference: input.reference,
512 args: ["mr", "view", "--output", "json", "--", input.reference],
@@ -530,9 +531,10 @@ export const make = Effect.gen(function* () {
531 }),
532 ),
533 ),
533 - ),
534 - getRepositoryCloneUrls: (input) =>
535 - execute({
534 + );
535 + }),
536 + getRepositoryCloneUrls: Effect.fn("GitLabCli.getRepositoryCloneUrls")(function (input) {
537 + return execute({
538 cwd: input.cwd,
539 args: ["api", `projects/${encodeURIComponent(input.repository)}`],
540 }).pipe(
@@ -552,8 +554,9 @@ export const make = Effect.gen(function* () {
554 ),
555 ),
556 Effect.map(normalizeRepositoryCloneUrls),
555 - ),
556 - createRepository: (input) => {
557 + );
558 + }),
559 + createRepository: Effect.fn("GitLabCli.createRepository")(function (input) {
560 const { namespacePath, projectPath } = parseRepositoryPath(input.repository);
561 const namespaceId: Effect.Effect<number | null, GitLabCliError> = namespacePath
562 ? execute({
@@ -617,8 +620,8 @@ export const make = Effect.gen(function* () {
620 ),
621 Effect.map(normalizeRepositoryCloneUrls),
622 );
620 - },
621 - createMergeRequest: (input) => {
623 + }),
624 + createMergeRequest: Effect.fn("GitLabCli.createMergeRequest")(function (input) {
625 const sourceProject = sourceProjectIdentifier(input.source);
626 return execute({
627 cwd: input.cwd,
@@ -638,9 +641,9 @@ export const make = Effect.gen(function* () {
641 `description=@${input.bodyFile}`,
642 ],
643 }).pipe(Effect.asVoid);
641 - },
642 - getDefaultBranch: (input) =>
643 - execute({
644 + }),
645 + getDefaultBranch: Effect.fn("GitLabCli.getDefaultBranch")(function (input) {
646 + return execute({
647 cwd: input.cwd,
648 args: ["api", "projects/:fullpath"],
649 }).pipe(
@@ -659,13 +662,15 @@ export const make = Effect.gen(function* () {
662 ),
663 ),
664 Effect.map((value) => value.default_branch ?? null),
662 - ),
663 - checkoutMergeRequest: (input) =>
664 - executeMergeRequest({
665 + );
666 + }),
667 + checkoutMergeRequest: Effect.fn("GitLabCli.checkoutMergeRequest")(function (input) {
668 + return executeMergeRequest({
669 cwd: input.cwd,
670 reference: input.reference,
671 args: ["mr", "checkout", "--", input.reference],
668 - }).pipe(Effect.asVoid),
672 + }).pipe(Effect.asVoid);
673 + }),
674 });
675 });
676
packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+112 -85
@@ -1120,17 +1120,21 @@ export const make = Effect.gen(function* () {
1120 return GitLabPullRequestCli.of({
1121 getViewerUsername: viewerUsername,
1122
1123 - listMergeRequests: (input) => {
1123 + listMergeRequests: Effect.fn("GitLabPullRequestCli.listMergeRequests")(function (input) {
1124 const perPage = Math.min(input.limit + 1, MAX_PAGE_SIZE);
1125 const page = Math.floor((input.cursor?.delivered ?? 0) / perPage) + 1;
1126 return listPage({ ...input, page, collected: [], cursorAdvance: 0 });
1127 - },
1127 + }),
1128
1129 getMergeRequestDetail: mergeRequestDetail,
1130
1131 - listNotes: (input) => notesPage({ ...input, page: 1, collected: [] }),
1131 + listNotes: Effect.fn("GitLabPullRequestCli.listNotes")(function (input) {
1132 + return notesPage({ ...input, page: 1, collected: [] });
1133 + }),
1134
1133 - listReactions: (input) => awardsPage({ ...input, cursor: null, page: 1, collected: null }),
1135 + listReactions: Effect.fn("GitLabPullRequestCli.listReactions")(function (input) {
1136 + return awardsPage({ ...input, cursor: null, page: 1, collected: null });
1137 + }),
1138
1139 getFileRevisions: fileRevisions,
1140
@@ -1168,8 +1172,8 @@ export const make = Effect.gen(function* () {
1172 });
1173 }),
1174
1171 - listCommits: (input) =>
1172 - api({
1175 + listCommits: Effect.fn("GitLabPullRequestCli.listCommits")(function (input) {
1176 + return api({
1177 cwd: input.cwd,
1178 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/commits?${query(
1179 [
@@ -1191,11 +1195,12 @@ export const make = Effect.gen(function* () {
1195 }),
1196 );
1197 }),
1194 - ),
1198 + );
1199 + }),
1200
1196 - getMergeRequestDiff: (input) => {
1201 + getMergeRequestDiff: Effect.fn("GitLabPullRequestCli.getMergeRequestDiff")(function* (input) {
1202 if (input.commit !== undefined && !isCommitSha(input.commit)) {
1198 - return Effect.fail(new GitLabDiffCommitError({ command: "glab", cwd: input.cwd }));
1203 + return yield* new GitLabDiffCommitError({ command: "glab", cwd: input.cwd });
1204 }
1205 const target = {
1206 cwd: input.cwd,
@@ -1204,13 +1209,13 @@ export const make = Effect.gen(function* () {
1209 ...(input.commit === undefined ? {} : { commit: input.commit }),
1210 };
1211 if (input.cursor === undefined) {
1207 - return diffPage({ ...target, page: 1 });
1212 + return yield* diffPage({ ...target, page: 1 });
1213 }
1214 const page = diffCursorPage(input.cursor);
1210 - return page === null
1211 - ? Effect.fail(new GitLabDiffCursorError({ command: "glab", cwd: input.cwd }))
1212 - : diffPage({ ...target, page });
1213 - },
1215 + if (page === null)
1216 + return yield* new GitLabDiffCursorError({ command: "glab", cwd: input.cwd });
1217 + return yield* diffPage({ ...target, page });
1218 + }),
1219
1220 getMergeRequestDiffFileContents: Effect.fn(
1221 "GitLabPullRequestCli.getMergeRequestDiffFileContents",
@@ -1264,28 +1269,31 @@ export const make = Effect.gen(function* () {
1269 return { oldContents, newContents };
1270 }),
1271
1267 - getProjectMergeCapabilities: (input) =>
1268 - api({
1269 - cwd: input.cwd,
1270 - path: `projects/${projectPath(input.repository)}?license=false`,
1271 - }).pipe(
1272 - Effect.flatMap((result) => {
1273 - const decoded = decodeProjectMergeCapabilitiesJson(result.stdout.trim());
1274 - return Result.isSuccess(decoded)
1275 - ? Effect.succeed(decoded.success)
1276 - : Effect.fail(
1277 - new GitLabMergeRequestReadError({
1278 - command: "glab",
1279 - cwd: input.cwd,
1280 - operation: "getProjectMergeCapabilities",
1281 - cause: decoded.failure,
1282 - }),
1283 - );
1284 - }),
1285 - ),
1272 + getProjectMergeCapabilities: Effect.fn("GitLabPullRequestCli.getProjectMergeCapabilities")(
1273 + function (input) {
1274 + return api({
1275 + cwd: input.cwd,
1276 + path: `projects/${projectPath(input.repository)}?license=false`,
1277 + }).pipe(
1278 + Effect.flatMap((result) => {
1279 + const decoded = decodeProjectMergeCapabilitiesJson(result.stdout.trim());
1280 + return Result.isSuccess(decoded)
1281 + ? Effect.succeed(decoded.success)
1282 + : Effect.fail(
1283 + new GitLabMergeRequestReadError({
1284 + command: "glab",
1285 + cwd: input.cwd,
1286 + operation: "getProjectMergeCapabilities",
1287 + cause: decoded.failure,
1288 + }),
1289 + );
1290 + }),
1291 + );
1292 + },
1293 + ),
1294
1287 - listProjectLabels: (input) =>
1288 - api({
1295 + listProjectLabels: Effect.fn("GitLabPullRequestCli.listProjectLabels")(function (input) {
1296 + return api({
1297 cwd: input.cwd,
1298 path: `projects/${projectPath(input.repository)}/labels?${query([
1299 ["per_page", String(MAX_PAGE_SIZE)],
@@ -1308,35 +1316,42 @@ export const make = Effect.gen(function* () {
1316 }),
1317 );
1318 }),
1311 - ),
1319 + );
1320 + }),
1321
1313 - listProjectUsers: (input) =>
1314 - projectUsers(input).pipe(
1322 + listProjectUsers: Effect.fn("GitLabPullRequestCli.listProjectUsers")(function (input) {
1323 + return projectUsers(input).pipe(
1324 Effect.map(({ candidates, rawCount }) => ({
1325 items: candidates.map(({ login, name, avatarUrl }) => ({ login, name, avatarUrl })),
1326 truncated: rawCount >= MAX_PAGE_SIZE,
1327 })),
1319 - ),
1328 + );
1329 + }),
1330
1321 - listReviewerCandidates: (input) =>
1322 - Effect.all([mergeRequestDetail(input), projectUsers(input)], { concurrency: 2 }).pipe(
1323 - Effect.map(([mergeRequest, users]) => {
1324 - const author = mergeRequest.author?.login;
1325 - const requested = new Set(mergeRequest.reviewRequestLogins);
1326 - return {
1327 - // GitLab forbids requesting a review from the MR author.
1328 - candidates: users.candidates.flatMap((candidate) =>
1329 - candidate.login === author
1330 - ? []
1331 - : [{ ...candidate, isRequested: requested.has(candidate.login) }],
1332 - ),
1333 - truncated: users.rawCount >= MAX_PAGE_SIZE,
1334 - };
1335 - }),
1336 - ),
1331 + listReviewerCandidates: Effect.fn("GitLabPullRequestCli.listReviewerCandidates")(
1332 + function (input) {
1333 + return Effect.all([mergeRequestDetail(input), projectUsers(input)], {
1334 + concurrency: 2,
1335 + }).pipe(
1336 + Effect.map(([mergeRequest, users]) => {
1337 + const author = mergeRequest.author?.login;
1338 + const requested = new Set(mergeRequest.reviewRequestLogins);
1339 + return {
1340 + // GitLab forbids requesting a review from the MR author.
1341 + candidates: users.candidates.flatMap((candidate) =>
1342 + candidate.login === author
1343 + ? []
1344 + : [{ ...candidate, isRequested: requested.has(candidate.login) }],
1345 + ),
1346 + truncated: users.rawCount >= MAX_PAGE_SIZE,
1347 + };
1348 + }),
1349 + );
1350 + },
1351 + ),
1352
1338 - setReviewerRequest: (input) =>
1339 - mergeRequestDetail(input).pipe(
1353 + setReviewerRequest: Effect.fn("GitLabPullRequestCli.setReviewerRequest")(function (input) {
1354 + return mergeRequestDetail(input).pipe(
1355 Effect.flatMap((mergeRequest) => {
1356 // GitLab replaces reviewer_ids wholesale.
1357 const ids = new Set(mergeRequest.reviewerIds);
@@ -1354,7 +1369,8 @@ export const make = Effect.gen(function* () {
1369 });
1370 }),
1371 Effect.asVoid,
1357 - ),
1372 + );
1373 + }),
1374
1375 runMergeRequestAction: Effect.fn("GitLabPullRequestCli.runMergeRequestAction")(
1376 function* (input) {
@@ -1386,8 +1402,8 @@ export const make = Effect.gen(function* () {
1402 },
1403 ),
1404
1389 - updateMergeRequest: (input) =>
1390 - api({
1405 + updateMergeRequest: Effect.fn("GitLabPullRequestCli.updateMergeRequest")(function (input) {
1406 + return api({
1407 cwd: input.cwd,
1408 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}`,
1409 method: "PUT",
@@ -1396,28 +1412,35 @@ export const make = Effect.gen(function* () {
1412 ...(input.title === undefined ? {} : { title: input.title }),
1413 ...(input.description === undefined ? {} : { description: input.description }),
1414 }),
1399 - }).pipe(Effect.asVoid),
1415 + }).pipe(Effect.asVoid);
1416 + }),
1417
1401 - commentOnMergeRequest: (input) =>
1402 - api({
1403 - cwd: input.cwd,
1404 - path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes`,
1405 - method: "POST",
1406 - // JSON avoids glab's coercion of numeric/boolean comment bodies.
1407 - stdin: JSON.stringify({ body: input.body }),
1408 - }).pipe(Effect.asVoid),
1418 + commentOnMergeRequest: Effect.fn("GitLabPullRequestCli.commentOnMergeRequest")(
1419 + function (input) {
1420 + return api({
1421 + cwd: input.cwd,
1422 + path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes`,
1423 + method: "POST",
1424 + // JSON avoids glab's coercion of numeric/boolean comment bodies.
1425 + stdin: JSON.stringify({ body: input.body }),
1426 + }).pipe(Effect.asVoid);
1427 + },
1428 + ),
1429
1410 - updateNote: (input) =>
1411 - api({
1430 + updateNote: Effect.fn("GitLabPullRequestCli.updateNote")(function (input) {
1431 + return api({
1432 cwd: input.cwd,
1433 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/notes/${encodeURIComponent(
1434 input.noteId,
1435 )}`,
1436 method: "PUT",
1437 stdin: JSON.stringify({ body: input.body }),
1418 - }).pipe(Effect.asVoid),
1438 + }).pipe(Effect.asVoid);
1439 + }),
1440
1420 - listDiscussions: (input) => discussionsPage({ ...input, page: 1, collected: [] }),
1441 + listDiscussions: Effect.fn("GitLabPullRequestCli.listDiscussions")(function (input) {
1442 + return discussionsPage({ ...input, page: 1, collected: [] });
1443 + }),
1444
1445 submitReview: Effect.fn("GitLabPullRequestCli.submitReview")(function* (input) {
1446 const project = projectPath(input.repository);
@@ -1468,25 +1491,29 @@ export const make = Effect.gen(function* () {
1491 }
1492 }),
1493
1471 - replyToDiscussion: (input) =>
1472 - api({
1494 + replyToDiscussion: Effect.fn("GitLabPullRequestCli.replyToDiscussion")(function (input) {
1495 + return api({
1496 cwd: input.cwd,
1497 path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions/${encodeURIComponent(
1498 input.discussionId,
1499 )}/notes`,
1500 method: "POST",
1501 stdin: JSON.stringify({ body: input.body }),
1479 - }).pipe(Effect.asVoid),
1502 + }).pipe(Effect.asVoid);
1503 + }),
1504
1481 - setDiscussionResolution: (input) =>
1482 - api({
1483 - cwd: input.cwd,
1484 - path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions/${encodeURIComponent(
1485 - input.discussionId,
1486 - )}`,
1487 - method: "PUT",
1488 - stdin: JSON.stringify({ resolved: input.resolved }),
1489 - }).pipe(Effect.asVoid),
1505 + setDiscussionResolution: Effect.fn("GitLabPullRequestCli.setDiscussionResolution")(
1506 + function (input) {
1507 + return api({
1508 + cwd: input.cwd,
1509 + path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/discussions/${encodeURIComponent(
1510 + input.discussionId,
1511 + )}`,
1512 + method: "PUT",
1513 + stdin: JSON.stringify({ resolved: input.resolved }),
1514 + }).pipe(Effect.asVoid);
1515 + },
1516 + ),
1517 });
1518 });
1519
packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts
+106 -90
@@ -208,8 +208,11 @@ export const make = Effect.gen(function* () {
208
209 return SourceControlProvider.SourceControlProvider.of({
210 kind: SourceControlProviderKind.make("gitlab"),
211 - readChangeRequestTemplate: ({ cwd, treeish }) =>
212 - GitLabChangeRequestTemplate.detect(cwd, treeish, git.execute),
211 + readChangeRequestTemplate: Effect.fn("GitLabSourceControlProvider.readChangeRequestTemplate")(
212 + function ({ cwd, treeish }) {
213 + return GitLabChangeRequestTemplate.detect(cwd, treeish, git.execute);
214 + },
215 + ),
216 refineRepositoryIdentity,
217 resolveLink: (input) => {
218 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
@@ -223,36 +226,38 @@ export const make = Effect.gen(function* () {
226 `projects/${encodeURIComponent(match[1]!)}/${match[2]}/${match[3]}`,
227 );
228 },
226 - listChangeRequests: (input) => {
227 - const source = SourceControlProvider.sourceControlRefFromInput(input);
228 - return gitlab
229 - .listMergeRequests({
230 - cwd: input.cwd,
231 - headSelector: input.headSelector,
232 - ...(source ? { source } : {}),
233 - state: input.state,
234 - ...(input.limit !== undefined ? { limit: input.limit } : {}),
235 - })
236 - .pipe(
237 - Effect.map((items) => items.map(toChangeRequest)),
238 - Effect.mapError(
239 - (error) =>
240 - new SourceControlProviderError({
241 - provider: SourceControlProviderKind.make("gitlab"),
242 - operation: "listChangeRequests",
243 - command: error.command,
244 - cwd: input.cwd,
245 - reference: SourceControlProvider.transportSafeSourceControlErrorValue(
246 - input.headSelector,
247 - ),
248 - detail: error.detail,
249 - cause: error,
250 - }),
251 - ),
252 - );
253 - },
254 - getChangeRequest: (input) =>
255 - gitlab.getMergeRequest(input).pipe(
229 + listChangeRequests: Effect.fn("GitLabSourceControlProvider.listChangeRequests")(
230 + function (input) {
231 + const source = SourceControlProvider.sourceControlRefFromInput(input);
232 + return gitlab
233 + .listMergeRequests({
234 + cwd: input.cwd,
235 + headSelector: input.headSelector,
236 + ...(source ? { source } : {}),
237 + state: input.state,
238 + ...(input.limit !== undefined ? { limit: input.limit } : {}),
239 + })
240 + .pipe(
241 + Effect.map((items) => items.map(toChangeRequest)),
242 + Effect.mapError(
243 + (error) =>
244 + new SourceControlProviderError({
245 + provider: SourceControlProviderKind.make("gitlab"),
246 + operation: "listChangeRequests",
247 + command: error.command,
248 + cwd: input.cwd,
249 + reference: SourceControlProvider.transportSafeSourceControlErrorValue(
250 + input.headSelector,
251 + ),
252 + detail: error.detail,
253 + cause: error,
254 + }),
255 + ),
256 + );
257 + },
258 + ),
259 + getChangeRequest: Effect.fn("GitLabSourceControlProvider.getChangeRequest")(function (input) {
260 + return gitlab.getMergeRequest(input).pipe(
261 Effect.map(toChangeRequest),
262 Effect.mapError(
263 (error) =>
@@ -268,55 +273,61 @@ export const make = Effect.gen(function* () {
273 cause: error,
274 }),
275 ),
271 - ),
272 - createChangeRequest: (input) => {
273 - const source = SourceControlProvider.sourceControlRefFromInput(input);
274 - return gitlab
275 - .createMergeRequest({
276 - cwd: input.cwd,
277 - baseBranch: input.baseRefName,
278 - headSelector: input.headSelector,
279 - ...(source ? { source } : {}),
280 - ...(input.target ? { target: input.target } : {}),
281 - title: input.title,
282 - bodyFile: input.bodyFile,
283 - })
284 - .pipe(
276 + );
277 + }),
278 + createChangeRequest: Effect.fn("GitLabSourceControlProvider.createChangeRequest")(
279 + function (input) {
280 + const source = SourceControlProvider.sourceControlRefFromInput(input);
281 + return gitlab
282 + .createMergeRequest({
283 + cwd: input.cwd,
284 + baseBranch: input.baseRefName,
285 + headSelector: input.headSelector,
286 + ...(source ? { source } : {}),
287 + ...(input.target ? { target: input.target } : {}),
288 + title: input.title,
289 + bodyFile: input.bodyFile,
290 + })
291 + .pipe(
292 + Effect.mapError(
293 + (error) =>
294 + new SourceControlProviderError({
295 + provider: SourceControlProviderKind.make("gitlab"),
296 + operation: "createChangeRequest",
297 + command: error.command,
298 + cwd: input.cwd,
299 + reference: SourceControlProvider.transportSafeSourceControlErrorValue(
300 + input.headSelector,
301 + ),
302 + detail: error.detail,
303 + cause: error,
304 + }),
305 + ),
306 + );
307 + },
308 + ),
309 + getRepositoryCloneUrls: Effect.fn("GitLabSourceControlProvider.getRepositoryCloneUrls")(
310 + function (input) {
311 + return gitlab.getRepositoryCloneUrls(input).pipe(
312 Effect.mapError(
313 (error) =>
314 new SourceControlProviderError({
315 provider: SourceControlProviderKind.make("gitlab"),
289 - operation: "createChangeRequest",
316 + operation: "getRepositoryCloneUrls",
317 command: error.command,
318 cwd: input.cwd,
292 - reference: SourceControlProvider.transportSafeSourceControlErrorValue(
293 - input.headSelector,
319 + repository: SourceControlProvider.transportSafeSourceControlErrorValue(
320 + input.repository,
321 ),
322 detail: error.detail,
323 cause: error,
324 }),
325 ),
326 );
300 - },
301 - getRepositoryCloneUrls: (input) =>
302 - gitlab.getRepositoryCloneUrls(input).pipe(
303 - Effect.mapError(
304 - (error) =>
305 - new SourceControlProviderError({
306 - provider: SourceControlProviderKind.make("gitlab"),
307 - operation: "getRepositoryCloneUrls",
308 - command: error.command,
309 - cwd: input.cwd,
310 - repository: SourceControlProvider.transportSafeSourceControlErrorValue(
311 - input.repository,
312 - ),
313 - detail: error.detail,
314 - cause: error,
315 - }),
316 - ),
317 - ),
318 - createRepository: (input) =>
319 - gitlab.createRepository(input).pipe(
327 + },
328 + ),
329 + createRepository: Effect.fn("GitLabSourceControlProvider.createRepository")(function (input) {
330 + return gitlab.createRepository(input).pipe(
331 Effect.mapError(
332 (error) =>
333 new SourceControlProviderError({
@@ -331,9 +342,10 @@ export const make = Effect.gen(function* () {
342 cause: error,
343 }),
344 ),
334 - ),
335 - getDefaultBranch: (input) =>
336 - gitlab.getDefaultBranch(input).pipe(
345 + );
346 + }),
347 + getDefaultBranch: Effect.fn("GitLabSourceControlProvider.getDefaultBranch")(function (input) {
348 + return gitlab.getDefaultBranch(input).pipe(
349 Effect.mapError(
350 (error) =>
351 new SourceControlProviderError({
@@ -345,23 +357,27 @@ export const make = Effect.gen(function* () {
357 cause: error,
358 }),
359 ),
348 - ),
349 - checkoutChangeRequest: (input) =>
350 - gitlab.checkoutMergeRequest(input).pipe(
351 - Effect.mapError(
352 - (error) =>
353 - new SourceControlProviderError({
354 - provider: SourceControlProviderKind.make("gitlab"),
355 - operation: "checkoutChangeRequest",
356 - command: error.command,
357 - cwd: input.cwd,
358 - reference: SourceControlProvider.transportSafeSourceControlErrorValue(
359 - input.reference,
360 - ),
361 - detail: error.detail,
362 - cause: error,
363 - }),
364 - ),
365 - ),
360 + );
361 + }),
362 + checkoutChangeRequest: Effect.fn("GitLabSourceControlProvider.checkoutChangeRequest")(
363 + function (input) {
364 + return gitlab.checkoutMergeRequest(input).pipe(
365 + Effect.mapError(
366 + (error) =>
367 + new SourceControlProviderError({
368 + provider: SourceControlProviderKind.make("gitlab"),
369 + operation: "checkoutChangeRequest",
370 + command: error.command,
371 + cwd: input.cwd,
372 + reference: SourceControlProvider.transportSafeSourceControlErrorValue(
373 + input.reference,
374 + ),
375 + detail: error.detail,
376 + cause: error,
377 + }),
378 + ),
379 + );
380 + },
381 + ),
382 });
383 });
packages/ssh/src/auth.ts
+3 -1
@@ -48,7 +48,9 @@ export class SshPasswordPrompt extends Context.Service<SshPasswordPrompt, SshPas
48 SshPasswordPrompt,
49 SshPasswordPrompt.of({
50 isAvailable: false,
51 - request: () => Effect.succeed(null),
51 + request: Effect.fn("SshPasswordPrompt.request")(function () {
52 + return Effect.succeed(null);
53 + }),
54 }),
55 );
56 }
packages/ssh/src/command.ts
+16 -16
@@ -308,22 +308,22 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
308 Effect.flatMap((result) =>
309 Option.match(result, {
310 onSome: Effect.succeed,
311 - onNone: () =>
312 - Effect.gen(function* () {
313 - yield* Effect.logWarning("ssh.command.timedOut", {
314 - ...sshTargetLogFields(target),
315 - timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
316 - remoteCommandArgs: input.remoteCommandArgs ?? [],
317 - preHostArgs: input.preHostArgs ?? [],
318 - hasStdin: input.stdin !== undefined,
319 - });
320 - return yield* new SshCommandError({
321 - command: ["ssh"],
322 - exitCode: null,
323 - stderr: "",
324 - message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,
325 - });
326 - }),
311 + // The enclosing operation owns the span for this inline handler.
312 + onNone: Effect.fnUntraced(function* () {
313 + yield* Effect.logWarning("ssh.command.timedOut", {
314 + ...sshTargetLogFields(target),
315 + timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
316 + remoteCommandArgs: input.remoteCommandArgs ?? [],
317 + preHostArgs: input.preHostArgs ?? [],
318 + hasStdin: input.stdin !== undefined,
319 + });
320 + return yield* new SshCommandError({
321 + command: ["ssh"],
322 + exitCode: null,
323 + stderr: "",
324 + message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,
325 + });
326 + }),
327 }),
328 ),
329 );
tsconfig.base.json
+1 -1
@@ -47,7 +47,7 @@
47 "mapSomeToAsSome": "error",
48 "unnecessaryPipeChain": "error",
49 "returnEffectInGen": "off",
50 - "effectFnOpportunity": "suggestion",
50 + "effectFnOpportunity": "error",
51 "anyUnknownInErrorContext": "error",
52 "unsafeEffectTypeAssertion": "error",
53 "instanceOfSchema": "error",