@devries-cameron20 / t3code-1 / commits / 221d8494c7
Fork 0

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

refactor(server): trace reusable domain operations (#21996)

Julius Marminge committed Oct 19, 2026 at 18:31 UTC 221d8494c75fc619c36b117ffc423846733ef353
45 files changed +2357 -2260
apps/server/src/background/BackgroundPolicy.ts
+11 -10
@@ -289,16 +289,17 @@ export const make = Effect.fn("background.policy.make")(function* () {
289 const hasDemand: BackgroundPolicy["Service"]["hasDemand"] = (scope) =>
290 Effect.map(snapshot, (current) => current.activeScopeKeys.includes(scopeKey(scope)));
291
292 - const shouldRunScopeWork: BackgroundPolicy["Service"]["shouldRunScopeWork"] = (scope) =>
293 - Effect.gen(function* () {
294 - const [current, settings] = yield* Effect.all([snapshot, backgroundActivitySettings]);
295 - if (isHostConstrained(current.hostPower, settings)) {
296 - return false;
297 - }
298 - return current.leases.some((lease) =>
299 - leaseMayRunScopedWork(lease, scope, current.updatedAt, settings),
300 - );
301 - });
292 + const shouldRunScopeWork: BackgroundPolicy["Service"]["shouldRunScopeWork"] = Effect.fn(
293 + "BackgroundPolicy.shouldRunScopeWork",
294 + )(function* (scope) {
295 + const [current, settings] = yield* Effect.all([snapshot, backgroundActivitySettings]);
296 + if (isHostConstrained(current.hostPower, settings)) {
297 + return false;
298 + }
299 + return current.leases.some((lease) =>
300 + leaseMayRunScopedWork(lease, scope, current.updatedAt, settings),
301 + );
302 + });
303
304 const shouldRunOpportunisticWork = Effect.map(
305 snapshot,
apps/server/src/desktopUpdate/DesktopAppUpdate.ts
+56 -59
@@ -66,74 +66,71 @@ export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* (
66 ? new ServerSelfUpdateError({ reason })
67 : new ServerSelfUpdateError({ reason, cause });
68
69 - const consumeReports = (
69 + const consumeReports = Effect.fn("DesktopAppUpdate.consumeReports")(function* (
70 requestId: string,
71 changes: Stream.Stream<DesktopUpdateStatusReport>,
72 reportProgress: (
73 stage: ServerSelfUpdateProgressStage,
74 ) => Effect.Effect<void, ServerSelfUpdateError>,
75 - ) =>
76 - Effect.gen(function* () {
77 - const lastStage = yield* Ref.make<ServerSelfUpdateProgressStage | null>(null);
78 - const emitStage = (
79 - stage: ServerSelfUpdateProgressStage | null,
80 - ): Effect.Effect<void, ServerSelfUpdateError> =>
81 - stage === null
82 - ? Effect.void
83 - : Ref.get(lastStage).pipe(
84 - Effect.flatMap((previous) =>
85 - previous === stage
86 - ? Effect.void
87 - : Ref.set(lastStage, stage).pipe(Effect.andThen(reportProgress(stage))),
88 - ),
89 - );
75 + ) {
76 + const lastStage = yield* Ref.make<ServerSelfUpdateProgressStage | null>(null);
77 + const emitStage = (
78 + stage: ServerSelfUpdateProgressStage | null,
79 + ): Effect.Effect<void, ServerSelfUpdateError> =>
80 + stage === null
81 + ? Effect.void
82 + : Ref.get(lastStage).pipe(
83 + Effect.flatMap((previous) =>
84 + previous === stage
85 + ? Effect.void
86 + : Ref.set(lastStage, stage).pipe(Effect.andThen(reportProgress(stage))),
87 + ),
88 + );
89
91 - const terminal = yield* changes.pipe(
92 - Stream.filter((report) => report.requestId === requestId),
93 - Stream.mapEffect(
94 - (
95 - report,
96 - ): Effect.Effect<Option.Option<DesktopUpdateStatusReport>, ServerSelfUpdateError> =>
97 - report.outcome === undefined
98 - ? emitStage(desktopUpdateProgressStage(report.state)).pipe(
99 - Effect.as(Option.none<DesktopUpdateStatusReport>()),
100 - )
101 - : Effect.succeedSome(report),
102 - ),
103 - Stream.filterMap(
104 - Option.match({
105 - onNone: () => Result.failVoid,
106 - onSome: Result.succeed,
107 - }),
108 - ),
109 - Stream.runHead,
110 - );
111 - if (Option.isNone(terminal)) {
112 - return yield* failWith("The desktop app stopped reporting its update.");
113 - }
90 + const terminal = yield* changes.pipe(
91 + Stream.filter((report) => report.requestId === requestId),
92 + Stream.mapEffect(
93 + (report): Effect.Effect<Option.Option<DesktopUpdateStatusReport>, ServerSelfUpdateError> =>
94 + report.outcome === undefined
95 + ? emitStage(desktopUpdateProgressStage(report.state)).pipe(
96 + Effect.as(Option.none<DesktopUpdateStatusReport>()),
97 + )
98 + : Effect.succeedSome(report),
99 + ),
100 + Stream.filterMap(
101 + Option.match({
102 + onNone: () => Result.failVoid,
103 + onSome: Result.succeed,
104 + }),
105 + ),
106 + Stream.runHead,
107 + );
108 + if (Option.isNone(terminal)) {
109 + return yield* failWith("The desktop app stopped reporting its update.");
110 + }
111
115 - const report = terminal.value;
116 - if (report.outcome === "ready-to-install") {
117 - yield* emitStage("installing");
118 - const targetVersion =
119 - report.state.downloadedVersion ??
120 - report.state.availableVersion ??
121 - report.state.currentVersion;
122 - yield* Effect.logInfo("Desktop app update prepared for install.", {
123 - targetVersion,
124 - });
125 - yield* Ref.set(inFlight, false);
126 - return { targetVersion, method: "desktop-app" as const, desktopUpdateToken: requestId };
127 - }
128 - if (report.outcome === "up-to-date") {
129 - return yield* failWith(
130 - `The T3 Code desktop app on this machine is already up to date on ${report.state.currentVersion}.`,
131 - );
132 - }
112 + const report = terminal.value;
113 + if (report.outcome === "ready-to-install") {
114 + yield* emitStage("installing");
115 + const targetVersion =
116 + report.state.downloadedVersion ??
117 + report.state.availableVersion ??
118 + report.state.currentVersion;
119 + yield* Effect.logInfo("Desktop app update prepared for install.", {
120 + targetVersion,
121 + });
122 + yield* Ref.set(inFlight, false);
123 + return { targetVersion, method: "desktop-app" as const, desktopUpdateToken: requestId };
124 + }
125 + if (report.outcome === "up-to-date") {
126 return yield* failWith(
134 - report.reason ?? report.state.message ?? "The desktop app update failed.",
127 + `The T3 Code desktop app on this machine is already up to date on ${report.state.currentVersion}.`,
128 );
136 - });
129 + }
130 + return yield* failWith(
131 + report.reason ?? report.state.message ?? "The desktop app update failed.",
132 + );
133 + });
134
135 const run: DesktopAppUpdate["Service"]["run"] = Effect.fn("desktopUpdate.desktopAppUpdate.run")(
136 function* (reportProgress) {
apps/server/src/device/DeviceActions.ts
+38 -36
@@ -206,20 +206,23 @@ const simctl = (run: Runner, udid: string, args: ReadonlyArray<string>, operatio
206 Effect.flatMap(ok(operation)),
207 );
208
209 -const axSettings = (ready: DeviceHostReady, udid: string, args: ReadonlyArray<string>) =>
210 - Effect.gen(function* () {
211 - const helper = ready.helpers.serveSimAxSettings;
212 - if (!helper) {
213 - return yield* new DeviceActionUnavailableError({
214 - operation: "accessibility",
215 - platform: "ios",
216 - reason: "helper_missing",
217 - });
218 - }
219 - return yield* ready
220 - .run("xcrun", ["simctl", "spawn", udid, helper, ...args])
221 - .pipe(Effect.flatMap(ok("accessibility")));
222 - });
209 +const axSettings = Effect.fn("DeviceActions.axSettings")(function* (
210 + ready: DeviceHostReady,
211 + udid: string,
212 + args: ReadonlyArray<string>,
213 +) {
214 + const helper = ready.helpers.serveSimAxSettings;
215 + if (!helper) {
216 + return yield* new DeviceActionUnavailableError({
217 + operation: "accessibility",
218 + platform: "ios",
219 + reason: "helper_missing",
220 + });
221 + }
222 + return yield* ready
223 + .run("xcrun", ["simctl", "spawn", udid, helper, ...args])
224 + .pipe(Effect.flatMap(ok("accessibility")));
225 +});
226
227 const runIos = Effect.fn("DeviceActions.runIos")(function* (
228 ready: DeviceHostReady,
@@ -318,31 +321,30 @@ const runIos = Effect.fn("DeviceActions.runIos")(function* (
321 }
322 });
323
321 -const serveSimPermissions = (
324 +const serveSimPermissions = Effect.fn("DeviceActions.serveSimPermissions")(function* (
325 ready: DeviceHostReady,
326 udid: string,
327 input: Extract<DeviceActionInput, { type: "setPermission" }>,
325 -) =>
326 - Effect.gen(function* () {
327 - const cli = ready.helpers.serveSimCli;
328 - if (!cli)
329 - return yield* new DeviceActionUnavailableError({
330 - operation: "permission",
331 - platform: "ios",
332 - reason: "helper_missing",
333 - });
334 - yield* ready
335 - .run(ready.nodePath, [
336 - cli,
337 - "permissions",
338 - input.decision,
339 - input.permission,
340 - input.appId,
341 - "-d",
342 - udid,
343 - ])
344 - .pipe(Effect.flatMap(ok("permission")));
345 - });
328 +) {
329 + const cli = ready.helpers.serveSimCli;
330 + if (!cli)
331 + return yield* new DeviceActionUnavailableError({
332 + operation: "permission",
333 + platform: "ios",
334 + reason: "helper_missing",
335 + });
336 + yield* ready
337 + .run(ready.nodePath, [
338 + cli,
339 + "permissions",
340 + input.decision,
341 + input.permission,
342 + input.appId,
343 + "-d",
344 + udid,
345 + ])
346 + .pipe(Effect.flatMap(ok("permission")));
347 +});
348
349 const adb = (run: Runner, serial: string, args: ReadonlyArray<string>, operation: string) =>
350 run("adb", ["-s", serial, ...args]).pipe(Effect.flatMap(ok(operation)));
apps/server/src/device/DeviceHubProxy.ts
+3 -2
@@ -99,8 +99,9 @@ const proxyWebSocket = Effect.fn("DeviceHubProxy.proxyWebSocket")(function* (
99 return HttpServerResponse.empty();
100 });
101
102 -const pumpFrames = (source: Socket.Socket, sink: Socket.Writer) =>
103 - Effect.gen(function* () {
102 +const pumpFrames =
103 + /* Frame pumping runs continuously; a span per frame stream adds no diagnostic value. */
104 + Effect.fnUntraced(function* (source: Socket.Socket, sink: Socket.Writer) {
105 const { pull } = yield* source.reader;
106 while (true) {
107 yield* sink.writeAll(yield* pull);
apps/server/src/device/DeviceService.ts
+120 -119
@@ -236,15 +236,16 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
236 return PubSub.publish(statePubSub, next).pipe(Effect.as({ state: next }));
237 }).pipe(Effect.map(({ state }) => state));
238
239 - const resolveHost = (hostId: DeviceHostId | undefined) =>
240 - Effect.gen(function* () {
241 - const id = hostId ?? LOCAL_DEVICE_HOST_ID;
242 - const host = hosts.get(id);
243 - if (!host) {
244 - return yield* new DeviceHostUnavailableError({ hostId: id, reason: "Unknown host." });
245 - }
246 - return host;
247 - });
239 + const resolveHost = Effect.fn("DeviceService.resolveHost")(function* (
240 + hostId: DeviceHostId | undefined,
241 + ) {
242 + const id = hostId ?? LOCAL_DEVICE_HOST_ID;
243 + const host = hosts.get(id);
244 + if (!host) {
245 + return yield* new DeviceHostUnavailableError({ hostId: id, reason: "Unknown host." });
246 + }
247 + return host;
248 + });
249
250 const setHostStatus = (
251 hostId: DeviceHostId,
@@ -991,33 +992,32 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`,
992 reason: "Agent CLI installation is unavailable in this device service.",
993 }),
994 ),
994 - agentTarget: (input) =>
995 - Effect.gen(function* () {
996 - const host = yield* resolveHost(input.hostId);
997 - const ready = yield* agentReadinessIfSupported(input.hostId);
998 - if (!ready)
999 - return yield* new DeviceHostUnavailableError({
1000 - hostId: input.hostId,
1001 - reason:
1002 - "Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",
1003 - });
1004 - const configPath = yield* lifecycleLock.withPermit(
1005 - Effect.gen(function* () {
1006 - if (hosts.get(host.id) !== host)
1007 - return yield* new DeviceHostUnavailableError({
1008 - hostId: host.id,
1009 - reason: "Host configuration changed. Retry the operation.",
1010 - });
1011 - return yield* configureAgent(input.hostId, ready);
1012 - }),
1013 - );
1014 - const session = yield* agentDeviceSession(
1015 - input.threadId,
1016 - input.hostId,
1017 - input.deviceId,
1018 - ).pipe(Effect.provideService(Crypto.Crypto, crypto));
1019 - return ["--config", configPath, "--session", session];
1020 - }),
995 + agentTarget: Effect.fn("DeviceService.agentTarget")(function* (input) {
996 + const host = yield* resolveHost(input.hostId);
997 + const ready = yield* agentReadinessIfSupported(input.hostId);
998 + if (!ready)
999 + return yield* new DeviceHostUnavailableError({
1000 + hostId: input.hostId,
1001 + reason:
1002 + "Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",
1003 + });
1004 + const configPath = yield* lifecycleLock.withPermit(
1005 + Effect.gen(function* () {
1006 + if (hosts.get(host.id) !== host)
1007 + return yield* new DeviceHostUnavailableError({
1008 + hostId: host.id,
1009 + reason: "Host configuration changed. Retry the operation.",
1010 + });
1011 + return yield* configureAgent(input.hostId, ready);
1012 + }),
1013 + );
1014 + const session = yield* agentDeviceSession(
1015 + input.threadId,
1016 + input.hostId,
1017 + input.deviceId,
1018 + ).pipe(Effect.provideService(Crypto.Crypto, crypto));
1019 + return ["--config", configPath, "--session", session];
1020 + }),
1021 state: SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state)),
1022 subscribe: PubSub.subscribe(statePubSub),
1023 configure,
@@ -1072,23 +1072,23 @@ export const make = Effect.gen(function* () {
1072 agentDeviceConfigPath(config.stateDir, hostId, path).pipe(
1073 Effect.provideService(Crypto.Crypto, crypto),
1074 );
1075 - const configureAgent = (hostId: DeviceHostId, ready: DeviceHost.DeviceHostAgentReady) =>
1076 - Effect.gen(function* () {
1075 + const configureAgent = Effect.fn("DeviceService.configureAgent")(
1076 + function* (hostId: DeviceHostId, ready: DeviceHost.DeviceHostAgentReady) {
1077 const file = yield* configPath(hostId);
1078 yield* writeAgentDeviceConfig(file, ready.agentDevice);
1079 return file;
1080 - }).pipe(
1081 - Effect.provideService(FileSystem.FileSystem, fs),
1082 - Effect.provideService(Path.Path, path),
1083 - Effect.mapError(
1084 - (cause) =>
1085 - new DeviceOperationError({
1086 - operation: "configure agent",
1087 - reason: "settings_failed",
1088 - cause,
1089 - }),
1090 - ),
1091 - );
1080 + },
1081 + Effect.provideService(FileSystem.FileSystem, fs),
1082 + Effect.provideService(Path.Path, path),
1083 + Effect.mapError(
1084 + (cause) =>
1085 + new DeviceOperationError({
1086 + operation: "configure agent",
1087 + reason: "settings_failed",
1088 + cause,
1089 + }),
1090 + ),
1091 + );
1092 const probeContext =
1093 yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.probe>>>();
1094 const localTargetContext =
@@ -1132,78 +1132,79 @@ export const make = Effect.gen(function* () {
1132 const hostContext =
1133 yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.make>>>();
1134 const configured = new Map<string, { config: SshDeviceHostConfig; scope: Scope.Closeable }>();
1135 - const reconcile = (configuredHosts: ReadonlyArray<SshDeviceHostConfig>) =>
1136 - Effect.gen(function* () {
1137 - const next = yield* remoteSshDeviceHosts(configuredHosts).pipe(
1138 - Effect.provide(localTargetContext),
1139 - );
1140 - const removed = yield* service.withLifecycleLock(
1141 - Effect.gen(function* () {
1142 - const removed: Array<{ id: string; scope: Scope.Closeable }> = [];
1143 - for (const [id, previous] of configured) {
1144 - if (
1145 - next.some(
1146 - (host) =>
1147 - host.id === id &&
1148 - host.label === previous.config.label &&
1149 - host.target === previous.config.target &&
1150 - host.port === previous.config.port &&
1151 - host.identityFile === previous.config.identityFile,
1152 - )
1135 + const reconcile = Effect.fn("DeviceService.reconcile")(function* (
1136 + configuredHosts: ReadonlyArray<SshDeviceHostConfig>,
1137 + ) {
1138 + const next = yield* remoteSshDeviceHosts(configuredHosts).pipe(
1139 + Effect.provide(localTargetContext),
1140 + );
1141 + const removed = yield* service.withLifecycleLock(
1142 + Effect.gen(function* () {
1143 + const removed: Array<{ id: string; scope: Scope.Closeable }> = [];
1144 + for (const [id, previous] of configured) {
1145 + if (
1146 + next.some(
1147 + (host) =>
1148 + host.id === id &&
1149 + host.label === previous.config.label &&
1150 + host.target === previous.config.target &&
1151 + host.port === previous.config.port &&
1152 + host.identityFile === previous.config.identityFile,
1153 )
1154 - continue;
1155 - hosts.delete(id);
1156 - configured.delete(id);
1157 - removed.push({ id, scope: previous.scope });
1158 - }
1159 - if (removed.length > 0) yield* service.refreshHosts;
1160 - return removed;
1161 - }),
1162 - );
1163 - // Stop old writers before deleting config files or publishing replacements, without blocking healthy hosts.
1164 - yield* Effect.forEach(
1165 - removed,
1166 - ({ id, scope }) =>
1167 - Effect.gen(function* () {
1168 - yield* Scope.close(scope, Exit.void);
1169 - yield* fs.remove(yield* configPath(id), { force: true }).pipe(Effect.ignore);
1170 - }),
1171 - { concurrency: 4, discard: true },
1172 - );
1173 - yield* service.withLifecycleLock(
1154 + )
1155 + continue;
1156 + hosts.delete(id);
1157 + configured.delete(id);
1158 + removed.push({ id, scope: previous.scope });
1159 + }
1160 + if (removed.length > 0) yield* service.refreshHosts;
1161 + return removed;
1162 + }),
1163 + );
1164 + // Stop old writers before deleting config files or publishing replacements, without blocking healthy hosts.
1165 + yield* Effect.forEach(
1166 + removed,
1167 + ({ id, scope }) =>
1168 Effect.gen(function* () {
1175 - let added = false;
1176 - for (const host of next) {
1177 - if (configured.has(host.id)) continue;
1178 - added = true;
1179 - const hostScope = yield* Scope.fork(scope);
1180 - const instance = yield* SshDeviceHost.make(
1181 - host,
1182 - (ready) =>
1183 - configureAgent(host.id, ready).pipe(
1184 - Effect.asVoid,
1185 - Effect.mapError(
1186 - (error) =>
1187 - new DeviceHost.DeviceHostError({
1188 - hostId: host.id,
1189 - step: "configuring agent access",
1190 - cause: error,
1191 - }),
1192 - ),
1193 - ),
1194 - (status, detail) =>
1195 - service
1196 - .setHostStatus(host.id, { status, ...(detail ? { detail } : {}) })
1197 - .pipe(Effect.asVoid),
1198 - ).pipe(Effect.provideService(Scope.Scope, hostScope), Effect.provide(hostContext));
1199 - hosts.set(host.id, instance);
1200 - configured.set(host.id, { config: host, scope: hostScope });
1201 - }
1202 - // Refresh again after removed scopes closed so a late status write from an old host cannot linger.
1203 - if (added || removed.length > 0) yield* service.refreshHosts;
1169 + yield* Scope.close(scope, Exit.void);
1170 + yield* fs.remove(yield* configPath(id), { force: true }).pipe(Effect.ignore);
1171 }),
1205 - );
1206 - });
1172 + { concurrency: 4, discard: true },
1173 + );
1174 + yield* service.withLifecycleLock(
1175 + Effect.gen(function* () {
1176 + let added = false;
1177 + for (const host of next) {
1178 + if (configured.has(host.id)) continue;
1179 + added = true;
1180 + const hostScope = yield* Scope.fork(scope);
1181 + const instance = yield* SshDeviceHost.make(
1182 + host,
1183 + (ready) =>
1184 + configureAgent(host.id, ready).pipe(
1185 + Effect.asVoid,
1186 + Effect.mapError(
1187 + (error) =>
1188 + new DeviceHost.DeviceHostError({
1189 + hostId: host.id,
1190 + step: "configuring agent access",
1191 + cause: error,
1192 + }),
1193 + ),
1194 + ),
1195 + (status, detail) =>
1196 + service
1197 + .setHostStatus(host.id, { status, ...(detail ? { detail } : {}) })
1198 + .pipe(Effect.asVoid),
1199 + ).pipe(Effect.provideService(Scope.Scope, hostScope), Effect.provide(hostContext));
1200 + hosts.set(host.id, instance);
1201 + configured.set(host.id, { config: host, scope: hostScope });
1202 + }
1203 + // Refresh again after removed scopes closed so a late status write from an old host cannot linger.
1204 + if (added || removed.length > 0) yield* service.refreshHosts;
1205 + }),
1206 + );
1207 + });
1208 const changes = yield* settings.subscribeChanges;
1209 yield* reconcile((yield* settings.getSettings).deviceHosts);
1210 yield* changes.pipe(
apps/server/src/device/LocalDeviceHost.ts
+28 -26
@@ -493,32 +493,34 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
493 Effect.ignoreCause,
494 );
495
496 - const superviseHub = (hub: HubProcess, hubTool: DeviceToolPaths): Effect.Effect<void> =>
497 - Effect.gen(function* () {
498 - yield* Effect.result(hub.child.exitCode);
499 - const running = yield* Ref.get(runningRef);
500 - if (running?.hub.child.pid !== hub.child.pid) return;
501 - const uptime = (yield* Clock.currentTimeMillis) - hub.startedAtMillis;
502 - const delay = yield* Ref.modify(restartDelayRef, (current) => {
503 - if (uptime >= HUB_RESTART_STABLE_UPTIME_MS) return [0, 0];
504 - const next = current === 0 ? 1_000 : Math.min(current * 2, HUB_RESTART_MAX_DELAY_MS);
505 - return [current, next];
506 - });
507 - yield* Effect.logWarning("Device hub exited; restarting", {
508 - pid: Number(hub.child.pid),
509 - delayMs: delay,
510 - });
511 - yield* Effect.sleep(Duration.millis(delay));
512 - yield* startLock.withPermits(1)(
513 - Effect.gen(function* () {
514 - const current = yield* Ref.get(runningRef);
515 - if (current?.hub.child.pid !== hub.child.pid) return;
516 - const replacement = yield* spawnHub(hubTool, hub.nodePath);
517 - yield* Ref.set(runningRef, { ...current, hub: replacement });
518 - yield* Effect.forkDetach(superviseHub(replacement, hubTool));
519 - }),
520 - );
521 - }).pipe(
496 + // Waits for the hub's lifetime and re-forks on restart; a span would nest across restarts.
497 + const superviseHub: (hub: HubProcess, hubTool: DeviceToolPaths) => Effect.Effect<void> =
498 + Effect.fnUntraced(
499 + function* (hub: HubProcess, hubTool: DeviceToolPaths) {
500 + yield* Effect.result(hub.child.exitCode);
501 + const running = yield* Ref.get(runningRef);
502 + if (running?.hub.child.pid !== hub.child.pid) return;
503 + const uptime = (yield* Clock.currentTimeMillis) - hub.startedAtMillis;
504 + const delay = yield* Ref.modify(restartDelayRef, (current) => {
505 + if (uptime >= HUB_RESTART_STABLE_UPTIME_MS) return [0, 0];
506 + const next = current === 0 ? 1_000 : Math.min(current * 2, HUB_RESTART_MAX_DELAY_MS);
507 + return [current, next];
508 + });
509 + yield* Effect.logWarning("Device hub exited; restarting", {
510 + pid: Number(hub.child.pid),
511 + delayMs: delay,
512 + });
513 + yield* Effect.sleep(Duration.millis(delay));
514 + yield* startLock.withPermits(1)(
515 + Effect.gen(function* () {
516 + const current = yield* Ref.get(runningRef);
517 + if (current?.hub.child.pid !== hub.child.pid) return;
518 + const replacement = yield* spawnHub(hubTool, hub.nodePath);
519 + yield* Ref.set(runningRef, { ...current, hub: replacement });
520 + yield* Effect.forkDetach(superviseHub(replacement, hubTool));
521 + }),
522 + );
523 + },
524 Effect.catchCause((cause) => Effect.logWarning("Device hub supervisor failed", { cause })),
525 );
526
apps/server/src/diagnostics/TraceDiagnostics.ts
+5 -7
@@ -469,11 +469,9 @@ export const make = Effect.gen(function* () {
469
470 export const layer = Layer.effect(TraceDiagnostics, make);
471
472 -export function readTraceDiagnostics(
472 +export const readTraceDiagnostics = Effect.fn("TraceDiagnostics.readTraceDiagnostics")(function* (
473 options: TraceDiagnosticsOptions,
474 -): Effect.Effect<ServerTraceDiagnosticsResult, never, TraceDiagnostics> {
475 - return Effect.gen(function* () {
476 - const diagnostics = yield* TraceDiagnostics;
477 - return yield* diagnostics.read(options);
478 - });
479 -}
474 +): Effect.fn.Return<ServerTraceDiagnosticsResult, never, TraceDiagnostics> {
475 + const diagnostics = yield* TraceDiagnostics;
476 + return yield* diagnostics.read(options);
477 +});
apps/server/src/git/GitManager.ts
+76 -73
@@ -755,8 +755,8 @@ export const make = Effect.gen(function* () {
755 return yield* gitCore.createWorktree(input, { worktreesDirectory, ...options, submodules });
756 });
757
758 - const readRepositoryInstructions = (cwd: string, fileName: string) =>
759 - Effect.gen(function* () {
758 + const readRepositoryInstructions = Effect.fn("GitManager.readRepositoryInstructions")(
759 + function* (cwd: string, fileName: string) {
760 const root = yield* fileSystem.realPath(cwd);
761 const instructionPath = yield* fileSystem.realPath(path.join(root, fileName));
762 const relative = path.relative(root, instructionPath);
@@ -768,7 +768,9 @@ export const make = Effect.gen(function* () {
768 return "";
769 }
770 return (yield* fileSystem.readFileString(instructionPath)).trim();
771 - }).pipe(Effect.orElseSucceed(() => ""));
771 + },
772 + Effect.orElseSucceed(() => ""),
773 + );
774
775 const readRecentCommitSubjects = (cwd: string) =>
776 gitCore
@@ -787,51 +789,53 @@ export const make = Effect.gen(function* () {
789 Effect.orElseSucceed(() => []),
790 );
791
790 - const resolveStylePolicy = (cwd: string, settings: SourceControlTextGenerationSettings) =>
791 - Effect.gen(function* () {
792 - switch (settings.style.mode) {
793 - case "conventional_commits":
794 - return conventionalCommitsTextGenerationPolicy;
795 - case "custom":
796 - return customTextGenerationPolicy(
797 - settings.style.customInstructions
798 - ? {
799 - commitInstructions: settings.style.customInstructions,
800 - changeRequestInstructions: settings.style.customInstructions,
801 - }
802 - : {},
792 + const resolveStylePolicy = Effect.fn("GitManager.resolveStylePolicy")(function* (
793 + cwd: string,
794 + settings: SourceControlTextGenerationSettings,
795 + ) {
796 + switch (settings.style.mode) {
797 + case "conventional_commits":
798 + return conventionalCommitsTextGenerationPolicy;
799 + case "custom":
800 + return customTextGenerationPolicy(
801 + settings.style.customInstructions
802 + ? {
803 + commitInstructions: settings.style.customInstructions,
804 + changeRequestInstructions: settings.style.customInstructions,
805 + }
806 + : {},
807 + );
808 + case "repo_conventions": {
809 + const subjects = yield* readRecentCommitSubjects(cwd);
810 + const agentInstructions = yield* readRepositoryInstructions(cwd, "AGENTS.md");
811 + const isClaudeWriter =
812 + settings.modelSelection.instanceId === "claudeAgent" ||
813 + (yield* providerRegistry.getProviders).some(
814 + (provider) =>
815 + provider.instanceId === settings.modelSelection.instanceId &&
816 + provider.driver === "claudeAgent",
817 );
804 - case "repo_conventions": {
805 - const subjects = yield* readRecentCommitSubjects(cwd);
806 - const agentInstructions = yield* readRepositoryInstructions(cwd, "AGENTS.md");
807 - const isClaudeWriter =
808 - settings.modelSelection.instanceId === "claudeAgent" ||
809 - (yield* providerRegistry.getProviders).some(
810 - (provider) =>
811 - provider.instanceId === settings.modelSelection.instanceId &&
812 - provider.driver === "claudeAgent",
813 - );
814 - const claudeInstructions = isClaudeWriter
815 - ? yield* readRepositoryInstructions(cwd, "CLAUDE.md")
816 - : "";
817 - const examples = [
818 - ...(subjects.length > 0
819 - ? [["Recent commit subjects from this repository:", ...subjects].join("\n")]
820 - : []),
821 - ...(agentInstructions ? [`Local AGENTS.md:\n${agentInstructions}`] : []),
822 - ...(claudeInstructions ? [`Local CLAUDE.md:\n${claudeInstructions}`] : []),
823 - ].join("\n\n");
824 - if (!examples) {
825 - return repositoryConventionsTextGenerationPolicy;
826 - }
827 - return {
828 - ...repositoryConventionsTextGenerationPolicy,
829 - commitInstructions: `${repositoryConventionsTextGenerationPolicy.commitInstructions}\n\n${examples}`,
830 - changeRequestInstructions: `${repositoryConventionsTextGenerationPolicy.changeRequestInstructions}\n\n${examples}`,
831 - };
818 + const claudeInstructions = isClaudeWriter
819 + ? yield* readRepositoryInstructions(cwd, "CLAUDE.md")
820 + : "";
821 + const examples = [
822 + ...(subjects.length > 0
823 + ? [["Recent commit subjects from this repository:", ...subjects].join("\n")]
824 + : []),
825 + ...(agentInstructions ? [`Local AGENTS.md:\n${agentInstructions}`] : []),
826 + ...(claudeInstructions ? [`Local CLAUDE.md:\n${claudeInstructions}`] : []),
827 + ].join("\n\n");
828 + if (!examples) {
829 + return repositoryConventionsTextGenerationPolicy;
830 }
831 + return {
832 + ...repositoryConventionsTextGenerationPolicy,
833 + commitInstructions: `${repositoryConventionsTextGenerationPolicy.commitInstructions}\n\n${examples}`,
834 + changeRequestInstructions: `${repositoryConventionsTextGenerationPolicy.changeRequestInstructions}\n\n${examples}`,
835 + };
836 }
834 - });
837 + }
838 + });
839 const randomUUIDv4 = (cwd: string) =>
840 crypto.randomUUIDv4().pipe(
841 Effect.mapError(
@@ -2370,39 +2374,38 @@ export const make = Effect.gen(function* () {
2374 string,
2375 { readonly readAtMs: number; readonly value: string | null }
2376 >();
2373 - const rememberPrLookupGitState = <E>(
2377 + const rememberPrLookupGitState = Effect.fn("GitManager.rememberPrLookupGitState")(function* <E>(
2378 cwd: string,
2379 key: string,
2380 fresh: boolean,
2381 read: Effect.Effect<string | null, E>,
2378 - ) =>
2379 - Effect.gen(function* () {
2380 - const entryKey = `${cwd}\u0000${key}`;
2381 - const readAtMs = yield* Clock.currentTimeMillis;
2382 - const remembered = prLookupGitStateByKey.get(entryKey);
2383 - if (
2384 - !fresh &&
2385 - remembered !== undefined &&
2386 - readAtMs - remembered.readAtMs < Duration.toMillis(PR_LOOKUP_GIT_STATE_TTL)
2387 - ) {
2388 - return remembered.value;
2389 - }
2390 - // invalidateStatus bumps the epoch. A read that started before a T3 git
2391 - // action, or before a newer read finished, must not replace their state.
2392 - const epoch = prLookupEpoch(cwd);
2393 - const value = yield* read;
2394 - const latest = prLookupGitStateByKey.get(entryKey);
2395 - if (prLookupEpoch(cwd) !== epoch || (latest !== undefined && latest.readAtMs > readAtMs)) {
2396 - return value;
2397 - }
2398 - prLookupGitStateByKey.delete(entryKey);
2399 - if (prLookupGitStateByKey.size >= PR_LOOKUP_CACHE_CAPACITY) {
2400 - const oldestKey = prLookupGitStateByKey.keys().next().value;
2401 - if (oldestKey !== undefined) prLookupGitStateByKey.delete(oldestKey);
2402 - }
2403 - prLookupGitStateByKey.set(entryKey, { readAtMs, value });
2382 + ) {
2383 + const entryKey = `${cwd}\u0000${key}`;
2384 + const readAtMs = yield* Clock.currentTimeMillis;
2385 + const remembered = prLookupGitStateByKey.get(entryKey);
2386 + if (
2387 + !fresh &&
2388 + remembered !== undefined &&
2389 + readAtMs - remembered.readAtMs < Duration.toMillis(PR_LOOKUP_GIT_STATE_TTL)
2390 + ) {
2391 + return remembered.value;
2392 + }
2393 + // invalidateStatus bumps the epoch. A read that started before a T3 git
2394 + // action, or before a newer read finished, must not replace their state.
2395 + const epoch = prLookupEpoch(cwd);
2396 + const value = yield* read;
2397 + const latest = prLookupGitStateByKey.get(entryKey);
2398 + if (prLookupEpoch(cwd) !== epoch || (latest !== undefined && latest.readAtMs > readAtMs)) {
2399 return value;
2405 - });
2400 + }
2401 + prLookupGitStateByKey.delete(entryKey);
2402 + if (prLookupGitStateByKey.size >= PR_LOOKUP_CACHE_CAPACITY) {
2403 + const oldestKey = prLookupGitStateByKey.keys().next().value;
2404 + if (oldestKey !== undefined) prLookupGitStateByKey.delete(oldestKey);
2405 + }
2406 + prLookupGitStateByKey.set(entryKey, { readAtMs, value });
2407 + return value;
2408 + });
2409 const forgetPrLookupGitState = (cwd: string) =>
2410 normalizeStatusCacheKey(cwd).pipe(
2411 Effect.map((cacheCwd) => {
apps/server/src/git/detachStackFrame.ts
+7 -5
@@ -12,9 +12,11 @@ const snapshotStack = (
12 /**
13 * Wrap a `Cache.get` so its lookup fiber inherits a materialized stack. The lazy
14 * caller frame would otherwise retain the caller's request snapshot for the TTL.
15 + * Stay untraced so this helper does not introduce another lazy frame to retain.
16 */
16 -export const detachStackFrame = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
17 - Effect.gen(function* () {
18 - const frame = snapshotStack(yield* References.CurrentStackFrame);
19 - return yield* Effect.provideService(effect, References.CurrentStackFrame, frame);
20 - });
17 +export const detachStackFrame = Effect.fnUntraced(function* <A, E, R>(
18 + effect: Effect.Effect<A, E, R>,
19 +) {
20 + const frame = snapshotStack(yield* References.CurrentStackFrame);
21 + return yield* Effect.provideService(effect, References.CurrentStackFrame, frame);
22 +});
apps/server/src/git/linkCreatedPullRequest.ts
+38 -31
@@ -48,38 +48,45 @@ export function createdPullRequestKey(
48 * Never fails: the git action already succeeded and its result is on its way to the client, so
49 * a link that cannot be made is logged and dropped.
50 */
51 -export const linkCreatedPullRequest = <E>(input: {
51 +export const linkCreatedPullRequest: <E>(input: {
52 readonly threadId: ThreadId;
53 readonly result: Pick<GitRunStackedActionResult, "pr">;
54 readonly commandId: Effect.Effect<CommandId, E>;
55 -}): Effect.Effect<void, never, Orchestrator.OrchestratorV2 | ProjectService.ProjectService> =>
56 - Effect.gen(function* () {
57 - const engine = yield* Orchestrator.OrchestratorV2;
58 - const projects = yield* ProjectService.ProjectService;
59 - const thread = yield* engine
60 - .getThreadShell(input.threadId)
61 - .pipe(Effect.map(Option.fromNullishOr));
62 - if (Option.isNone(thread)) return;
63 - const project = Option.getOrUndefined(yield* projects.getShell(thread.value.projectId));
64 - const key = createdPullRequestKey(input.result, project);
65 - if (key === null) return;
66 - const commandId = yield* input.commandId;
67 - yield* engine
68 - .dispatch({
69 - type: "thread.pull-request.link",
70 - commandId,
71 - threadId: input.threadId,
72 - ...key,
73 - source: "created",
74 - })
75 - .pipe(Effect.asVoid);
76 - }).pipe(
77 - Effect.withSpan("linkCreatedPullRequest"),
78 - Effect.catchCause((cause) =>
79 - Cause.hasInterruptsOnly(cause)
80 - ? Effect.failCause(cause as Cause.Cause<never>)
81 - : Effect.logWarning("failed to link created pull request to thread", {
82 - threadId: input.threadId,
83 - }),
84 - ),
55 +}) => Effect.Effect<void, never, Orchestrator.OrchestratorV2 | ProjectService.ProjectService> =
56 + Effect.fn("linkCreatedPullRequest")(
57 + function* <E>(input: {
58 + readonly threadId: ThreadId;
59 + readonly result: Pick<GitRunStackedActionResult, "pr">;
60 + readonly commandId: Effect.Effect<CommandId, E>;
61 + }) {
62 + const engine = yield* Orchestrator.OrchestratorV2;
63 + const projects = yield* ProjectService.ProjectService;
64 + const thread = yield* engine
65 + .getThreadShell(input.threadId)
66 + .pipe(Effect.map(Option.fromNullishOr));
67 + if (Option.isNone(thread)) return;
68 + const project = Option.getOrUndefined(yield* projects.getShell(thread.value.projectId));
69 + const key = createdPullRequestKey(input.result, project);
70 + if (key === null) return;
71 + const commandId = yield* input.commandId;
72 + yield* engine
73 + .dispatch({
74 + type: "thread.pull-request.link",
75 + commandId,
76 + threadId: input.threadId,
77 + ...key,
78 + source: "created",
79 + })
80 + .pipe(Effect.asVoid);
81 + },
82 + (effect, input) =>
83 + effect.pipe(
84 + Effect.catchCause((cause) =>
85 + Cause.hasInterruptsOnly(cause)
86 + ? Effect.failCause(cause as Cause.Cause<never>)
87 + : Effect.logWarning("failed to link created pull request to thread", {
88 + threadId: input.threadId,
89 + }),
90 + ),
91 + ),
92 );
apps/server/src/htmlRender/HtmlRender.ts
+9 -10
@@ -341,8 +341,8 @@ const make = Effect.gen(function* () {
341 ),
342 );
343
344 - const measure = (html: string) =>
345 - Effect.gen(function* () {
344 + const measure = Effect.fn("HtmlRender.measure")(
345 + function* (html: string) {
346 const executable = yield* previewBrowser.installed;
347 if (Option.isNone(executable)) return undefined;
348 const heights = yield* launching(executable.value, (noSandbox) =>
@@ -365,14 +365,13 @@ const make = Effect.gen(function* () {
365 }),
366 );
367 return heights.toSorted(([left], [right]) => left - right);
368 - }).pipe(
369 - Effect.catch((cause) =>
370 - Effect.logWarning("Could not measure an HTML render; publishing it without heights.", {
371 - cause,
372 - }).pipe(Effect.as(undefined)),
373 - ),
374 - Effect.withSpan("HtmlRender.measure"),
375 - );
368 + },
369 + Effect.catch((cause) =>
370 + Effect.logWarning("Could not measure an HTML render; publishing it without heights.", {
371 + cause,
372 + }).pipe(Effect.as(undefined)),
373 + ),
374 + );
375
376 // The bootstrap goes in first so its head scan never runs over inlined image data.
377 const inline = (html: string) =>
apps/server/src/htmlRender/headlessChrome.ts
+20 -21
@@ -381,31 +381,30 @@ const launchBrowser = Effect.fnUntraced(function* (input: {
381 Effect.forkScoped,
382 );
383
384 - const send = <A>(
384 + const send = Effect.fn("headlessChrome.send")(function* <A>(
385 method: string,
386 params: Record<string, unknown>,
387 result: Schema.Decoder<A>,
388 sessionId?: string,
389 - ) =>
390 - Effect.gen(function* () {
391 - if (disconnected) return yield* disconnected;
392 - const id = ++nextId;
393 - const reply = yield* Deferred.make<unknown, BrowserFailure>();
394 - pending.set(id, { method, reply });
395 - const message = encodeCdpCommand({ id, method, params, ...(sessionId ? { sessionId } : {}) });
396 - yield* Queue.offer(outgoing, new TextEncoder().encode(`${message}\0`));
397 - return yield* Deferred.await(reply).pipe(
398 - Effect.flatMap(Schema.decodeUnknownEffect(result)),
399 - Effect.mapError((error) =>
400 - error._tag === "HtmlRenderBrowserError"
401 - ? error
402 - : new HtmlRenderBrowserError({
403 - reason: `${method} returned an unexpected result`,
404 - cause: error,
405 - }),
406 - ),
407 - );
408 - });
389 + ) {
390 + if (disconnected) return yield* disconnected;
391 + const id = ++nextId;
392 + const reply = yield* Deferred.make<unknown, BrowserFailure>();
393 + pending.set(id, { method, reply });
394 + const message = encodeCdpCommand({ id, method, params, ...(sessionId ? { sessionId } : {}) });
395 + yield* Queue.offer(outgoing, new TextEncoder().encode(`${message}\0`));
396 + return yield* Deferred.await(reply).pipe(
397 + Effect.flatMap(Schema.decodeUnknownEffect(result)),
398 + Effect.mapError((error) =>
399 + error._tag === "HtmlRenderBrowserError"
400 + ? error
401 + : new HtmlRenderBrowserError({
402 + reason: `${method} returned an unexpected result`,
403 + cause: error,
404 + }),
405 + ),
406 + );
407 + });
408
409 const openPage = Effect.fnUntraced(function* (width: number) {
410 const { targetId } = yield* send(
apps/server/src/keybindings.ts
+16 -17
@@ -66,24 +66,23 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
66 Effect.map((resolved) => resolved),
67 ),
68
69 - encode: (resolved) =>
70 - Effect.gen(function* () {
71 - const key = encodeShortcut(resolved.shortcut);
72 - if (!key) {
73 - return yield* Effect.fail(
74 - new SchemaIssue.InvalidValue({
75 - message: "Resolved shortcut cannot be encoded to key string",
76 - }),
77 - );
78 - }
69 + encode: Effect.fn("keybindings.encode")(function* (resolved) {
70 + const key = encodeShortcut(resolved.shortcut);
71 + if (!key) {
72 + return yield* Effect.fail(
73 + new SchemaIssue.InvalidValue({
74 + message: "Resolved shortcut cannot be encoded to key string",
75 + }),
76 + );
77 + }
78
80 - const when = resolved.whenAst ? encodeWhenAst(resolved.whenAst) : undefined;
81 - return {
82 - key,
83 - command: resolved.command,
84 - when,
85 - };
86 - }),
79 + const when = resolved.whenAst ? encodeWhenAst(resolved.whenAst) : undefined;
80 + return {
81 + key,
82 + command: resolved.command,
83 + when,
84 + };
85 + }),
86 }),
87 ),
88 );
apps/server/src/launcherWatch.ts
+17 -18
@@ -21,25 +21,24 @@ const startupParentPid = process.ppid;
21 * lose, and Windows keeps the original parent id after the parent exits, so
22 * neither is watched.
23 */
24 -export const awaitLauncherLoss = (options?: {
24 +export const awaitLauncherLoss = Effect.fn("launcherWatch.awaitLauncherLoss")(function* (options?: {
25 readonly launcherPid?: number;
26 readonly getParentPid?: () => number;
27 readonly interval?: Duration.Input;
28 -}): Effect.Effect<void> =>
29 - Effect.gen(function* () {
30 - const platform = yield* HostProcess.Platform;
31 - const launcherPid = options?.launcherPid ?? startupParentPid;
32 - const getParentPid = options?.getParentPid ?? (() => process.ppid);
33 - const interval = options?.interval ?? DEFAULT_POLL_INTERVAL;
34 - if (platform === "win32" || launcherPid <= 1) return yield* Effect.never;
35 - const poll: Effect.Effect<void> = Effect.suspend(() => {
36 - const parentPid = getParentPid();
37 - return parentPid === launcherPid
38 - ? Effect.flatMap(Effect.sleep(interval), () => poll)
39 - : Effect.logWarning("desktop launcher is gone; shutting down the backend", {
40 - launcherPid,
41 - parentPid,
42 - });
43 - });
44 - return yield* poll;
28 +}): Effect.fn.Return<void> {
29 + const platform = yield* HostProcess.Platform;
30 + const launcherPid = options?.launcherPid ?? startupParentPid;
31 + const getParentPid = options?.getParentPid ?? (() => process.ppid);
32 + const interval = options?.interval ?? DEFAULT_POLL_INTERVAL;
33 + if (platform === "win32" || launcherPid <= 1) return yield* Effect.never;
34 + const poll: Effect.Effect<void> = Effect.suspend(() => {
35 + const parentPid = getParentPid();
36 + return parentPid === launcherPid
37 + ? Effect.flatMap(Effect.sleep(interval), () => poll)
38 + : Effect.logWarning("desktop launcher is gone; shutting down the backend", {
39 + launcherPid,
40 + parentPid,
41 + });
42 });
43 + return yield* poll;
44 +});
apps/server/src/observability/Metrics.ts
+7 -6
@@ -101,12 +101,13 @@ export interface WithMetricsOptions {
101 ) => Readonly<Record<string, unknown>>;
102 }
103
104 -const recordMetrics = (
105 - options: WithMetricsOptions,
106 - startedAt: bigint,
107 - exit: Exit.Exit<unknown, unknown>,
108 -) =>
109 - Effect.gen(function* () {
104 +const recordMetrics =
105 + /* Instrumentation must not create its own span for every recorded operation. */
106 + Effect.fnUntraced(function* (
107 + options: WithMetricsOptions,
108 + startedAt: bigint,
109 + exit: Exit.Exit<unknown, unknown>,
110 + ) {
111 const duration = Duration.nanos((yield* Clock.monotonicTimeNanos) - startedAt);
112 const baseAttributes =
113 typeof options.attributes === "function" ? options.attributes() : (options.attributes ?? {});
apps/server/src/persistence/DatabaseMaintenance.ts
+15 -14
@@ -126,20 +126,21 @@ const readStorage = Effect.gen(function* () {
126 * refused while any other connection has the file open, even an idle one,
127 * which is how a running server or desktop app is detected.
128 */
129 -const lockExclusively = (databasePath: string) =>
130 - Effect.gen(function* () {
131 - const sql = yield* SqlClient.SqlClient;
132 - yield* sql`PRAGMA busy_timeout = 0`;
133 - yield* sql`PRAGMA locking_mode = EXCLUSIVE`;
134 - yield* sql`BEGIN EXCLUSIVE`.pipe(
135 - Effect.mapError((cause) =>
136 - isSqlError(cause) && cause.reason._tag === "LockTimeoutError"
137 - ? new DatabaseInUseError({ path: databasePath, cause })
138 - : cause,
139 - ),
140 - );
141 - yield* sql`COMMIT`;
142 - });
129 +const lockExclusively = Effect.fn("DatabaseMaintenance.lockExclusively")(function* (
130 + databasePath: string,
131 +) {
132 + const sql = yield* SqlClient.SqlClient;
133 + yield* sql`PRAGMA busy_timeout = 0`;
134 + yield* sql`PRAGMA locking_mode = EXCLUSIVE`;
135 + yield* sql`BEGIN EXCLUSIVE`.pipe(
136 + Effect.mapError((cause) =>
137 + isSqlError(cause) && cause.reason._tag === "LockTimeoutError"
138 + ? new DatabaseInUseError({ path: databasePath, cause })
139 + : cause,
140 + ),
141 + );
142 + yield* sql`COMMIT`;
143 +});
144
145 const make = Effect.gen(function* () {
146 const fs = yield* FileSystem.FileSystem;
apps/server/src/process/agentScope.ts
+95 -91
@@ -121,31 +121,32 @@ export const make = Effect.gen(function* () {
121 // Old agents keep their scopes when the server is killed, and the restarted
122 // server resumes their sessions. Stop them first, so two copies of one
123 // session never work in the same worktree.
124 - const stopLeftoverAgents = (systemctl: string) =>
125 - Effect.gen(function* () {
126 - const shown = yield* run(systemctl, [
127 - "--user",
128 - "show",
129 - ownedSlice,
130 - "--property=ActiveState,ControlGroup",
131 - ]);
132 - if (shown._tag === "None") return;
133 - const values = parseKeyValues(shown.value.stdout);
134 - if (values.get("ActiveState") !== "active") return;
135 - const controlGroup = values.get("ControlGroup") ?? "";
136 - const events = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";
137 - if (parseCgroupCounter(events, "populated") === 0) return;
138 - yield* Effect.logWarning("Stopping agents left by a previous server", { slice: ownedSlice });
139 - const stopped = yield* runner
140 - .run({ command: systemctl, args: ["--user", "stop", ownedSlice], timeout: "30 seconds" })
141 - .pipe(Effect.option);
142 - if (stopped._tag === "None" || stopped.value.code !== 0) {
143 - yield* Effect.logWarning("Could not stop agents left by a previous server", {
144 - slice: ownedSlice,
145 - stderr: stopped._tag === "Some" ? stopped.value.stderr.trim() : undefined,
146 - });
147 - }
148 - });
124 + const stopLeftoverAgents = Effect.fn("agentScope.stopLeftoverAgents")(function* (
125 + systemctl: string,
126 + ) {
127 + const shown = yield* run(systemctl, [
128 + "--user",
129 + "show",
130 + ownedSlice,
131 + "--property=ActiveState,ControlGroup",
132 + ]);
133 + if (shown._tag === "None") return;
134 + const values = parseKeyValues(shown.value.stdout);
135 + if (values.get("ActiveState") !== "active") return;
136 + const controlGroup = values.get("ControlGroup") ?? "";
137 + const events = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";
138 + if (parseCgroupCounter(events, "populated") === 0) return;
139 + yield* Effect.logWarning("Stopping agents left by a previous server", { slice: ownedSlice });
140 + const stopped = yield* runner
141 + .run({ command: systemctl, args: ["--user", "stop", ownedSlice], timeout: "30 seconds" })
142 + .pipe(Effect.option);
143 + if (stopped._tag === "None" || stopped.value.code !== 0) {
144 + yield* Effect.logWarning("Could not stop agents left by a previous server", {
145 + slice: ownedSlice,
146 + stderr: stopped._tag === "Some" ? stopped.value.stderr.trim() : undefined,
147 + });
148 + }
149 + });
150
151 const systemd = yield* Effect.cached(
152 Effect.gen(function* () {
@@ -202,73 +203,76 @@ export const make = Effect.gen(function* () {
203
204 const scopeByThread = new Map<string, { unit: string; oomKilled: boolean }>();
205
205 - const readScope = (systemctl: string, unit: string) =>
206 - Effect.gen(function* () {
207 - const shown = yield* run(systemctl, [
208 - "--user",
209 - "show",
210 - unit,
211 - "--property=LoadState,ActiveState,Result,ControlGroup",
212 - ]);
213 - if (shown._tag === "None" || shown.value.code !== 0) return undefined;
214 - const values = parseKeyValues(shown.value.stdout);
215 - const controlGroup = values.get("ControlGroup") ?? "";
216 - const memoryEvents = controlGroup ? yield* readCgroupFile(controlGroup, "memory.events") : "";
217 - const cgroupEvents = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";
218 - const populated = parseCgroupCounter(cgroupEvents, "populated");
219 - return {
220 - loadState: values.get("LoadState") ?? "",
221 - activeState: values.get("ActiveState") ?? "",
222 - result: values.get("Result") ?? "",
223 - oomKills: parseCgroupCounter(memoryEvents, "oom_kill") ?? 0,
224 - populated: populated === undefined ? undefined : populated === 1,
225 - } satisfies ScopeState;
226 - });
206 + const readScope = Effect.fn("agentScope.readScope")(function* (systemctl: string, unit: string) {
207 + const shown = yield* run(systemctl, [
208 + "--user",
209 + "show",
210 + unit,
211 + "--property=LoadState,ActiveState,Result,ControlGroup",
212 + ]);
213 + if (shown._tag === "None" || shown.value.code !== 0) return undefined;
214 + const values = parseKeyValues(shown.value.stdout);
215 + const controlGroup = values.get("ControlGroup") ?? "";
216 + const memoryEvents = controlGroup ? yield* readCgroupFile(controlGroup, "memory.events") : "";
217 + const cgroupEvents = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : "";
218 + const populated = parseCgroupCounter(cgroupEvents, "populated");
219 + return {
220 + loadState: values.get("LoadState") ?? "",
221 + activeState: values.get("ActiveState") ?? "",
222 + result: values.get("Result") ?? "",
223 + oomKills: parseCgroupCounter(memoryEvents, "oom_kill") ?? 0,
224 + populated: populated === undefined ? undefined : populated === 1,
225 + } satisfies ScopeState;
226 + });
227
228 - const clearFailed = (systemctl: string, unit: string) =>
229 - Effect.gen(function* () {
230 - for (let attempt = 0; attempt < CLEAR_FAILED_ATTEMPTS; attempt++) {
231 - const state = yield* readScope(systemctl, unit);
232 - if (state === undefined) return;
233 - if (state.activeState === "failed") {
234 - yield* run(systemctl, ["--user", "reset-failed", unit]);
235 - return;
236 - }
237 - if (state.activeState !== "deactivating") return;
238 - yield* Effect.sleep(CLEAR_FAILED_INTERVAL);
228 + const clearFailed = Effect.fn("agentScope.clearFailed")(function* (
229 + systemctl: string,
230 + unit: string,
231 + ) {
232 + for (let attempt = 0; attempt < CLEAR_FAILED_ATTEMPTS; attempt++) {
233 + const state = yield* readScope(systemctl, unit);
234 + if (state === undefined) return;
235 + if (state.activeState === "failed") {
236 + yield* run(systemctl, ["--user", "reset-failed", unit]);
237 + return;
238 }
240 - });
239 + if (state.activeState !== "deactivating") return;
240 + yield* Effect.sleep(CLEAR_FAILED_INTERVAL);
241 + }
242 + });
243
244 const forget = (systemctl: string, unit: string) =>
245 clearFailed(systemctl, unit).pipe(Effect.forkIn(layerScope), Effect.asVoid);
246
245 - const evictOldest = (systemctl: string) =>
246 - Effect.gen(function* () {
247 - const oldest = scopeByThread.entries().next();
248 - if (oldest.done === true) return;
249 - const [threadId, tracked] = oldest.value;
250 - const state = yield* readScope(systemctl, tracked.unit);
251 - if (scopeByThread.get(threadId) !== tracked) return;
252 - scopeByThread.delete(threadId);
253 - const status = state === undefined ? "running" : classifyScope(state);
254 - if (status === "running" || status === "stopping") {
255 - scopeByThread.set(threadId, tracked);
256 - return;
257 - }
258 - yield* forget(systemctl, tracked.unit);
259 - });
247 + const evictOldest = Effect.fn("agentScope.evictOldest")(function* (systemctl: string) {
248 + const oldest = scopeByThread.entries().next();
249 + if (oldest.done === true) return;
250 + const [threadId, tracked] = oldest.value;
251 + const state = yield* readScope(systemctl, tracked.unit);
252 + if (scopeByThread.get(threadId) !== tracked) return;
253 + scopeByThread.delete(threadId);
254 + const status = state === undefined ? "running" : classifyScope(state);
255 + if (status === "running" || status === "stopping") {
256 + scopeByThread.set(threadId, tracked);
257 + return;
258 + }
259 + yield* forget(systemctl, tracked.unit);
260 + });
261
261 - const track = (systemctl: string, threadId: string, unit: string | undefined) =>
262 - Effect.gen(function* () {
263 - const previous = scopeByThread.get(threadId);
264 - scopeByThread.delete(threadId);
265 - if (unit !== undefined) scopeByThread.set(threadId, { unit, oomKilled: false });
266 - if (previous !== undefined) yield* forget(systemctl, previous.unit);
267 - if (scopeByThread.size > MAX_TRACKED_THREADS) yield* evictOldest(systemctl);
268 - });
262 + const track = Effect.fn("agentScope.track")(function* (
263 + systemctl: string,
264 + threadId: string,
265 + unit: string | undefined,
266 + ) {
267 + const previous = scopeByThread.get(threadId);
268 + scopeByThread.delete(threadId);
269 + if (unit !== undefined) scopeByThread.set(threadId, { unit, oomKilled: false });
270 + if (previous !== undefined) yield* forget(systemctl, previous.unit);
271 + if (scopeByThread.size > MAX_TRACKED_THREADS) yield* evictOldest(systemctl);
272 + });
273
270 - const oomKilled: AgentScopeShape["oomKilled"] = (threadId) =>
271 - Effect.gen(function* () {
274 + const oomKilled: AgentScopeShape["oomKilled"] = Effect.fn("agentScope.oomKilled")(
275 + function* (threadId) {
276 const tracked = scopeByThread.get(threadId);
277 if (tracked === undefined) return false;
278 if (tracked.oomKilled) return true;
@@ -293,14 +297,14 @@ export const make = Effect.gen(function* () {
297 return true;
298 }
299 return false;
296 - });
300 + },
301 + );
302
298 - const clear: AgentScopeShape["clear"] = (threadId) =>
299 - Effect.gen(function* () {
300 - if (!scopeByThread.has(threadId)) return;
301 - const scope = yield* systemd;
302 - if (scope !== undefined) yield* track(scope.systemctl, threadId, undefined);
303 - });
303 + const clear: AgentScopeShape["clear"] = Effect.fn("agentScope.clear")(function* (threadId) {
304 + if (!scopeByThread.has(threadId)) return;
305 + const scope = yield* systemd;
306 + if (scope !== undefined) yield* track(scope.systemctl, threadId, undefined);
307 + });
308
309 return {
310 wrap: Effect.fn("AgentScope.wrap")(function* ({
apps/server/src/project/ProjectCloneTracker.ts
+78 -71
@@ -133,20 +133,21 @@ export const make = Effect.gen(function* () {
133 return next;
134 }).pipe(Effect.andThen(publish));
135
136 - const scheduleRemoval = (projectId: ProjectId) =>
137 - Effect.gen(function* () {
138 - yield* clearRetention(projectId);
139 - const fiber = yield* remove(projectId).pipe(
140 - Effect.delay(DONE_RETENTION),
141 - Effect.ensuring(
142 - Effect.sync(() => {
143 - if (retentionFibers.get(projectId) === fiber) retentionFibers.delete(projectId);
144 - }),
145 - ),
146 - Effect.forkDetach,
147 - );
148 - retentionFibers.set(projectId, fiber);
149 - });
136 + const scheduleRemoval = Effect.fn("ProjectCloneTracker.scheduleRemoval")(function* (
137 + projectId: ProjectId,
138 + ) {
139 + yield* clearRetention(projectId);
140 + const fiber = yield* remove(projectId).pipe(
141 + Effect.delay(DONE_RETENTION),
142 + Effect.ensuring(
143 + Effect.sync(() => {
144 + if (retentionFibers.get(projectId) === fiber) retentionFibers.delete(projectId);
145 + }),
146 + ),
147 + Effect.forkDetach,
148 + );
149 + retentionFibers.set(projectId, fiber);
150 + });
151
152 const progress = (
153 projectId: ProjectId,
@@ -167,26 +168,25 @@ export const make = Effect.gen(function* () {
168 },
169 })).pipe(Effect.asVoid);
170
170 - const finish = (
171 + const finish = Effect.fn("ProjectCloneTracker.finish")(function* (
172 projectId: ProjectId,
173 phase: "done" | "failed" | "cancelled",
174 error: string | null,
174 - ) =>
175 - Effect.gen(function* () {
176 - const endedAt = yield* nowIso;
177 - yield* modify(projectId, (tracked) => ({
178 - ...tracked,
179 - fiber: null,
180 - snapshot: {
181 - ...tracked.snapshot,
182 - phase,
183 - endedAt,
184 - percent: phase === "done" ? 100 : tracked.snapshot.percent,
185 - error: error === null ? null : clampText(error, PROJECT_CLONE_ERROR_MAX_LENGTH),
186 - },
187 - }));
188 - if (phase === "done") yield* scheduleRemoval(projectId);
189 - });
175 + ) {
176 + const endedAt = yield* nowIso;
177 + yield* modify(projectId, (tracked) => ({
178 + ...tracked,
179 + fiber: null,
180 + snapshot: {
181 + ...tracked.snapshot,
182 + phase,
183 + endedAt,
184 + percent: phase === "done" ? 100 : tracked.snapshot.percent,
185 + error: error === null ? null : clampText(error, PROJECT_CLONE_ERROR_MAX_LENGTH),
186 + },
187 + }));
188 + if (phase === "done") yield* scheduleRemoval(projectId);
189 + });
190
191 /**
192 * Runs in its own fiber; the tracker records the outcome through `onExit`,
@@ -217,20 +217,19 @@ export const make = Effect.gen(function* () {
217 Effect.ignoreCause(),
218 );
219
220 - const launch = (projectId: ProjectId) =>
221 - Effect.gen(function* () {
222 - const current = yield* Ref.get(clones);
223 - const tracked = current.get(projectId);
224 - if (!tracked) return;
225 - const fiber = yield* runClone(projectId, tracked).pipe(Effect.forkIn(cloneScope));
226 - yield* Ref.update(clones, (map) => {
227 - const existing = map.get(projectId);
228 - if (!existing) return map;
229 - const next = new Map(map);
230 - next.set(projectId, { ...existing, fiber });
231 - return next;
232 - });
220 + const launch = Effect.fn("ProjectCloneTracker.launch")(function* (projectId: ProjectId) {
221 + const current = yield* Ref.get(clones);
222 + const tracked = current.get(projectId);
223 + if (!tracked) return;
224 + const fiber = yield* runClone(projectId, tracked).pipe(Effect.forkIn(cloneScope));
225 + yield* Ref.update(clones, (map) => {
226 + const existing = map.get(projectId);
227 + if (!existing) return map;
228 + const next = new Map(map);
229 + next.set(projectId, { ...existing, fiber });
230 + return next;
231 });
232 + });
233
234 const start: ProjectCloneTracker["Service"]["start"] = Effect.fn("ProjectCloneTracker.start")(
235 function* (input, hooks) {
@@ -307,8 +306,8 @@ export const make = Effect.gen(function* () {
306 const get: ProjectCloneTracker["Service"]["get"] = (projectId) =>
307 Ref.get(clones).pipe(Effect.map((current) => current.get(projectId)?.snapshot ?? null));
308
310 - const cancel: ProjectCloneTracker["Service"]["cancel"] = (projectId) =>
311 - Effect.gen(function* () {
309 + const cancel: ProjectCloneTracker["Service"]["cancel"] = Effect.fn("ProjectCloneTracker.cancel")(
310 + function* (projectId) {
311 const current = yield* Ref.get(clones);
312 const tracked = current.get(projectId);
313 if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) return false;
@@ -324,10 +323,11 @@ export const make = Effect.gen(function* () {
323 }),
324 );
325 return true;
327 - });
326 + },
327 + );
328
329 - const retry: ProjectCloneTracker["Service"]["retry"] = (projectId) =>
330 - Effect.gen(function* () {
329 + const retry: ProjectCloneTracker["Service"]["retry"] = Effect.fn("ProjectCloneTracker.retry")(
330 + function* (projectId) {
331 const current = yield* Ref.get(clones);
332 const tracked = current.get(projectId);
333 if (
@@ -353,23 +353,25 @@ export const make = Effect.gen(function* () {
353 }));
354 yield* launch(projectId);
355 return true;
356 - });
356 + },
357 + );
358
358 - const discard: ProjectCloneTracker["Service"]["discard"] = (projectId) =>
359 - Effect.gen(function* () {
360 - const current = yield* Ref.get(clones);
361 - const tracked = current.get(projectId);
362 - if (!tracked) return;
363 - if (tracked.fiber) yield* Fiber.interrupt(tracked.fiber);
364 - // Git may have finished while the interrupt was landing; the project
365 - // is going away either way, but a complete checkout is the user's.
366 - const after = yield* get(projectId);
367 - if (after?.phase !== "done") {
368 - yield* repositories.discardClone(tracked.input.destinationPath).pipe(Effect.ignore);
369 - }
370 - yield* clearRetention(projectId);
371 - yield* remove(projectId);
372 - });
359 + const discard: ProjectCloneTracker["Service"]["discard"] = Effect.fn(
360 + "ProjectCloneTracker.discard",
361 + )(function* (projectId) {
362 + const current = yield* Ref.get(clones);
363 + const tracked = current.get(projectId);
364 + if (!tracked) return;
365 + if (tracked.fiber) yield* Fiber.interrupt(tracked.fiber);
366 + // Git may have finished while the interrupt was landing; the project
367 + // is going away either way, but a complete checkout is the user's.
368 + const after = yield* get(projectId);
369 + if (after?.phase !== "done") {
370 + yield* repositories.discardClone(tracked.input.destinationPath).pipe(Effect.ignore);
371 + }
372 + yield* clearRetention(projectId);
373 + yield* remove(projectId);
374 + });
375
376 const stream: ProjectCloneTracker["Service"]["stream"] = Stream.callback<
377 ReadonlyArray<ProjectCloneSnapshot>
@@ -405,11 +407,15 @@ const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);
407 * client can start a thread on an empty tree, and no attachment copies are made
408 * for a command that is about to be refused.
409 */
408 -export const rejectCommandsDuringClone = (
409 - tracker: ProjectCloneTracker["Service"],
410 - command: { readonly type: string; readonly projectId?: ProjectId; readonly bootstrap?: unknown },
411 -): Effect.Effect<void, OrchestrationDispatchCommandError> =>
412 - Effect.gen(function* () {
410 +export const rejectCommandsDuringClone = Effect.fn("ProjectCloneTracker.rejectCommandsDuringClone")(
411 + function* (
412 + tracker: ProjectCloneTracker["Service"],
413 + command: {
414 + readonly type: string;
415 + readonly projectId?: ProjectId;
416 + readonly bootstrap?: unknown;
417 + },
418 + ): Effect.fn.Return<void, OrchestrationDispatchCommandError> {
419 const projectId =
420 command.type === "thread.create"
421 ? (command.projectId ?? null)
@@ -425,7 +431,8 @@ export const rejectCommandsDuringClone = (
431 ? "The repository is still being cloned."
432 : "The repository was not cloned. Retry the clone first.",
433 });
428 - });
434 + },
435 +);
436
437 function bootstrapProjectId(bootstrap: unknown): ProjectId | null {
438 if (typeof bootstrap !== "object" || bootstrap === null) return null;
apps/server/src/project/ProjectFaviconResolver.ts
+10 -11
@@ -238,20 +238,19 @@ export const make = Effect.gen(function* () {
238 // matters when the disk is slow. Fibers are joined in order, so a hit returns
239 // without waiting for lower-ranked probes (the scope interrupts them), and a
240 // failure surfaces only when no earlier probe found a file.
241 - const firstInOrder = <A>(
241 + const firstInOrder = Effect.fn("ProjectFaviconResolver.firstInOrder")(function* <A>(
242 items: ReadonlyArray<A>,
243 probe: (item: A) => Effect.Effect<string | null, ProjectFaviconResolutionError>,
244 - ) =>
245 - Effect.gen(function* () {
246 - const fibers = yield* Effect.forEach(items, (item) => Effect.forkScoped(probe(item)));
247 - for (const fiber of fibers) {
248 - const found = yield* Fiber.join(fiber);
249 - if (found) {
250 - return found;
251 - }
244 + ) {
245 + const fibers = yield* Effect.forEach(items, (item) => Effect.forkScoped(probe(item)));
246 + for (const fiber of fibers) {
247 + const found = yield* Fiber.join(fiber);
248 + if (found) {
249 + return found;
250 }
253 - return null;
254 - }).pipe(Effect.scoped);
251 + }
252 + return null;
253 + }, Effect.scoped);
254
255 const resolvePathUncached = Effect.fn("ProjectFaviconResolver.resolvePathUncached")(function* (
256 cwd: string,
apps/server/src/project/ProjectSetupScriptRunner.ts
+12 -11
@@ -191,16 +191,16 @@ export const make = Effect.gen(function* () {
191 yield* HostProcess.Environment,
192 );
193
194 - const observeTerminalCompletion = (input: {
195 - readonly threadId: string;
196 - readonly terminalId: string;
197 - readonly sentinel: string;
198 - readonly sentinelPattern: RegExp;
199 - /** The shell echoes typed input; lines ending with these are the wrapper, not output. */
200 - readonly echoedWrapperLines: ReadonlyArray<string>;
201 - readonly onOutputLine: ((line: string) => Effect.Effect<void>) | undefined;
202 - }) =>
203 - Effect.gen(function* () {
194 + const observeTerminalCompletion = Effect.fn("ProjectSetupScriptRunner.observeTerminalCompletion")(
195 + function* (input: {
196 + readonly threadId: string;
197 + readonly terminalId: string;
198 + readonly sentinel: string;
199 + readonly sentinelPattern: RegExp;
200 + /** The shell echoes typed input; lines ending with these are the wrapper, not output. */
201 + readonly echoedWrapperLines: ReadonlyArray<string>;
202 + readonly onOutputLine: ((line: string) => Effect.Effect<void>) | undefined;
203 + }) {
204 const startedAtMs = yield* Clock.currentTimeMillis;
205 const done = yield* Deferred.make<ProjectSetupScriptCompletion>();
206 // The shell redraws its prompt just after the sentinel. Closing before
@@ -278,7 +278,8 @@ export const make = Effect.gen(function* () {
278 Effect.ensuring(Effect.sync(() => unsubscribe())),
279 );
280 return { completion, unsubscribe };
281 - });
281 + },
282 + );
283
284 const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn(
285 "ProjectSetupScriptRunner.runForThread",
apps/server/src/project/WorktreeSetupTracker.ts
+53 -50
@@ -147,8 +147,8 @@ export const make = Effect.gen(function* () {
147 Effect.tap(() => Effect.sync(() => lastSequenceByThread.delete(threadId))),
148 );
149
150 - const begin: WorktreeSetupTracker["Service"]["begin"] = (input) =>
151 - Effect.gen(function* () {
150 + const begin: WorktreeSetupTracker["Service"]["begin"] = Effect.fn("WorktreeSetupTracker.begin")(
151 + function* (input) {
152 yield* clearRetention(input.threadId);
153 const startedAt = yield* nowIso;
154 const ordered = WORKTREE_SETUP_STAGE_ORDER.filter((id) => input.stages.includes(id));
@@ -172,7 +172,8 @@ export const make = Effect.gen(function* () {
172 return next;
173 });
174 yield* publish(input.threadId, snapshot);
175 - });
175 + },
176 + );
177
178 const update: WorktreeSetupTracker["Service"]["update"] = (threadId, mutate) =>
179 modify(threadId, (tracked) => ({ ...tracked, snapshot: mutate(tracked.snapshot) })).pipe(
@@ -235,44 +236,45 @@ export const make = Effect.gen(function* () {
236 ),
237 }));
238
238 - const finish: WorktreeSetupTracker["Service"]["finish"] = (threadId, phase, error) =>
239 - Effect.gen(function* () {
240 - const endedAt = yield* nowIso;
241 - const snapshot = yield* modify(threadId, (tracked) => ({
242 - fiber: null,
243 - snapshot: {
244 - ...tracked.snapshot,
245 - phase,
246 - endedAt,
247 - error:
248 - error === undefined || error === null
249 - ? null
250 - : clampText(error, WORKTREE_SETUP_ERROR_MAX_LENGTH),
251 - stages: tracked.snapshot.stages.map((entry) =>
252 - entry.status === "running"
253 - ? {
254 - ...entry,
255 - status: phase === "done" ? "done" : phase === "cancelled" ? "skipped" : "failed",
256 - endedAt,
257 - }
258 - : entry,
259 - ),
260 - },
261 - }));
262 - if (!snapshot) return null;
263 - yield* clearRetention(threadId);
264 - const fiber = yield* remove(threadId).pipe(
265 - Effect.delay(FINISHED_RETENTION),
266 - Effect.ensuring(
267 - Effect.sync(() => {
268 - if (retentionFibers.get(threadId) === fiber) retentionFibers.delete(threadId);
269 - }),
239 + const finish: WorktreeSetupTracker["Service"]["finish"] = Effect.fn(
240 + "WorktreeSetupTracker.finish",
241 + )(function* (threadId, phase, error) {
242 + const endedAt = yield* nowIso;
243 + const snapshot = yield* modify(threadId, (tracked) => ({
244 + fiber: null,
245 + snapshot: {
246 + ...tracked.snapshot,
247 + phase,
248 + endedAt,
249 + error:
250 + error === undefined || error === null
251 + ? null
252 + : clampText(error, WORKTREE_SETUP_ERROR_MAX_LENGTH),
253 + stages: tracked.snapshot.stages.map((entry) =>
254 + entry.status === "running"
255 + ? {
256 + ...entry,
257 + status: phase === "done" ? "done" : phase === "cancelled" ? "skipped" : "failed",
258 + endedAt,
259 + }
260 + : entry,
261 ),
271 - Effect.forkDetach,
272 - );
273 - retentionFibers.set(threadId, fiber);
274 - return snapshot;
275 - });
262 + },
263 + }));
264 + if (!snapshot) return null;
265 + yield* clearRetention(threadId);
266 + const fiber = yield* remove(threadId).pipe(
267 + Effect.delay(FINISHED_RETENTION),
268 + Effect.ensuring(
269 + Effect.sync(() => {
270 + if (retentionFibers.get(threadId) === fiber) retentionFibers.delete(threadId);
271 + }),
272 + ),
273 + Effect.forkDetach,
274 + );
275 + retentionFibers.set(threadId, fiber);
276 + return snapshot;
277 + });
278
279 const markUncancellable: WorktreeSetupTracker["Service"]["markUncancellable"] = (threadId) =>
280 Ref.update(setups, (current) => {
@@ -283,16 +285,17 @@ export const make = Effect.gen(function* () {
285 return next;
286 });
287
286 - const cancel: WorktreeSetupTracker["Service"]["cancel"] = (threadId) =>
287 - Effect.gen(function* () {
288 - const current = yield* Ref.get(setups);
289 - const tracked = current.get(threadId);
290 - if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) {
291 - return false;
292 - }
293 - yield* Fiber.interrupt(tracked.fiber);
294 - return true;
295 - });
288 + const cancel: WorktreeSetupTracker["Service"]["cancel"] = Effect.fn(
289 + "WorktreeSetupTracker.cancel",
290 + )(function* (threadId) {
291 + const current = yield* Ref.get(setups);
292 + const tracked = current.get(threadId);
293 + if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) {
294 + return false;
295 + }
296 + yield* Fiber.interrupt(tracked.fiber);
297 + return true;
298 + });
299
300 const get: WorktreeSetupTracker["Service"]["get"] = (threadId) =>
301 Ref.get(setups).pipe(Effect.map((current) => current.get(threadId)?.snapshot ?? null));
apps/server/src/pullRequest/PullRequestReadCache.ts
+10 -10
@@ -153,8 +153,8 @@ export const make = Effect.gen(function* () {
153 lock.withPermits(1),
154 );
155 }),
156 - invalidate: (scope) =>
157 - Effect.gen(function* () {
156 + invalidate: Effect.fn("PullRequestReadCache.invalidate")(
157 + function* (scope) {
158 const now = clock.currentTimeMillisUnsafe();
159 const current = yield* Cache.get(revisions, undefined);
160 const next = Object.fromEntries(
@@ -164,14 +164,14 @@ export const make = Effect.gen(function* () {
164 const encoded = yield* Schema.encodeEffect(revisionCodec)(next);
165 yield* backing.set("revisions", encoded);
166 yield* Cache.set(revisions, undefined, next);
167 - }).pipe(
168 - Effect.catch(() => {
169 - enabled = false;
170 - return Effect.logWarning("PR cache disabled after clearing failed");
171 - }),
172 - Effect.uninterruptible,
173 - lock.withPermits(CONCURRENT_READS),
174 - ),
167 + },
168 + Effect.catch(() => {
169 + enabled = false;
170 + return Effect.logWarning("PR cache disabled after clearing failed");
171 + }),
172 + Effect.uninterruptible,
173 + lock.withPermits(CONCURRENT_READS),
174 + ),
175 });
176 });
177
apps/server/src/pullRequest/PullRequestService.ts
+383 -389
@@ -1075,294 +1075,291 @@ export const make = Effect.gen(function* () {
1075 const searchVisibilityKey = (host: string, repository: string) =>
1076 `${host}\n${repository.trim().toLowerCase()}`;
1077
1078 - const listUncached: PullRequestService["Service"]["list"] = (input) =>
1079 - Effect.gen(function* () {
1080 - const involvement = input.involvement ?? "all";
1081 - const continuation = yield* decodeCursors(input.cursors);
1082 - const {
1083 - supported: projects,
1084 - unimplemented,
1085 - viewerRoots,
1086 - } = yield* listWorkspaceProjects(input);
1087 - const projectCounts = new Map<string, number>();
1088 - for (const { host } of projects) {
1089 - projectCounts.set(host, (projectCounts.get(host) ?? 0) + 1);
1090 - }
1078 + const listUncached: PullRequestService["Service"]["list"] = Effect.fn(
1079 + "PullRequestService.listUncached",
1080 + )(function* (input) {
1081 + const involvement = input.involvement ?? "all";
1082 + const continuation = yield* decodeCursors(input.cursors);
1083 + const { supported: projects, unimplemented, viewerRoots } = yield* listWorkspaceProjects(input);
1084 + const projectCounts = new Map<string, number>();
1085 + for (const { host } of projects) {
1086 + projectCounts.set(host, (projectCounts.get(host) ?? 0) + 1);
1087 + }
1088
1092 - const viewerResults = yield* resolveViewers(projects, viewerRoots);
1093 - const viewers: Record<string, string> = {};
1094 - for (const result of viewerResults) {
1095 - if (result.viewer !== null) viewers[result.host] = result.viewer;
1089 + const viewerResults = yield* resolveViewers(projects, viewerRoots);
1090 + const viewers: Record<string, string> = {};
1091 + for (const result of viewerResults) {
1092 + if (result.viewer !== null) viewers[result.host] = result.viewer;
1093 + }
1094 +
1095 + const providers: ReadonlyArray<PullRequestProviderSummary> = [
1096 + ...viewerResults.map((result) => {
1097 + const capabilities = projects.find((project) => project.host === result.host)?.api
1098 + .capabilities;
1099 + return {
1100 + host: result.host,
1101 + kind: result.kind,
1102 + searchesOnHost: capabilities?.search ?? false,
1103 + actions: capabilities?.actions ?? [],
1104 + projectCount: projectCounts.get(result.host) ?? 1,
1105 + configured: result.viewer !== null,
1106 + detail: result.error === null ? null : providerDetail(result.error),
1107 + };
1108 + }),
1109 + ...[...unimplemented].map(([host, { kind, projectCount }]) => ({
1110 + host,
1111 + kind,
1112 + searchesOnHost: false,
1113 + actions: [],
1114 + projectCount,
1115 + configured: false,
1116 + detail: "This host cannot be browsed here yet.",
1117 + })),
1118 + ];
1119 +
1120 + const selected =
1121 + continuation === null
1122 + ? projects
1123 + : projects.filter(({ cursorKey }) => continuation.has(cursorKey));
1124 + const readable = selected.filter(({ host }) => viewers[host] !== undefined);
1125 + const unreadable = selected
1126 + .filter(({ host }) => viewers[host] === undefined)
1127 + .map(({ project, repository }) => ({
1128 + projectId: project.id,
1129 + projectTitle: project.title,
1130 + message: `${repository} could not be read.`,
1131 + }));
1132 + if (readable.length === 0) {
1133 + const errors = viewerResults.flatMap((result) =>
1134 + result.error === null || !selected.some(({ host }) => host === result.host)
1135 + ? []
1136 + : [result.error],
1137 + );
1138 + const blocking = errors.find(isProviderUnusable) ?? errors[0];
1139 + if (blocking) {
1140 + return yield* toPullRequestError("list")(blocking);
1141 }
1142
1098 - const providers: ReadonlyArray<PullRequestProviderSummary> = [
1099 - ...viewerResults.map((result) => {
1100 - const capabilities = projects.find((project) => project.host === result.host)?.api
1101 - .capabilities;
1102 - return {
1103 - host: result.host,
1104 - kind: result.kind,
1105 - searchesOnHost: capabilities?.search ?? false,
1106 - actions: capabilities?.actions ?? [],
1107 - projectCount: projectCounts.get(result.host) ?? 1,
1108 - configured: result.viewer !== null,
1109 - detail: result.error === null ? null : providerDetail(result.error),
1110 - };
1111 - }),
1112 - ...[...unimplemented].map(([host, { kind, projectCount }]) => ({
1113 - host,
1114 - kind,
1115 - searchesOnHost: false,
1116 - actions: [],
1117 - projectCount,
1118 - configured: false,
1119 - detail: "This host cannot be browsed here yet.",
1120 - })),
1121 - ];
1143 + return {
1144 + viewers: viewers as PullRequestListResult["viewers"],
1145 + providers,
1146 + entries: [],
1147 + errors: [],
1148 + truncated: false,
1149 + nextCursors: {},
1150 + };
1151 + }
1152
1123 - const selected =
1124 - continuation === null
1125 - ? projects
1126 - : projects.filter(({ cursorKey }) => continuation.has(cursorKey));
1127 - const readable = selected.filter(({ host }) => viewers[host] !== undefined);
1128 - const unreadable = selected
1129 - .filter(({ host }) => viewers[host] === undefined)
1130 - .map(({ project, repository }) => ({
1131 - projectId: project.id,
1132 - projectTitle: project.title,
1133 - message: `${repository} could not be read.`,
1134 - }));
1135 - if (readable.length === 0) {
1136 - const errors = viewerResults.flatMap((result) =>
1137 - result.error === null || !selected.some(({ host }) => host === result.host)
1138 - ? []
1139 - : [result.error],
1140 - );
1141 - const blocking = errors.find(isProviderUnusable) ?? errors[0];
1142 - if (blocking) {
1143 - return yield* toPullRequestError("list")(blocking);
1144 - }
1153 + const limit = input.limit ?? DEFAULT_REPOSITORY_LIST_LIMIT;
1154 + const cursorOf = (project: SupportedProject): ListCursor | undefined =>
1155 + continuation?.get(project.cursorKey);
1156
1146 - return {
1147 - viewers: viewers as PullRequestListResult["viewers"],
1148 - providers,
1149 - entries: [],
1150 - errors: [],
1151 - truncated: false,
1152 - nextCursors: {},
1153 - };
1157 + const readRepository = (project: SupportedProject): Effect.Effect<RepositoryBatch> => {
1158 + {
1159 + const viewer = viewers[project.host]!;
1160 + const key = project.cursorKey;
1161 + const cursor = cursorOf(project);
1162 + return project.api
1163 + .listChangeRequests({
1164 + cwd: project.project.workspaceRoot,
1165 + repository: project.repository,
1166 + host: project.host,
1167 + state: input.state,
1168 + involvement,
1169 + viewer,
1170 + limit,
1171 + query: input.query,
1172 + filters: input.filters,
1173 + ...(cursor === undefined
1174 + ? {}
1175 + : {
1176 + cursor: {
1177 + updatedBefore: cursor.updatedBefore,
1178 + delivered: cursor.delivered,
1179 + seenAt: cursor.seenAt,
1180 + },
1181 + }),
1182 + })
1183 + .pipe(
1184 + observeRead,
1185 + Effect.map(({ value: page, observedAt }): RepositoryBatch => {
1186 + // The boundary instant was asked for inclusively, so the rows already sent at it
1187 + // come back with the slice. Dropping them here rather than asking for strictly
1188 + // older is what keeps their neighbours at the same instant from being skipped.
1189 + const items =
1190 + cursor === undefined
1191 + ? page.items
1192 + : page.items.filter(
1193 + (item) =>
1194 + item.updatedAt !== cursor.updatedBefore ||
1195 + !cursor.seenAt.includes(item.number),
1196 + );
1197 + return {
1198 + key,
1199 + entries: items
1200 + .filter((item) => matchesRowFilters(item, input.filters, viewer))
1201 + .map((item) => toEntry({ project, item, viewer, observedAt })),
1202 + errors: [],
1203 + truncated: page.truncated,
1204 + nextCursor:
1205 + page.continues && page.truncated
1206 + ? nextListCursor(cursor, page.items, items, page.cursorAdvance)
1207 + : null,
1208 + };
1209 + }),
1210 + Effect.orElseSucceed((): RepositoryBatch => ({
1211 + key,
1212 + entries: [],
1213 + errors: [
1214 + {
1215 + projectId: project.project.id,
1216 + projectTitle: project.project.title,
1217 + message: `${project.repository} could not be read.`,
1218 + },
1219 + ],
1220 + truncated: false,
1221 + nextCursor: null,
1222 + })),
1223 + );
1224 }
1225 + };
1226
1156 - const limit = input.limit ?? DEFAULT_REPOSITORY_LIST_LIMIT;
1157 - const cursorOf = (project: SupportedProject): ListCursor | undefined =>
1158 - continuation?.get(project.cursorKey);
1159 -
1160 - const readRepository = (project: SupportedProject): Effect.Effect<RepositoryBatch> => {
1161 - {
1162 - const viewer = viewers[project.host]!;
1163 - const key = project.cursorKey;
1164 - const cursor = cursorOf(project);
1165 - return project.api
1166 - .listChangeRequests({
1167 - cwd: project.project.workspaceRoot,
1168 - repository: project.repository,
1169 - host: project.host,
1170 - state: input.state,
1171 - involvement,
1172 - viewer,
1173 - limit,
1174 - query: input.query,
1175 - filters: input.filters,
1176 - ...(cursor === undefined
1177 - ? {}
1178 - : {
1179 - cursor: {
1180 - updatedBefore: cursor.updatedBefore,
1181 - delivered: cursor.delivered,
1182 - seenAt: cursor.seenAt,
1183 - },
1184 - }),
1185 - })
1186 - .pipe(
1187 - observeRead,
1188 - Effect.map(({ value: page, observedAt }): RepositoryBatch => {
1189 - // The boundary instant was asked for inclusively, so the rows already sent at it
1190 - // come back with the slice. Dropping them here rather than asking for strictly
1191 - // older is what keeps their neighbours at the same instant from being skipped.
1227 + const readTogether = (
1228 + chunk: ReadonlyArray<SupportedProject>,
1229 + ): Effect.Effect<ReadonlyArray<RepositoryBatch>> => {
1230 + const first = chunk[0]!;
1231 + const readAcross = first.api.listChangeRequestsAcross;
1232 + const separately = () =>
1233 + Effect.forEach(chunk, readRepository, { concurrency: REPOSITORY_CONCURRENCY });
1234 + if (readAcross === undefined) return separately();
1235 + const viewer = viewers[first.host]!;
1236 + const cursor = cursorOf(first);
1237 + return readAcross({
1238 + cwd: first.project.workspaceRoot,
1239 + host: first.host,
1240 + repositories: chunk.map((project) => project.repository),
1241 + state: input.state,
1242 + involvement,
1243 + viewer,
1244 + limit,
1245 + query: input.query,
1246 + filters: input.filters,
1247 + ...(cursor === undefined
1248 + ? {}
1249 + : { cursor: { updatedBefore: cursor.updatedBefore, delivered: cursor.delivered } }),
1250 + }).pipe(
1251 + observeRead,
1252 + Effect.flatMap(({ value: page, observedAt }) =>
1253 + Effect.flatMap(Clock.currentTimeMillis, (now) => {
1254 + const rows = new Map<string, Array<ProviderChangeRequest>>();
1255 + for (const [key, visibleAt] of searchVisibleAt) {
1256 + if (now - visibleAt > Duration.toMillis(SEARCH_VISIBILITY_TTL)) {
1257 + searchVisibleAt.delete(key);
1258 + }
1259 + }
1260 + for (const item of page.items) {
1261 + const key = item.repository.trim().toLowerCase();
1262 + const held = rows.get(key);
1263 + if (held === undefined) rows.set(key, [item]);
1264 + else held.push(item);
1265 + searchVisibleAt.set(searchVisibilityKey(first.host, item.repository), now);
1266 + }
1267 + const boundary = page.items.reduce<string | null>(
1268 + (oldest, item) =>
1269 + oldest === null || item.updatedAt < oldest ? item.updatedAt : oldest,
1270 + null,
1271 + );
1272 + return Effect.forEach(
1273 + chunk,
1274 + (project): Effect.Effect<RepositoryBatch> => {
1275 + const fetched = rows.get(project.repository.trim().toLowerCase()) ?? [];
1276 + // GitHub does not index every repository for search — a renamed one answers for
1277 + // its old name with silence rather than with an error — so a repository the
1278 + // search said nothing at all about is read on its own, once, before it is
1279 + // believed. Only on its first slice: after that it has a boundary to carry on
1280 + // from, and silence past one means the rows are older rather than absent.
1281 + const lastVisible = searchVisibleAt.get(
1282 + searchVisibilityKey(project.host, project.repository),
1283 + );
1284 + const searchIsKnownVisible =
1285 + !page.truncated &&
1286 + lastVisible !== undefined &&
1287 + now - lastVisible <= Duration.toMillis(SEARCH_VISIBILITY_TTL);
1288 + if (
1289 + fetched.length === 0 &&
1290 + cursorOf(project) === undefined &&
1291 + !searchIsKnownVisible
1292 + ) {
1293 + return readRepository(project);
1294 + }
1295 + const cursorHere = cursorOf(project);
1296 const items =
1193 - cursor === undefined
1194 - ? page.items
1195 - : page.items.filter(
1297 + cursorHere === undefined
1298 + ? fetched
1299 + : fetched.filter(
1300 (item) =>
1197 - item.updatedAt !== cursor.updatedBefore ||
1198 - !cursor.seenAt.includes(item.number),
1301 + item.updatedAt !== cursorHere.updatedBefore ||
1302 + !cursorHere.seenAt.includes(item.number),
1303 );
1200 - return {
1201 - key,
1304 + return Effect.succeed({
1305 + key: project.cursorKey,
1306 entries: items
1307 .filter((item) => matchesRowFilters(item, input.filters, viewer))
1308 .map((item) => toEntry({ project, item, viewer, observedAt })),
1309 errors: [],
1310 truncated: page.truncated,
1311 nextCursor:
1208 - page.continues && page.truncated
1209 - ? nextListCursor(cursor, page.items, items, page.cursorAdvance)
1312 + page.truncated && boundary !== null
1313 + ? listCursorAt(cursorHere, boundary, fetched, items.length)
1314 : null,
1211 - };
1212 - }),
1213 - Effect.orElseSucceed((): RepositoryBatch => ({
1214 - key,
1215 - entries: [],
1216 - errors: [
1217 - {
1218 - projectId: project.project.id,
1219 - projectTitle: project.project.title,
1220 - message: `${project.repository} could not be read.`,
1221 - },
1222 - ],
1223 - truncated: false,
1224 - nextCursor: null,
1225 - })),
1315 + });
1316 + },
1317 + { concurrency: REPOSITORY_CONCURRENCY },
1318 );
1227 - }
1228 - };
1229 -
1230 - const readTogether = (
1231 - chunk: ReadonlyArray<SupportedProject>,
1232 - ): Effect.Effect<ReadonlyArray<RepositoryBatch>> => {
1233 - const first = chunk[0]!;
1234 - const readAcross = first.api.listChangeRequestsAcross;
1235 - const separately = () =>
1236 - Effect.forEach(chunk, readRepository, { concurrency: REPOSITORY_CONCURRENCY });
1237 - if (readAcross === undefined) return separately();
1238 - const viewer = viewers[first.host]!;
1239 - const cursor = cursorOf(first);
1240 - return readAcross({
1241 - cwd: first.project.workspaceRoot,
1242 - host: first.host,
1243 - repositories: chunk.map((project) => project.repository),
1244 - state: input.state,
1245 - involvement,
1246 - viewer,
1247 - limit,
1248 - query: input.query,
1249 - filters: input.filters,
1250 - ...(cursor === undefined
1251 - ? {}
1252 - : { cursor: { updatedBefore: cursor.updatedBefore, delivered: cursor.delivered } }),
1253 - }).pipe(
1254 - observeRead,
1255 - Effect.flatMap(({ value: page, observedAt }) =>
1256 - Effect.flatMap(Clock.currentTimeMillis, (now) => {
1257 - const rows = new Map<string, Array<ProviderChangeRequest>>();
1258 - for (const [key, visibleAt] of searchVisibleAt) {
1259 - if (now - visibleAt > Duration.toMillis(SEARCH_VISIBILITY_TTL)) {
1260 - searchVisibleAt.delete(key);
1261 - }
1262 - }
1263 - for (const item of page.items) {
1264 - const key = item.repository.trim().toLowerCase();
1265 - const held = rows.get(key);
1266 - if (held === undefined) rows.set(key, [item]);
1267 - else held.push(item);
1268 - searchVisibleAt.set(searchVisibilityKey(first.host, item.repository), now);
1269 - }
1270 - const boundary = page.items.reduce<string | null>(
1271 - (oldest, item) =>
1272 - oldest === null || item.updatedAt < oldest ? item.updatedAt : oldest,
1273 - null,
1274 - );
1275 - return Effect.forEach(
1276 - chunk,
1277 - (project): Effect.Effect<RepositoryBatch> => {
1278 - const fetched = rows.get(project.repository.trim().toLowerCase()) ?? [];
1279 - // GitHub does not index every repository for search — a renamed one answers for
1280 - // its old name with silence rather than with an error — so a repository the
1281 - // search said nothing at all about is read on its own, once, before it is
1282 - // believed. Only on its first slice: after that it has a boundary to carry on
1283 - // from, and silence past one means the rows are older rather than absent.
1284 - const lastVisible = searchVisibleAt.get(
1285 - searchVisibilityKey(project.host, project.repository),
1286 - );
1287 - const searchIsKnownVisible =
1288 - !page.truncated &&
1289 - lastVisible !== undefined &&
1290 - now - lastVisible <= Duration.toMillis(SEARCH_VISIBILITY_TTL);
1291 - if (
1292 - fetched.length === 0 &&
1293 - cursorOf(project) === undefined &&
1294 - !searchIsKnownVisible
1295 - ) {
1296 - return readRepository(project);
1297 - }
1298 - const cursorHere = cursorOf(project);
1299 - const items =
1300 - cursorHere === undefined
1301 - ? fetched
1302 - : fetched.filter(
1303 - (item) =>
1304 - item.updatedAt !== cursorHere.updatedBefore ||
1305 - !cursorHere.seenAt.includes(item.number),
1306 - );
1307 - return Effect.succeed({
1308 - key: project.cursorKey,
1309 - entries: items
1310 - .filter((item) => matchesRowFilters(item, input.filters, viewer))
1311 - .map((item) => toEntry({ project, item, viewer, observedAt })),
1312 - errors: [],
1313 - truncated: page.truncated,
1314 - nextCursor:
1315 - page.truncated && boundary !== null
1316 - ? listCursorAt(cursorHere, boundary, fetched, items.length)
1317 - : null,
1318 - });
1319 - },
1320 - { concurrency: REPOSITORY_CONCURRENCY },
1321 - );
1322 - }),
1323 - ),
1324 - Effect.catch(separately),
1325 - );
1326 - };
1319 + }),
1320 + ),
1321 + Effect.catch(separately),
1322 + );
1323 + };
1324
1328 - const together = new Map<string, Array<SupportedProject>>();
1329 - const separate: Array<SupportedProject> = [];
1330 - for (const project of readable) {
1331 - if (project.api.listChangeRequestsAcross === undefined) {
1332 - separate.push(project);
1333 - continue;
1334 - }
1335 - const key = `${project.host}\n${cursorOf(project)?.updatedBefore ?? ""}`;
1336 - const group = together.get(key);
1337 - if (group === undefined) together.set(key, [project]);
1338 - else group.push(project);
1325 + const together = new Map<string, Array<SupportedProject>>();
1326 + const separate: Array<SupportedProject> = [];
1327 + for (const project of readable) {
1328 + if (project.api.listChangeRequestsAcross === undefined) {
1329 + separate.push(project);
1330 + continue;
1331 }
1340 - const reads: Array<Effect.Effect<ReadonlyArray<RepositoryBatch>>> = separate.map((project) =>
1341 - readRepository(project).pipe(Effect.map((batch) => [batch])),
1342 - );
1343 - for (const group of together.values()) {
1344 - for (let start = 0; start < group.length; start += REPOSITORY_SEARCH_CHUNK) {
1345 - reads.push(readTogether(group.slice(start, start + REPOSITORY_SEARCH_CHUNK)));
1346 - }
1332 + const key = `${project.host}\n${cursorOf(project)?.updatedBefore ?? ""}`;
1333 + const group = together.get(key);
1334 + if (group === undefined) together.set(key, [project]);
1335 + else group.push(project);
1336 + }
1337 + const reads: Array<Effect.Effect<ReadonlyArray<RepositoryBatch>>> = separate.map((project) =>
1338 + readRepository(project).pipe(Effect.map((batch) => [batch])),
1339 + );
1340 + for (const group of together.values()) {
1341 + for (let start = 0; start < group.length; start += REPOSITORY_SEARCH_CHUNK) {
1342 + reads.push(readTogether(group.slice(start, start + REPOSITORY_SEARCH_CHUNK)));
1343 }
1348 - const batches = (yield* Effect.all(reads, { concurrency: REPOSITORY_CONCURRENCY })).flat();
1344 + }
1345 + const batches = (yield* Effect.all(reads, { concurrency: REPOSITORY_CONCURRENCY })).flat();
1346
1350 - const nextCursors: Record<string, string> = {};
1351 - for (const batch of batches) {
1352 - if (batch.nextCursor !== null) nextCursors[batch.key] = batch.nextCursor;
1353 - }
1347 + const nextCursors: Record<string, string> = {};
1348 + for (const batch of batches) {
1349 + if (batch.nextCursor !== null) nextCursors[batch.key] = batch.nextCursor;
1350 + }
1351
1355 - return {
1356 - viewers: viewers as PullRequestListResult["viewers"],
1357 - providers,
1358 - entries: batches
1359 - .flatMap((batch) => batch.entries)
1360 - .toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)),
1361 - errors: [...unreadable, ...batches.flatMap((batch) => batch.errors)],
1362 - truncated: batches.some((batch) => batch.truncated),
1363 - nextCursors,
1364 - };
1365 - });
1352 + return {
1353 + viewers: viewers as PullRequestListResult["viewers"],
1354 + providers,
1355 + entries: batches
1356 + .flatMap((batch) => batch.entries)
1357 + .toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)),
1358 + errors: [...unreadable, ...batches.flatMap((batch) => batch.errors)],
1359 + truncated: batches.some((batch) => batch.truncated),
1360 + nextCursors,
1361 + };
1362 + });
1363
1364 const viewerOf = (project: SupportedProject): Effect.Effect<string | null> =>
1365 routingCredential.pipe(
@@ -1396,36 +1393,34 @@ export const make = Effect.gen(function* () {
1393 return { ...identity, host, provider: "github" as const };
1394 });
1395
1399 - const withRoutingCredential: PullRequestService["Service"]["withRoutingCredential"] = (
1400 - input,
1401 - operation,
1402 - ) =>
1403 - Effect.gen(function* () {
1404 - if (input.expectedAccountId === undefined) return yield* operation;
1405 - const rejected = () =>
1406 - new PullRequestOperationError({
1407 - operation: "routeIdentity",
1408 - detail: "The GitHub account could not be verified before starting the operation.",
1409 - });
1410 - const project = yield* requireProject(input).pipe(Effect.mapError(rejected));
1411 - const api = registry.get(project.api.kind);
1412 - if (
1413 - api?.withVerifiedCredential === undefined ||
1414 - input.host?.toLowerCase() !== project.host.toLowerCase()
1415 - ) {
1416 - return yield* rejected();
1417 - }
1418 - const result = yield* api
1419 - .withVerifiedCredential(
1420 - { cwd: project.project.workspaceRoot, host: project.host },
1421 - (identity) =>
1422 - identity.accountId === input.expectedAccountId
1423 - ? operation.pipe(Effect.provideService(routingCredential, identity), Effect.result)
1424 - : Effect.fail(rejected()),
1425 - )
1426 - .pipe(Effect.catchTags({ PullRequestProviderError: () => Effect.fail(rejected()) }));
1427 - return yield* Effect.fromResult(result);
1428 - });
1396 + const withRoutingCredential: PullRequestService["Service"]["withRoutingCredential"] = Effect.fn(
1397 + "PullRequestService.withRoutingCredential",
1398 + )(function* (input, operation) {
1399 + if (input.expectedAccountId === undefined) return yield* operation;
1400 + const rejected = () =>
1401 + new PullRequestOperationError({
1402 + operation: "routeIdentity",
1403 + detail: "The GitHub account could not be verified before starting the operation.",
1404 + });
1405 + const project = yield* requireProject(input).pipe(Effect.mapError(rejected));
1406 + const api = registry.get(project.api.kind);
1407 + if (
1408 + api?.withVerifiedCredential === undefined ||
1409 + input.host?.toLowerCase() !== project.host.toLowerCase()
1410 + ) {
1411 + return yield* rejected();
1412 + }
1413 + const result = yield* api
1414 + .withVerifiedCredential(
1415 + { cwd: project.project.workspaceRoot, host: project.host },
1416 + (identity) =>
1417 + identity.accountId === input.expectedAccountId
1418 + ? operation.pipe(Effect.provideService(routingCredential, identity), Effect.result)
1419 + : Effect.fail(rejected()),
1420 + )
1421 + .pipe(Effect.catchTags({ PullRequestProviderError: () => Effect.fail(rejected()) }));
1422 + return yield* Effect.fromResult(result);
1423 + });
1424
1425 const routing = Effect.fn("PullRequestService.routing")(function* (input: PullRequestRef) {
1426 const project = yield* requireProject(input);
@@ -2351,78 +2346,78 @@ export const make = Effect.gen(function* () {
2346 * The line counts for rows already on the page, which the listing left out because on GitHub
2347 * they cost more than everything else on the row put together.
2348 */
2354 - const listStatsUncached: PullRequestService["Service"]["listStats"] = (input) =>
2355 - Effect.gen(function* () {
2356 - if (input.refs.length === 0) return { stats: [] };
2357 - const { supported } = yield* listWorkspaceProjects({});
2358 - const byProject = new Map(supported.map((project) => [project.project.id, project]));
2359 - const wanted = new Map<
2360 - string,
2361 - { readonly project: SupportedProject; readonly number: number }
2362 - >();
2363 - for (const ref of input.refs) {
2364 - const project = byProject.get(ref.projectId);
2365 - if (
2366 - project === undefined ||
2367 - project.api.listChangeRequestStats === undefined ||
2368 - project.repository.toLowerCase() !== ref.repository.trim().toLowerCase()
2369 - ) {
2370 - continue;
2371 - }
2372 - wanted.set(`${project.project.id} ${ref.number}`, { project, number: ref.number });
2373 - }
2374 - const byHost = new Map<string, Array<{ project: SupportedProject; number: number }>>();
2375 - for (const entry of wanted.values()) {
2376 - const held = byHost.get(entry.project.host);
2377 - if (held === undefined) byHost.set(entry.project.host, [entry]);
2378 - else held.push(entry);
2349 + const listStatsUncached: PullRequestService["Service"]["listStats"] = Effect.fn(
2350 + "PullRequestService.listStatsUncached",
2351 + )(function* (input) {
2352 + if (input.refs.length === 0) return { stats: [] };
2353 + const { supported } = yield* listWorkspaceProjects({});
2354 + const byProject = new Map(supported.map((project) => [project.project.id, project]));
2355 + const wanted = new Map<
2356 + string,
2357 + { readonly project: SupportedProject; readonly number: number }
2358 + >();
2359 + for (const ref of input.refs) {
2360 + const project = byProject.get(ref.projectId);
2361 + if (
2362 + project === undefined ||
2363 + project.api.listChangeRequestStats === undefined ||
2364 + project.repository.toLowerCase() !== ref.repository.trim().toLowerCase()
2365 + ) {
2366 + continue;
2367 }
2380 - const stats = yield* Effect.forEach(
2381 - [...byHost.values()],
2382 - (entries) => {
2383 - const first = entries[0]!;
2384 - const readStats = first.project.api.listChangeRequestStats;
2385 - if (readStats === undefined)
2386 - return Effect.succeed<ReadonlyArray<PullRequestDiffStat>>([]);
2387 - const projectsByRepository = new Map(
2388 - entries.map((entry) => [
2389 - `${entry.project.repository.toLowerCase()} ${entry.number}`,
2390 - entry.project,
2391 - ]),
2392 - );
2393 - return readStats({
2394 - cwd: first.project.project.workspaceRoot,
2395 - host: first.project.host,
2396 - changeRequests: entries.map((entry) => ({
2397 - repository: entry.project.repository,
2398 - number: entry.number,
2399 - })),
2400 - }).pipe(
2401 - Effect.map((read) =>
2402 - read.flatMap((stat): ReadonlyArray<PullRequestDiffStat> => {
2403 - const project = projectsByRepository.get(
2404 - `${stat.repository.toLowerCase()} ${stat.number}`,
2405 - );
2406 - return project === undefined
2407 - ? []
2408 - : [
2409 - {
2410 - projectId: project.project.id,
2411 - repository: project.repository,
2412 - number: stat.number,
2413 - additions: stat.additions,
2414 - deletions: stat.deletions,
2415 - },
2416 - ];
2417 - }),
2418 - ),
2419 - Effect.orElseSucceed((): ReadonlyArray<PullRequestDiffStat> => []),
2420 - );
2421 - },
2422 - { concurrency: REPOSITORY_CONCURRENCY },
2423 - );
2424 - return { stats: stats.flat() };
2425 - });
2368 + wanted.set(`${project.project.id} ${ref.number}`, { project, number: ref.number });
2369 + }
2370 + const byHost = new Map<string, Array<{ project: SupportedProject; number: number }>>();
2371 + for (const entry of wanted.values()) {
2372 + const held = byHost.get(entry.project.host);
2373 + if (held === undefined) byHost.set(entry.project.host, [entry]);
2374 + else held.push(entry);
2375 + }
2376 + const stats = yield* Effect.forEach(
2377 + [...byHost.values()],
2378 + (entries) => {
2379 + const first = entries[0]!;
2380 + const readStats = first.project.api.listChangeRequestStats;
2381 + if (readStats === undefined) return Effect.succeed<ReadonlyArray<PullRequestDiffStat>>([]);
2382 + const projectsByRepository = new Map(
2383 + entries.map((entry) => [
2384 + `${entry.project.repository.toLowerCase()} ${entry.number}`,
2385 + entry.project,
2386 + ]),
2387 + );
2388 + return readStats({
2389 + cwd: first.project.project.workspaceRoot,
2390 + host: first.project.host,
2391 + changeRequests: entries.map((entry) => ({
2392 + repository: entry.project.repository,
2393 + number: entry.number,
2394 + })),
2395 + }).pipe(
2396 + Effect.map((read) =>
2397 + read.flatMap((stat): ReadonlyArray<PullRequestDiffStat> => {
2398 + const project = projectsByRepository.get(
2399 + `${stat.repository.toLowerCase()} ${stat.number}`,
2400 + );
2401 + return project === undefined
2402 + ? []
2403 + : [
2404 + {
2405 + projectId: project.project.id,
2406 + repository: project.repository,
2407 + number: stat.number,
2408 + additions: stat.additions,
2409 + deletions: stat.deletions,
2410 + },
2411 + ];
2412 + }),
2413 + ),
2414 + Effect.orElseSucceed((): ReadonlyArray<PullRequestDiffStat> => []),
2415 + );
2416 + },
2417 + { concurrency: REPOSITORY_CONCURRENCY },
2418 + );
2419 + return { stats: stats.flat() };
2420 + });
2421
2422 const revalidate = <A, E>(read: Effect.Effect<A, E>) =>
2423 Effect.context<never>().pipe(
@@ -3270,30 +3265,29 @@ export const make = Effect.gen(function* () {
3265 const fileKey = (oldPath: string, newPath: string) => JSON.stringify([oldPath, newPath]);
3266 const sliceKey = (input: PullRequestDiffInput) =>
3267 JSON.stringify([refCacheKey(input), input.cursor ?? null, input.commit ?? null]);
3273 - const read = (input: PullRequestDiffInput) =>
3274 - Effect.gen(function* () {
3275 - const key = sliceKey(input);
3276 - const now = yield* Clock.currentTimeMillis;
3277 - const cached = held.get(key);
3278 - if (cached !== undefined && now - cached.at <= ttlMs) return cached;
3279 - const slice = yield* diff(input);
3280 - const entry = {
3281 - at: now,
3282 - files: new Set(
3283 - parseDiffFilePaths(slice.patch).map((file) =>
3284 - fileKey(file.oldPath ?? file.newPath ?? "", file.newPath ?? file.oldPath ?? ""),
3285 - ),
3268 + const read = Effect.fn("PullRequestService.read")(function* (input: PullRequestDiffInput) {
3269 + const key = sliceKey(input);
3270 + const now = yield* Clock.currentTimeMillis;
3271 + const cached = held.get(key);
3272 + if (cached !== undefined && now - cached.at <= ttlMs) return cached;
3273 + const slice = yield* diff(input);
3274 + const entry = {
3275 + at: now,
3276 + files: new Set(
3277 + parseDiffFilePaths(slice.patch).map((file) =>
3278 + fileKey(file.oldPath ?? file.newPath ?? "", file.newPath ?? file.oldPath ?? ""),
3279 ),
3287 - nextCursor: slice.nextCursor,
3288 - };
3289 - held.delete(key);
3290 - if (held.size >= DIFF_CACHE_CAPACITY) {
3291 - const oldest = held.keys().next().value;
3292 - if (oldest !== undefined) held.delete(oldest);
3293 - }
3294 - held.set(key, entry);
3295 - return entry;
3296 - });
3280 + ),
3281 + nextCursor: slice.nextCursor,
3282 + };
3283 + held.delete(key);
3284 + if (held.size >= DIFF_CACHE_CAPACITY) {
3285 + const oldest = held.keys().next().value;
3286 + if (oldest !== undefined) held.delete(oldest);
3287 + }
3288 + held.set(key, entry);
3289 + return entry;
3290 + });
3291 return { read: credentialCached(read), fileKey };
3292 })();
3293 /**
apps/server/src/pullRequest/pullRequestViewedFiles.ts
+14 -12
@@ -196,11 +196,11 @@ export const make = (dependencies: Dependencies) => {
196 cause,
197 });
198
199 - const environmentFilesViewed = (
200 - project: SupportedProject,
201 - ref: PullRequestRef,
202 - ): Effect.Effect<PullRequestFilesViewedResult, PullRequestError> =>
203 - Effect.gen(function* () {
199 + const environmentFilesViewed = Effect.fn("pullRequestViewedFiles.environmentFilesViewed")(
200 + function* (
201 + project: SupportedProject,
202 + ref: PullRequestRef,
203 + ): Effect.fn.Return<PullRequestFilesViewedResult, PullRequestError> {
204 const viewer = yield* requiredViewerOf(project, "filesViewed");
205 const held = yield* filesViewedStore
206 .list(filesViewedScope(project, ref.number, viewer))
@@ -234,7 +234,8 @@ export const make = (dependencies: Dependencies) => {
234 }),
235 truncated: held.truncated,
236 };
237 - });
237 + },
238 + );
239
240 /**
241 * A tick's host round trip is slower than an untick's, so unordered presses could finish
@@ -271,11 +272,11 @@ export const make = (dependencies: Dependencies) => {
272 );
273 });
274
274 - const environmentSetFilesViewed = (
275 - project: SupportedProject,
276 - input: PullRequestSetFilesViewedInput,
277 - ): Effect.Effect<void, PullRequestError> =>
278 - Effect.gen(function* () {
275 + const environmentSetFilesViewed = Effect.fn("pullRequestViewedFiles.environmentSetFilesViewed")(
276 + function* (
277 + project: SupportedProject,
278 + input: PullRequestSetFilesViewedInput,
279 + ): Effect.fn.Return<void, PullRequestError> {
280 const viewer = yield* requiredViewerOf(project, "setFilesViewed");
281 const cleared = input.files.filter((file) => file.viewed).map((file) => file.path);
282 const revisions =
@@ -304,7 +305,8 @@ export const make = (dependencies: Dependencies) => {
305 viewedAt,
306 })
307 .pipe(Effect.mapError(toFilesViewedStoreError("setFilesViewed")));
307 - });
308 + },
309 + );
310
311 const filesViewed = (input: PullRequestRef) =>
312 requireProject(input).pipe(
apps/server/src/relay/AgentAwarenessRelay.test.ts
+25
@@ -15,6 +15,7 @@ import {
15 TurnItemId,
16 } from "@t3tools/contracts";
17 import { RelayAgentActivityState } from "@t3tools/contracts/relay";
18 +import { RelayClientTracer } from "@t3tools/shared/relayTracing";
19 import * as DateTime from "effect/DateTime";
20 import * as Deferred from "effect/Deferred";
21 import * as Effect from "effect/Effect";
@@ -24,6 +25,7 @@ import * as Queue from "effect/Queue";
25 import * as Ref from "effect/Ref";
26 import * as Schema from "effect/Schema";
27 import * as Stream from "effect/Stream";
28 +import * as Tracer from "effect/Tracer";
29 import * as TestClock from "effect/testing/TestClock";
30 import * as FetchHttpClient from "effect/http/FetchHttpClient";
31
@@ -373,6 +375,29 @@ describe("AgentAwarenessRelay", () => {
375 }),
376 );
377
378 + it.effect("exports the publication span through the relay tracer", () => {
379 + const relaySpans: string[] = [];
380 + const localSpans: string[] = [];
381 + const collectingTracer = (spans: string[]) =>
382 + Tracer.make({
383 + span: (options) => {
384 + spans.push(options.name);
385 + return new Tracer.NativeSpan(options);
386 + },
387 + });
388 +
389 + return Effect.gen(function* () {
390 + const { relay, publications } = yield* makeTestRelay();
391 + yield* relay.publishThread(THREAD_ID);
392 + assert.equal(publications.length, 1);
393 + assert.include(relaySpans, "relay.agent_activity.publish");
394 + assert.notInclude(localSpans, "relay.agent_activity.publish");
395 + }).pipe(
396 + Effect.provideService(RelayClientTracer, Option.some(collectingTracer(relaySpans))),
397 + Effect.withTracer(collectingTracer(localSpans)),
398 + );
399 + });
400 +
401 it.effect("deduplicates state and republishes title changes", () =>
402 Effect.gen(function* () {
403 const { relay, currentShell, publications } = yield* makeTestRelay();
apps/server/src/relay/AgentAwarenessRelay.ts
+68 -67
@@ -462,54 +462,53 @@ export const make = Effect.gen(function* () {
462 }
463 const environmentId = yield* serverEnvironment.getEnvironmentId;
464
465 - const publishState = (input: {
465 + const publishState = Effect.fn("relay.agent_activity.publish")(function* (input: {
466 readonly projectId: string | null;
467 readonly state: RelayAgentActivityState | null;
468 readonly reason: string;
469 - }) =>
470 - Effect.gen(function* () {
471 - if (cachedRelayClient === undefined) {
472 - cachedRelayClient = yield* makeRelayClient(relayConfig);
473 - }
474 - const relayClient = cachedRelayClient;
475 - const proof = yield* makePublishProof({
476 - privateKey: cloudLinkKeyPair.privateKey,
477 - relayIssuer: relayConfig.issuer,
478 - environmentId,
479 - threadId,
480 - state: input.state,
481 - jti: yield* crypto.randomUUIDv4(),
482 - });
469 + }) {
470 + if (cachedRelayClient === undefined) {
471 + cachedRelayClient = yield* makeRelayClient(relayConfig);
472 + }
473 + const relayClient = cachedRelayClient;
474 + const proof = yield* makePublishProof({
475 + privateKey: cloudLinkKeyPair.privateKey,
476 + relayIssuer: relayConfig.issuer,
477 + environmentId,
478 + threadId,
479 + state: input.state,
480 + jti: yield* crypto.randomUUIDv4(),
481 + });
482
484 - yield* Effect.logInfo("publishing agent activity for thread", {
485 - environmentId,
486 - threadId,
487 - projectId: input.projectId,
488 - statePhase: input.state?.phase ?? null,
489 - hasState: input.state !== null,
490 - reason: input.reason,
491 - });
483 + yield* Effect.logInfo("publishing agent activity for thread", {
484 + environmentId,
485 + threadId,
486 + projectId: input.projectId,
487 + statePhase: input.state?.phase ?? null,
488 + hasState: input.state !== null,
489 + reason: input.reason,
490 + });
491
493 - const response = yield* relayClient.server
494 - .publishAgentActivity({
495 - params: {
496 - environmentId,
497 - threadId,
498 - },
499 - payload: {
500 - state: input.state,
501 - proof,
502 - },
503 - })
504 - .pipe(Effect.timeout("10 seconds"));
505 -
506 - yield* Effect.logInfo("agent activity publish completed", {
507 - environmentId,
508 - threadId,
509 - ok: response.ok,
510 - deliveries: deliveryStats(response.deliveries),
511 - });
512 - }).pipe(Effect.withSpan("relay.agent_activity.publish"), withRelayClientTracing);
492 + const response = yield* relayClient.server
493 + .publishAgentActivity({
494 + params: {
495 + environmentId,
496 + threadId,
497 + },
498 + payload: {
499 + state: input.state,
500 + proof,
501 + },
502 + })
503 + .pipe(Effect.timeout("10 seconds"));
504 +
505 + yield* Effect.logInfo("agent activity publish completed", {
506 + environmentId,
507 + threadId,
508 + ok: response.ok,
509 + deliveries: deliveryStats(response.deliveries),
510 + });
511 + });
512
513 // Per-thread shell read: this publish runs for every activity-relevant
514 // domain event, so materializing the full shell here would make the cost
@@ -614,7 +613,7 @@ export const make = Effect.gen(function* () {
613 projectId: snapshot.projectId,
614 state: snapshot.state,
615 reason: snapshot.reason,
617 - });
616 + }).pipe(withRelayClientTracing);
617 publishConfirmDeadlines.delete(threadId);
618 yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {
619 const nextPublishedStates = new Map(publishedStates);
@@ -729,31 +728,33 @@ export const make = Effect.gen(function* () {
728
729 // Many environments never link, so while unlinked the retry backs off from 5
730 // s to 60 s. A linked environment keeps the 5 s retry, because `t3 connect
732 - // publish` can turn publishing on from another process.
733 - const publishActiveThreadsOnceWhenConfigured = (logEnabledWhenReady: boolean) =>
734 - Effect.gen(function* () {
735 - let unlinkedRetryDelayMs = 5_000;
736 - while (!(yield* Ref.get(activeSnapshotPublishedRef))) {
737 - const result = yield* publishActiveThreadsUnsafe.pipe(
738 - Effect.orElseSucceed(() => "failed" as const),
739 - );
740 - if (result === "published") {
741 - yield* Ref.set(activeSnapshotPublishedRef, true);
742 - if (logEnabledWhenReady) {
743 - const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
744 - yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
745 - relayUrl: relayConfig?.url,
746 - });
747 - }
748 - return;
749 - }
750 - const retryDelayMs = result === "unlinked" ? unlinkedRetryDelayMs : 5_000;
751 - yield* Effect.race(Effect.sleep(retryDelayMs), Queue.take(catchUpRequests));
752 - if (result === "unlinked") {
753 - unlinkedRetryDelayMs = Math.min(unlinkedRetryDelayMs * 2, 60_000);
731 + // publish` can turn publishing on from another process. Keep this untraced:
732 + // an unlinked environment can retry for the lifetime of the process.
733 + const publishActiveThreadsOnceWhenConfigured = Effect.fnUntraced(function* (
734 + logEnabledWhenReady: boolean,
735 + ) {
736 + let unlinkedRetryDelayMs = 5_000;
737 + while (!(yield* Ref.get(activeSnapshotPublishedRef))) {
738 + const result = yield* publishActiveThreadsUnsafe.pipe(
739 + Effect.orElseSucceed(() => "failed" as const),
740 + );
741 + if (result === "published") {
742 + yield* Ref.set(activeSnapshotPublishedRef, true);
743 + if (logEnabledWhenReady) {
744 + const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
745 + yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {
746 + relayUrl: relayConfig?.url,
747 + });
748 }
749 + return;
750 }
756 - });
751 + const retryDelayMs = result === "unlinked" ? unlinkedRetryDelayMs : 5_000;
752 + yield* Effect.race(Effect.sleep(retryDelayMs), Queue.take(catchUpRequests));
753 + if (result === "unlinked") {
754 + unlinkedRetryDelayMs = Math.min(unlinkedRetryDelayMs * 2, 60_000);
755 + }
756 + }
757 + });
758
759 schedulePublishConfirm = (threadId) =>
760 Effect.forkIn(
apps/server/src/resourceTelemetry/NativeTelemetryClient.ts
+90 -90
@@ -279,23 +279,22 @@ export function resolveNativeSampleIntervalMs(
279 return SAMPLE_INTERVAL_MS;
280 }
281
282 -export function commitCollectionControlUpdate<E, R>(
282 +// Desktop power samples also commit control state; avoid a span for each sample.
283 +export const commitCollectionControlUpdate = Effect.fnUntraced(function* <E, R>(
284 desiredState: Ref.Ref<CollectionControl>,
285 appliedState: Ref.Ref<CollectionControl>,
286 update: (current: CollectionControl) => CollectionControl,
287 apply: (previous: CollectionControl, next: CollectionControl) => Effect.Effect<void, E, R>,
287 -): Effect.Effect<readonly [CollectionControl, CollectionControl], E, R> {
288 - return Effect.gen(function* () {
289 - const [previousDesired, next] = yield* Ref.modify(desiredState, (previous) => {
290 - const next = update(previous);
291 - return [[previous, next] as const, next];
292 - });
293 - const previousApplied = yield* Ref.get(appliedState);
294 - yield* apply(previousApplied, next);
295 - yield* Ref.set(appliedState, next);
296 - return [previousDesired, next] as const;
288 +): Effect.fn.Return<readonly [CollectionControl, CollectionControl], E, R> {
289 + const [previousDesired, next] = yield* Ref.modify(desiredState, (previous) => {
290 + const next = update(previous);
291 + return [[previous, next] as const, next];
292 });
298 -}
293 + const previousApplied = yield* Ref.get(appliedState);
294 + yield* apply(previousApplied, next);
295 + yield* Ref.set(appliedState, next);
296 + return [previousDesired, next] as const;
297 +});
298
299 export function synchronizeCollectionControlOnStart<E1, R1, E2, R2>(
300 mutex: Semaphore.Semaphore,
@@ -411,23 +410,22 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
410 Effect.asVoid,
411 );
412
414 - const failPending = (error: NativeTelemetryClientError) =>
415 - Effect.gen(function* () {
416 - const samples = yield* Ref.getAndSet(pendingSamples, new Map());
417 - const processTables = yield* Ref.getAndSet(pendingProcessTables, new Map());
418 - const histories = yield* Ref.getAndSet(pendingHistories, new Map());
419 - yield* Effect.forEach(samples.values(), (deferred) => Deferred.fail(deferred, error), {
420 - discard: true,
421 - });
422 - yield* Effect.forEach(processTables.values(), (deferred) => Deferred.fail(deferred, error), {
423 - discard: true,
424 - });
425 - yield* Effect.forEach(
426 - histories.values(),
427 - (request) => Deferred.fail(request.deferred, error),
428 - { discard: true },
429 - );
413 + const failPending = Effect.fn("NativeTelemetryClient.failPending")(function* (
414 + error: NativeTelemetryClientError,
415 + ) {
416 + const samples = yield* Ref.getAndSet(pendingSamples, new Map());
417 + const processTables = yield* Ref.getAndSet(pendingProcessTables, new Map());
418 + const histories = yield* Ref.getAndSet(pendingHistories, new Map());
419 + yield* Effect.forEach(samples.values(), (deferred) => Deferred.fail(deferred, error), {
420 + discard: true,
421 + });
422 + yield* Effect.forEach(processTables.values(), (deferred) => Deferred.fail(deferred, error), {
423 + discard: true,
424 + });
425 + yield* Effect.forEach(histories.values(), (request) => Deferred.fail(request.deferred, error), {
426 + discard: true,
427 });
428 + });
429
430 const writeCommand = (
431 handle: ChildProcessSpawner.ChildProcessHandle,
@@ -777,9 +775,11 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
775 Effect.forkScoped,
776 );
777
780 - const applyCollectionControl = Effect.fn(
781 - "resourceTelemetry.nativeTelemetryClient.applyCollectionControl",
782 - )(function* (previous: CollectionControl, next: CollectionControl) {
778 + // Desktop power samples reach this even when the control state has not changed.
779 + const applyCollectionControl = Effect.fnUntraced(function* (
780 + previous: CollectionControl,
781 + next: CollectionControl,
782 + ) {
783 const current = yield* Ref.get(state);
784 if (canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) {
785 const handle = Option.getOrThrow(current.handle);
@@ -842,10 +842,9 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
842 }),
843 );
844
845 - const setExternalProcesses: NativeTelemetryClient["Service"]["setExternalProcesses"] = (
846 - processes,
847 - ) =>
848 - Effect.gen(function* () {
845 + // Desktop telemetry refreshes this process set on every sample.
846 + const setExternalProcesses: NativeTelemetryClient["Service"]["setExternalProcesses"] =
847 + Effect.fnUntraced(function* (processes) {
848 yield* Ref.set(externalProcesses, [...processes]);
849 const current = yield* Ref.get(state);
850 if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) return;
@@ -856,64 +855,65 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
855 });
856 });
857
859 - const readHistory: NativeTelemetryClient["Service"]["readHistory"] = (windowMs) =>
860 - Effect.gen(function* () {
861 - const current = yield* Ref.get(state);
862 - if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) {
863 - return yield* new NativeTelemetryUnavailable({
864 - reason: Option.getOrElse(current.lastError, () => "sidecar is not running"),
865 - });
866 - }
867 - const requestId = yield* crypto.randomUUIDv4().pipe(
868 - Effect.mapError(
869 - (cause) =>
870 - new NativeTelemetryCommandFailed({
871 - operation: "createHistoryRequestId",
872 - cause,
873 - }),
874 - ),
875 - );
876 - const deferred = yield* Deferred.make<
877 - ReadonlyArray<ResourceMonitorSnapshotEvent>,
878 - NativeTelemetryClientError
879 - >();
880 - yield* Ref.update(pendingHistories, (pending) => {
881 - const next = new Map(pending);
882 - next.set(requestId, { deferred, snapshots: [] });
883 - return next;
858 + const readHistory: NativeTelemetryClient["Service"]["readHistory"] = Effect.fn(
859 + "NativeTelemetryClient.readHistory",
860 + )(function* (windowMs) {
861 + const current = yield* Ref.get(state);
862 + if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) {
863 + return yield* new NativeTelemetryUnavailable({
864 + reason: Option.getOrElse(current.lastError, () => "sidecar is not running"),
865 });
885 - return yield* writeCommand(Option.getOrThrow(current.handle), {
886 - version: RESOURCE_MONITOR_PROTOCOL_VERSION,
887 - type: "readHistory",
888 - requestId,
889 - windowMs: Math.max(0, Math.round(windowMs)),
890 - }).pipe(
891 - Effect.andThen(
892 - Deferred.await(deferred).pipe(
893 - Effect.timeoutOption(HISTORY_REQUEST_TIMEOUT),
894 - Effect.flatMap(
895 - Option.match({
896 - onNone: () =>
897 - Effect.fail(
898 - new NativeTelemetryRequestTimedOut({
899 - operation: "readHistory",
900 - timeoutMs: Duration.toMillis(HISTORY_REQUEST_TIMEOUT),
901 - }),
902 - ),
903 - onSome: Effect.succeed,
904 - }),
905 - ),
906 - ),
907 - ),
908 - Effect.ensuring(
909 - Ref.update(pendingHistories, (pending) => {
910 - const next = new Map(pending);
911 - next.delete(requestId);
912 - return next;
866 + }
867 + const requestId = yield* crypto.randomUUIDv4().pipe(
868 + Effect.mapError(
869 + (cause) =>
870 + new NativeTelemetryCommandFailed({
871 + operation: "createHistoryRequestId",
872 + cause,
873 }),
914 - ),
915 - );
874 + ),
875 + );
876 + const deferred = yield* Deferred.make<
877 + ReadonlyArray<ResourceMonitorSnapshotEvent>,
878 + NativeTelemetryClientError
879 + >();
880 + yield* Ref.update(pendingHistories, (pending) => {
881 + const next = new Map(pending);
882 + next.set(requestId, { deferred, snapshots: [] });
883 + return next;
884 });
885 + return yield* writeCommand(Option.getOrThrow(current.handle), {
886 + version: RESOURCE_MONITOR_PROTOCOL_VERSION,
887 + type: "readHistory",
888 + requestId,
889 + windowMs: Math.max(0, Math.round(windowMs)),
890 + }).pipe(
891 + Effect.andThen(
892 + Deferred.await(deferred).pipe(
893 + Effect.timeoutOption(HISTORY_REQUEST_TIMEOUT),
894 + Effect.flatMap(
895 + Option.match({
896 + onNone: () =>
897 + Effect.fail(
898 + new NativeTelemetryRequestTimedOut({
899 + operation: "readHistory",
900 + timeoutMs: Duration.toMillis(HISTORY_REQUEST_TIMEOUT),
901 + }),
902 + ),
903 + onSome: Effect.succeed,
904 + }),
905 + ),
906 + ),
907 + ),
908 + Effect.ensuring(
909 + Ref.update(pendingHistories, (pending) => {
910 + const next = new Map(pending);
911 + next.delete(requestId);
912 + return next;
913 + }),
914 + ),
915 + );
916 + });
917
918 const sampleNow: NativeTelemetryClient["Service"]["sampleNow"] = Effect.gen(function* () {
919 const current = yield* Ref.get(state);
apps/server/src/resourceTelemetry/ResourceTelemetry.ts
+33 -33
@@ -333,8 +333,9 @@ export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(functi
333
334 const ingestNative = (snapshot: NativeTelemetryClient.NativeTelemetrySnapshot) =>
335 rebuild({ nativeSnapshot: snapshot, updatePrevious: true });
336 - const ingestDesktop = (snapshot: DesktopHostTelemetrySnapshot) =>
337 - Effect.gen(function* () {
336 + const ingestDesktop =
337 + /* Desktop samples arrive continuously; avoid a span per telemetry sample. */
338 + Effect.fnUntraced(function* (snapshot: DesktopHostTelemetrySnapshot) {
339 const electronRoot = snapshot.electronProcesses.find(
340 (process) => process.pid === snapshot.electronPid,
341 );
@@ -412,39 +413,38 @@ export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(functi
413 );
414 const liveChanges = Stream.unwrap(Effect.map(subscribe, ({ changes }) => changes));
415
415 - const readHistory: ResourceTelemetry["Service"]["readHistory"] = (input) =>
416 - Effect.gen(function* () {
417 - const readAt = yield* DateTime.now;
418 - const normalizedInput = normalizeResourceTelemetryHistoryInput(input);
419 - const historyResult = yield* Effect.result(
420 - nativeClient.readHistory(normalizedInput.windowMs),
421 - );
422 - if (Result.isFailure(historyResult)) {
423 - yield* Effect.logWarning("Failed to read native resource telemetry history", {
424 - cause: historyResult.failure.message,
425 - });
426 - }
427 - const [nativeHealth, desktopHealth] = yield* Effect.all([
428 - nativeClient.health,
429 - desktopReceiver.health,
430 - ]);
431 - const current = yield* Ref.get(state);
432 - return buildResourceTelemetryHistory({
433 - readAt,
434 - windowMs: normalizedInput.windowMs,
435 - bucketMs: normalizedInput.bucketMs,
436 - sampleIntervalMs: nativeHealth.sampleIntervalMs,
437 - serverPid: process.pid,
438 - sidecarPid: Option.map(nativeHealth.hello, (hello) => hello.sidecarPid),
439 - desktopSnapshot: current.desktopSnapshot,
440 - snapshots: Result.isSuccess(historyResult) ? historyResult.success : [],
441 - health: buildHealth({
442 - native: nativeHealth,
443 - desktop: desktopHealth,
444 - nativeSnapshot: current.nativeSnapshot,
445 - }),
416 + const readHistory: ResourceTelemetry["Service"]["readHistory"] = Effect.fn(
417 + "ResourceTelemetry.readHistory",
418 + )(function* (input) {
419 + const readAt = yield* DateTime.now;
420 + const normalizedInput = normalizeResourceTelemetryHistoryInput(input);
421 + const historyResult = yield* Effect.result(nativeClient.readHistory(normalizedInput.windowMs));
422 + if (Result.isFailure(historyResult)) {
423 + yield* Effect.logWarning("Failed to read native resource telemetry history", {
424 + cause: historyResult.failure.message,
425 });
426 + }
427 + const [nativeHealth, desktopHealth] = yield* Effect.all([
428 + nativeClient.health,
429 + desktopReceiver.health,
430 + ]);
431 + const current = yield* Ref.get(state);
432 + return buildResourceTelemetryHistory({
433 + readAt,
434 + windowMs: normalizedInput.windowMs,
435 + bucketMs: normalizedInput.bucketMs,
436 + sampleIntervalMs: nativeHealth.sampleIntervalMs,
437 + serverPid: process.pid,
438 + sidecarPid: Option.map(nativeHealth.hello, (hello) => hello.sidecarPid),
439 + desktopSnapshot: current.desktopSnapshot,
440 + snapshots: Result.isSuccess(historyResult) ? historyResult.success : [],
441 + health: buildHealth({
442 + native: nativeHealth,
443 + desktop: desktopHealth,
444 + nativeSnapshot: current.nativeSnapshot,
445 + }),
446 });
447 + });
448 yield* nativeHealthSubscription.changes.pipe(
449 Stream.runForEach(() => refreshHealth),
450 Effect.forkScoped,
apps/server/src/scheduledTasks/RelayDeliveryProof.ts
+5 -3
@@ -44,8 +44,8 @@ export class RelayDeliveryProof extends Context.Service<
44 const make = Effect.gen(function* () {
45 const secrets = yield* ServerSecretStore.ServerSecretStore;
46 const environment = yield* ServerEnvironment.ServerEnvironment;
47 - const verify: RelayDeliveryProof["Service"]["verify"] = (input) =>
48 - Effect.gen(function* () {
47 + const verify: RelayDeliveryProof["Service"]["verify"] = Effect.fn("webhook.verifyRelayDelivery")(
48 + function* (input) {
49 const proof = input.headers[RELAY_HOOK_DELIVERY_HEADER];
50 const deliveryId = input.headers["x-t3-relay-delivery-id"];
51 const receivedAt = input.headers["x-t3-relay-received-at"];
@@ -80,7 +80,9 @@ const make = Effect.gen(function* () {
80 return Option.none();
81 }
82 return Option.some({ deliveryId, receivedAt });
83 - }).pipe(Effect.orElseSucceed(Option.none), Effect.withSpan("webhook.verifyRelayDelivery"));
83 + },
84 + Effect.orElseSucceed(Option.none),
85 + );
86 return RelayDeliveryProof.of({ verify });
87 });
88
apps/server/src/scheduledTasks/ScheduledTaskService.ts
+474 -464
@@ -281,8 +281,9 @@ function webhookEndpoint(
281 };
282 }
283
284 -const decodeRow = (row: ScheduledTaskRow, origin: WebhookOrigin | null = null) =>
285 - Effect.gen(function* () {
284 +// Runs per task row; list and lookup operations already own the span.
285 +const decodeRow = Effect.fnUntraced(
286 + function* (row: ScheduledTaskRow, origin: WebhookOrigin | null = null) {
287 const schedule = yield* decodeScheduleJson(row.schedule_json);
288 const webhook = schedule.type === "webhook" ? webhookEndpoint(row, origin) : undefined;
289 const workspaceStrategy = yield* decodeWorkspaceStrategyJson(row.workspace_strategy_json);
@@ -310,15 +311,18 @@ const decodeRow = (row: ScheduledTaskRow, origin: WebhookOrigin | null = null) =
311 runCount: row.run_count,
312 ...(webhook === undefined ? {} : { webhook }),
313 });
313 - }).pipe(
314 - Effect.mapError((cause) => {
315 - const taskId = decodeTaskId(row.task_id);
316 - return taskError("Could not decode schedule task row.", {
317 - ...(Option.isSome(taskId) ? { taskId: taskId.value } : {}),
318 - cause,
319 - });
320 - }),
321 - );
314 + },
315 + (effect, row, _origin?) =>
316 + effect.pipe(
317 + Effect.mapError((cause) => {
318 + const taskId = decodeTaskId(row.task_id);
319 + return taskError("Could not decode schedule task row.", {
320 + ...(Option.isSome(taskId) ? { taskId: taskId.value } : {}),
321 + cause,
322 + });
323 + }),
324 + ),
325 +);
326
327 export const listDueTasks = Effect.fn("ScheduledTaskService.listDueTasks")(function* (
328 now: DateTime.DateTime,
@@ -639,8 +643,8 @@ export const layer = Layer.effect(
643 // the task forever (it filters out 'running' rows) nor re-fires it
644 // immediately: the dispatch may already have gone out, so next_run_at must
645 // advance and run_count must count the attempt.
642 - const releaseStuckRun = (task: ScheduledTask, message: string) =>
643 - Effect.gen(function* () {
646 + const releaseStuckRun = Effect.fn("ScheduledTaskService.releaseStuckRun")(
647 + function* (task: ScheduledTask, message: string) {
648 const now = yield* localNow;
649 const reread = yield* Effect.result(findTask(task.id));
650 if (Result.isSuccess(reread) && reread.success === null) return;
@@ -655,14 +659,17 @@ export const layer = Layer.effect(
659 WHERE task_id = ${task.id} AND last_run_status = 'running'
660 `;
661 yield* notifyChanged;
658 - }).pipe(
659 - Effect.catch((cause) =>
660 - Effect.logWarning("Could not release stuck schedule task run", {
661 - taskId: task.id,
662 - cause,
663 - }),
662 + },
663 + (effect, task, _message) =>
664 + effect.pipe(
665 + Effect.catch((cause) =>
666 + Effect.logWarning("Could not release stuck schedule task run", {
667 + taskId: task.id,
668 + cause,
669 + }),
670 + ),
671 ),
665 - );
672 + );
673
674 const runTask = Effect.fn("ScheduledTaskService.runTask")(function* (
675 task: ScheduledTask,
@@ -935,130 +942,131 @@ export const layer = Layer.effect(
942 }),
943 );
944
938 - const upsert: ScheduledTaskService["Service"]["upsert"] = (input) =>
939 - Effect.gen(function* () {
940 - const now = yield* localNow;
941 - const uuid =
942 - input.commandId === undefined
943 - ? yield* crypto
944 - .randomUUIDv4()
945 - .pipe(
946 - Effect.mapError((cause) =>
947 - taskError("Could not generate schedule task id.", { cause }),
948 - ),
949 - )
950 - : null;
951 - const id =
952 - input.id ??
953 - ScheduledTaskId.make(
954 - input.commandId ? `scheduled-task:${input.commandId}` : `scheduled-task:${uuid}`,
955 - );
956 - // Look up by the *resolved* id so idempotent creates (commandId replays)
957 - // keep their run history, and so real load failures propagate instead
958 - // of silently resetting an existing row.
959 - const existingTask = yield* findTask(id);
960 - // Keep the existing next_run_at when the schedule itself is untouched:
961 - // editing a title or prompt must not postpone (or resurrect) a due
962 - // run — only schedule/enabled changes restart the clock.
963 - const schedule: ScheduledTask["schedule"] =
964 - input.schedule.type === "webhook"
965 - ? {
966 - type: "webhook",
967 - signature:
968 - input.schedule.signature == null
969 - ? null
970 - : {
971 - header: input.schedule.signature.header.toLowerCase(),
972 - encoding: input.schedule.signature.encoding,
973 - prefix: input.schedule.signature.prefix,
974 - },
975 - maxDeliveryAgeMinutes: input.schedule.maxDeliveryAgeMinutes ?? null,
945 + const upsert: ScheduledTaskService["Service"]["upsert"] = Effect.fn(
946 + "ScheduledTaskService.upsert",
947 + )(function* (input) {
948 + const now = yield* localNow;
949 + const uuid =
950 + input.commandId === undefined
951 + ? yield* crypto
952 + .randomUUIDv4()
953 + .pipe(
954 + Effect.mapError((cause) =>
955 + taskError("Could not generate schedule task id.", { cause }),
956 + ),
957 + )
958 + : null;
959 + const id =
960 + input.id ??
961 + ScheduledTaskId.make(
962 + input.commandId ? `scheduled-task:${input.commandId}` : `scheduled-task:${uuid}`,
963 + );
964 + // Look up by the *resolved* id so idempotent creates (commandId replays)
965 + // keep their run history, and so real load failures propagate instead
966 + // of silently resetting an existing row.
967 + const existingTask = yield* findTask(id);
968 + // Keep the existing next_run_at when the schedule itself is untouched:
969 + // editing a title or prompt must not postpone (or resurrect) a due
970 + // run — only schedule/enabled changes restart the clock.
971 + const schedule: ScheduledTask["schedule"] =
972 + input.schedule.type === "webhook"
973 + ? {
974 + type: "webhook",
975 + signature:
976 + input.schedule.signature == null
977 + ? null
978 + : {
979 + header: input.schedule.signature.header.toLowerCase(),
980 + encoding: input.schedule.signature.encoding,
981 + prefix: input.schedule.signature.prefix,
982 + },
983 + maxDeliveryAgeMinutes: input.schedule.maxDeliveryAgeMinutes ?? null,
984 + }
985 + : input.schedule;
986 + const webhook =
987 + input.schedule.type === "webhook"
988 + ? yield* Effect.gen(function* () {
989 + const existing = existingTask === null ? null : yield* findWebhookCredentials(id);
990 + const token = existing?.token ?? (yield* newWebhookToken);
991 + const signature = input.schedule.type === "webhook" ? input.schedule.signature : null;
992 + // A secretRef is a value the user entered for an agent; this
993 + // save consumes it, so it cannot be used again. A replay of a
994 + // save that already used it keeps the secret that save stored.
995 + const replay = input.commandId !== undefined && existing?.secret != null;
996 + const fromRef =
997 + signature?.secretRef === undefined
998 + ? undefined
999 + : yield* secretRequests
1000 + .consume({ ref: signature.secretRef, projectId: input.projectId })
1001 + .pipe(
1002 + Effect.catch((error) =>
1003 + replay
1004 + ? Effect.succeed(undefined)
1005 + : Effect.fail(taskError(error.message, { taskId: id })),
1006 + ),
1007 + );
1008 + // A ref, when given, is the only source: a plain secret sent
1009 + // alongside it must not replace what a replayed save stored.
1010 + const provided = signature?.secretRef === undefined ? signature?.secret : fromRef;
1011 + const secret = signature == null ? null : (provided ?? existing?.secret ?? null);
1012 + const secretChanged =
1013 + signature == null || provided !== undefined || existing === null;
1014 + if (signature != null && secret === null) {
1015 + return yield* taskError("A webhook signature check needs a signing secret.", {
1016 + taskId: id,
1017 + });
1018 }
977 - : input.schedule;
978 - const webhook =
979 - input.schedule.type === "webhook"
980 - ? yield* Effect.gen(function* () {
981 - const existing = existingTask === null ? null : yield* findWebhookCredentials(id);
982 - const token = existing?.token ?? (yield* newWebhookToken);
983 - const signature =
984 - input.schedule.type === "webhook" ? input.schedule.signature : null;
985 - // A secretRef is a value the user entered for an agent; this
986 - // save consumes it, so it cannot be used again. A replay of a
987 - // save that already used it keeps the secret that save stored.
988 - const replay = input.commandId !== undefined && existing?.secret != null;
989 - const fromRef =
990 - signature?.secretRef === undefined
991 - ? undefined
992 - : yield* secretRequests
993 - .consume({ ref: signature.secretRef, projectId: input.projectId })
994 - .pipe(
995 - Effect.catch((error) =>
996 - replay
997 - ? Effect.succeed(undefined)
998 - : Effect.fail(taskError(error.message, { taskId: id })),
999 - ),
1000 - );
1001 - // A ref, when given, is the only source: a plain secret sent
1002 - // alongside it must not replace what a replayed save stored.
1003 - const provided = signature?.secretRef === undefined ? signature?.secret : fromRef;
1004 - const secret = signature == null ? null : (provided ?? existing?.secret ?? null);
1005 - const secretChanged =
1006 - signature == null || provided !== undefined || existing === null;
1007 - if (signature != null && secret === null) {
1008 - return yield* taskError("A webhook signature check needs a signing secret.", {
1009 - taskId: id,
1010 - });
1011 - }
1012 - return { token, secret, secretChanged };
1013 - })
1014 - : { token: null, secret: null, secretChanged: true };
1015 - const workspaceStrategy: ScheduledTask["workspaceStrategy"] =
1016 - input.workspaceStrategy.type === "worktree" &&
1017 - (yield* managedFolders.isScratchProject(input.projectId))
1018 - ? { type: "root" }
1019 - : input.workspaceStrategy;
1020 - const scheduleUnchanged =
1021 - existingTask !== null &&
1022 - existingTask.enabled === input.enabled &&
1023 - isSameSchedule(existingTask.schedule, schedule);
1024 - const task: ScheduledTask = {
1025 - id,
1026 - title: input.title,
1027 - prompt: input.prompt,
1028 - enabled: input.enabled,
1029 - schedule,
1030 - projectId: input.projectId,
1031 - threadId: input.threadId ?? null,
1032 - workspaceStrategy,
1033 - modelSelection: input.modelSelection,
1034 - runtimeMode: input.runtimeMode,
1035 - interactionMode: input.interactionMode,
1036 - createdBy: existingTask?.createdBy ?? input.createdBy ?? "user",
1037 - creationSource: input.creationSource ?? "web",
1038 - createdAt: existingTask?.createdAt ?? iso(now),
1039 - updatedAt: iso(now),
1040 - nextRunAt: scheduleUnchanged
1041 - ? existingTask.nextRunAt
1042 - : nextRunAt({ enabled: input.enabled, schedule }, now),
1043 - lastRunAt: existingTask?.lastRunAt ?? null,
1044 - lastRunStatus: existingTask?.lastRunStatus ?? "never",
1045 - lastRunError: existingTask?.lastRunError ?? null,
1046 - runCount: existingTask?.runCount ?? 0,
1047 - };
1048 - yield* saveTask(task, input.requireExisting === true, webhook);
1049 - yield* notifyChanged;
1050 - return { task: (yield* findTask(id)) ?? task };
1051 - });
1019 + return { token, secret, secretChanged };
1020 + })
1021 + : { token: null, secret: null, secretChanged: true };
1022 + const workspaceStrategy: ScheduledTask["workspaceStrategy"] =
1023 + input.workspaceStrategy.type === "worktree" &&
1024 + (yield* managedFolders.isScratchProject(input.projectId))
1025 + ? { type: "root" }
1026 + : input.workspaceStrategy;
1027 + const scheduleUnchanged =
1028 + existingTask !== null &&
1029 + existingTask.enabled === input.enabled &&
1030 + isSameSchedule(existingTask.schedule, schedule);
1031 + const task: ScheduledTask = {
1032 + id,
1033 + title: input.title,
1034 + prompt: input.prompt,
1035 + enabled: input.enabled,
1036 + schedule,
1037 + projectId: input.projectId,
1038 + threadId: input.threadId ?? null,
1039 + workspaceStrategy,
1040 + modelSelection: input.modelSelection,
1041 + runtimeMode: input.runtimeMode,
1042 + interactionMode: input.interactionMode,
1043 + createdBy: existingTask?.createdBy ?? input.createdBy ?? "user",
1044 + creationSource: input.creationSource ?? "web",
1045 + createdAt: existingTask?.createdAt ?? iso(now),
1046 + updatedAt: iso(now),
1047 + nextRunAt: scheduleUnchanged
1048 + ? existingTask.nextRunAt
1049 + : nextRunAt({ enabled: input.enabled, schedule }, now),
1050 + lastRunAt: existingTask?.lastRunAt ?? null,
1051 + lastRunStatus: existingTask?.lastRunStatus ?? "never",
1052 + lastRunError: existingTask?.lastRunError ?? null,
1053 + runCount: existingTask?.runCount ?? 0,
1054 + };
1055 + yield* saveTask(task, input.requireExisting === true, webhook);
1056 + yield* notifyChanged;
1057 + return { task: (yield* findTask(id)) ?? task };
1058 + });
1059
1053 - const setEnabled: ScheduledTaskService["Service"]["setEnabled"] = (input) =>
1054 - Effect.gen(function* () {
1055 - const existing = yield* loadTask(input.id);
1056 - if (existing.enabled === input.enabled) return { task: existing };
1057 - const now = yield* localNow;
1058 - const next = nextRunAt({ enabled: input.enabled, schedule: existing.schedule }, now);
1059 - // RETURNING so a task deleted between the load and this UPDATE is a
1060 - // visible not-found error, not a false success.
1061 - const updated = yield* sql<{ task_id: string }>`
1060 + const setEnabled: ScheduledTaskService["Service"]["setEnabled"] = Effect.fn(
1061 + "ScheduledTaskService.setEnabled",
1062 + )(function* (input) {
1063 + const existing = yield* loadTask(input.id);
1064 + if (existing.enabled === input.enabled) return { task: existing };
1065 + const now = yield* localNow;
1066 + const next = nextRunAt({ enabled: input.enabled, schedule: existing.schedule }, now);
1067 + // RETURNING so a task deleted between the load and this UPDATE is a
1068 + // visible not-found error, not a false success.
1069 + const updated = yield* sql<{ task_id: string }>`
1070 UPDATE scheduled_tasks
1071 SET enabled = ${input.enabled ? 1 : 0},
1072 next_run_at = ${next},
@@ -1066,18 +1074,18 @@ export const layer = Layer.effect(
1074 WHERE task_id = ${input.id}
1075 RETURNING task_id
1076 `.pipe(
1069 - Effect.mapError((cause) =>
1070 - taskError("Could not update schedule task.", { taskId: input.id, cause }),
1071 - ),
1072 - );
1073 - if (updated.length === 0) {
1074 - return yield* taskError("Schedule task not found.", { taskId: input.id });
1075 - }
1076 - yield* notifyChanged;
1077 - return {
1078 - task: { ...existing, enabled: input.enabled, nextRunAt: next, updatedAt: iso(now) },
1079 - };
1080 - });
1077 + Effect.mapError((cause) =>
1078 + taskError("Could not update schedule task.", { taskId: input.id, cause }),
1079 + ),
1080 + );
1081 + if (updated.length === 0) {
1082 + return yield* taskError("Schedule task not found.", { taskId: input.id });
1083 + }
1084 + yield* notifyChanged;
1085 + return {
1086 + task: { ...existing, enabled: input.enabled, nextRunAt: next, updatedAt: iso(now) },
1087 + };
1088 + });
1089
1090 const deleteTask: ScheduledTaskService["Service"]["delete"] = (input) =>
1091 deleteRow(input.id).pipe(
@@ -1099,48 +1107,50 @@ export const layer = Layer.effect(
1107 Effect.as({ id: input.id }),
1108 );
1109
1102 - const runNow: ScheduledTaskService["Service"]["runNow"] = (input: ScheduledTaskRunNowInput) =>
1103 - Effect.gen(function* () {
1104 - const task = yield* loadTask(input.id);
1105 - if (task.schedule.type === "webhook") {
1106 - return yield* taskError("Webhook tasks run when their URL receives a request.", {
1107 - taskId: input.id,
1108 - });
1109 - }
1110 - const next = yield* runTask(task, "manual").pipe(
1111 - Effect.mapError((cause) =>
1112 - taskError("Could not run schedule task.", { taskId: input.id, cause }),
1113 - ),
1114 - );
1115 - return { task: next };
1116 - });
1110 + const runNow: ScheduledTaskService["Service"]["runNow"] = Effect.fn(
1111 + "ScheduledTaskService.runNow",
1112 + )(function* (input: ScheduledTaskRunNowInput) {
1113 + const task = yield* loadTask(input.id);
1114 + if (task.schedule.type === "webhook") {
1115 + return yield* taskError("Webhook tasks run when their URL receives a request.", {
1116 + taskId: input.id,
1117 + });
1118 + }
1119 + const next = yield* runTask(task, "manual").pipe(
1120 + Effect.mapError((cause) =>
1121 + taskError("Could not run schedule task.", { taskId: input.id, cause }),
1122 + ),
1123 + );
1124 + return { task: next };
1125 + });
1126
1118 - const rotateWebhookToken: ScheduledTaskService["Service"]["rotateWebhookToken"] = (input) =>
1119 - Effect.gen(function* () {
1120 - const task = yield* loadTask(input.id);
1121 - if (task.schedule.type !== "webhook") {
1122 - return yield* taskError("Only webhook tasks have a URL token.", { taskId: input.id });
1123 - }
1124 - const token = yield* newWebhookToken;
1125 - const now = yield* localNow;
1126 - // Matching created_at keeps a rotation from landing on a task deleted
1127 - // and recreated under the same id since it was loaded.
1128 - const updated = yield* sql<{ task_id: string }>`
1127 + const rotateWebhookToken: ScheduledTaskService["Service"]["rotateWebhookToken"] = Effect.fn(
1128 + "ScheduledTaskService.rotateWebhookToken",
1129 + )(function* (input) {
1130 + const task = yield* loadTask(input.id);
1131 + if (task.schedule.type !== "webhook") {
1132 + return yield* taskError("Only webhook tasks have a URL token.", { taskId: input.id });
1133 + }
1134 + const token = yield* newWebhookToken;
1135 + const now = yield* localNow;
1136 + // Matching created_at keeps a rotation from landing on a task deleted
1137 + // and recreated under the same id since it was loaded.
1138 + const updated = yield* sql<{ task_id: string }>`
1139 UPDATE scheduled_tasks
1140 SET webhook_token = ${token}, updated_at = ${iso(now)}
1141 WHERE task_id = ${input.id} AND created_at = ${task.createdAt}
1142 RETURNING task_id
1143 `.pipe(
1134 - Effect.mapError((cause) =>
1135 - taskError("Could not rotate webhook token.", { taskId: input.id, cause }),
1136 - ),
1137 - );
1138 - if (updated.length === 0) {
1139 - return yield* taskError("Schedule task was deleted or replaced.", { taskId: input.id });
1140 - }
1141 - yield* notifyChanged;
1142 - return { task: yield* loadTask(input.id) };
1143 - });
1144 + Effect.mapError((cause) =>
1145 + taskError("Could not rotate webhook token.", { taskId: input.id, cause }),
1146 + ),
1147 + );
1148 + if (updated.length === 0) {
1149 + return yield* taskError("Schedule task was deleted or replaced.", { taskId: input.id });
1150 + }
1151 + yield* notifyChanged;
1152 + return { task: yield* loadTask(input.id) };
1153 + });
1154
1155 const deliveryHeaders = (row: WebhookDeliveryRow): Readonly<Record<string, string>> =>
1156 Option.getOrElse(decodeHeadersJson(row.headers_json), () => ({}));
@@ -1171,31 +1181,32 @@ export const layer = Layer.effect(
1181 ),
1182 );
1183
1174 - const getWebhookDelivery: ScheduledTaskService["Service"]["getWebhookDelivery"] = (input) =>
1175 - Effect.gen(function* () {
1176 - const rows = yield* sql<WebhookDeliveryRow>`
1184 + const getWebhookDelivery: ScheduledTaskService["Service"]["getWebhookDelivery"] = Effect.fn(
1185 + "ScheduledTaskService.getWebhookDelivery",
1186 + )(function* (input) {
1187 + const rows = yield* sql<WebhookDeliveryRow>`
1188 SELECT * FROM scheduled_task_webhook_deliveries
1189 WHERE task_id = ${input.id} AND delivery_id = ${input.deliveryId}
1190 `.pipe(
1180 - Effect.mapError((cause) =>
1181 - taskError("Could not load webhook delivery.", { taskId: input.id, cause }),
1182 - ),
1183 - );
1184 - const row = rows[0];
1185 - if (row === undefined) {
1186 - return yield* taskError("Webhook delivery not found.", { taskId: input.id });
1187 - }
1188 - return {
1189 - delivery: {
1190 - ...decodeDeliverySummary(row),
1191 - query: row.query,
1192 - headers: deliveryHeaders(row),
1193 - body: row.body,
1194 - bodyTruncated: row.body_truncated === 1,
1195 - renderedPrompt: row.rendered_prompt,
1196 - },
1197 - };
1198 - });
1191 + Effect.mapError((cause) =>
1192 + taskError("Could not load webhook delivery.", { taskId: input.id, cause }),
1193 + ),
1194 + );
1195 + const row = rows[0];
1196 + if (row === undefined) {
1197 + return yield* taskError("Webhook delivery not found.", { taskId: input.id });
1198 + }
1199 + return {
1200 + delivery: {
1201 + ...decodeDeliverySummary(row),
1202 + query: row.query,
1203 + headers: deliveryHeaders(row),
1204 + body: row.body,
1205 + bodyTruncated: row.body_truncated === 1,
1206 + renderedPrompt: row.rendered_prompt,
1207 + },
1208 + };
1209 + });
1210
1211 const recordDelivery = (input: {
1212 readonly id: string;
@@ -1298,43 +1309,44 @@ export const layer = Layer.effect(
1309 },
1310 );
1311
1301 - const webhookPermit = (id: ScheduledTaskId) =>
1302 - Effect.gen(function* () {
1303 - const existing = (yield* Ref.get(webhookPermits)).get(id);
1304 - if (existing !== undefined) return existing;
1305 - const created = yield* Semaphore.make(1);
1306 - return yield* Ref.modify(webhookPermits, (permits) => {
1307 - const raced = permits.get(id);
1308 - return raced === undefined
1309 - ? [created, new Map(permits).set(id, created)]
1310 - : [raced, permits];
1311 - });
1312 + const webhookPermit = Effect.fn("ScheduledTaskService.webhookPermit")(function* (
1313 + id: ScheduledTaskId,
1314 + ) {
1315 + const existing = (yield* Ref.get(webhookPermits)).get(id);
1316 + if (existing !== undefined) return existing;
1317 + const created = yield* Semaphore.make(1);
1318 + return yield* Ref.modify(webhookPermits, (permits) => {
1319 + const raced = permits.get(id);
1320 + return raced === undefined
1321 + ? [created, new Map(permits).set(id, created)]
1322 + : [raced, permits];
1323 });
1324 + });
1325
1326 const serviceScope = yield* Effect.scope;
1327
1316 - const observeDelivery = (
1328 + // Delivery attributes belong to the enclosing triggerWebhook span.
1329 + const observeDelivery = Effect.fnUntraced(function* (
1330 request: WebhookTriggerRequest,
1331 outcome: WebhookDeliveryOutcome,
1332 receivedAt: DateTime.DateTime | undefined,
1333 now: DateTime.DateTime | undefined,
1321 - ) =>
1322 - Effect.gen(function* () {
1323 - const source = request.relayDeliveryId === undefined ? "direct" : "relay";
1324 - yield* Effect.annotateCurrentSpan({
1325 - "scheduled_task.webhook.outcome": outcome,
1326 - "scheduled_task.webhook.source": source,
1327 - });
1328 - yield* Metrics.increment(Metrics.webhookDeliveriesTotal, { outcome, source });
1329 - if (request.receivedAt !== undefined && receivedAt !== undefined && now !== undefined) {
1330 - const heldMs = Math.max(
1331 - 0,
1332 - DateTime.toEpochMillis(now) - DateTime.toEpochMillis(receivedAt),
1333 - );
1334 - yield* Effect.annotateCurrentSpan({ "scheduled_task.webhook.held_ms": heldMs });
1335 - yield* Metric.update(Metrics.webhookHeldDelay, Duration.millis(heldMs));
1336 - }
1334 + ) {
1335 + const source = request.relayDeliveryId === undefined ? "direct" : "relay";
1336 + yield* Effect.annotateCurrentSpan({
1337 + "scheduled_task.webhook.outcome": outcome,
1338 + "scheduled_task.webhook.source": source,
1339 });
1340 + yield* Metrics.increment(Metrics.webhookDeliveriesTotal, { outcome, source });
1341 + if (request.receivedAt !== undefined && receivedAt !== undefined && now !== undefined) {
1342 + const heldMs = Math.max(
1343 + 0,
1344 + DateTime.toEpochMillis(now) - DateTime.toEpochMillis(receivedAt),
1345 + );
1346 + yield* Effect.annotateCurrentSpan({ "scheduled_task.webhook.held_ms": heldMs });
1347 + yield* Metric.update(Metrics.webhookHeldDelay, Duration.millis(heldMs));
1348 + }
1349 + });
1350
1351 const triggerWebhook: ScheduledTaskService["Service"]["triggerWebhook"] = (request) =>
1352 triggerWebhookUnobserved(request).pipe(
@@ -1350,252 +1362,250 @@ export const layer = Layer.effect(
1362 }),
1363 );
1364
1353 - const triggerWebhookUnobserved = (request: WebhookTriggerRequest) =>
1354 - Effect.gen(function* () {
1355 - const taskId = decodeTaskId(request.hookId);
1356 - const notFound = observeDelivery(request, "not_found", undefined, undefined).pipe(
1357 - Effect.as({ _tag: "not_found" as const }),
1358 - );
1359 - if (Option.isNone(taskId)) return yield* notFound;
1360 - const rows = yield* getRows(taskId.value).pipe(
1361 - Effect.mapError((cause) =>
1362 - taskError("Could not load schedule task.", { taskId: taskId.value, cause }),
1363 - ),
1364 - );
1365 - const row = rows[0];
1366 - // A wrong token is indistinguishable from an unknown hook, so the URL
1367 - // does not reveal which hooks exist.
1368 - if (
1369 - row === undefined ||
1370 - row.webhook_token === null ||
1371 - !constantTimeEquals(request.token, row.webhook_token)
1372 - ) {
1373 - return yield* notFound;
1374 - }
1375 - const task = yield* decodeRow(row);
1376 - yield* Effect.annotateCurrentSpan({ "scheduled_task.id": task.id });
1377 - const schedule = task.schedule;
1378 - if (schedule.type !== "webhook") return yield* notFound;
1365 + // triggerWebhook owns the operation span and its task-id annotation.
1366 + const triggerWebhookUnobserved = Effect.fnUntraced(function* (request: WebhookTriggerRequest) {
1367 + const taskId = decodeTaskId(request.hookId);
1368 + const notFound = observeDelivery(request, "not_found", undefined, undefined).pipe(
1369 + Effect.as({ _tag: "not_found" as const }),
1370 + );
1371 + if (Option.isNone(taskId)) return yield* notFound;
1372 + const rows = yield* getRows(taskId.value).pipe(
1373 + Effect.mapError((cause) =>
1374 + taskError("Could not load schedule task.", { taskId: taskId.value, cause }),
1375 + ),
1376 + );
1377 + const row = rows[0];
1378 + // A wrong token is indistinguishable from an unknown hook, so the URL
1379 + // does not reveal which hooks exist.
1380 + if (
1381 + row === undefined ||
1382 + row.webhook_token === null ||
1383 + !constantTimeEquals(request.token, row.webhook_token)
1384 + ) {
1385 + return yield* notFound;
1386 + }
1387 + const task = yield* decodeRow(row);
1388 + yield* Effect.annotateCurrentSpan({ "scheduled_task.id": task.id });
1389 + const schedule = task.schedule;
1390 + if (schedule.type !== "webhook") return yield* notFound;
1391
1380 - const now = yield* localNow;
1381 - // Anyone can reach the tunnel directly and set the relay's header, so
1382 - // a receive time is never later than now: a future one would pin the
1383 - // delivery in the log and slip past the task's max age.
1384 - const receivedAt =
1385 - request.receivedAt === undefined
1386 - ? now
1387 - : DateTime.min(
1388 - Option.getOrElse(DateTime.make(request.receivedAt), () => now),
1389 - now,
1390 - );
1391 - const observe = (outcome: WebhookDeliveryOutcome) =>
1392 - observeDelivery(request, outcome, receivedAt, now);
1393 - const deliveryId = ScheduledTaskWebhookDeliveryId.make(
1394 - request.relayDeliveryId === undefined
1395 - ? `delivery:${yield* crypto
1396 - .randomUUIDv4()
1397 - .pipe(
1398 - Effect.mapError((cause) =>
1399 - taskError("Could not generate delivery id.", { cause }),
1400 - ),
1401 - )}`
1402 - : `delivery:relay:${request.relayDeliveryId}`,
1403 - );
1404 - // Claimed in its own table, kept longer than the relay holds a request,
1405 - // because the delivery log is trimmed. A rate-limited delivery stays
1406 - // held on the relay, so it must give up its claim or the next pass
1407 - // would treat it as already delivered.
1408 - let claimAcquired = false;
1409 - const releaseClaim = <A>(result: A) =>
1410 - !claimAcquired || request.relayDeliveryId === undefined
1411 - ? Effect.succeed(result)
1412 - : sql`
1392 + const now = yield* localNow;
1393 + // Anyone can reach the tunnel directly and set the relay's header, so
1394 + // a receive time is never later than now: a future one would pin the
1395 + // delivery in the log and slip past the task's max age.
1396 + const receivedAt =
1397 + request.receivedAt === undefined
1398 + ? now
1399 + : DateTime.min(
1400 + Option.getOrElse(DateTime.make(request.receivedAt), () => now),
1401 + now,
1402 + );
1403 + const observe = (outcome: WebhookDeliveryOutcome) =>
1404 + observeDelivery(request, outcome, receivedAt, now);
1405 + const deliveryId = ScheduledTaskWebhookDeliveryId.make(
1406 + request.relayDeliveryId === undefined
1407 + ? `delivery:${yield* crypto
1408 + .randomUUIDv4()
1409 + .pipe(
1410 + Effect.mapError((cause) => taskError("Could not generate delivery id.", { cause })),
1411 + )}`
1412 + : `delivery:relay:${request.relayDeliveryId}`,
1413 + );
1414 + // Claimed in its own table, kept longer than the relay holds a request,
1415 + // because the delivery log is trimmed. A rate-limited delivery stays
1416 + // held on the relay, so it must give up its claim or the next pass
1417 + // would treat it as already delivered.
1418 + let claimAcquired = false;
1419 + const releaseClaim = <A>(result: A) =>
1420 + !claimAcquired || request.relayDeliveryId === undefined
1421 + ? Effect.succeed(result)
1422 + : sql`
1423 DELETE FROM scheduled_task_webhook_relay_deliveries
1424 WHERE relay_delivery_id = ${request.relayDeliveryId}
1425 `.pipe(Effect.ignore, Effect.as(result));
1416 - // From the claim until the run is forked nothing may interrupt: a
1417 - // request dropped in between (the relay hangs up after its timeout)
1418 - // would leave a claimed delivery that never runs, or a queue slot that
1419 - // is never released.
1420 - return yield* Effect.uninterruptible(
1421 - Effect.gen(function* () {
1422 - if (request.relayDeliveryId !== undefined) {
1423 - const claimed = yield* sql<{ relay_delivery_id: string }>`
1426 + // From the claim until the run is forked nothing may interrupt: a
1427 + // request dropped in between (the relay hangs up after its timeout)
1428 + // would leave a claimed delivery that never runs, or a queue slot that
1429 + // is never released.
1430 + return yield* Effect.uninterruptible(
1431 + Effect.gen(function* () {
1432 + if (request.relayDeliveryId !== undefined) {
1433 + const claimed = yield* sql<{ relay_delivery_id: string }>`
1434 INSERT INTO scheduled_task_webhook_relay_deliveries
1435 (relay_delivery_id, task_id, seen_at)
1436 VALUES (${request.relayDeliveryId}, ${task.id}, ${iso(now)})
1437 ON CONFLICT (relay_delivery_id) DO NOTHING
1438 RETURNING relay_delivery_id
1439 `.pipe(
1430 - Effect.mapError((cause) =>
1431 - taskError("Could not record webhook delivery.", { taskId: task.id, cause }),
1432 - ),
1433 - );
1434 - if (claimed.length === 0) {
1435 - yield* observe("duplicate");
1436 - return { _tag: "accepted" as const, deliveryId, outcome: "duplicate" as const };
1437 - }
1438 - claimAcquired = true;
1439 - yield* sql`
1440 + Effect.mapError((cause) =>
1441 + taskError("Could not record webhook delivery.", { taskId: task.id, cause }),
1442 + ),
1443 + );
1444 + if (claimed.length === 0) {
1445 + yield* observe("duplicate");
1446 + return { _tag: "accepted" as const, deliveryId, outcome: "duplicate" as const };
1447 + }
1448 + claimAcquired = true;
1449 + yield* sql`
1450 DELETE FROM scheduled_task_webhook_relay_deliveries
1451 WHERE seen_at < ${iso(DateTime.subtract(now, { hours: 48 }))}
1452 `.pipe(Effect.ignore);
1443 - }
1444 - const log = (
1445 - outcome: ScheduledTaskWebhookDeliveryOutcome,
1446 - details: {
1447 - readonly signatureVerified?: boolean;
1448 - readonly missing?: ReadonlyArray<string>;
1449 - readonly renderedPrompt?: string;
1450 - readonly error?: string;
1451 - } = {},
1452 - ) =>
1453 - recordDelivery({
1454 - id: deliveryId,
1455 - taskId: task.id,
1456 - receivedAt: iso(receivedAt),
1457 - request,
1458 - outcome,
1459 - signatureVerified: details.signatureVerified ?? false,
1460 - missing: details.missing ?? [],
1461 - renderedPrompt: details.renderedPrompt ?? null,
1462 - ...(details.error === undefined ? {} : { error: details.error }),
1463 - });
1464 -
1465 - // Only the first rejected request in a window is logged, so a flood
1466 - // cannot write rows or push the real deliveries out of the log.
1467 - const slot = yield* takeRateSlot(task.id, DateTime.toEpochMillis(now));
1468 - if (slot !== "allowed") {
1469 - if (slot === "first_rejected") yield* log("rate_limited");
1470 - yield* observe("rate_limited");
1471 - return yield* releaseClaim({
1472 - _tag: "rate_limited" as const,
1473 - outcome: "rate_limited" as const,
1474 - });
1475 - }
1476 - if (!task.enabled) {
1477 - yield* log("disabled");
1478 - yield* observe("disabled");
1479 - return { _tag: "disabled" as const };
1480 - }
1481 - const signature = schedule.signature;
1482 - if (signature !== null) {
1483 - const verified =
1484 - row.webhook_secret !== null &&
1485 - verifyWebhookSignature({
1486 - signature,
1487 - secret: row.webhook_secret,
1488 - headers: request.headers,
1489 - body: request.body,
1490 - });
1491 - if (!verified) {
1492 - yield* log("rejected_signature");
1493 - yield* observe("rejected_signature");
1494 - return { _tag: "rejected_signature" as const };
1495 - }
1496 - }
1497 - const maxAgeMinutes = schedule.maxDeliveryAgeMinutes ?? null;
1498 - if (
1499 - maxAgeMinutes !== null &&
1500 - DateTime.toEpochMillis(now) - DateTime.toEpochMillis(receivedAt) >
1501 - maxAgeMinutes * 60_000
1502 - ) {
1503 - yield* log("expired", { signatureVerified: signature !== null });
1504 - yield* observe("expired");
1505 - return { _tag: "expired" as const };
1506 - }
1453 + }
1454 + const log = (
1455 + outcome: ScheduledTaskWebhookDeliveryOutcome,
1456 + details: {
1457 + readonly signatureVerified?: boolean;
1458 + readonly missing?: ReadonlyArray<string>;
1459 + readonly renderedPrompt?: string;
1460 + readonly error?: string;
1461 + } = {},
1462 + ) =>
1463 + recordDelivery({
1464 + id: deliveryId,
1465 + taskId: task.id,
1466 + receivedAt: iso(receivedAt),
1467 + request,
1468 + outcome,
1469 + signatureVerified: details.signatureVerified ?? false,
1470 + missing: details.missing ?? [],
1471 + renderedPrompt: details.renderedPrompt ?? null,
1472 + ...(details.error === undefined ? {} : { error: details.error }),
1473 + });
1474
1508 - const frameId = yield* crypto.randomBytes(6).pipe(
1509 - Effect.map((bytes) => Buffer.from(bytes).toString("hex")),
1510 - Effect.mapError((cause) => taskError("Could not generate frame id.", { cause })),
1511 - );
1512 - const rendered = renderWebhookPrompt(task.prompt, request, frameId);
1513 - // Providers trim the prompt before checking, so whitespace around
1514 - // it is free.
1515 - if (rendered.prompt.trim().length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) {
1516 - yield* log("dispatch_failed", {
1517 - signatureVerified: signature !== null,
1518 - missing: rendered.missing,
1519 - renderedPrompt: rendered.prompt,
1520 - error: "The filled-in prompt is too long.",
1521 - });
1522 - yield* observe("prompt_too_long");
1523 - return { _tag: "accepted" as const, deliveryId, outcome: "prompt_too_long" as const };
1524 - }
1525 - // Bound the deliveries one task holds, so steady traffic to a stuck
1526 - // task cannot pile up parked fibers.
1527 - const queueKey = `${task.id}\u0000${task.createdAt}`;
1528 - const queued = yield* Ref.modify(webhookQueued, (counts) => {
1529 - const count = counts.get(queueKey) ?? 0;
1530 - return count >= WEBHOOK_MAX_QUEUED_PER_TASK
1531 - ? ([false, counts] as const)
1532 - : ([true, new Map(counts).set(queueKey, count + 1)] as const);
1475 + // Only the first rejected request in a window is logged, so a flood
1476 + // cannot write rows or push the real deliveries out of the log.
1477 + const slot = yield* takeRateSlot(task.id, DateTime.toEpochMillis(now));
1478 + if (slot !== "allowed") {
1479 + if (slot === "first_rejected") yield* log("rate_limited");
1480 + yield* observe("rate_limited");
1481 + return yield* releaseClaim({
1482 + _tag: "rate_limited" as const,
1483 + outcome: "rate_limited" as const,
1484 });
1534 - if (!queued) {
1535 - yield* observe("queue_full");
1536 - return yield* releaseClaim({
1537 - _tag: "rate_limited" as const,
1538 - outcome: "queue_full" as const,
1485 + }
1486 + if (!task.enabled) {
1487 + yield* log("disabled");
1488 + yield* observe("disabled");
1489 + return { _tag: "disabled" as const };
1490 + }
1491 + const signature = schedule.signature;
1492 + if (signature !== null) {
1493 + const verified =
1494 + row.webhook_secret !== null &&
1495 + verifyWebhookSignature({
1496 + signature,
1497 + secret: row.webhook_secret,
1498 + headers: request.headers,
1499 + body: request.body,
1500 });
1501 + if (!verified) {
1502 + yield* log("rejected_signature");
1503 + yield* observe("rejected_signature");
1504 + return { _tag: "rejected_signature" as const };
1505 }
1541 - const release = Ref.update(webhookQueued, (counts) => {
1542 - const next = new Map(counts);
1543 - const count = (next.get(queueKey) ?? 1) - 1;
1544 - if (count <= 0) next.delete(queueKey);
1545 - else next.set(queueKey, count);
1546 - return next;
1547 - });
1548 - yield* log("accepted", {
1506 + }
1507 + const maxAgeMinutes = schedule.maxDeliveryAgeMinutes ?? null;
1508 + if (
1509 + maxAgeMinutes !== null &&
1510 + DateTime.toEpochMillis(now) - DateTime.toEpochMillis(receivedAt) >
1511 + maxAgeMinutes * 60_000
1512 + ) {
1513 + yield* log("expired", { signatureVerified: signature !== null });
1514 + yield* observe("expired");
1515 + return { _tag: "expired" as const };
1516 + }
1517 +
1518 + const frameId = yield* crypto.randomBytes(6).pipe(
1519 + Effect.map((bytes) => Buffer.from(bytes).toString("hex")),
1520 + Effect.mapError((cause) => taskError("Could not generate frame id.", { cause })),
1521 + );
1522 + const rendered = renderWebhookPrompt(task.prompt, request, frameId);
1523 + // Providers trim the prompt before checking, so whitespace around
1524 + // it is free.
1525 + if (rendered.prompt.trim().length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) {
1526 + yield* log("dispatch_failed", {
1527 signatureVerified: signature !== null,
1528 missing: rendered.missing,
1529 renderedPrompt: rendered.prompt,
1552 - }).pipe(Effect.onError(() => release));
1553 - yield* observe("accepted");
1554 - const permit = yield* webhookPermit(task.id);
1555 - const runOutcome = (outcome: "started" | "skipped" | "failed") =>
1556 - Effect.all([
1557 - Effect.annotateCurrentSpan({ "scheduled_task.webhook.run_outcome": outcome }),
1558 - Metrics.increment(Metrics.webhookRunsTotal, { outcome }),
1559 - ]);
1560 - yield* runTask(task, "webhook", { deliveryId, prompt: rendered.prompt }).pipe(
1561 - Effect.flatMap((completed) =>
1562 - completed.lastRunStatus === "failed"
1563 - ? runOutcome("failed").pipe(
1564 - Effect.andThen(markDeliveryFailed(deliveryId, "The run failed to start.")),
1565 - )
1566 - : runOutcome("started"),
1567 - ),
1568 - Effect.catchTags({
1569 - WebhookDeliverySkipped: (skipped) =>
1570 - runOutcome("skipped").pipe(
1571 - Effect.andThen(markDeliveryFailed(deliveryId, skipped.reason)),
1572 - ),
1573 - }),
1574 - // The log is readable over RPC, so it gets a fixed reason; the
1575 - // cause, which can carry request data, stays in the server log.
1576 - Effect.catchCause((cause) =>
1577 - Effect.logWarning("Webhook dispatch failed", { taskId: task.id, cause }).pipe(
1578 - Effect.andThen(runOutcome("failed")),
1579 - Effect.andThen(markDeliveryFailed(deliveryId, "The run failed to start.")),
1530 + error: "The filled-in prompt is too long.",
1531 + });
1532 + yield* observe("prompt_too_long");
1533 + return { _tag: "accepted" as const, deliveryId, outcome: "prompt_too_long" as const };
1534 + }
1535 + // Bound the deliveries one task holds, so steady traffic to a stuck
1536 + // task cannot pile up parked fibers.
1537 + const queueKey = `${task.id}\u0000${task.createdAt}`;
1538 + const queued = yield* Ref.modify(webhookQueued, (counts) => {
1539 + const count = counts.get(queueKey) ?? 0;
1540 + return count >= WEBHOOK_MAX_QUEUED_PER_TASK
1541 + ? ([false, counts] as const)
1542 + : ([true, new Map(counts).set(queueKey, count + 1)] as const);
1543 + });
1544 + if (!queued) {
1545 + yield* observe("queue_full");
1546 + return yield* releaseClaim({
1547 + _tag: "rate_limited" as const,
1548 + outcome: "queue_full" as const,
1549 + });
1550 + }
1551 + const release = Ref.update(webhookQueued, (counts) => {
1552 + const next = new Map(counts);
1553 + const count = (next.get(queueKey) ?? 1) - 1;
1554 + if (count <= 0) next.delete(queueKey);
1555 + else next.set(queueKey, count);
1556 + return next;
1557 + });
1558 + yield* log("accepted", {
1559 + signatureVerified: signature !== null,
1560 + missing: rendered.missing,
1561 + renderedPrompt: rendered.prompt,
1562 + }).pipe(Effect.onError(() => release));
1563 + yield* observe("accepted");
1564 + const permit = yield* webhookPermit(task.id);
1565 + const runOutcome = (outcome: "started" | "skipped" | "failed") =>
1566 + Effect.all([
1567 + Effect.annotateCurrentSpan({ "scheduled_task.webhook.run_outcome": outcome }),
1568 + Metrics.increment(Metrics.webhookRunsTotal, { outcome }),
1569 + ]);
1570 + yield* runTask(task, "webhook", { deliveryId, prompt: rendered.prompt }).pipe(
1571 + Effect.flatMap((completed) =>
1572 + completed.lastRunStatus === "failed"
1573 + ? runOutcome("failed").pipe(
1574 + Effect.andThen(markDeliveryFailed(deliveryId, "The run failed to start.")),
1575 + )
1576 + : runOutcome("started"),
1577 + ),
1578 + Effect.catchTags({
1579 + WebhookDeliverySkipped: (skipped) =>
1580 + runOutcome("skipped").pipe(
1581 + Effect.andThen(markDeliveryFailed(deliveryId, skipped.reason)),
1582 ),
1583 + }),
1584 + // The log is readable over RPC, so it gets a fixed reason; the
1585 + // cause, which can carry request data, stays in the server log.
1586 + Effect.catchCause((cause) =>
1587 + Effect.logWarning("Webhook dispatch failed", { taskId: task.id, cause }).pipe(
1588 + Effect.andThen(runOutcome("failed")),
1589 + Effect.andThen(markDeliveryFailed(deliveryId, "The run failed to start.")),
1590 ),
1582 - permit.withPermits(1),
1583 - Effect.withSpan("ScheduledTaskService.runWebhookDelivery", {
1584 - root: true,
1585 - attributes: {
1586 - "scheduled_task.id": task.id,
1587 - "scheduled_task.webhook.delivery_id": deliveryId,
1588 - },
1589 - }),
1590 - Effect.ensuring(release),
1591 - Effect.forkIn(serviceScope),
1592 - );
1593 - // Dispatch owns the accepted delivery now; retries must keep its claim.
1594 - claimAcquired = false;
1595 - return { _tag: "accepted" as const, deliveryId, outcome: "accepted" as const };
1596 - }).pipe(Effect.onError(() => releaseClaim(undefined))),
1597 - );
1598 - });
1591 + ),
1592 + permit.withPermits(1),
1593 + Effect.withSpan("ScheduledTaskService.runWebhookDelivery", {
1594 + root: true,
1595 + attributes: {
1596 + "scheduled_task.id": task.id,
1597 + "scheduled_task.webhook.delivery_id": deliveryId,
1598 + },
1599 + }),
1600 + Effect.ensuring(release),
1601 + Effect.forkIn(serviceScope),
1602 + );
1603 + // Dispatch owns the accepted delivery now; retries must keep its claim.
1604 + claimAcquired = false;
1605 + return { _tag: "accepted" as const, deliveryId, outcome: "accepted" as const };
1606 + }).pipe(Effect.onError(() => releaseClaim(undefined))),
1607 + );
1608 + });
1609
1610 return ScheduledTaskService.of({
1611 list,
apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts
+28
@@ -15,6 +15,7 @@ import * as EffectScheduler from "effect/Scheduler";
15 import * as Schema from "effect/Schema";
16 import * as SqlClient from "effect/sql/SqlClient";
17 import * as TestClock from "effect/testing/TestClock";
18 +import * as Tracer from "effect/Tracer";
19
20 import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
21 import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
@@ -881,6 +882,33 @@ const deliveriesCounted = (outcome: string, source: "relay" | "direct") =>
882 }),
883 );
884
885 +it.effect("keeps delivery attributes on the webhook operation span", () =>
886 + withService(({ service }) =>
887 + Effect.gen(function* () {
888 + const { task } = yield* service.upsert(yield* webhookTaskInput({ enabled: false }));
889 + const spans: Tracer.NativeSpan[] = [];
890 + const tracer = Tracer.make({
891 + span: (options) => {
892 + const span = new Tracer.NativeSpan(options);
893 + spans.push(span);
894 + return span;
895 + },
896 + });
897 + const receivedAt = DateTime.formatIso(DateTime.subtract(yield* DateTime.now, { seconds: 1 }));
898 + yield* service
899 + .triggerWebhook(requestFor(task, { receivedAt, relayDeliveryId: "traced-delivery" }))
900 + .pipe(Effect.withTracer(tracer));
901 +
902 + const span = spans.find((entry) => entry.name === "ScheduledTaskService.triggerWebhook");
903 + assert.isDefined(span);
904 + assert.equal(span?.attributes.get("scheduled_task.id"), task.id);
905 + assert.equal(span?.attributes.get("scheduled_task.webhook.outcome"), "disabled");
906 + assert.equal(span?.attributes.get("scheduled_task.webhook.source"), "relay");
907 + assert.equal(span?.attributes.get("scheduled_task.webhook.held_ms"), 1_000);
908 + }),
909 + ),
910 +);
911 +
912 it.effect("counts each handled request by what happened to it", () =>
913 withService(({ service, launches }) =>
914 Effect.gen(function* () {
apps/server/src/scheduledTasks/webhookRoute.ts
+83 -83
@@ -33,98 +33,98 @@ export const layer = HttpApiBuilder.group(
33 * The endpoint is raw so the signature is checked over the exact body
34 * bytes; the service checks the token and signature.
35 */
36 - const handler = ({
36 + // Only verified relay deliveries join a trace; direct requests keep their existing context.
37 + const handler = Effect.fnUntraced(function* ({
38 params,
39 request,
40 }: {
41 readonly params: { readonly hookId: string; readonly token: string };
42 readonly request: HttpServerRequest.HttpServerRequest;
42 - }) =>
43 - Effect.gen(function* () {
44 - const contentLength = Number(request.headers["content-length"] ?? "0");
45 - if (!Number.isFinite(contentLength) || contentLength > WEBHOOK_MAX_BODY_BYTES) {
46 - return json(413, { error: "body_too_large" }, "body_too_large");
47 - }
48 - // Chunked requests carry no content-length, so the reader itself is capped.
49 - const body = yield* request.arrayBuffer.pipe(
50 - Effect.map((buffer) => new Uint8Array(buffer)),
51 - Effect.provideService(
52 - HttpIncomingMessage.MaxBodySize,
53 - ByteSize.bytes(WEBHOOK_MAX_BODY_BYTES),
54 - ),
55 - Effect.option,
56 - );
57 - const tooLarge = (error: string) =>
58 - Metrics.increment(Metrics.webhookDeliveriesTotal, {
59 - outcome: "body_too_large",
60 - source: request.headers["x-t3-relay-delivery-id"] ? "relay" : "direct",
61 - }).pipe(Effect.as(json(413, { error }, "body_too_large")));
62 - if (Option.isNone(body)) return yield* tooLarge("body_too_large_or_unreadable");
63 - if (body.value.byteLength > WEBHOOK_MAX_BODY_BYTES) {
64 - return yield* tooLarge("body_too_large");
65 - }
43 + }) {
44 + const contentLength = Number(request.headers["content-length"] ?? "0");
45 + if (!Number.isFinite(contentLength) || contentLength > WEBHOOK_MAX_BODY_BYTES) {
46 + return json(413, { error: "body_too_large" }, "body_too_large");
47 + }
48 + // Chunked requests carry no content-length, so the reader itself is capped.
49 + const body = yield* request.arrayBuffer.pipe(
50 + Effect.map((buffer) => new Uint8Array(buffer)),
51 + Effect.provideService(
52 + HttpIncomingMessage.MaxBodySize,
53 + ByteSize.bytes(WEBHOOK_MAX_BODY_BYTES),
54 + ),
55 + Effect.option,
56 + );
57 + const tooLarge = (error: string) =>
58 + Metrics.increment(Metrics.webhookDeliveriesTotal, {
59 + outcome: "body_too_large",
60 + source: request.headers["x-t3-relay-delivery-id"] ? "relay" : "direct",
61 + }).pipe(Effect.as(json(413, { error }, "body_too_large")));
62 + if (Option.isNone(body)) return yield* tooLarge("body_too_large_or_unreadable");
63 + if (body.value.byteLength > WEBHOOK_MAX_BODY_BYTES) {
64 + return yield* tooLarge("body_too_large");
65 + }
66
67 - const headers: Record<string, string> = {};
68 - for (const [name, value] of Object.entries(request.headers)) {
69 - if (typeof value === "string") headers[name.toLowerCase()] = value;
70 - }
71 - const queryIndex = request.url.indexOf("?");
72 - // The relay's delivery id and receive time count only with its signed
73 - // proof; the URL can also be called directly. The receive time matters
74 - // for requests the relay held while we were offline.
75 - const relay = yield* relayDeliveryProof.verify({ headers, hookId: params.hookId });
76 - const relayDeliveryId = Option.isSome(relay) ? relay.value.deliveryId : undefined;
77 - const relayReceivedAt = Option.isSome(relay) ? relay.value.receivedAt : undefined;
67 + const headers: Record<string, string> = {};
68 + for (const [name, value] of Object.entries(request.headers)) {
69 + if (typeof value === "string") headers[name.toLowerCase()] = value;
70 + }
71 + const queryIndex = request.url.indexOf("?");
72 + // The relay's delivery id and receive time count only with its signed
73 + // proof; the URL can also be called directly. The receive time matters
74 + // for requests the relay held while we were offline.
75 + const relay = yield* relayDeliveryProof.verify({ headers, hookId: params.hookId });
76 + const relayDeliveryId = Option.isSome(relay) ? relay.value.deliveryId : undefined;
77 + const relayReceivedAt = Option.isSome(relay) ? relay.value.receivedAt : undefined;
78
79 - // A relay delivery joins the relay's trace, and goes to the T3 Connect
80 - // tracer with it. Anyone else's traceparent is never trusted.
81 - const relayParent = Option.isSome(relay)
82 - ? HttpTraceContext.fromHeaders(request.headers)
83 - : Option.none<Tracer.ExternalSpan>();
84 - const result = yield* scheduledTasks
85 - .triggerWebhook({
86 - hookId: params.hookId,
87 - token: params.token,
88 - method: request.method,
89 - path: `${ScheduledTaskService.WEBHOOK_ROUTE_PREFIX}/${encodeURIComponent(params.hookId)}`,
90 - query: queryIndex === -1 ? "" : request.url.slice(queryIndex + 1),
91 - headers,
92 - body: body.value,
93 - bodyText: new TextDecoder().decode(body.value),
94 - ...(relayDeliveryId ? { relayDeliveryId } : {}),
95 - ...(relayReceivedAt ? { receivedAt: relayReceivedAt } : {}),
96 - })
97 - .pipe(
98 - Option.isSome(relayParent)
99 - ? (effect) =>
100 - effect.pipe(Effect.withParentSpan(relayParent.value), withRelayClientTracing)
101 - : (effect) => effect,
102 - Effect.catchCause((cause) =>
103 - Effect.logWarning("Webhook delivery failed").pipe(
104 - Effect.annotateLogs({ hookId: params.hookId }),
105 - Effect.andThen(Effect.logDebug("Webhook delivery failure cause", { cause })),
106 - Effect.as({ _tag: "error" as const }),
107 - ),
79 + // A relay delivery joins the relay's trace, and goes to the T3 Connect
80 + // tracer with it. Anyone else's traceparent is never trusted.
81 + const relayParent = Option.isSome(relay)
82 + ? HttpTraceContext.fromHeaders(request.headers)
83 + : Option.none<Tracer.ExternalSpan>();
84 + const result = yield* scheduledTasks
85 + .triggerWebhook({
86 + hookId: params.hookId,
87 + token: params.token,
88 + method: request.method,
89 + path: `${ScheduledTaskService.WEBHOOK_ROUTE_PREFIX}/${encodeURIComponent(params.hookId)}`,
90 + query: queryIndex === -1 ? "" : request.url.slice(queryIndex + 1),
91 + headers,
92 + body: body.value,
93 + bodyText: new TextDecoder().decode(body.value),
94 + ...(relayDeliveryId ? { relayDeliveryId } : {}),
95 + ...(relayReceivedAt ? { receivedAt: relayReceivedAt } : {}),
96 + })
97 + .pipe(
98 + Option.isSome(relayParent)
99 + ? (effect) =>
100 + effect.pipe(Effect.withParentSpan(relayParent.value), withRelayClientTracing)
101 + : (effect) => effect,
102 + Effect.catchCause((cause) =>
103 + Effect.logWarning("Webhook delivery failed").pipe(
104 + Effect.annotateLogs({ hookId: params.hookId }),
105 + Effect.andThen(Effect.logDebug("Webhook delivery failure cause", { cause })),
106 + Effect.as({ _tag: "error" as const }),
107 ),
109 - );
108 + ),
109 + );
110
111 - switch (result._tag) {
112 - case "accepted":
113 - return json(202, { deliveryId: result.deliveryId }, result.outcome);
114 - case "not_found":
115 - return json(404, { error: "hook_not_found" }, "not_found");
116 - case "rejected_signature":
117 - return json(401, { error: "invalid_signature" }, "rejected_signature");
118 - case "disabled":
119 - return json(409, { error: "hook_disabled" }, "disabled");
120 - case "rate_limited":
121 - return json(429, { error: "rate_limited" }, result.outcome);
122 - case "expired":
123 - return json(410, { error: "delivery_too_old" }, "expired");
124 - case "error":
125 - return json(500, { error: "internal_error" }, "error");
126 - }
127 - });
111 + switch (result._tag) {
112 + case "accepted":
113 + return json(202, { deliveryId: result.deliveryId }, result.outcome);
114 + case "not_found":
115 + return json(404, { error: "hook_not_found" }, "not_found");
116 + case "rejected_signature":
117 + return json(401, { error: "invalid_signature" }, "rejected_signature");
118 + case "disabled":
119 + return json(409, { error: "hook_disabled" }, "disabled");
120 + case "rate_limited":
121 + return json(429, { error: "rate_limited" }, result.outcome);
122 + case "expired":
123 + return json(410, { error: "delivery_too_old" }, "expired");
124 + case "error":
125 + return json(500, { error: "internal_error" }, "error");
126 + }
127 + });
128 return handlers
129 .handleRaw("webhookPost", handler)
130 .handleRaw("webhookPut", handler)
apps/server/src/secrets/SecretRequests.ts
+34 -30
@@ -73,8 +73,8 @@ const make = Effect.gen(function* () {
73 yield* store.getOrCreateRandom("secret-request-salt", 32).pipe(Effect.orDie),
74 ).toString("hex");
75
76 - const answer: SecretRequests["Service"]["answer"] = (input) =>
77 - Effect.gen(function* () {
76 + const answer: SecretRequests["Service"]["answer"] = Effect.fn("SecretRequests.answer")(
77 + function* (input) {
78 yield* Effect.annotateCurrentSpan({
79 "orchestration_v2.thread_id": input.threadId,
80 "secret_request.answer": input.answer.type,
@@ -159,14 +159,16 @@ const make = Effect.gen(function* () {
159 yield* removeLogged(storeName(refFor(salt, input.threadId, item.id)));
160 return yield* new SecretRequestError({ reason: "agent_stopped" });
161 }
162 - }).pipe(Effect.withSpan("SecretRequests.answer"));
162 + },
163 + );
164
164 - const savedRef: SecretRequests["Service"]["savedRef"] = (input) =>
165 - Effect.gen(function* () {
165 + const savedRef: SecretRequests["Service"]["savedRef"] = Effect.fn("SecretRequests.savedRef")(
166 + function* (input) {
167 const ref = refFor(salt, input.threadId, input.turnItemId);
168 const stored = yield* store.get(storeName(ref)).pipe(Effect.orElseSucceed(Option.none));
169 return Option.map(stored, () => ref);
169 - });
170 + },
171 + );
172
173 const removeLogged = (name: string) =>
174 store.remove(name).pipe(
@@ -191,30 +193,32 @@ const make = Effect.gen(function* () {
193 Effect.withSpan("SecretRequests.consume"),
194 );
195
194 - const consumeRef = (input: { readonly ref: SecretRef; readonly projectId: ProjectId }) =>
195 - Effect.gen(function* () {
196 - if (!REF_PATTERN.test(input.ref))
197 - return yield* new SecretRequestError({ reason: "invalid_ref" });
198 - const stored = yield* store
199 - .get(storeName(input.ref))
200 - .pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "read_failed", cause })));
201 - const decoded = Option.flatMap(stored, (bytes) =>
202 - decodeStored(new TextDecoder().decode(bytes)),
203 - );
204 - if (Option.isNone(decoded) || decoded.value.projectId !== input.projectId) {
205 - return yield* new SecretRequestError({ reason: "ref_unavailable" });
206 - }
207 - if ((yield* Clock.currentTimeMillis) - decoded.value.savedAt > SECRET_REF_TTL_MS) {
208 - yield* removeLogged(storeName(input.ref));
209 - return yield* new SecretRequestError({ reason: "ref_expired" });
210 - }
211 - // One use: the value moves into whatever consumed it. If it cannot be
212 - // deleted, it is not handed out, so a ref is never used twice.
213 - if (!(yield* removeLogged(storeName(input.ref)))) {
214 - return yield* new SecretRequestError({ reason: "consume_failed" });
215 - }
216 - return decoded.value.value;
217 - });
196 + const consumeRef = Effect.fn("SecretRequests.consumeRef")(function* (input: {
197 + readonly ref: SecretRef;
198 + readonly projectId: ProjectId;
199 + }) {
200 + if (!REF_PATTERN.test(input.ref))
201 + return yield* new SecretRequestError({ reason: "invalid_ref" });
202 + const stored = yield* store
203 + .get(storeName(input.ref))
204 + .pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "read_failed", cause })));
205 + const decoded = Option.flatMap(stored, (bytes) =>
206 + decodeStored(new TextDecoder().decode(bytes)),
207 + );
208 + if (Option.isNone(decoded) || decoded.value.projectId !== input.projectId) {
209 + return yield* new SecretRequestError({ reason: "ref_unavailable" });
210 + }
211 + if ((yield* Clock.currentTimeMillis) - decoded.value.savedAt > SECRET_REF_TTL_MS) {
212 + yield* removeLogged(storeName(input.ref));
213 + return yield* new SecretRequestError({ reason: "ref_expired" });
214 + }
215 + // One use: the value moves into whatever consumed it. If it cannot be
216 + // deleted, it is not handed out, so a ref is never used twice.
217 + if (!(yield* removeLogged(storeName(input.ref)))) {
218 + return yield* new SecretRequestError({ reason: "consume_failed" });
219 + }
220 + return decoded.value.value;
221 + });
222
223 const sweepExpired = Effect.gen(function* () {
224 if (store.directory === undefined) return;
apps/server/src/serverActivation.ts
+13 -14
@@ -9,21 +9,20 @@ export class ServerActivation extends Context.Reference<Effect.Effect<void> | un
9 { defaultValue: () => undefined },
10 ) {}
11
12 -export const forkParkedFiber = <A, E, R>(
12 +export const forkParkedFiber = Effect.fn("serverActivation.forkParkedFiber")(function* <A, E, R>(
13 effect: Effect.Effect<A, E, R>,
14 -): Effect.Effect<Fiber.Fiber<A, E>, never, Scope.Scope | R> =>
15 - Effect.gen(function* () {
16 - const activation = yield* ServerActivation;
17 - if (activation === undefined) {
18 - return yield* Effect.forkScoped(effect);
19 - }
20 - const parked = yield* Deferred.make<void>();
21 - const fiber = yield* Effect.forkScoped(
22 - Deferred.succeed(parked, undefined).pipe(Effect.andThen(activation), Effect.andThen(effect)),
23 - );
24 - yield* Deferred.await(parked);
25 - return fiber;
26 - });
14 +): Effect.fn.Return<Fiber.Fiber<A, E>, never, Scope.Scope | R> {
15 + const activation = yield* ServerActivation;
16 + if (activation === undefined) {
17 + return yield* Effect.forkScoped(effect);
18 + }
19 + const parked = yield* Deferred.make<void>();
20 + const fiber = yield* Effect.forkScoped(
21 + Deferred.succeed(parked, undefined).pipe(Effect.andThen(activation), Effect.andThen(effect)),
22 + );
23 + yield* Deferred.await(parked);
24 + return fiber;
25 +});
26
27 export const forkParked = <A, E, R>(
28 effect: Effect.Effect<A, E, R>,
apps/server/src/serverRuntimeState.ts
+41 -38
@@ -85,30 +85,31 @@ export const persistServerRuntimeState = (input: {
85 ),
86 );
87
88 -export const clearPersistedServerRuntimeState = (path: string) =>
89 - Effect.gen(function* () {
90 - const fs = yield* FileSystem.FileSystem;
91 - yield* fs.remove(path, { force: true }).pipe(
92 - Effect.mapError(
93 - (cause) =>
94 - new ServerRuntimeStateError({
95 - operation: "clear",
96 - statePath: path,
97 - cause,
88 +export const clearPersistedServerRuntimeState = Effect.fn(
89 + "serverRuntimeState.clearPersistedServerRuntimeState",
90 +)(function* (path: string) {
91 + const fs = yield* FileSystem.FileSystem;
92 + yield* fs.remove(path, { force: true }).pipe(
93 + Effect.mapError(
94 + (cause) =>
95 + new ServerRuntimeStateError({
96 + operation: "clear",
97 + statePath: path,
98 + cause,
99 + }),
100 + ),
101 + Effect.catchTags({
102 + ServerRuntimeStateError: (error) =>
103 + Effect.logWarning(error.message).pipe(
104 + Effect.annotateLogs({
105 + operation: error.operation,
106 + statePath: error.statePath,
107 + cause: error,
108 }),
99 - ),
100 - Effect.catchTags({
101 - ServerRuntimeStateError: (error) =>
102 - Effect.logWarning(error.message).pipe(
103 - Effect.annotateLogs({
104 - operation: error.operation,
105 - statePath: error.statePath,
106 - cause: error,
107 - }),
108 - ),
109 - }),
110 - );
111 - });
109 + ),
110 + }),
111 + );
112 +});
113
114 /**
115 * Signal 0 delivers nothing; it only reports whether the pid exists. EPERM
@@ -124,8 +125,10 @@ export const isProcessAlive = (pid: number): boolean => {
125 }
126 };
127
127 -export const readPersistedServerRuntimeState = (path: string) =>
128 - Effect.gen(function* () {
128 +export const readPersistedServerRuntimeState = Effect.fn(
129 + "serverRuntimeState.readPersistedServerRuntimeState",
130 +)(
131 + function* (path: string) {
132 const fs = yield* FileSystem.FileSystem;
133 const raw = yield* fs.readFileString(path).pipe(
134 Effect.matchEffect({
@@ -162,16 +165,16 @@ export const readPersistedServerRuntimeState = (path: string) =>
165 }),
166 ),
167 );
165 - }).pipe(
166 - Effect.catchTags({
167 - ServerRuntimeStateError: (error) =>
168 - Effect.logWarning(error.message).pipe(
169 - Effect.annotateLogs({
170 - operation: error.operation,
171 - statePath: error.statePath,
172 - cause: error,
173 - }),
174 - Effect.as(Option.none<PersistedServerRuntimeState>()),
175 - ),
176 - }),
177 - );
168 + },
169 + Effect.catchTags({
170 + ServerRuntimeStateError: (error) =>
171 + Effect.logWarning(error.message).pipe(
172 + Effect.annotateLogs({
173 + operation: error.operation,
174 + statePath: error.statePath,
175 + cause: error,
176 + }),
177 + Effect.as(Option.none<PersistedServerRuntimeState>()),
178 + ),
179 + }),
180 +);
apps/server/src/serverSettings.ts
+60 -63
@@ -203,62 +203,59 @@ export class ServerSettingsService extends Context.Service<
203 static readonly layerTest = (overrides: DeepPartial<ServerSettings> = {}) => layerTest(overrides);
204 }
205
206 -const makeTest = (overrides: DeepPartial<ServerSettings> = {}) =>
207 - Effect.gen(function* () {
208 - const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } =
209 - overrides;
210 - const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge);
211 - const initialSettings = yield* normalizeServerSettings({
212 - ...merged,
213 - ...(automaticGitFetchInterval !== undefined
214 - ? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration }
215 - : {}),
216 - ...(providerHealthRefreshInterval !== undefined
217 - ? { providerHealthRefreshInterval: providerHealthRefreshInterval as Duration.Duration }
218 - : {}),
219 - });
220 - const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);
221 - const writeSemaphore = yield* Semaphore.make(1);
222 - const getSettings = Ref.get(currentSettingsRef).pipe(Effect.map(resolveTextGenerationProvider));
223 -
224 - const updateTestSettings = (
225 - update: (current: ServerSettings) => Effect.Effect<ServerSettings, ServerSettingsError>,
226 - ): Effect.Effect<ServerSettings, ServerSettingsError> =>
227 - writeSemaphore.withPermits(1)(
228 - Ref.get(currentSettingsRef).pipe(
229 - Effect.flatMap(update),
230 - Effect.flatMap(normalizeServerSettings),
231 - Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
232 - Effect.map(resolveTextGenerationProvider),
233 - ),
234 - );
235 -
236 - return {
237 - start: Effect.void,
238 - ready: Effect.void,
239 - getSettings,
240 - updateSettings: (patch) =>
241 - updateTestSettings((currentSettings) =>
242 - Effect.succeed(applyServerSettingsPatch(currentSettings, patch)),
243 - ),
244 - updateProviderInstance: (mutation, patch = {}) =>
245 - updateTestSettings((currentSettings) =>
246 - Effect.gen(function* () {
247 - yield* ensureProviderInstanceMutationAllowed(
248 - currentSettings,
249 - mutation,
250 - "test settings",
251 - );
252 - const patched = applyServerSettingsPatch(currentSettings, patch);
253 - return applyProviderInstanceMutation(patched, mutation);
254 - }),
255 - ),
256 - withSettingsSnapshot: (use) =>
257 - writeSemaphore.withPermits(1)(getSettings.pipe(Effect.flatMap(use))),
258 - streamChanges: Stream.empty,
259 - subscribeChanges: Effect.succeed(Stream.empty),
260 - } satisfies ServerSettingsService["Service"];
206 +const makeTest = Effect.fn("serverSettings.makeTest")(function* (
207 + overrides: DeepPartial<ServerSettings> = {},
208 +) {
209 + const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } =
210 + overrides;
211 + const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge);
212 + const initialSettings = yield* normalizeServerSettings({
213 + ...merged,
214 + ...(automaticGitFetchInterval !== undefined
215 + ? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration }
216 + : {}),
217 + ...(providerHealthRefreshInterval !== undefined
218 + ? { providerHealthRefreshInterval: providerHealthRefreshInterval as Duration.Duration }
219 + : {}),
220 });
221 + const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);
222 + const writeSemaphore = yield* Semaphore.make(1);
223 + const getSettings = Ref.get(currentSettingsRef).pipe(Effect.map(resolveTextGenerationProvider));
224 +
225 + const updateTestSettings = (
226 + update: (current: ServerSettings) => Effect.Effect<ServerSettings, ServerSettingsError>,
227 + ): Effect.Effect<ServerSettings, ServerSettingsError> =>
228 + writeSemaphore.withPermits(1)(
229 + Ref.get(currentSettingsRef).pipe(
230 + Effect.flatMap(update),
231 + Effect.flatMap(normalizeServerSettings),
232 + Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
233 + Effect.map(resolveTextGenerationProvider),
234 + ),
235 + );
236 +
237 + return {
238 + start: Effect.void,
239 + ready: Effect.void,
240 + getSettings,
241 + updateSettings: (patch) =>
242 + updateTestSettings((currentSettings) =>
243 + Effect.succeed(applyServerSettingsPatch(currentSettings, patch)),
244 + ),
245 + updateProviderInstance: (mutation, patch = {}) =>
246 + updateTestSettings((currentSettings) =>
247 + Effect.gen(function* () {
248 + yield* ensureProviderInstanceMutationAllowed(currentSettings, mutation, "test settings");
249 + const patched = applyServerSettingsPatch(currentSettings, patch);
250 + return applyProviderInstanceMutation(patched, mutation);
251 + }),
252 + ),
253 + withSettingsSnapshot: (use) =>
254 + writeSemaphore.withPermits(1)(getSettings.pipe(Effect.flatMap(use))),
255 + streamChanges: Stream.empty,
256 + subscribeChanges: Effect.succeed(Stream.empty),
257 + } satisfies ServerSettingsService["Service"];
258 +});
259
260 export const layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
261 Layer.effect(ServerSettingsService, makeTest(overrides));
@@ -625,8 +622,8 @@ const make = Effect.gen(function* () {
622 ),
623 );
624
628 - const moveInlineSettingsSecrets = (settings: ServerSettings) =>
629 - Effect.gen(function* () {
625 + const moveInlineSettingsSecrets = Effect.fn("serverSettings.moveInlineSettingsSecrets")(
626 + function* (settings: ServerSettings) {
627 const pending: SettingsSecret[] = [];
628 mapSettingsSecrets(settings, (secret) => {
629 if (secret.kind === "field" && !secret.redacted && secret.value.length > 0) {
@@ -652,7 +649,8 @@ const make = Effect.gen(function* () {
649 return mapSettingsSecrets(settings, (secret) =>
650 moved.has(secret.secretName) ? { value: "", redacted: true } : secret,
651 );
655 - });
652 + },
653 + );
654
655 const loadSettingsFromDisk = Effect.gen(function* () {
656 let settings = DEFAULT_SERVER_SETTINGS;
@@ -802,10 +800,8 @@ const make = Effect.gen(function* () {
800 Effect.andThen(Cache.get(settingsCache, cacheKey)),
801 );
802
805 - const materializeSettingsSecrets = (
806 - settings: ServerSettings,
807 - ): Effect.Effect<ServerSettings, ServerSettingsError> =>
808 - Effect.gen(function* () {
803 + const materializeSettingsSecrets = Effect.fn("serverSettings.materializeSettingsSecrets")(
804 + function* (settings: ServerSettings): Effect.fn.Return<ServerSettings, ServerSettingsError> {
805 const storedSecrets = new Map<string, string>();
806 const pending = new Map<string, SettingsSecret>();
807 mapSettingsSecrets(settings, (secret) => {
@@ -837,7 +833,8 @@ const make = Effect.gen(function* () {
833 : secret.value,
834 redacted: secret.sensitive && secret.kind === "environment" && secret.redacted,
835 }));
840 - });
836 + },
837 + );
838
839 const materializeChanges = (changes: Stream.Stream<ServerSettings>) =>
840 changes.pipe(
apps/server/src/storageCleanup.ts
+6 -6
@@ -247,8 +247,8 @@ const make = Effect.gen(function* () {
247 );
248 });
249
250 - const measureWorktree = (worktreePath: string) =>
251 - Effect.gen(function* () {
250 + const measureWorktree = Effect.fn("storageCleanup.measureWorktree")(
251 + function* (worktreePath: string) {
252 const root = yield* fs.realPath(worktreePath);
253 const pending = [root];
254 let entries = 1;
@@ -289,10 +289,10 @@ const make = Effect.gen(function* () {
289 }
290 }
291 return bytes;
292 - }).pipe(
293 - Effect.timeout("30 seconds"),
294 - Effect.orElseSucceed(() => null),
295 - );
292 + },
293 + Effect.timeout("30 seconds"),
294 + Effect.orElseSucceed(() => null),
295 + );
296
297 // The snapshot takes seconds on large databases, so it runs on the reader
298 // worker instead of the event loop.
apps/server/src/telemetry/DelegatedTaskAnalytics.ts
+6 -3
@@ -40,8 +40,9 @@ const make = Effect.gen(function* () {
40 // A task can be re-reported with the same final status; count it once per process.
41 const reported = new Set<string>();
42
43 - const onSubagent = (event: SubagentEvent) =>
44 - Effect.gen(function* () {
43 + // Runs for every subagent update; most return early, so avoid a span per event.
44 + const onSubagent = Effect.fnUntraced(
45 + function* (event: SubagentEvent) {
46 const task = event.payload;
47 if (task.origin !== "app_owned" || !FINAL_STATUSES.has(task.status)) return;
48 if (reported.has(task.id)) return;
@@ -79,7 +80,9 @@ const make = Effect.gen(function* () {
80 });
81 // Only after recording: a failed lookup leaves the next final update to report it.
82 reported.add(task.id);
82 - }).pipe(Effect.ignoreCause);
83 + },
84 + (effect) => effect.pipe(Effect.ignoreCause),
85 + );
86
87 yield* forkParked(
88 Stream.runForEach(orchestrator.streamDomainEvents, (event) =>
apps/server/src/terminal/Manager.ts
+80 -78
@@ -1541,8 +1541,9 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
1541 const workerScope = yield* Scope.make("sequential");
1542 yield* Effect.addFinalizer(() => Scope.close(workerScope, Exit.void));
1543
1544 - const publishEvent = (event: TerminalEvent) =>
1545 - Effect.gen(function* () {
1544 + const publishEvent =
1545 + /* Provider events include streaming deltas; avoid a span for each update. */
1546 + Effect.fnUntraced(function* (event: TerminalEvent) {
1547 for (const listener of terminalEventListeners) {
1548 yield* listener(event).pipe(Effect.ignoreCause({ log: true }));
1549 }
@@ -3016,84 +3017,85 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
3017 }),
3018 );
3019
3019 - const restartResolved = (input: TerminalRestartInput) =>
3020 - Effect.gen(function* () {
3021 - yield* increment(terminalRestartsTotal, { scope: "thread" });
3022 - const terminalId = input.terminalId;
3023 - yield* assertValidCwd(input.cwd);
3024 -
3025 - const sessionKey = toSessionKey(input.threadId, terminalId);
3026 - const existingSession = yield* getSession(input.threadId, terminalId);
3027 - let session: TerminalSessionState;
3028 - if (Option.isNone(existingSession)) {
3029 - const cols = input.cols ?? DEFAULT_OPEN_COLS;
3030 - const rows = input.rows ?? DEFAULT_OPEN_ROWS;
3031 - session = {
3032 - threadId: input.threadId,
3033 - terminalId,
3034 - cwd: input.cwd,
3035 - worktreePath: input.worktreePath ?? null,
3036 - status: "starting",
3037 - pid: null,
3038 - history: new BoundedTerminalHistory(historyLineLimit, "", historyByteLimit),
3039 - pendingHistoryControlSequence: "",
3040 - pendingProcessEvents: [],
3041 - pendingProcessEventIndex: 0,
3042 - processEventDrainRunning: false,
3043 - exitCode: null,
3044 - exitSignal: null,
3045 - updatedAt: yield* nowIso,
3046 - eventSequence: 0,
3047 - inputCount: 0,
3048 - cols,
3049 - rows,
3050 - process: null,
3051 - unsubscribeData: null,
3052 - unsubscribeExit: null,
3053 - hasRunningSubprocess: false,
3054 - childCommandLabel: null,
3055 - runtimeEnv: normalizedRuntimeEnv(input.env),
3056 - };
3057 - const createdSession = session;
3058 - yield* modifyManagerState((state) => {
3059 - const sessions = new Map(state.sessions);
3060 - sessions.set(sessionKey, createdSession);
3061 - closedSessionKeys.delete(sessionKey);
3062 - return [undefined, { ...state, sessions }] as const;
3063 - });
3064 - yield* evictInactiveSessionsIfNeeded();
3065 - } else {
3066 - session = existingSession.value;
3067 - yield* stopProcess(session);
3068 - session.cwd = input.cwd;
3069 - session.worktreePath = input.worktreePath ?? null;
3070 - session.runtimeEnv = normalizedRuntimeEnv(input.env);
3071 - }
3020 + const restartResolved = Effect.fn("Manager.restartResolved")(function* (
3021 + input: TerminalRestartInput,
3022 + ) {
3023 + yield* increment(terminalRestartsTotal, { scope: "thread" });
3024 + const terminalId = input.terminalId;
3025 + yield* assertValidCwd(input.cwd);
3026
3073 - const cols = input.cols ?? session.cols;
3074 - const rows = input.rows ?? session.rows;
3027 + const sessionKey = toSessionKey(input.threadId, terminalId);
3028 + const existingSession = yield* getSession(input.threadId, terminalId);
3029 + let session: TerminalSessionState;
3030 + if (Option.isNone(existingSession)) {
3031 + const cols = input.cols ?? DEFAULT_OPEN_COLS;
3032 + const rows = input.rows ?? DEFAULT_OPEN_ROWS;
3033 + session = {
3034 + threadId: input.threadId,
3035 + terminalId,
3036 + cwd: input.cwd,
3037 + worktreePath: input.worktreePath ?? null,
3038 + status: "starting",
3039 + pid: null,
3040 + history: new BoundedTerminalHistory(historyLineLimit, "", historyByteLimit),
3041 + pendingHistoryControlSequence: "",
3042 + pendingProcessEvents: [],
3043 + pendingProcessEventIndex: 0,
3044 + processEventDrainRunning: false,
3045 + exitCode: null,
3046 + exitSignal: null,
3047 + updatedAt: yield* nowIso,
3048 + eventSequence: 0,
3049 + inputCount: 0,
3050 + cols,
3051 + rows,
3052 + process: null,
3053 + unsubscribeData: null,
3054 + unsubscribeExit: null,
3055 + hasRunningSubprocess: false,
3056 + childCommandLabel: null,
3057 + runtimeEnv: normalizedRuntimeEnv(input.env),
3058 + };
3059 + const createdSession = session;
3060 + yield* modifyManagerState((state) => {
3061 + const sessions = new Map(state.sessions);
3062 + sessions.set(sessionKey, createdSession);
3063 + closedSessionKeys.delete(sessionKey);
3064 + return [undefined, { ...state, sessions }] as const;
3065 + });
3066 + yield* evictInactiveSessionsIfNeeded();
3067 + } else {
3068 + session = existingSession.value;
3069 + yield* stopProcess(session);
3070 + session.cwd = input.cwd;
3071 + session.worktreePath = input.worktreePath ?? null;
3072 + session.runtimeEnv = normalizedRuntimeEnv(input.env);
3073 + }
3074
3076 - session.history.clear();
3077 - session.pendingHistoryControlSequence = "";
3078 - session.pendingProcessEvents = [];
3079 - session.pendingProcessEventIndex = 0;
3080 - session.processEventDrainRunning = false;
3081 - yield* persistHistory(input.threadId, terminalId, session.history);
3082 - yield* startSession(
3083 - session,
3084 - {
3085 - threadId: input.threadId,
3086 - terminalId,
3087 - cwd: input.cwd,
3088 - ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
3089 - cols,
3090 - rows,
3091 - ...(input.env ? { env: input.env } : {}),
3092 - },
3093 - "restarted",
3094 - );
3095 - return snapshot(session);
3096 - });
3075 + const cols = input.cols ?? session.cols;
3076 + const rows = input.rows ?? session.rows;
3077 +
3078 + session.history.clear();
3079 + session.pendingHistoryControlSequence = "";
3080 + session.pendingProcessEvents = [];
3081 + session.pendingProcessEventIndex = 0;
3082 + session.processEventDrainRunning = false;
3083 + yield* persistHistory(input.threadId, terminalId, session.history);
3084 + yield* startSession(
3085 + session,
3086 + {
3087 + threadId: input.threadId,
3088 + terminalId,
3089 + cwd: input.cwd,
3090 + ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
3091 + cols,
3092 + rows,
3093 + ...(input.env ? { env: input.env } : {}),
3094 + },
3095 + "restarted",
3096 + );
3097 + return snapshot(session);
3098 + });
3099
3100 const restart: TerminalManager["Service"]["restart"] = (input) =>
3101 withThreadLock(
apps/server/src/usage/UsageLimitSources.ts
+26 -26
@@ -74,13 +74,14 @@ export const make = Effect.gen(function* () {
74 return { ...base, accounts: accounts.success };
75 });
76
77 - const publish = (next: ReadonlyArray<UsageLimitSourceSnapshot>) =>
78 - Effect.gen(function* () {
79 - const changed = yield* Ref.modify(stateRef, (previous) =>
80 - Equal.equals(previous, next) ? [false, previous] : [true, next],
81 - );
82 - if (changed) yield* PubSub.publish(changes, next);
83 - });
77 + const publish = Effect.fn("UsageLimitSources.publish")(function* (
78 + next: ReadonlyArray<UsageLimitSourceSnapshot>,
79 + ) {
80 + const changed = yield* Ref.modify(stateRef, (previous) =>
81 + Equal.equals(previous, next) ? [false, previous] : [true, next],
82 + );
83 + if (changed) yield* PubSub.publish(changes, next);
84 + });
85
86 // One refresh at a time: a slow hub read started before a settings change
87 // must not publish after the change's own refresh and resurrect a removed
@@ -102,25 +103,24 @@ export const make = Effect.gen(function* () {
103 }).pipe(refreshLock.withPermits(1), Effect.ignoreCause({ log: true }));
104
105 // Shares the refresh lock so a stale in-flight read cannot overwrite a redemption.
105 - const consumeResetCredit = (input: UsageLimitSourceConsumeResetCreditInput) =>
106 - Effect.gen(function* () {
107 - const settings = yield* settingsService.getSettings.pipe(
108 - Effect.mapError(
109 - () => new UsageLimitSourceError({ detail: "Could not read hub settings." }),
110 - ),
111 - );
112 - const config = settings.usageLimitSources[input.sourceId];
113 - if (!config?.enabled || !config.managementKey) {
114 - return yield* new UsageLimitSourceError({
115 - detail: "The usage limit source is missing or disabled.",
116 - });
117 - }
118 - const result = yield* api.consume(config, input.accountId, input.creditId);
119 - const snapshot = yield* readSource(input.sourceId, config);
120 - const previous = yield* Ref.get(stateRef);
121 - yield* publish(previous.map((source) => (source.id === input.sourceId ? snapshot : source)));
122 - return result;
123 - }).pipe(refreshLock.withPermits(1));
106 + const consumeResetCredit = Effect.fn("UsageLimitSources.consumeResetCredit")(function* (
107 + input: UsageLimitSourceConsumeResetCreditInput,
108 + ) {
109 + const settings = yield* settingsService.getSettings.pipe(
110 + Effect.mapError(() => new UsageLimitSourceError({ detail: "Could not read hub settings." })),
111 + );
112 + const config = settings.usageLimitSources[input.sourceId];
113 + if (!config?.enabled || !config.managementKey) {
114 + return yield* new UsageLimitSourceError({
115 + detail: "The usage limit source is missing or disabled.",
116 + });
117 + }
118 + const result = yield* api.consume(config, input.accountId, input.creditId);
119 + const snapshot = yield* readSource(input.sourceId, config);
120 + const previous = yield* Ref.get(stateRef);
121 + yield* publish(previous.map((source) => (source.id === input.sourceId ? snapshot : source)));
122 + return result;
123 + }, refreshLock.withPermits(1));
124
125 yield* settingsService.streamChanges.pipe(
126 Stream.map((settings) => settings.usageLimitSources),
apps/server/src/usage/UsageService.ts
+46 -49
@@ -451,66 +451,63 @@ export const make = Effect.gen(function* () {
451 * than completion order: saved records of deleted transcripts aggregate in
452 * cache order, where the first copy of a duplicate wins.
453 */
454 - const readFileRecords = (
454 + const readFileRecords = Effect.fn("UsageService.readFileRecords")(function* (
455 filePath: string,
456 size: number,
457 mtimeMs: number,
458 provider: UsageProviderKind,
459 format: TranscriptUsageFormat<unknown>,
460 - ): Effect.Effect<{
460 + ): Effect.fn.Return<{
461 readonly records: readonly UsageRecord[];
462 readonly failed?: true;
463 readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined };
464 - }> =>
465 - Effect.gen(function* () {
466 - const cached = fileCache.get(filePath);
467 - // Provider is part of the identity: if both providers were ever pointed
468 - // at one directory, a hit parsed by the other parser must not be reused.
469 - if (
470 - cached &&
471 - cached.size === size &&
472 - cached.mtimeMs === mtimeMs &&
473 - cached.provider === provider
474 - ) {
475 - return {
476 - records:
477 - cached.tailRecords.length === 0
478 - ? cached.records
479 - : [...cached.records, ...cached.tailRecords],
480 - };
481 - }
482 -
483 - // Only a strictly grown file may resume. Same size with a new mtime, or
484 - // a shrunken file, means rewritten content; re-parse it whole.
485 - const resumeFrom =
486 - cached !== undefined && cached.provider === provider && size > cached.size
487 - ? cached.position
488 - : undefined;
489 -
490 - const parsed = yield* Effect.promise(() =>
491 - readTranscriptRecords(filePath, format, resumeFrom),
492 - );
493 - // A read failure is not an empty transcript: caching it under this
494 - // (size, mtime) would silently drop the file's usage until it changes.
495 - if (parsed === null)
496 - return {
497 - records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [],
498 - failed: true,
499 - };
500 -
501 - const base = parsed.resumed && cached !== undefined ? cached.records : [];
502 - const seen = new Set<string>();
503 - const records = dedupeWithinFile([...base, ...parsed.records], seen);
504 - const tailRecords = dedupeWithinFile(parsed.tailRecords, seen);
464 + }> {
465 + const cached = fileCache.get(filePath);
466 + // Provider is part of the identity: if both providers were ever pointed
467 + // at one directory, a hit parsed by the other parser must not be reused.
468 + if (
469 + cached &&
470 + cached.size === size &&
471 + cached.mtimeMs === mtimeMs &&
472 + cached.provider === provider
473 + ) {
474 + return {
475 + records:
476 + cached.tailRecords.length === 0
477 + ? cached.records
478 + : [...cached.records, ...cached.tailRecords],
479 + };
480 + }
481
482 + // Only a strictly grown file may resume. Same size with a new mtime, or
483 + // a shrunken file, means rewritten content; re-parse it whole.
484 + const resumeFrom =
485 + cached !== undefined && cached.provider === provider && size > cached.size
486 + ? cached.position
487 + : undefined;
488 +
489 + const parsed = yield* Effect.promise(() => readTranscriptRecords(filePath, format, resumeFrom));
490 + // A read failure is not an empty transcript: caching it under this
491 + // (size, mtime) would silently drop the file's usage until it changes.
492 + if (parsed === null)
493 return {
507 - records: tailRecords.length === 0 ? records : [...records, ...tailRecords],
508 - update: {
509 - entry: { size, mtimeMs, provider, records, tailRecords, position: parsed.position },
510 - replaces: cached,
511 - },
494 + records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [],
495 + failed: true,
496 };
513 - });
497 +
498 + const base = parsed.resumed && cached !== undefined ? cached.records : [];
499 + const seen = new Set<string>();
500 + const records = dedupeWithinFile([...base, ...parsed.records], seen);
501 + const tailRecords = dedupeWithinFile(parsed.tailRecords, seen);
502 +
503 + return {
504 + records: tailRecords.length === 0 ? records : [...records, ...tailRecords],
505 + update: {
506 + entry: { size, mtimeMs, provider, records, tailRecords, position: parsed.position },
507 + replaces: cached,
508 + },
509 + };
510 + });
511
512 interface ScannedDir {
513 readonly provider: UsageProviderKind;
apps/server/src/vcs/GitVcsDriver.ts
+10 -9
@@ -783,16 +783,17 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
783 }),
784 );
785
786 - const resolveGitCommonDir = (cwd: string) =>
787 - Effect.gen(function* () {
788 - const result = yield* execute({
789 - operation: "GitVcsDriver.checkpoints.resolveGitCommonDir",
790 - cwd,
791 - args: ["rev-parse", "--git-common-dir"],
792 - });
793 - const gitCommonDir = result.stdout.trim();
794 - return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
786 + const resolveGitCommonDir = Effect.fn("GitVcsDriver.resolveGitCommonDir")(function* (
787 + cwd: string,
788 + ) {
789 + const result = yield* execute({
790 + operation: "GitVcsDriver.checkpoints.resolveGitCommonDir",
791 + cwd,
792 + args: ["rev-parse", "--git-common-dir"],
793 });
794 + const gitCommonDir = result.stdout.trim();
795 + return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
796 + });
797
798 // Git renames loose objects and refs into place without fsync by default, so
799 // an unclean restart can leave 0-byte files under refs/t3/** that break every
apps/server/src/vcs/GitVcsDriverCore.ts
+29 -26
@@ -600,14 +600,16 @@ const nowUnixNano = DateTime.now.pipe(
600 Effect.map((now) => BigInt(DateTime.toEpochMillis(now)) * 1_000_000n),
601 );
602
603 -const addCurrentSpanEvent = (name: string, attributes: Record<string, unknown>) =>
604 - Effect.gen(function* () {
605 - const span = yield* Effect.currentSpan;
606 - const timestamp = yield* nowUnixNano;
607 - yield* Effect.sync(() => {
608 - span.event(name, timestamp, compactTraceAttributes(attributes));
609 - });
610 - }).pipe(
603 +const addCurrentSpanEvent =
604 + /* This helper annotates the existing operation span. */
605 + Effect.fnUntraced(
606 + function* (name: string, attributes: Record<string, unknown>) {
607 + const span = yield* Effect.currentSpan;
608 + const timestamp = yield* nowUnixNano;
609 + yield* Effect.sync(() => {
610 + span.event(name, timestamp, compactTraceAttributes(attributes));
611 + });
612 + },
613 Effect.catchTags({
614 NoSuchElementError: () => Effect.void,
615 }),
@@ -1440,15 +1442,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1442 }),
1443 },
1444 );
1443 - const invalidateStatusStaticCaches = (cwd: string) =>
1444 - Effect.gen(function* () {
1445 + const invalidateStatusStaticCaches = Effect.fn("GitVcsDriverCore.invalidateStatusStaticCaches")(
1446 + function* (cwd: string) {
1447 const repositoryPaths = yield* resolveRepositoryPaths(cwd).pipe(
1448 Effect.catchTags({ GitCommandError: () => Effect.succeed(null) }),
1449 );
1450 const cacheKey = repositoryPaths?.gitCommonDir ?? normalizeRepositoryPathsCacheKey(cwd);
1451 yield* Cache.invalidate(defaultBranchCache, cacheKey);
1452 yield* Cache.invalidate(originExistsCache, cacheKey);
1451 - });
1453 + },
1454 + );
1455
1456 const resolveGitCommonDir = Effect.fn("resolveGitCommonDir")(function* (cwd: string) {
1457 const repositoryPaths = yield* resolveRepositoryPaths(cwd);
@@ -3994,22 +3997,22 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3997 * Unlinks links under `target` without following them and removes the
3998 * directories that leaves empty. Returns false when anything else remains.
3999 */
3997 - const removeLeftoverLinks = (
4000 + // Recursive filesystem traversal can visit many entries; removeWorktree owns the operation span.
4001 + const removeLeftoverLinks = Effect.fnUntraced(function* (
4002 target: string,
3999 - ): Effect.Effect<boolean, PlatformError.PlatformError | Cause.UnknownError> =>
4000 - Effect.gen(function* () {
4001 - if (Option.isSome(yield* fileSystem.readLink(target).pipe(Effect.option))) {
4002 - yield* fileSystem.remove(target);
4003 - return true;
4004 - }
4005 - if ((yield* fileSystem.stat(target)).type !== "Directory") return false;
4006 - let empty = true;
4007 - for (const name of yield* fileSystem.readDirectory(target)) {
4008 - if (!(yield* removeLeftoverLinks(path.join(target, name)))) empty = false;
4009 - }
4010 - // Only an empty directory goes, so files written since the listing stay.
4011 - return empty && (yield* removeEmptyDirectory(target));
4012 - });
4003 + ): Effect.fn.Return<boolean, PlatformError.PlatformError | Cause.UnknownError> {
4004 + if (Option.isSome(yield* fileSystem.readLink(target).pipe(Effect.option))) {
4005 + yield* fileSystem.remove(target);
4006 + return true;
4007 + }
4008 + if ((yield* fileSystem.stat(target)).type !== "Directory") return false;
4009 + let empty = true;
4010 + for (const name of yield* fileSystem.readDirectory(target)) {
4011 + if (!(yield* removeLeftoverLinks(path.join(target, name)))) empty = false;
4012 + }
4013 + // Only an empty directory goes, so files written since the listing stay.
4014 + return empty && (yield* removeEmptyDirectory(target));
4015 + });
4016
4017 const removeWorktree: GitVcsDriver.GitVcsDriver["Service"]["removeWorktree"] = Effect.fn(
4018 "removeWorktree",
apps/server/src/vcs/VcsStatusBroadcaster.ts
+70 -71
@@ -555,88 +555,87 @@ export const make = Effect.gen(function* () {
555 );
556 });
557
558 - const makeRemoteRefreshLoop = (
558 + // A subscription owns this loop; keep each poll's spans out of a never-ending parent span.
559 + const makeRemoteRefreshLoop = Effect.fnUntraced(function* (
560 cwd: string,
561 demandCwdsRef: Ref.Ref<ReadonlyMap<string, number>>,
562 refreshImmediately: boolean,
562 - ) => {
563 - return Effect.gen(function* () {
564 - const consecutiveFailuresRef = yield* Ref.make(0);
565 - const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
566 - const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
567 - const configuredInterval = yield* automaticFetchInterval;
568 - const activeInterval = Duration.isZero(configuredInterval)
569 - ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
570 - : configuredInterval;
571 - const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
572 - if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
573 - return activeInterval;
574 - }
563 + ) {
564 + const consecutiveFailuresRef = yield* Ref.make(0);
565 + const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
566 + const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
567 + const configuredInterval = yield* automaticFetchInterval;
568 + const activeInterval = Duration.isZero(configuredInterval)
569 + ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
570 + : configuredInterval;
571 + const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
572 + if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
573 + return activeInterval;
574 + }
575
576 - const demandCwds = yield* Ref.get(demandCwdsRef);
577 - const shouldRun =
578 - needsInitialRefresh ||
579 - (yield* Effect.forEach(
580 - [...demandCwds.keys()],
581 - (demandCwd) =>
582 - backgroundPolicy.shouldRunScopeWork({
583 - type: "vcs-status",
584 - cwd: demandCwd,
585 - }),
586 - { concurrency: "unbounded" },
587 - )).some(Boolean);
588 - if (!shouldRun) {
589 - return activeInterval;
590 - }
576 + const demandCwds = yield* Ref.get(demandCwdsRef);
577 + const shouldRun =
578 + needsInitialRefresh ||
579 + (yield* Effect.forEach(
580 + [...demandCwds.keys()],
581 + (demandCwd) =>
582 + backgroundPolicy.shouldRunScopeWork({
583 + type: "vcs-status",
584 + cwd: demandCwd,
585 + }),
586 + { concurrency: "unbounded" },
587 + )).some(Boolean);
588 + if (!shouldRun) {
589 + return activeInterval;
590 + }
591
592 - const exit = yield* refreshRemoteStatus(cwd, {
593 - refreshUpstream: !Duration.isZero(configuredInterval),
594 - policyCwds: [...demandCwds.keys()],
595 - }).pipe(Effect.exit);
596 - if (Exit.isSuccess(exit)) {
597 - yield* Ref.set(needsInitialRefreshRef, false);
598 - yield* Ref.set(consecutiveFailuresRef, 0);
599 - return activeInterval;
600 - }
592 + const exit = yield* refreshRemoteStatus(cwd, {
593 + refreshUpstream: !Duration.isZero(configuredInterval),
594 + policyCwds: [...demandCwds.keys()],
595 + }).pipe(Effect.exit);
596 + if (Exit.isSuccess(exit)) {
597 + yield* Ref.set(needsInitialRefreshRef, false);
598 + yield* Ref.set(consecutiveFailuresRef, 0);
599 + return activeInterval;
600 + }
601
602 - const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
603 - if (interruptionReasons.length > 0) {
604 - return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
605 - }
602 + const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
603 + if (interruptionReasons.length > 0) {
604 + return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
605 + }
606
607 - const consecutiveFailures = yield* Ref.updateAndGet(
608 - consecutiveFailuresRef,
609 - (count) => count + 1,
610 - );
611 - const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
612 - yield* Effect.logWarning("VCS remote status refresh failed", {
613 - cwdLength: cwd.length,
614 - ...remoteRefreshFailureDiagnostics(exit.cause),
615 - consecutiveFailures,
616 - nextDelayMs: Duration.toMillis(nextDelay),
617 - });
618 - return nextDelay;
607 + const consecutiveFailures = yield* Ref.updateAndGet(
608 + consecutiveFailuresRef,
609 + (count) => count + 1,
610 + );
611 + const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
612 + yield* Effect.logWarning("VCS remote status refresh failed", {
613 + cwdLength: cwd.length,
614 + ...remoteRefreshFailureDiagnostics(exit.cause),
615 + consecutiveFailures,
616 + nextDelayMs: Duration.toMillis(nextDelay),
617 });
618 + return nextDelay;
619 + });
620
621 - if (!refreshImmediately) {
622 - const configuredInterval = yield* automaticFetchInterval;
623 - yield* Effect.sleep(
624 - Duration.isZero(configuredInterval)
625 - ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
626 - : configuredInterval,
627 - );
628 - }
621 + if (!refreshImmediately) {
622 + const configuredInterval = yield* automaticFetchInterval;
623 + yield* Effect.sleep(
624 + Duration.isZero(configuredInterval)
625 + ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
626 + : configuredInterval,
627 + );
628 + }
629
630 - return yield* refreshRemoteStatusIfEnabled.pipe(
631 - Effect.repeat(
632 - Schedule.identity<Duration.Duration>().pipe(
633 - Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),
634 - ),
630 + return yield* refreshRemoteStatusIfEnabled.pipe(
631 + Effect.repeat(
632 + Schedule.identity<Duration.Duration>().pipe(
633 + Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),
634 ),
636 - Effect.asVoid,
637 - );
638 - });
639 - };
635 + ),
636 + Effect.asVoid,
637 + );
638 + });
639
640 const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
641 cwd: string,
apps/server/src/workspace/WorkspaceEntries.ts
+9 -8
@@ -160,20 +160,21 @@ export const make = Effect.gen(function* () {
160 if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {
161 continue;
162 }
163 - const recoverRefreshFailure = (
164 - cause:
165 - | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
166 - | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
167 - | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
168 - ) =>
169 - Effect.gen(function* () {
163 + const recoverRefreshFailure = Effect.fn("WorkspaceEntries.recoverRefreshFailure")(
164 + function* (
165 + cause:
166 + | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
167 + | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
168 + | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
169 + ) {
170 yield* Effect.logWarning("Failed to refresh workspace search index", {
171 cwd,
172 variant,
173 cause,
174 });
175 yield* workspaceSearchIndexes.invalidate(indexKey);
176 - });
176 + },
177 + );
178 yield* Effect.gen(function* () {
179 const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
180 yield* searchIndex.refresh();