From 538ff76dd68f50caa44cc143dfa1808d777f21fa Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 12:28:47 +0100 Subject: [PATCH 01/13] fix(server): a late daily task runs once instead of being skipped A fixed-time task whose occurrence was more than 10 minutes late (machine asleep, server down) was silently rescheduled to the next day, so the work never ran. Drop the grace window: any due occurrence now runs when the scheduler can run it. The run's completion computes the next occurrence from the completion time, so a backlog of missed days produces one catch-up run, then the task continues on its normal schedule. Interval and one-time schedules already ran late occurrences this way. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/scheduledTasks/Schedule.ts | 13 ---- .../ScheduledTaskService.schedule.test.ts | 71 +++++++++++++++++++ .../scheduledTasks/ScheduledTaskService.ts | 39 ++-------- 3 files changed, 76 insertions(+), 47 deletions(-) diff --git a/apps/server/src/scheduledTasks/Schedule.ts b/apps/server/src/scheduledTasks/Schedule.ts index f8fb648aaaaa9..0e2abe8df948f 100644 --- a/apps/server/src/scheduledTasks/Schedule.ts +++ b/apps/server/src/scheduledTasks/Schedule.ts @@ -2,8 +2,6 @@ import { MIN_SCHEDULED_TASK_INTERVAL_MS, type ScheduledTaskSchedule } from "@t3t import * as DateTime from "effect/DateTime"; import * as Option from "effect/Option"; -const MINUTE_MS = 60_000; - function parseTimeOfDay(value: string): { hour: number; minute: number } | null { const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(value.trim()); if (!match) return null; @@ -69,14 +67,3 @@ export function isSameSchedule(a: ScheduledTaskSchedule, b: ScheduledTaskSchedul weekdayKey(a.weekdays) === weekdayKey(b.weekdays) ); } - -const MISSED_FIXED_TIME_GRACE_MS = 10 * MINUTE_MS; - -export function isMissedFixedTimeRun( - schedule: ScheduledTaskSchedule, - dueAt: DateTime.DateTime, - now: DateTime.DateTime, -): boolean { - if (schedule.type !== "fixed_time") return false; - return DateTime.toEpochMillis(now) - DateTime.toEpochMillis(dueAt) > MISSED_FIXED_TIME_GRACE_MS; -} diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts index a6adcdaba9108..27b2503eb6125 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts @@ -5,8 +5,12 @@ import { ScheduledTaskUpsertInput } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; @@ -14,6 +18,7 @@ import * as ThreadManagementService from "../orchestration-v2/ThreadManagementSe import * as SecretRequests from "../secrets/SecretRequests.ts"; import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { ServerActivation } from "../serverActivation.ts"; import * as ScheduledTaskService from "./ScheduledTaskService.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; @@ -234,3 +239,69 @@ it.effect( }).pipe(Effect.provide(ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies)))); }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); + +it.effect("a fixed-time run missed by hours runs once, then keeps its daily time", () => + Effect.gen(function* () { + const dueAt = DateTime.makeZonedUnsafe( + { year: 2026, month: 7, day: 1, hour: 9, minute: 0, second: 0, millisecond: 0 }, + { timeZone: DateTime.zoneMakeLocal(), adjustForTimeZone: true }, + ); + yield* TestClock.setTime(DateTime.toEpochMillis(dueAt) - 1_000); + const launches = yield* Ref.make(0); + const layerDependencies = Layer.mergeAll( + NodeCrypto.layer, + Scheduler.layer, + ManagedPolicy.layerTest(), + Layer.mock(ThreadLaunchService.ThreadLaunchService)({ + launch: () => + Ref.update(launches, (count) => count + 1).pipe( + Effect.as({ threadId: "thread-missed-run", resumed: false } as never), + ), + }), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), + Layer.mock(ThreadManagementService.ThreadManagementService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + ); + const serviceLayer = ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies)); + const created = yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + return yield* service.upsert( + yield* decodeUpsertInput({ + title: "Morning review", + prompt: "Review the open pull requests.", + enabled: true, + schedule: { type: "fixed_time", timeOfDay: "09:00" }, + projectId: "project-missed-run", + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + }), + ); + }).pipe( + Effect.provide(serviceLayer), + // The server is down while several days of occurrences pass. + Effect.provideService(ServerActivation, Effect.never), + ); + yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.add(dueAt, { days: 3, hours: 6 }))); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const completedRun = yield* service.subscribeList().pipe( + Stream.map(({ tasks }) => tasks.find((task) => task.id === created.task.id)), + Stream.filter((task) => task !== undefined && task.runCount > 0), + Stream.runHead, + Effect.forkChild, + ); + yield* TestClock.adjust("6 seconds"); + const task = Option.getOrThrow(yield* Fiber.join(completedRun)); + expect(task?.nextRunAt).toBe( + DateTime.formatIso(DateTime.toUtc(DateTime.add(dueAt, { days: 4 }))), + ); + yield* TestClock.adjust("6 seconds"); + expect(yield* Ref.get(launches)).toBe(1); + }).pipe(Effect.provide(serviceLayer)); + }).pipe(Effect.provide(SqlitePersistence.layerMemory)), +); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 4fd59e610f0f3..1fe1845818856 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -57,7 +57,7 @@ import * as SecretRequests from "../secrets/SecretRequests.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import * as DueHint from "../scheduling/DueHint.ts"; import * as Scheduler from "../scheduling/Scheduler.ts"; -import { isMissedFixedTimeRun, isSameSchedule, nextScheduledRunAt } from "./Schedule.ts"; +import { isSameSchedule, nextScheduledRunAt } from "./Schedule.ts"; import { redactHeaders, redactQuery, @@ -1111,29 +1111,6 @@ export const layer = Layer.effect( ); }); - const rescheduleMissedRun = Effect.fn("ScheduledTaskService.rescheduleMissedRun")(function* ( - task: ScheduledTask, - now: DateTime.DateTime, - ) { - const next = nextRunAt(task, now); - yield* Effect.logInfo("Skipping missed schedule task run", { - taskId: task.id, - missedRunAt: task.nextRunAt, - rescheduledTo: next, - }); - yield* sql` - UPDATE scheduled_tasks - SET next_run_at = ${next}, - updated_at = ${iso(now)} - WHERE task_id = ${task.id} - `.pipe( - Effect.mapError((cause) => - taskError("Could not reschedule missed schedule task run.", { taskId: task.id, cause }), - ), - ); - yield* notifyChanged; - }); - const runDueTasks = Effect.fn("ScheduledTaskService.runDueTasks")(function* () { const now = yield* localNow; const nowMs = DateTime.toEpochMillis(now); @@ -1161,17 +1138,11 @@ export const layer = Layer.effect( const tasks = yield* listDueTasks(now).pipe( Effect.mapError((cause) => taskError("Could not list schedule tasks.", { cause })), ); - const due = tasks.flatMap((task) => - task.nextRunAt === null ? [] : [{ task, dueAt: DateTime.makeUnsafe(task.nextRunAt) }], - ); + // A run missed while the server was down runs once; completion schedules the next future one. yield* Effect.forEach( - due, - ({ task, dueAt }) => - Effect.suspend(() => - isMissedFixedTimeRun(task.schedule, dueAt, now) - ? rescheduleMissedRun(task, now) - : runTask(task, "scheduled"), - ).pipe( + tasks, + (task) => + runTask(task, "scheduled").pipe( Effect.catch((cause) => Effect.logWarning("Scheduled task run failed", { taskId: task.id, cause }), ), From 55d9b7c75c3e68af53cdfc87271d7b040df59135 Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 12:30:16 +0100 Subject: [PATCH 02/13] fix(server): resume usage-limited threads however long ago the limit reset A usage-limited thread was only armed for auto-resume while its reset time was less than 24 hours in the past. If the server was down or the machine asleep across that window, the pending recovery was dropped and the thread never continued. Remove the cutoff so a failed usage-limited thread is armed and resumed once its limit has reset, regardless of how late the server sees it. Archived, settled, and otherwise ineligible threads are still excluded by the existing checks. Co-Authored-By: Claude Opus 5.5 --- .../UsageLimitRecoveryWorker.test.ts | 27 +++++-------------- .../UsageLimitRecoveryWorker.ts | 3 --- 2 files changed, 6 insertions(+), 24 deletions(-) diff --git a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.test.ts b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.test.ts index 430018adcb06a..846c9fa145c6a 100644 --- a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.test.ts +++ b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.test.ts @@ -93,26 +93,11 @@ const failedThread = (failedAgoMs: number, resetAgoMs: number) => { }; describe("limitRecoveryCommand arming", () => { - it("does not freshly arm a failure whose reset passed days ago", () => { - const thread = failedThread(5 * 24 * HOUR_MS, 4 * 24 * HOUR_MS); - assert.isNull(limitRecoveryCommand(thread, true, nowMs)); - assert.isNull(limitRecoveryCommand(thread, true, nowMs, true)); - }); - - it("still arms a failure whose reset only just passed", () => { - const thread = failedThread(6 * HOUR_MS, HOUR_MS); - const arm = limitRecoveryCommand(thread, true, nowMs); - assert.equal(arm?.type, "thread.metadata.update"); - }); - - it("arms a reset that is exactly 24 hours overdue", () => { - const thread = failedThread(30 * HOUR_MS, 24 * HOUR_MS); - const arm = limitRecoveryCommand(thread, true, nowMs); - assert.equal(arm?.type, "thread.metadata.update"); - }); - - it("does not arm a reset that is 24 hours and 1ms overdue", () => { - const thread = failedThread(30 * HOUR_MS, 24 * HOUR_MS + 1); - assert.isNull(limitRecoveryCommand(thread, true, nowMs)); + it.each([ + ["only just passed", 6 * HOUR_MS, HOUR_MS], + ["passed days ago, such as while the server was down", 5 * 24 * HOUR_MS, 4 * 24 * HOUR_MS], + ])("arms a failure whose reset %s", (_label, failedAgoMs, resetAgoMs) => { + const thread = failedThread(failedAgoMs, resetAgoMs); + assert.equal(limitRecoveryCommand(thread, true, nowMs)?.type, "thread.metadata.update"); }); }); diff --git a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts index 985815bd73eb4..401b116233ca0 100644 --- a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts +++ b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts @@ -12,8 +12,6 @@ import * as ProjectionStore from "./ProjectionStore.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ThreadManagement from "./ThreadManagementService.ts"; -const MAX_OVERDUE_ARM_MS = 24 * 60 * 60 * 1000; - export function limitRecoveryCommand( thread: ProjectionStore.ProjectionLimitRecoveryCandidate, autoResume: boolean, @@ -40,7 +38,6 @@ export function limitRecoveryCommand( const identity = `${thread.id}:${thread.latestRunId}:${resetMs}`; const recovery = thread.limitRecovery; if (recovery?.runId !== thread.latestRunId || recovery.resetAt !== thread.usageLimitResetAt) { - if (nowMs - resetMs > MAX_OVERDUE_ARM_MS) return null; if (!autoResume && (!snooze || resetMs <= nowMs)) return null; return { type: "thread.metadata.update", From f55d81dc7db88ed7b5cc56152b740b5704ac38c7 Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 12:32:07 +0100 Subject: [PATCH 03/13] fix(server): keep early Claude subagent messages instead of dropping them Messages that arrive before their Claude subagent is registered are buffered until its task_started. The buffer held at most 64 subagents and 256 messages each, so a long early burst lost subagent output; evicted launch details (model, effort, owner) were dropped without any log. Raise the bounds to 4096 subagents and 65,536 messages each, append buffered messages in place so a long burst stays linear, and log a warning when launch details are evicted (message drops were already logged). Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 10 ++ .../Adapters/ClaudeAdapterV2.ts | 96 ++++++++++++------- 2 files changed, 69 insertions(+), 37 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 4550692f3e18a..ecc3c1640c335 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -15098,6 +15098,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { const TASK_ID = "task-early-subagent"; const TOOL_USE_ID = "toolu-early-subagent"; const FINAL_REPORT = "Early auditor done."; + const EARLY_BURST = Array.from({ length: 300 }, (_, index) => `Early ${index}.`); const harness = yield* makeWakeHarness; const now = yield* DateTime.now; yield* harness.runtime.startTurn( @@ -15123,6 +15124,14 @@ describe("ClaudeAdapterV2 background wake turns", () => { uuid: "00000000-0000-4000-8000-000000000322", toolUseId: "toolu-early-bash", }), + // A long early burst still reaches the subagent once it registers. + ...EARLY_BURST.flatMap((text, index) => + makeSubagentAssistantFrames({ + parentToolUseId: TOOL_USE_ID, + uuid: `00000000-0000-4000-8001-${String(index).padStart(12, "0")}`, + text, + }), + ), makeSubagentTaskStartedFrame({ taskId: TASK_ID, toolUseId: TOOL_USE_ID, @@ -15170,6 +15179,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { ); assert.deepEqual(routing.assistantTexts(routing.childThreadId), [ "Starting early.", + ...EARLY_BURST, "Still working.", FINAL_REPORT, ]); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 4a252d6092edb..78c6167e03232 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -4548,22 +4548,24 @@ function claudeSubagentModelSelection( return { instanceId, model, ...(offered ? { options: [{ id: "effort", value: effort }] } : {}) }; } -const PENDING_CLAUDE_SUBAGENT_CAP = 64; -const PENDING_CLAUDE_SUBAGENT_FRAME_CAP = 256; +// Generous bounds on state for subagents that never register; overflow is logged, not silent. +const PENDING_CLAUDE_SUBAGENT_CAP = 4096; +const PENDING_CLAUDE_SUBAGENT_FRAME_CAP = 65_536; +/** Returns the tool use whose launch details were evicted to stay within the cap. */ function rememberPendingClaudeSubagentLaunch( pending: Map, toolUseId: string, launch: PendingClaudeSubagentLaunch, -): void { +): string | null { pending.set(toolUseId, { ...pending.get(toolUseId), ...launch }); if (pending.size <= PENDING_CLAUDE_SUBAGENT_CAP) { - return; + return null; } const oldest = pending.keys().next(); - if (!oldest.done) { - pending.delete(oldest.value); - } + if (oldest.done) return null; + pending.delete(oldest.value); + return oldest.value; } function rememberClaudeSubagentLaunch( @@ -4573,8 +4575,8 @@ function rememberClaudeSubagentLaunch( toolUseId: string, input: ClaudeNativeToolInput, ownerToolUseId: string | null, -): void { - if (context.subagentsByToolUseId.has(toolUseId)) return; +): string | null { + if (context.subagentsByToolUseId.has(toolUseId)) return null; const requested = firstStringInputField(input, ["model"]); const model = requested !== "inherit" @@ -4588,13 +4590,11 @@ function rememberClaudeSubagentLaunch( ...(effort === undefined ? {} : { effort }), ...(ownerToolUseId === null ? {} : { ownerToolUseId }), }; - if ( - launch.model !== undefined || + return launch.model !== undefined || launch.effort !== undefined || launch.ownerToolUseId !== undefined - ) { - rememberPendingClaudeSubagentLaunch(pending, toolUseId, launch); - } + ? rememberPendingClaudeSubagentLaunch(pending, toolUseId, launch) + : null; } type ClaudeApprovalResponse = { @@ -5281,9 +5281,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( // Buffered idle outcomes must not settle a resumed child again. const appliedSubagentOutcomes = new WeakSet(); // Subagent frames can precede the task_started that registers their owner. - const pendingSubagentFramesByToolUseId = yield* Ref.make( - new Map>(), - ); + const pendingSubagentFramesByToolUseId = yield* Ref.make(new Map()); + const warnEvictedSubagentLaunch = ( + context: ActiveClaudeTurnContext, + evictedToolUseId: string | null, + ) => + evictedToolUseId === null + ? Effect.void + : Effect.logWarning("orchestration-v2.claude-subagent-launch-dropped", { + providerTurnId: context.providerTurnId, + parentToolUseId: evictedToolUseId, + }); // A gateway's relative reset counts from the result's arrival, not its replay. const bufferedResultArrivals = new WeakMap(); const wakeBuffers = yield* Ref.make( @@ -9487,10 +9495,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (parentToolUseId !== null && model !== undefined) { const subagent = yield* resolveSubagentByToolUseId(context, parentToolUseId); if (subagent === undefined) { - rememberPendingClaudeSubagentLaunch( - pendingSubagentLaunchesByToolUseId, - parentToolUseId, - { model }, + yield* warnEvictedSubagentLaunch( + context, + rememberPendingClaudeSubagentLaunch( + pendingSubagentLaunchesByToolUseId, + parentToolUseId, + { model }, + ), ); } else if (subagent.task.status === "running" && subagent.task.model !== model) { yield* updateClaudeSubagentNode({ @@ -9512,11 +9523,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const droppedToolUseId = yield* Ref.modify( pendingSubagentFramesByToolUseId, (current) => { - const frames = current.get(frameParentToolUseId) ?? []; - if (frames.length >= PENDING_CLAUDE_SUBAGENT_FRAME_CAP) { - return [frameParentToolUseId, current] as const; + const frames = current.get(frameParentToolUseId); + if (frames !== undefined) { + if (frames.length >= PENDING_CLAUDE_SUBAGENT_FRAME_CAP) { + return [frameParentToolUseId, current] as const; + } + // Appending in place keeps a long burst linear; the map is local to this session. + frames.push(message); + return [null, current] as const; } - const next = new Map(current).set(frameParentToolUseId, [...frames, message]); + const next = new Map(current).set(frameParentToolUseId, [message]); const oldest = next.keys().next(); if (next.size > PENDING_CLAUDE_SUBAGENT_CAP && !oldest.done) { next.delete(oldest.value); @@ -9788,13 +9804,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( for (const toolUse of claudeToolUseBlocksFromAssistantMessage(message)) { const nativeToolInput = claudeNativeToolInputFromUnknown(toolUse.input); if (toolUse.name === "Agent") { - rememberClaudeSubagentLaunch( - modelCatalog, + yield* warnEvictedSubagentLaunch( context, - pendingSubagentLaunchesByToolUseId, - toolUse.id, - nativeToolInput, - parentToolUseIdFromSdkMessage(message), + rememberClaudeSubagentLaunch( + modelCatalog, + context, + pendingSubagentLaunchesByToolUseId, + toolUse.id, + nativeToolInput, + parentToolUseIdFromSdkMessage(message), + ), ); continue; } @@ -10406,13 +10425,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const heldForEcho = context.heldRootFrames.length > 0; const startToolCall = toolName !== "Agent" && options?.startToolCall !== false; if (toolName === "Agent") { - rememberClaudeSubagentLaunch( - modelCatalog, + yield* warnEvictedSubagentLaunch( context, - pendingSubagentLaunchesByToolUseId, - nativeRequestId, - nativeToolInput, - null, + rememberClaudeSubagentLaunch( + modelCatalog, + context, + pendingSubagentLaunchesByToolUseId, + nativeRequestId, + nativeToolInput, + null, + ), ); } else if (startToolCall && !heldForEcho) { yield* ensureToolCallStarted({ From 79a325b32f5bdf0cbdd1af56fad637e61672541e Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 12:35:46 +0100 Subject: [PATCH 04/13] fix(server): retry failed background cleanup for minutes, not seconds Every orchestration effect gave up after 5 attempts with about 1.5 s of total backoff, so a transient failure in session detach or thread resource cleanup permanently abandoned the work (for example, leaving a provider process or terminal running) with only a warning in the log. Background effects that nobody waits on (provider-session.detach and the scheduled-task, terminal, preview, and attachment cleanups) now retry 28 times with exponential backoff capped at 30 s, about ten minutes in total, and the final give-up is logged as an error. Effects a user waits on (turn start, restart, interrupt, steer, answers, rollback, checkpoint capture, title generation, delegated stop, restart continuation) keep the short budget: retry backoff blocks the thread's later effects, and those types already show their failure to the user after the last attempt. Non-retryable interrupt failures still settle immediately. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/EffectWorker.test.ts | 72 +++++++++++++++++++ .../src/orchestration-v2/EffectWorker.ts | 41 +++++++++-- 2 files changed, 109 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.ts index 3be77bba74c7c..24e7280093dab 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.test.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts @@ -395,6 +395,78 @@ it.effect("requeues a claim when a pre-execution worker check fails", () => }), ); +it.effect.each([ + // Background cleanup keeps retrying for about ten minutes, with backoff capped at 30 s. + { type: "terminal.cleanup", attemptCount: 5, expected: { retryDelayMs: 1_600 } }, + { type: "provider-session.detach", attemptCount: 20, expected: { retryDelayMs: 30_000 } }, + { type: "attachment.cleanup", attemptCount: 27, expected: { retryDelayMs: 30_000 } }, + { type: "terminal.cleanup", attemptCount: 28, expected: "failed" }, + // A user is waiting on these, and backoff blocks the thread's later effects. + { type: "provider-turn.start", attemptCount: 4, expected: { retryDelayMs: 800 } }, + { type: "provider-turn.start", attemptCount: 5, expected: "failed" }, +] as const)( + "after a failed $type attempt $attemptCount the worker settles with $expected", + ({ type, attemptCount, expected }) => + Effect.gen(function* () { + const now = DateTime.formatIso(yield* DateTime.now); + const workerId = "worker-retry-budget"; + const claimedEffect: EffectOutbox.OrchestrationEffectV2 = { + id: `effect:retry-budget:${type}`, + commandId: CommandId.make(`command:retry-budget:${type}`), + threadId: ThreadId.make("thread:retry-budget"), + request: + type === "provider-turn.start" + ? { type, runId: RunId.make("run:retry-budget") } + : type === "provider-session.detach" + ? { type, providerSessionId: oldSessionId } + : type === "attachment.cleanup" + ? { type, attachmentIds: [] } + : { type }, + status: "running", + attemptCount, + availableAt: now, + leaseOwner: workerId, + createdAt: now, + updatedAt: now, + completedAt: null, + lastError: null, + }; + const settled = yield* Ref.make>([]); + const settle = (outcome: unknown) => + Ref.update(settled, (existing) => [...existing, outcome]).pipe(Effect.as(true)); + const layerOutbox = Layer.mock(EffectOutbox.EffectOutboxV2)({ + claimNext: () => Effect.succeedSome(claimedEffect), + get: () => Effect.succeedSome(claimedEffect), + awaitCancellation: () => Effect.never, + clearCancellation: () => Effect.void, + retry: ({ delayMs }) => settle({ retryDelayMs: delayMs }), + fail: () => settle("failed"), + }); + const layerExecutor = Layer.succeed( + EffectWorker.OrchestrationEffectExecutorV2, + EffectWorker.OrchestrationEffectExecutorV2.of({ + execute: (effect) => + Effect.fail( + new EffectWorker.OrchestrationEffectExecutionError({ + effectId: effect.id, + effectType: effect.request.type, + cause: "simulated transient failure", + }), + ), + }), + ); + yield* EffectWorker.OrchestrationEffectWorkerV2.pipe( + Effect.flatMap((worker) => worker.runOnce), + Effect.provide( + EffectWorker.layerWithOptions({ workerId }).pipe( + Layer.provide(Layer.merge(layerOutbox, layerExecutor)), + ), + ), + ); + assert.deepEqual(yield* Ref.get(settled), [expected]); + }), +); + it.effect("arms cancellation before the durable pre-execution check", () => Effect.gen(function* () { const now = DateTime.formatIso(yield* DateTime.now); diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index c5b5ea9b383a9..7d6f449115a1e 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -628,6 +628,22 @@ export class OrchestrationEffectWorkerV2 extends Context.Service< OrchestrationEffectWorkerV2Shape >()("t3/orchestration-v2/EffectWorker/OrchestrationEffectWorkerV2") {} +// Retry backoff blocks the thread's later effects, so effects a user waits on keep a short +// budget (about 1.5 s) and surface their failure; cleanup nobody waits on retries for about +// ten minutes before giving up. +const INTERACTIVE_EFFECT_MAX_ATTEMPTS = 5; +const BACKGROUND_EFFECT_MAX_ATTEMPTS = 28; +const BACKGROUND_EFFECT_TYPES: ReadonlySet = + new Set([ + "provider-session.detach", + "scheduled-tasks.cleanup", + "terminal.cleanup", + "preview.cleanup", + "attachment.cleanup", + ]); +const retryDelayMs = (attemptCount: number) => + Math.min(30_000, 100 * 2 ** Math.max(0, attemptCount - 1)); + export interface OrchestrationEffectWorkerOptions { readonly workerId?: string; readonly maxAttempts?: number; @@ -646,7 +662,14 @@ export const layerWithOptions = ( const outbox = yield* EffectOutbox.EffectOutboxV2; const executor = yield* OrchestrationEffectExecutorV2; const workerId = options.workerId ?? `orchestration-v2:${process.pid}`; - const maxAttempts = Math.max(1, options.maxAttempts ?? 5); + const maxAttemptsFor = (effect: EffectOutbox.OrchestrationEffectV2) => + Math.max( + 1, + options.maxAttempts ?? + (BACKGROUND_EFFECT_TYPES.has(effect.request.type) + ? BACKGROUND_EFFECT_MAX_ATTEMPTS + : INTERACTIVE_EFFECT_MAX_ATTEMPTS), + ); const wasCancelled = (effectId: string) => outbox.get(effectId).pipe( Effect.map( @@ -783,7 +806,7 @@ export const layerWithOptions = ( if (cancelledBeforeExecution) return true; const execution = executor - .execute(effect, { willRetry: effect.attemptCount < maxAttempts }) + .execute(effect, { willRetry: effect.attemptCount < maxAttemptsFor(effect) }) .pipe(boundExecution(effect), Effect.as("executed" as const)); const exit = yield* Effect.exit(Effect.raceFirst(execution, cancellation)).pipe( Effect.ensuring(outbox.clearCancellation(effect.id)), @@ -815,11 +838,21 @@ export const layerWithOptions = ( nonRetryable, error, }); + const exhausted = !nonRetryable && effect.attemptCount >= maxAttemptsFor(effect); + if (exhausted) { + yield* Effect.logError("Orchestration effect gave up after its last attempt", { + effectId: effect.id, + effectType: effect.request.type, + threadId: effect.threadId, + attemptCount: effect.attemptCount, + error, + }); + } const updated = nonRetryable ? yield* outbox .succeed({ effectId: effect.id, workerId }) .pipe(Effect.onError((cause) => terminalizeClaim(effect, cause))) - : effect.attemptCount >= maxAttempts + : exhausted ? yield* outbox .fail({ effectId: effect.id, workerId, error }) .pipe(Effect.onError((cause) => terminalizeClaim(effect, cause))) @@ -828,7 +861,7 @@ export const layerWithOptions = ( effectId: effect.id, workerId, error, - delayMs: Math.min(30_000, 100 * 2 ** Math.max(0, effect.attemptCount - 1)), + delayMs: retryDelayMs(effect.attemptCount), }) .pipe(Effect.onError((cause) => requeueClaim(effect, cause))); if (!updated) { From 229f563493d50a40464f742ef720799056d94961 Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 12:42:49 +0100 Subject: [PATCH 05/13] fix(server): keep watching a pull request while host reads fail After 8 failed reads in a row (about 16 minutes), the watch reactor stopped watching the pull request for good, so an outage or a temporary permission problem silently ended a watch the agent relied on. Keep the watch instead. After 8 failures in a row the agent gets one notice that reads are failing, and sweeps back off, doubling the wait from 4 minutes up to 30 minutes; host change feeds still read immediately. When a read succeeds again the agent is told it can read the pull request again. The separate stop after 10 comment-only wakes in a row is unchanged. The settle test now stops the watch it restarts: tests share one database, and later tests' reactors used to end that watch by failing to read it. Co-Authored-By: Claude Opus 5.5 --- .../PullRequestWatchReactor.ts | 79 +++++++++++------ .../src/orchestration-v2/runtimeLayer.test.ts | 86 ++++++++++++------- docs/user/source-control.md | 6 +- 3 files changed, 110 insertions(+), 61 deletions(-) diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index 6eca0cb39aa24..5895a685ff904 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -45,7 +45,9 @@ import { /** Checks take minutes; faster sweeps waste the account's shared host quota. */ const SWEEP_MINUTES = 2; +/** Failed reads in a row before the agent is told; later reads back off up to the cap. */ const READ_FAILURE_LIMIT = 8; +const READ_BACKOFF_CAP_MS = 30 * 60_000; /** Group reads in flight at once, inside the host's own request limit. */ const GROUP_READS = 4; /** Without fingerprints, reread quiet PRs on snapshot changes or this interval to catch edits. */ @@ -93,6 +95,14 @@ interface LastRead { readonly remarks: string | null; } +interface ReadFailures { + readonly count: number; + /** Sweeps skip the group until then; host change feeds still read it. */ + readonly retryAt: number; + /** The agent was told reads are failing, so it is told when they recover. */ + readonly noticed: boolean; +} + interface ReadPlan { readonly detail: boolean; readonly activity: boolean; @@ -100,14 +110,7 @@ interface ReadPlan { const watchKey = ({ thread, watch }: WatchTarget) => `${thread.id} ${watch.startedAt}`; -type WatchEndReason = - | "merged" - | "closed" - | "unreadable" - | "comment-limit" - | "settled" - | "subagent" - | "stopped"; +type WatchEndReason = "merged" | "closed" | "comment-limit" | "settled" | "subagent" | "stopped"; interface WatchLife { readonly threadId: string; @@ -253,7 +256,7 @@ export const make = Effect.gen(function* () { const ended = (target: WatchTarget, reason: WatchEndReason) => Effect.suspend(() => reportEnd(lifeKey(target), lifeOf(target), reason)); - const readFailures = new Map(); + const readFailures = new Map(); /** The last sweep's groups, whose pull requests get host change feeds. */ let currentGroups: ReadonlyArray = []; // A pass reads watches and records new ones, so passes must not overlap. @@ -302,19 +305,25 @@ export const make = Effect.gen(function* () { }); }); - const giveUp = (target: WatchTarget) => - record(target, null, { - text: `T3 Code stopped watching pull request #${target.link.number} (${target.link.url}) because it failed to read it from the host ${READ_FAILURE_LIMIT} times in a row. Check it yourself, and call watch_pull_request to watch it again.`, + const reportUnreadable = (target: WatchTarget) => + record(target, target.watch, { + text: `T3 Code failed to read pull request #${target.link.number} (${target.link.url}) from the host ${READ_FAILURE_LIMIT} times in a row. It is still watching and retries less often, at least every 30 minutes, and will say when it can read it again. Check it yourself if you need it sooner, or call unwatch_pull_request to stop.`, notification: { source: { kind: "monitor" }, outcome: "failed", - summary: `#${target.link.number}: stopped watching, could not read it`, + summary: `#${target.link.number}: cannot read it, still watching`, }, - }).pipe( - Effect.tap(() => woke(target)), - Effect.catch(() => record(target, null)), - Effect.tap(() => ended(target, "unreadable")), - ); + }).pipe(Effect.tap(() => woke(target))); + + const reportReadable = (target: WatchTarget) => + record(target, target.watch, { + text: `T3 Code can read pull request #${target.link.number} (${target.link.url}) from the host again and is still watching it.`, + notification: { + source: { kind: "monitor" }, + outcome: "updated", + summary: `#${target.link.number}: readable again`, + }, + }).pipe(Effect.tap(() => woke(target))); const readRemarks = Effect.fn("PullRequestWatchReactor.readRemarks")( function* ( @@ -507,19 +516,32 @@ export const make = Effect.gen(function* () { lastReads.delete(group.key); const reason = providerFailureReason(read.cause); if (reason === "rate-limited") return; - // Transport and host failures can outlast the failure limit; keep the watch for recovery. + const previous = readFailures.get(group.key); + // Transport and host failures can outlast an outage; they do not count toward the notice. if (reason === "failed") { - readFailures.delete(group.key); + if (previous?.noticed !== true) readFailures.delete(group.key); return yield* Effect.failCause(read.cause); } - const failures = (readFailures.get(group.key) ?? 0) + 1; - readFailures.set(group.key, failures); - if (failures >= READ_FAILURE_LIMIT && (yield* eachTarget(group, giveUp))) { - readFailures.delete(group.key); - } + const count = (previous?.count ?? 0) + 1; + const backoffMs = + count < READ_FAILURE_LIMIT + ? 0 + : Math.min( + READ_BACKOFF_CAP_MS, + SWEEP_MINUTES * 60_000 * 2 ** (count - READ_FAILURE_LIMIT + 1), + ); + const noticed = + previous?.noticed === true || + (count >= READ_FAILURE_LIMIT && (yield* eachTarget(group, reportUnreadable))); + readFailures.set(group.key, { count, retryAt: now + backoffMs, noticed }); return yield* Effect.failCause(read.cause); } - readFailures.delete(group.key); + if (readFailures.get(group.key)?.noticed === true) { + // Keep the notice owed if telling the agent fails, so a later read retries it. + if (yield* eachTarget(group, reportReadable)) readFailures.delete(group.key); + } else { + readFailures.delete(group.key); + } const [detail, activity] = read.value; for (const target of group.targets) { const life = lifeOf(target); @@ -624,6 +646,7 @@ export const make = Effect.gen(function* () { const key = `${target.thread.projectId} ${threadPullRequestKeyOf(target.link)}`; byPullRequest.set(key, [...(byPullRequest.get(key) ?? []), target]); } + const now = yield* Clock.currentTimeMillis; const groups = [...byPullRequest].map(([key, members]): WatchGroup => ({ key, targets: members, @@ -653,7 +676,9 @@ export const make = Effect.gen(function* () { // as soon as its own answer lands rather than waiting on the slowest host. const reads = yield* Semaphore.make(GROUP_READS); yield* Effect.forEach( - groups, + changed === undefined + ? groups.filter((group) => (readFailures.get(group.key)?.retryAt ?? 0) <= now) + : groups, (group) => // The host just reported a change, so a cached fingerprint may predate it. (changed === undefined diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index a31a96cf5b463..b22fa150a9559 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -3222,6 +3222,12 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { commandId: CommandId.make(`pr-watch-settle-restart-${mode}`), }); assert.isDefined((yield* orchestrator.getThreadShell(threadId))?.pullRequests?.[0]?.watch); + // Later tests sweep every watch in this shared database, and failing reads keep one alive. + yield* orchestrator.dispatch({ + ...restart, + commandId: CommandId.make(`pr-watch-settle-stop-${mode}`), + watching: false, + }); }), ); @@ -3331,6 +3337,8 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { let disconnected = false; let passed = false; let genericFailure = false; + let currentPass = -1; + const passesRead = new Set(); const activityFailures = yield* Queue.unbounded(); const readFailure = (operation: string, failure: "failed" | "not-found" | "forbidden") => new PullRequestOperationError({ @@ -3351,29 +3359,35 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { Layer.mock(PullRequestService.PullRequestService)({ watchFingerprint: () => Effect.succeed(null), detail: () => - genericFailure - ? Effect.die("host read failed") - : disconnected - ? (activityFails ? Queue.take(activityFailures) : Effect.void).pipe( - Effect.andThen(Effect.fail(readFailure("detail", reason))), - ) - : Effect.succeed({ - ...watchedPullRequestDetail({ - projectId, - number: 8, - at: "2026-10-02T12:00:00.000Z", - }), - headSha: "abc1234def", - checks: [ - { - name: "test", - status: passed ? ("success" as const) : ("pending" as const), - description: null, - url: null, - required: true, - }, - ], - }), + Effect.sync(() => { + passesRead.add(currentPass); + }).pipe( + Effect.andThen(() => + genericFailure + ? Effect.die("host read failed") + : disconnected + ? (activityFails ? Queue.take(activityFailures) : Effect.void).pipe( + Effect.andThen(Effect.fail(readFailure("detail", reason))), + ) + : Effect.succeed({ + ...watchedPullRequestDetail({ + projectId, + number: 8, + at: "2026-10-02T12:00:00.000Z", + }), + headSha: "abc1234def", + checks: [ + { + name: "test", + status: passed ? ("success" as const) : ("pending" as const), + description: null, + url: null, + required: true, + }, + ], + }), + ), + ), activity: () => disconnected && activityFails ? Queue.offer(activityFailures, undefined).pipe( @@ -3392,35 +3406,43 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { ); const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; const sweep = reactor.sweep.pipe(Effect.andThen(worker.drain())); + // Notices from one pass carry random ids, so compare them in sorted order. const summaries = Effect.map( orchestrator.getThreadRecords(threadId, ["messages"]), - ({ messages }) => messages.flatMap((message) => message.notification?.summary ?? []), + ({ messages }) => + messages.flatMap((message) => message.notification?.summary ?? []).toSorted(), ); yield* sweep; assert.deepEqual(yield* summaries, []); disconnected = true; + passesRead.clear(); for (let pass = 0; pass < 15; pass += 1) { + currentPass = pass; genericFailure = reason === "failed" && (pass === 0 || (pass >= 2 && pass <= 8)); yield* TestClock.adjust("2 minutes"); yield* sweep; } const thread = yield* orchestrator.getThreadShell(threadId); - if (reason !== "failed") { - assert.isUndefined(thread?.pullRequests?.[0]?.watch); - assert.deepEqual(yield* summaries, ["#8: stopped watching, could not read it"]); - return; - } assert.isDefined(thread?.pullRequests?.[0]?.watch); - assert.deepEqual(yield* summaries, []); + const unreadable = reason === "failed" ? [] : ["#8: cannot read it, still watching"]; + assert.deepEqual(yield* summaries, unreadable); + // After 8 failures in a row, reads back off: 4 then 8 minutes later, then 16. + assert.equal(passesRead.size, reason === "failed" ? 15 : 10); disconnected = false; genericFailure = false; passed = true; + yield* TestClock.adjust("30 minutes"); yield* sweep; - assert.deepEqual(yield* summaries, ["#8: checks passed"]); + const recovered = [ + ...unreadable, + ...(reason === "failed" ? [] : ["#8: readable again"]), + "#8: checks passed", + ].toSorted(); + assert.deepEqual(yield* summaries, recovered); yield* TestClock.adjust("10 minutes"); yield* sweep; - assert.deepEqual(yield* summaries, ["#8: checks passed"]); + assert.deepEqual(yield* summaries, recovered); yield* orchestrator.dispatch({ type: "thread.pull-request.watch", commandId: CommandId.make(`pr-watch-unreadable-stop-${reason}-${activityFails}`), diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 8bbeb7e988cbe..54c60fd022206 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -329,8 +329,10 @@ check fails or waits for a maintainer's approval, the required checks pass, some conflict. Threads in a project that watch the same pull request share one check. On GitHub, a check first asks whether anything changed and reads the pull request only when it did, which keeps watching inside GitHub's rate limit. Comments from your own account do not wake it. Watching ends -when the pull request merges or closes, after 10 wakes in a row that bring only comments, after 8 -failed reads in a row, or when you press Stop on the thread. A rate limit only pauses watching. +when the pull request merges or closes, after 10 wakes in a row that bring only comments, or when +you press Stop on the thread. A rate limit only pauses watching. After 8 failed reads in a row, the +agent is told and the server keeps trying less often, at least every 30 minutes, and tells the agent +once it can read the pull request again. Settling or archiving a thread also ends all its watches. Unsettle the thread before starting a new watch. Watching a pull request again does not repeat check or conflict news its last watch already reported; unlinking the pull request clears that. Subagents cannot watch pull requests; the thread that delegated to them does. To start or stop From 2ed4832d0dcac102dedd8a3dd6b61f1bc66af339 Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 12:45:19 +0100 Subject: [PATCH 06/13] fix(server): keep uploads that an unsent draft still uses Attachments uploaded to an unsent draft or prompt stash were deleted 24 hours after upload. Drafts live only on clients (web local storage, mobile state), so the server had no way to tell that a draft still referenced the upload, and a draft opened the next day lost its files. Clients already ask the server for an upload's asset URL whenever a draft is opened, a stash is restored, or a mobile draft is sent, to check the upload still exists. That request now refreshes the pending upload's timestamp, and the sweep deletes only pending uploads untouched for 30 days. Interrupted partial uploads are still removed after an hour. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/assets/AssetAccess.test.ts | 28 +++++++++++++++++++ apps/server/src/assets/AssetAccess.ts | 18 +++++++++++- apps/server/src/attachmentStore.test.ts | 19 ++++++++++--- apps/server/src/attachmentStore.ts | 5 +++- .../src/components/chat/useComposerStash.ts | 2 +- apps/web/src/lib/attachmentUploadQueue.ts | 2 +- docs/user/composer.md | 4 +-- 7 files changed, 68 insertions(+), 10 deletions(-) diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index d762a15a830f8..1fe32e91dcb2b 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -27,6 +27,7 @@ import { vi } from "vite-plus/test"; import * as AssetSigner from "./AssetSigner.ts"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import { sweepStalePendingAttachments } from "../attachmentStore.ts"; import * as ServerConfig from "../config.ts"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts"; @@ -1276,6 +1277,33 @@ describe("AssetAccess", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("keeps a draft's pending upload alive whenever a client asks for its URL", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true }); + const now = 1_800_000_000_000; + const longAgo = DateTime.toDateUtc(DateTime.makeUnsafe(now - 60 * 24 * 60 * 60 * 1000)); + const attachmentId = "pending-00000000-0000-4000-8000-000000000042-pdf"; + const filePath = path.join(config.attachmentsDir, `${attachmentId}.pdf`); + const sidecarPath = `${filePath}.txt`; + for (const target of [filePath, sidecarPath]) { + yield* fileSystem.writeFileString(target, "draft"); + yield* fileSystem.utimes(target, longAgo, longAgo); + } + yield* TestClock.setTime(now); + + yield* issueAssetUrl({ resource: { _tag: "attachment", attachmentId } }); + + expect( + sweepStalePendingAttachments({ attachmentsDir: config.attachmentsDir, nowMs: now }), + ).toEqual({ deleted: 0 }); + expect(yield* fileSystem.exists(filePath)).toBe(true); + expect(yield* fileSystem.exists(sidecarPath)).toBe(true); + }).pipe(Effect.provide(layerTest)), + ); + it.effect("serves document attachments inline when a viewer requests it", () => Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index ee211b2bdc36d..b1a0434806889 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -38,6 +38,7 @@ import { import { isNetworkPath } from "@t3tools/shared/path"; import { MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH, toolOutputImages } from "@t3tools/shared/toolOutput"; import * as Clock from "effect/Clock"; +import * as DateTime from "effect/DateTime"; import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; @@ -50,7 +51,12 @@ import * as Stream from "effect/Stream"; import { base64UrlDecodeUtf8, base64UrlEncode } from "../auth/utils.ts"; import * as AssetSigner from "./AssetSigner.ts"; import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts"; -import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts"; +import { + parseAttachmentFileExtension, + parseThreadSegmentFromAttachmentId, + PENDING_ATTACHMENT_THREAD_SEGMENT, + resolveAttachmentPathById, +} from "../attachmentStore.ts"; import * as ServerConfig from "../config.ts"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; @@ -651,6 +657,16 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i resource: input.resource, }); } + if ( + parseThreadSegmentFromAttachmentId(input.resource.attachmentId) === + PENDING_ATTACHMENT_THREAD_SEGMENT + ) { + const touchedAt = DateTime.toDateUtc(yield* DateTime.now); + // Keeps the stale-upload sweep away from uploads an unsent draft still uses. + for (const target of [attachmentPath, `${attachmentPath}.txt`]) { + yield* fileSystem.utimes(target, touchedAt, touchedAt).pipe(Effect.ignore); + } + } const extension = parseAttachmentFileExtension(input.resource.attachmentId); const isGenericFile = extension !== null; const videoMimeType = input.resource.mimeType?.split(";", 1)[0]?.trim() ?? ""; diff --git a/apps/server/src/attachmentStore.test.ts b/apps/server/src/attachmentStore.test.ts index 053d3482a63ba..7e5f0c0bf423f 100644 --- a/apps/server/src/attachmentStore.test.ts +++ b/apps/server/src/attachmentStore.test.ts @@ -123,22 +123,32 @@ describe("attachmentStore", () => { } }); - it("removes expired pending and partial files without touching thread attachments", () => { + it("removes pending files untouched for 30 days and stale partials, keeping recent drafts", () => { const attachmentsDir = NodeFS.mkdtempSync( NodePath.join(NodeOS.tmpdir(), "t3code-attachment-sweep-"), ); try { const now = 1_800_000_000_000; - const oldTimeSeconds = (now - 2 * 24 * 60 * 60 * 1000) / 1000; + const daysAgoSeconds = (days: number) => (now - days * 24 * 60 * 60 * 1000) / 1000; const uuid = "00000000-0000-4000-8000-000000000002"; + const draftUuid = "00000000-0000-4000-8000-000000000003"; const pendingPath = NodePath.join(attachmentsDir, `pending-${uuid}.png`); const pendingFilePath = NodePath.join(attachmentsDir, `pending-${uuid}-pdf.pdf`); const sidecarPath = `${pendingFilePath}.txt`; const threadPath = NodePath.join(attachmentsDir, `thread-1-${uuid}.png`); const partialPath = NodePath.join(attachmentsDir, `${uuid}.part`); - for (const filePath of [pendingPath, pendingFilePath, sidecarPath, threadPath, partialPath]) { + // A draft's upload a few days old must survive; drafts live only on clients. + const draftPath = NodePath.join(attachmentsDir, `pending-${draftUuid}-pdf.pdf`); + for (const [filePath, days] of [ + [pendingPath, 31], + [pendingFilePath, 31], + [sidecarPath, 31], + [threadPath, 31], + [partialPath, 2], + [draftPath, 2], + ] as const) { NodeFS.writeFileSync(filePath, Buffer.from("pixels")); - NodeFS.utimesSync(filePath, oldTimeSeconds, oldTimeSeconds); + NodeFS.utimesSync(filePath, daysAgoSeconds(days), daysAgoSeconds(days)); } expect(sweepStalePendingAttachments({ attachmentsDir, nowMs: now })).toEqual({ deleted: 4 }); @@ -147,6 +157,7 @@ describe("attachmentStore", () => { expect(NodeFS.existsSync(sidecarPath)).toBe(false); expect(NodeFS.existsSync(partialPath)).toBe(false); expect(NodeFS.existsSync(threadPath)).toBe(true); + expect(NodeFS.existsSync(draftPath)).toBe(true); } finally { NodeFS.rmSync(attachmentsDir, { recursive: true, force: true }); } diff --git a/apps/server/src/attachmentStore.ts b/apps/server/src/attachmentStore.ts index a2b531e3fa5b0..e458ecc7d74f8 100644 --- a/apps/server/src/attachmentStore.ts +++ b/apps/server/src/attachmentStore.ts @@ -27,7 +27,10 @@ const ATTACHMENT_ID_PATTERN = new RegExp( ); export const PENDING_ATTACHMENT_THREAD_SEGMENT = "pending"; -const PENDING_ATTACHMENT_MAX_AGE_MS = 24 * 60 * 60 * 1000; +// Unsent drafts live on clients, so the server cannot see which uploads they still reference. +// Clients ask for an upload's URL whenever a draft is opened, restored, or sent, which refreshes +// its timestamp; an upload untouched this long belongs to no draft anyone still opens. +const PENDING_ATTACHMENT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; const PARTIAL_UPLOAD_MAX_AGE_MS = 60 * 60 * 1000; export function toSafeThreadAttachmentSegment(threadId: string): string | null { diff --git a/apps/web/src/components/chat/useComposerStash.ts b/apps/web/src/components/chat/useComposerStash.ts index 1d480dcf150e1..67bbfc2ec274a 100644 --- a/apps/web/src/components/chat/useComposerStash.ts +++ b/apps/web/src/components/chat/useComposerStash.ts @@ -399,7 +399,7 @@ export function useComposerStash(input: { } if (expiredFileNames.length > 0) { missingImageReasons.push( - `${expiredFileNames.join(", ")}: stashed files are kept for 24 hours and this upload expired. Attach the file again.`, + `${expiredFileNames.join(", ")}: stashed files are kept for 30 days and this upload expired. Attach the file again.`, ); } if (missingImageReasons.length > 0) { diff --git a/apps/web/src/lib/attachmentUploadQueue.ts b/apps/web/src/lib/attachmentUploadQueue.ts index 6477028fe6bad..d53eb559b6900 100644 --- a/apps/web/src/lib/attachmentUploadQueue.ts +++ b/apps/web/src/lib/attachmentUploadQueue.ts @@ -563,7 +563,7 @@ export function retryAttachmentUpload(input: { startAttachmentUpload(input); } -/** Verifies uploads before stash restore; pending uploads expire after 24 hours. */ +/** Verifies uploads before stash restore; pending uploads expire after 30 days unused. */ export function verifyStashedAttachmentUpload(input: { readonly environmentId: EnvironmentId; readonly attachmentId: string; diff --git a/docs/user/composer.md b/docs/user/composer.md index df880e49c6ca5..917480cbdb4e8 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -193,8 +193,8 @@ With an empty composer, the same shortcut restores a single stash or opens the stash menu when there are several. Stashes containing uploaded files must be restored in their original environment. -Those files are retained for 24 hours. After an upload expires, restore the prompt -and use **Attach again** or remove the missing file before sending. +Those files are kept until 30 days pass without the stash or a draft using them. After an upload +expires, restore the prompt and use **Attach again** or remove the missing file before sending. ## Voice input on web and desktop From 59761b45686f9f5473bd0d85ac13e3403d26c376 Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 13:13:28 +0100 Subject: [PATCH 07/13] Revert "fix(server): resume usage-limited threads however long ago the limit reset" This reverts commit 55d9b7c75c3e68af53cdfc87271d7b040df59135. --- .../UsageLimitRecoveryWorker.test.ts | 27 ++++++++++++++----- .../UsageLimitRecoveryWorker.ts | 3 +++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.test.ts b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.test.ts index 846c9fa145c6a..430018adcb06a 100644 --- a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.test.ts +++ b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.test.ts @@ -93,11 +93,26 @@ const failedThread = (failedAgoMs: number, resetAgoMs: number) => { }; describe("limitRecoveryCommand arming", () => { - it.each([ - ["only just passed", 6 * HOUR_MS, HOUR_MS], - ["passed days ago, such as while the server was down", 5 * 24 * HOUR_MS, 4 * 24 * HOUR_MS], - ])("arms a failure whose reset %s", (_label, failedAgoMs, resetAgoMs) => { - const thread = failedThread(failedAgoMs, resetAgoMs); - assert.equal(limitRecoveryCommand(thread, true, nowMs)?.type, "thread.metadata.update"); + it("does not freshly arm a failure whose reset passed days ago", () => { + const thread = failedThread(5 * 24 * HOUR_MS, 4 * 24 * HOUR_MS); + assert.isNull(limitRecoveryCommand(thread, true, nowMs)); + assert.isNull(limitRecoveryCommand(thread, true, nowMs, true)); + }); + + it("still arms a failure whose reset only just passed", () => { + const thread = failedThread(6 * HOUR_MS, HOUR_MS); + const arm = limitRecoveryCommand(thread, true, nowMs); + assert.equal(arm?.type, "thread.metadata.update"); + }); + + it("arms a reset that is exactly 24 hours overdue", () => { + const thread = failedThread(30 * HOUR_MS, 24 * HOUR_MS); + const arm = limitRecoveryCommand(thread, true, nowMs); + assert.equal(arm?.type, "thread.metadata.update"); + }); + + it("does not arm a reset that is 24 hours and 1ms overdue", () => { + const thread = failedThread(30 * HOUR_MS, 24 * HOUR_MS + 1); + assert.isNull(limitRecoveryCommand(thread, true, nowMs)); }); }); diff --git a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts index 401b116233ca0..985815bd73eb4 100644 --- a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts +++ b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts @@ -12,6 +12,8 @@ import * as ProjectionStore from "./ProjectionStore.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ThreadManagement from "./ThreadManagementService.ts"; +const MAX_OVERDUE_ARM_MS = 24 * 60 * 60 * 1000; + export function limitRecoveryCommand( thread: ProjectionStore.ProjectionLimitRecoveryCandidate, autoResume: boolean, @@ -38,6 +40,7 @@ export function limitRecoveryCommand( const identity = `${thread.id}:${thread.latestRunId}:${resetMs}`; const recovery = thread.limitRecovery; if (recovery?.runId !== thread.latestRunId || recovery.resetAt !== thread.usageLimitResetAt) { + if (nowMs - resetMs > MAX_OVERDUE_ARM_MS) return null; if (!autoResume && (!snooze || resetMs <= nowMs)) return null; return { type: "thread.metadata.update", From 19fe13f4b930ebf7ca18a87143da249b058fd73f Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 13:13:44 +0100 Subject: [PATCH 08/13] test(server): an armed usage-limit recovery resumes days late The 24-hour limit only applies to arming a recovery for the first time. A recovery armed before the reset resumes however late the server sees it, for example after the machine slept through the reset. Cover that case so the scenario stays protected. Co-Authored-By: Claude Opus 5.5 --- .../UsageLimitRecoveryWorker.test.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.test.ts b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.test.ts index 430018adcb06a..1acf641448198 100644 --- a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.test.ts +++ b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.test.ts @@ -115,4 +115,17 @@ describe("limitRecoveryCommand arming", () => { const thread = failedThread(30 * HOUR_MS, 24 * HOUR_MS + 1); assert.isNull(limitRecoveryCommand(thread, true, nowMs)); }); + + it("resumes a recovery armed before the reset, however late the server sees it", () => { + const thread = failedThread(5 * 24 * HOUR_MS, 4 * 24 * HOUR_MS); + const armed = { + ...thread, + limitRecovery: { + runId: thread.latestRunId!, + resetAt: thread.usageLimitResetAt!, + autoResume: true, + }, + }; + assert.equal(limitRecoveryCommand(armed, true, nowMs)?.type, "message.dispatch"); + }); }); From 1064b798905216950e321a79701242e73688e08b Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 13:15:46 +0100 Subject: [PATCH 09/13] fix(server): a retrying session detach no longer delays the next turn A provider or model switch queues the old session's detach ahead of the new turn's start, and the outbox kept every later effect on a thread behind one waiting to retry. With background cleanup now retrying for about ten minutes, a failing detach could hold the user's turn for that long. Background cleanup effects (session detach and the thread resource cleanups) that have failed at least once no longer block the thread's later effects while they wait to retry. Before their first attempt they still run first, and effects a user waits on, such as rollback, still block as before. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/EffectOutbox.ts | 19 +++++++- .../src/orchestration-v2/EffectWorker.ts | 12 ++--- .../FoundationPersistence.test.ts | 44 +++++++++++++++++++ 3 files changed, 65 insertions(+), 10 deletions(-) diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index 92e1e01ad43f2..ba10bfa71d600 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -122,6 +122,18 @@ export const OrchestrationEffectRequestV2 = Schema.Union([ ]); export type OrchestrationEffectRequestV2 = typeof OrchestrationEffectRequestV2.Type; +/** + * Cleanup no user waits on. It retries for minutes, and while it waits to retry it must not + * hold up the thread's later effects, such as the turn start queued behind a session detach. + */ +export const BACKGROUND_EFFECT_TYPES = [ + "provider-session.detach", + "scheduled-tasks.cleanup", + "terminal.cleanup", + "preview.cleanup", + "attachment.cleanup", +] as const satisfies ReadonlyArray; + export const REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS = [ "provider-runtime.continue", "provider-session.detach", @@ -310,7 +322,9 @@ export const layer: Layer.Layer = La available, Array.from({ length: Math.min(64, Math.max(0, Math.floor(count))) }, () => undefined), ).pipe(Effect.asVoid); - // Retry backoff must block later effects so turns cannot race a pending rollback. + // Retry backoff must block later effects so turns cannot race a pending rollback; + // background cleanup that already failed once waits without blocking. + const backgroundEffectTypes = sql.in(BACKGROUND_EFFECT_TYPES); const claimableCandidatePredicate = ( availableBefore?: string, excludeRestartContinuations = false, @@ -331,6 +345,9 @@ export const layer: Layer.Layer = La OR ( active.status = 'pending' AND active.rowid < candidate.rowid + AND NOT ( + active.attempt_count > 0 AND active.effect_type IN ${backgroundEffectTypes} + ) AND ${ excludeRestartContinuations ? sql`active.effect_type != 'provider-runtime.continue'` diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index 7d6f449115a1e..775ca94485a91 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -629,18 +629,12 @@ export class OrchestrationEffectWorkerV2 extends Context.Service< >()("t3/orchestration-v2/EffectWorker/OrchestrationEffectWorkerV2") {} // Retry backoff blocks the thread's later effects, so effects a user waits on keep a short -// budget (about 1.5 s) and surface their failure; cleanup nobody waits on retries for about -// ten minutes before giving up. +// budget (about 1.5 s) and surface their failure; background cleanup, which does not block, +// retries for about ten minutes before giving up. const INTERACTIVE_EFFECT_MAX_ATTEMPTS = 5; const BACKGROUND_EFFECT_MAX_ATTEMPTS = 28; const BACKGROUND_EFFECT_TYPES: ReadonlySet = - new Set([ - "provider-session.detach", - "scheduled-tasks.cleanup", - "terminal.cleanup", - "preview.cleanup", - "attachment.cleanup", - ]); + new Set(EffectOutbox.BACKGROUND_EFFECT_TYPES); const retryDelayMs = (attemptCount: number) => Math.min(30_000, 100 * 2 ** Math.max(0, attemptCount - 1)); diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index acf3cc27f6211..26c87cf4cca35 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -2786,6 +2786,50 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { }).pipe(Effect.provide(Layer.fresh(layerEffectOutboxProvided))), ); + it.effect("lets a queued turn start pass a session detach waiting to retry", () => + Effect.gen(function* () { + const outbox = yield* EffectOutbox.EffectOutboxV2; + const workerId = "retry-detach-worker"; + const commandId = CommandId.make("command:foundation-retry-detach"); + const threadId = ThreadId.make("thread:foundation-retry-detach"); + // A provider switch queues the old session's detach ahead of the new turn's start. + yield* outbox.enqueue([ + { + id: "effect:foundation-retry-detach:detach", + commandId, + threadId, + request: { + type: "provider-session.detach", + providerSessionId: ProviderSessionId.make("provider-session:foundation-retry-detach"), + }, + }, + { + id: "effect:foundation-retry-detach:start", + commandId, + threadId, + request: { + type: "provider-turn.start", + runId: RunId.make("run:foundation-retry-detach"), + }, + }, + ]); + const detach = yield* outbox.claimNext({ workerId }); + assert.equal(Option.getOrUndefined(detach)?.id, "effect:foundation-retry-detach:detach"); + // Before its first attempt the detach still runs first. + assert.isTrue(Option.isNone(yield* outbox.claimNext({ workerId }))); + yield* outbox.retry({ + effectId: "effect:foundation-retry-detach:detach", + workerId, + error: "detach failed once", + delayMs: 30_000, + }); + + const start = yield* outbox.claimNext({ workerId }); + assert.equal(Option.getOrUndefined(start)?.id, "effect:foundation-retry-detach:start"); + yield* outbox.succeed({ effectId: "effect:foundation-retry-detach:start", workerId }); + }).pipe(Effect.provide(Layer.fresh(layerEffectOutboxProvided))), + ); + it.effect("runs distinct threads concurrently while serializing effects within a thread", () => Effect.gen(function* () { const outbox = yield* EffectOutbox.EffectOutboxV2; From 074c3a9cbbe706dc340cdbbd7e3b69856ad91ceb Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 13:16:53 +0100 Subject: [PATCH 10/13] fix(server): a near-miss catch-up stands in for the next daily run A fixed-time run missed by almost a day ran on catch-up and then again at its regular time minutes later. When a scheduled fixed-time run starts, its next occurrence is now counted from at least an hour after the start, so an occurrence due within that hour is skipped. Runs on time are unaffected, since fixed-time occurrences are at least a day apart. Co-Authored-By: Claude Opus 5.5 --- .../ScheduledTaskService.schedule.test.ts | 129 +++++++++--------- .../scheduledTasks/ScheduledTaskService.ts | 7 +- 2 files changed, 74 insertions(+), 62 deletions(-) diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts index 27b2503eb6125..62139f611b457 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts @@ -240,68 +240,75 @@ it.effect( }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); -it.effect("a fixed-time run missed by hours runs once, then keeps its daily time", () => - Effect.gen(function* () { - const dueAt = DateTime.makeZonedUnsafe( - { year: 2026, month: 7, day: 1, hour: 9, minute: 0, second: 0, millisecond: 0 }, - { timeZone: DateTime.zoneMakeLocal(), adjustForTimeZone: true }, - ); - yield* TestClock.setTime(DateTime.toEpochMillis(dueAt) - 1_000); - const launches = yield* Ref.make(0); - const layerDependencies = Layer.mergeAll( - NodeCrypto.layer, - Scheduler.layer, - ManagedPolicy.layerTest(), - Layer.mock(ThreadLaunchService.ThreadLaunchService)({ - launch: () => - Ref.update(launches, (count) => count + 1).pipe( - Effect.as({ threadId: "thread-missed-run", resumed: false } as never), - ), - }), - Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ - namedProjectsRoot: "/projects", - isScratchProject: () => Effect.succeed(false), - }), - Layer.mock(ThreadManagementService.ThreadManagementService)({}), - Layer.mock(SecretRequests.SecretRequests)({}), - ); - const serviceLayer = ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies)); - const created = yield* Effect.gen(function* () { - const service = yield* ScheduledTaskService.ScheduledTaskService; - return yield* service.upsert( - yield* decodeUpsertInput({ - title: "Morning review", - prompt: "Review the open pull requests.", - enabled: true, - schedule: { type: "fixed_time", timeOfDay: "09:00" }, - projectId: "project-missed-run", - workspaceStrategy: { type: "root" }, - modelSelection: { instanceId: "codex", model: "gpt-5.4" }, - runtimeMode: "full-access", - interactionMode: "default", - }), +it.effect.each([ + // Several missed days produce one catch-up run. + { late: { days: 3, hours: 6 }, nextInDays: 4 }, + // A catch-up minutes before the next occurrence stands in for it. + { late: { hours: 23, minutes: 50 }, nextInDays: 2 }, +] as const)( + "a fixed-time run missed by $late runs once, then keeps its daily time", + ({ late, nextInDays }) => + Effect.gen(function* () { + const dueAt = DateTime.makeZonedUnsafe( + { year: 2026, month: 7, day: 1, hour: 9, minute: 0, second: 0, millisecond: 0 }, + { timeZone: DateTime.zoneMakeLocal(), adjustForTimeZone: true }, ); - }).pipe( - Effect.provide(serviceLayer), - // The server is down while several days of occurrences pass. - Effect.provideService(ServerActivation, Effect.never), - ); - yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.add(dueAt, { days: 3, hours: 6 }))); - yield* Effect.gen(function* () { - const service = yield* ScheduledTaskService.ScheduledTaskService; - const completedRun = yield* service.subscribeList().pipe( - Stream.map(({ tasks }) => tasks.find((task) => task.id === created.task.id)), - Stream.filter((task) => task !== undefined && task.runCount > 0), - Stream.runHead, - Effect.forkChild, + yield* TestClock.setTime(DateTime.toEpochMillis(dueAt) - 1_000); + const launches = yield* Ref.make(0); + const layerDependencies = Layer.mergeAll( + NodeCrypto.layer, + Scheduler.layer, + ManagedPolicy.layerTest(), + Layer.mock(ThreadLaunchService.ThreadLaunchService)({ + launch: () => + Ref.update(launches, (count) => count + 1).pipe( + Effect.as({ threadId: "thread-missed-run", resumed: false } as never), + ), + }), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), + Layer.mock(ThreadManagementService.ThreadManagementService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), ); - yield* TestClock.adjust("6 seconds"); - const task = Option.getOrThrow(yield* Fiber.join(completedRun)); - expect(task?.nextRunAt).toBe( - DateTime.formatIso(DateTime.toUtc(DateTime.add(dueAt, { days: 4 }))), + const serviceLayer = ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies)); + const created = yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + return yield* service.upsert( + yield* decodeUpsertInput({ + title: "Morning review", + prompt: "Review the open pull requests.", + enabled: true, + schedule: { type: "fixed_time", timeOfDay: "09:00" }, + projectId: "project-missed-run", + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + }), + ); + }).pipe( + Effect.provide(serviceLayer), + // The server is down while several days of occurrences pass. + Effect.provideService(ServerActivation, Effect.never), ); - yield* TestClock.adjust("6 seconds"); - expect(yield* Ref.get(launches)).toBe(1); - }).pipe(Effect.provide(serviceLayer)); - }).pipe(Effect.provide(SqlitePersistence.layerMemory)), + yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.add(dueAt, late))); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const completedRun = yield* service.subscribeList().pipe( + Stream.map(({ tasks }) => tasks.find((task) => task.id === created.task.id)), + Stream.filter((task) => task !== undefined && task.runCount > 0), + Stream.runHead, + Effect.forkChild, + ); + yield* TestClock.adjust("6 seconds"); + const task = Option.getOrThrow(yield* Fiber.join(completedRun)); + expect(task?.nextRunAt).toBe( + DateTime.formatIso(DateTime.toUtc(DateTime.add(dueAt, { days: nextInDays }))), + ); + yield* TestClock.adjust("6 seconds"); + expect(yield* Ref.get(launches)).toBe(1); + }).pipe(Effect.provide(serviceLayer)); + }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 1fe1845818856..b4dfe71e62585 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -1029,7 +1029,12 @@ export const layer = Layer.effect( // A manual run that starts before a one-time run must not use it up. nextRunAt: nextRunAt( scheduleSource, - scheduleSource.schedule.type === "once" ? startedAt : completedAt, + scheduleSource.schedule.type === "once" + ? startedAt + : trigger === "scheduled" && scheduleSource.schedule.type === "fixed_time" + ? // A late catch-up stands in for an occurrence due within the hour after it. + DateTime.max(completedAt, DateTime.add(startedAt, { hours: 1 })) + : completedAt, ), lastRunStatus, lastRunError, From 628736e73d9c3a71e735ee32c849f98ca9f9aef9 Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 13:19:22 +0100 Subject: [PATCH 11/13] fix(server): remember a pull request watch's failed reads across restarts The failed-read state was held only in memory: a restart could repeat the "cannot read it" notice and forgot to tell the agent when reads recovered. A pull request the host keeps reporting missing was also watched forever. The watch now records whether the agent was told reads are failing and when the host first reported the pull request missing. A restart reads again but does not repeat the notice, and the first successful read still sends the recovery notice and clears the state. If the host keeps reporting the pull request missing for 7 days, the watch ends with a visible notice. The notice no longer promises a follow-up that might not come, and the test now covers the 30-minute backoff cap. Both fields are optional, so watches saved earlier still decode. Co-Authored-By: Claude Opus 5.5 --- .../PullRequestWatchReactor.ts | 114 ++++++++++++++---- .../src/orchestration-v2/runtimeLayer.test.ts | 34 ++++-- docs/user/source-control.md | 7 +- packages/contracts/src/threadPullRequest.ts | 4 + 4 files changed, 127 insertions(+), 32 deletions(-) diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index 5895a685ff904..a376cd7942fa2 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -18,6 +18,7 @@ import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as FiberMap from "effect/FiberMap"; @@ -48,6 +49,8 @@ const SWEEP_MINUTES = 2; /** Failed reads in a row before the agent is told; later reads back off up to the cap. */ const READ_FAILURE_LIMIT = 8; const READ_BACKOFF_CAP_MS = 30 * 60_000; +/** A pull request the host keeps reporting missing this long is gone, not briefly hidden. */ +const NOT_FOUND_LIMIT_MS = 7 * 24 * 60 * 60_000; /** Group reads in flight at once, inside the host's own request limit. */ const GROUP_READS = 4; /** Without fingerprints, reread quiet PRs on snapshot changes or this interval to catch edits. */ @@ -95,12 +98,11 @@ interface LastRead { readonly remarks: string | null; } +/** In memory only: a restart reads again at once; what the agent was told lives on the watch. */ interface ReadFailures { readonly count: number; /** Sweeps skip the group until then; host change feeds still read it. */ readonly retryAt: number; - /** The agent was told reads are failing, so it is told when they recover. */ - readonly noticed: boolean; } interface ReadPlan { @@ -110,7 +112,21 @@ interface ReadPlan { const watchKey = ({ thread, watch }: WatchTarget) => `${thread.id} ${watch.startedAt}`; -type WatchEndReason = "merged" | "closed" | "comment-limit" | "settled" | "subagent" | "stopped"; +type WatchEndReason = + | "merged" + | "closed" + | "not-found" + | "comment-limit" + | "settled" + | "subagent" + | "stopped"; + +/** The watch without its failed-read state, as a successful read leaves it. */ +const withoutReadFailures = ({ + unreadableNotified: _notified, + notFoundSince: _since, + ...watch +}: ThreadPullRequestWatch): ThreadPullRequestWatch => watch; interface WatchLife { readonly threadId: string; @@ -305,9 +321,9 @@ export const make = Effect.gen(function* () { }); }); - const reportUnreadable = (target: WatchTarget) => - record(target, target.watch, { - text: `T3 Code failed to read pull request #${target.link.number} (${target.link.url}) from the host ${READ_FAILURE_LIMIT} times in a row. It is still watching and retries less often, at least every 30 minutes, and will say when it can read it again. Check it yourself if you need it sooner, or call unwatch_pull_request to stop.`, + const reportUnreadable = (target: WatchTarget, next: ThreadPullRequestWatch) => + record(target, next, { + text: `T3 Code failed to read pull request #${target.link.number} (${target.link.url}) from the host ${READ_FAILURE_LIMIT} times in a row. It keeps watching and retries less often, at most every 30 minutes. Check it yourself if you need it sooner, or call unwatch_pull_request to stop.`, notification: { source: { kind: "monitor" }, outcome: "failed", @@ -315,8 +331,8 @@ export const make = Effect.gen(function* () { }, }).pipe(Effect.tap(() => woke(target))); - const reportReadable = (target: WatchTarget) => - record(target, target.watch, { + const reportReadable = (target: WatchTarget, next: ThreadPullRequestWatch) => + record(target, next, { text: `T3 Code can read pull request #${target.link.number} (${target.link.url}) from the host again and is still watching it.`, notification: { source: { kind: "monitor" }, @@ -325,6 +341,63 @@ export const make = Effect.gen(function* () { }, }).pipe(Effect.tap(() => woke(target))); + const endNotFound = (target: WatchTarget) => + record(target, null, { + text: `T3 Code stopped watching pull request #${target.link.number} (${target.link.url}) because the host has reported it as not found for 7 days. Check it yourself, and call watch_pull_request to watch it again.`, + notification: { + source: { kind: "monitor" }, + outcome: "failed", + summary: `#${target.link.number}: stopped watching, not found`, + }, + }).pipe( + Effect.tap(() => woke(target)), + Effect.tap(() => ended(target, "not-found")), + ); + + const recordFailedRead = Effect.fn("PullRequestWatchReactor.recordFailedRead")(function* ( + target: WatchTarget, + input: { readonly count: number; readonly notFound: boolean; readonly now: number }, + ) { + const { watch } = target; + const notFoundSince = input.notFound + ? (watch.notFoundSince ?? DateTime.formatIso(DateTime.makeUnsafe(input.now))) + : undefined; + if ( + notFoundSince !== undefined && + input.now - Date.parse(notFoundSince) >= NOT_FOUND_LIMIT_MS + ) { + return yield* endNotFound(target); + } + const notify = input.count >= READ_FAILURE_LIMIT && watch.unreadableNotified !== true; + const next: ThreadPullRequestWatch = { + ...withoutReadFailures(watch), + ...(notify || watch.unreadableNotified === true ? { unreadableNotified: true } : {}), + ...(notFoundSince === undefined ? {} : { notFoundSince }), + }; + if (notify) return yield* reportUnreadable(target, next); + if (next.notFoundSince !== watch.notFoundSince) yield* record(target, next); + }); + + /** Clears failed-read state after a successful read, returning the watch to evaluate. */ + const recordReadableAgain = (target: WatchTarget) => { + const { watch } = target; + if (watch.unreadableNotified !== true && watch.notFoundSince === undefined) { + return Effect.succeed(target); + } + const next = withoutReadFailures(watch); + return ( + watch.unreadableNotified === true ? reportReadable(target, next) : record(target, next) + ).pipe( + Effect.as({ ...target, watch: next }), + Effect.catchCause((cause) => + logFailure("pull request watch update failed", { + threadId: target.thread.id, + pullRequest: threadPullRequestKeyOf(target.link), + })(cause).pipe(Effect.as(target)), + ), + ); + }; + const readRemarks = Effect.fn("PullRequestWatchReactor.readRemarks")( function* ( key: string, @@ -476,9 +549,10 @@ export const make = Effect.gen(function* () { ); const readGroup = Effect.fn("PullRequestWatchReactor.readGroup")(function* ( - group: WatchGroup, + input: WatchGroup, fingerprint: ProviderChangeRequestWatchFingerprint | null, ) { + let group = input; const now = yield* Clock.currentTimeMillis; const last = lastReads.get(group.key); const plan = planRead(group, last, fingerprint, now); @@ -516,13 +590,12 @@ export const make = Effect.gen(function* () { lastReads.delete(group.key); const reason = providerFailureReason(read.cause); if (reason === "rate-limited") return; - const previous = readFailures.get(group.key); // Transport and host failures can outlast an outage; they do not count toward the notice. if (reason === "failed") { - if (previous?.noticed !== true) readFailures.delete(group.key); + readFailures.delete(group.key); return yield* Effect.failCause(read.cause); } - const count = (previous?.count ?? 0) + 1; + const count = (readFailures.get(group.key)?.count ?? 0) + 1; const backoffMs = count < READ_FAILURE_LIMIT ? 0 @@ -530,18 +603,15 @@ export const make = Effect.gen(function* () { READ_BACKOFF_CAP_MS, SWEEP_MINUTES * 60_000 * 2 ** (count - READ_FAILURE_LIMIT + 1), ); - const noticed = - previous?.noticed === true || - (count >= READ_FAILURE_LIMIT && (yield* eachTarget(group, reportUnreadable))); - readFailures.set(group.key, { count, retryAt: now + backoffMs, noticed }); + readFailures.set(group.key, { count, retryAt: now + backoffMs }); + yield* eachTarget(group, (target) => + recordFailedRead(target, { count, notFound: reason === "not-found", now }), + ); return yield* Effect.failCause(read.cause); } - if (readFailures.get(group.key)?.noticed === true) { - // Keep the notice owed if telling the agent fails, so a later read retries it. - if (yield* eachTarget(group, reportReadable)) readFailures.delete(group.key); - } else { - readFailures.delete(group.key); - } + readFailures.delete(group.key); + // A failed recovery record keeps the old watch, so a later read retries the notice. + group = { ...group, targets: yield* Effect.forEach(group.targets, recordReadableAgain) }; const [detail, activity] = read.value; for (const target of group.targets) { const life = lifeOf(target); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index b22fa150a9559..d2344a44aff31 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -3351,7 +3351,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { detail: "host read failed", }), }); - const reactor = yield* PullRequestWatchReactor.make.pipe( + const makeReactor = PullRequestWatchReactor.make.pipe( Effect.provide( Layer.mergeAll( NodeServices.layer, @@ -3405,7 +3405,8 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { ), ); const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const sweep = reactor.sweep.pipe(Effect.andThen(worker.drain())); + let reactor = yield* makeReactor; + const sweep = Effect.suspend(() => reactor.sweep).pipe(Effect.andThen(worker.drain())); // Notices from one pass carry random ids, so compare them in sorted order. const summaries = Effect.map( orchestrator.getThreadRecords(threadId, ["messages"]), @@ -3416,19 +3417,38 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { assert.deepEqual(yield* summaries, []); disconnected = true; passesRead.clear(); - for (let pass = 0; pass < 15; pass += 1) { + for (let pass = 0; pass < 37; pass += 1) { currentPass = pass; genericFailure = reason === "failed" && (pass === 0 || (pass >= 2 && pass <= 8)); yield* TestClock.adjust("2 minutes"); yield* sweep; } - const thread = yield* orchestrator.getThreadShell(threadId); - assert.isDefined(thread?.pullRequests?.[0]?.watch); + const watchOf = Effect.map( + orchestrator.getThreadShell(threadId), + (thread) => thread?.pullRequests?.[0]?.watch, + ); + assert.isDefined(yield* watchOf); const unreadable = reason === "failed" ? [] : ["#8: cannot read it, still watching"]; assert.deepEqual(yield* summaries, unreadable); - // After 8 failures in a row, reads back off: 4 then 8 minutes later, then 16. - assert.equal(passesRead.size, reason === "failed" ? 15 : 10); + // After 8 failures in a row, reads wait 4, 8, 16, then at most 30 minutes. + assert.equal(passesRead.size, reason === "failed" ? 37 : 12); + + // A restart neither repeats the notice nor forgets it is owed a recovery notice. + reactor = yield* makeReactor; + yield* TestClock.adjust("2 minutes"); + yield* sweep; + assert.deepEqual(yield* summaries, unreadable); + if (reason === "not-found") { + yield* TestClock.adjust("7 days"); + yield* sweep; + assert.isUndefined(yield* watchOf); + assert.deepEqual( + yield* summaries, + [...unreadable, "#8: stopped watching, not found"].toSorted(), + ); + return; + } disconnected = false; genericFailure = false; passed = true; diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 54c60fd022206..613b9b188ea3f 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -330,9 +330,10 @@ conflict. Threads in a project that watch the same pull request share one check. first asks whether anything changed and reads the pull request only when it did, which keeps watching inside GitHub's rate limit. Comments from your own account do not wake it. Watching ends when the pull request merges or closes, after 10 wakes in a row that bring only comments, or when -you press Stop on the thread. A rate limit only pauses watching. After 8 failed reads in a row, the -agent is told and the server keeps trying less often, at least every 30 minutes, and tells the agent -once it can read the pull request again. +you press Stop on the thread, or when the host has reported the pull request as not found for 7 +days. A rate limit only pauses watching. After 8 failed reads in a row, the agent is told and the +server keeps trying less often, at most 30 minutes apart, and tells the agent when a read succeeds +again. Settling or archiving a thread also ends all its watches. Unsettle the thread before starting a new watch. Watching a pull request again does not repeat check or conflict news its last watch already reported; unlinking the pull request clears that. Subagents cannot watch pull requests; the thread that delegated to them does. To start or stop diff --git a/packages/contracts/src/threadPullRequest.ts b/packages/contracts/src/threadPullRequest.ts index bd0a65a3c0bc9..0df3fd238af3d 100644 --- a/packages/contracts/src/threadPullRequest.ts +++ b/packages/contracts/src/threadPullRequest.ts @@ -104,6 +104,10 @@ export const ThreadPullRequestWatch = Schema.Struct({ * none did. Null once either happened; absent on watches saved before it existed. */ checksAwaitedSince: Schema.optional(Schema.NullOr(IsoDateTime)), + /** The agent was told host reads keep failing, and is told again once one succeeds. */ + unreadableNotified: Schema.optional(Schema.Boolean), + /** When the host first reported the pull request missing in the current run of failed reads. */ + notFoundSince: Schema.optional(IsoDateTime), }); export type ThreadPullRequestWatch = typeof ThreadPullRequestWatch.Type; From d880bcaf24fa64d3cd0a77c73f37f81bfdc79a81 Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 13:21:28 +0100 Subject: [PATCH 12/13] fix(server): bound early Claude subagent frames by a session budget Raising the per-subagent limits left the early-frame buffer able to hold 4096 subagents of 65,536 messages each, with no bound on total memory. Frames buffered before their subagent registers now also share a 64 MiB session budget, measured by serialized size. A frame that would exceed it is dropped with the existing warning; released frames return their share. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 203 +++++++++--------- .../Adapters/ClaudeAdapterV2.ts | 86 +++++--- 2 files changed, 162 insertions(+), 127 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index ecc3c1640c335..1327d6e62aa87 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -15092,109 +15092,118 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("holds subagent frames that precede task_started and shows its result once", () => - Effect.scoped( - Effect.gen(function* () { - const TASK_ID = "task-early-subagent"; - const TOOL_USE_ID = "toolu-early-subagent"; - const FINAL_REPORT = "Early auditor done."; - const EARLY_BURST = Array.from({ length: 300 }, (_, index) => `Early ${index}.`); - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-early-subagent"), - text: "Run an auditor.", - attachments: [], - }), - ); - const frames = [ - // Child frames can precede the task_started that registers their subagent. - ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000321", - text: "Starting early.", - bashToolUseId: "toolu-early-bash", - }), - makeSubagentToolResultFrame({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000322", - toolUseId: "toolu-early-bash", - }), - // A long early burst still reaches the subagent once it registers. - ...EARLY_BURST.flatMap((text, index) => - makeSubagentAssistantFrames({ + it.effect.each([ + { burst: "300 short messages", count: 300, size: 0, kept: 300 }, + // The session buffers at most 64 MiB of early frames; the rest are dropped with a warning. + { burst: "70 MiB of messages", count: 70, size: 1024 * 1024, kept: 63 }, + ])( + "holds subagent frames that precede task_started and shows its result once: $burst", + ({ count, size, kept }) => + Effect.scoped( + Effect.gen(function* () { + const TASK_ID = "task-early-subagent"; + const TOOL_USE_ID = "toolu-early-subagent"; + const FINAL_REPORT = "Early auditor done."; + const EARLY_BURST = Array.from( + { length: count }, + (_, index) => `Early ${index}.${"x".repeat(size)}`, + ); + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-early-subagent"), + text: "Run an auditor.", + attachments: [], + }), + ); + const frames = [ + // Child frames can precede the task_started that registers their subagent. + ...makeSubagentAssistantFrames({ parentToolUseId: TOOL_USE_ID, - uuid: `00000000-0000-4000-8001-${String(index).padStart(12, "0")}`, - text, + uuid: "00000000-0000-4000-8000-000000000321", + text: "Starting early.", + bashToolUseId: "toolu-early-bash", }), - ), - makeSubagentTaskStartedFrame({ - taskId: TASK_ID, - toolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000323", - }), - ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000324", - text: "Still working.", - }), - claudeSdkFrame({ - type: "system", - subtype: "task_progress", - task_id: TASK_ID, - description: "Checking the diffs", - uuid: "00000000-0000-4000-8000-000000000325", - session_id: WAKE_NATIVE_SESSION, - }), - ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000326", - text: FINAL_REPORT, - }), - makeSubagentNotificationFrame({ - taskId: TASK_ID, - toolUseId: TOOL_USE_ID, - summary: FINAL_REPORT, - uuid: "00000000-0000-4000-8000-000000000327", - }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000328", - result: "The auditor finished.", - }), - ]; - for (const frame of frames) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* harness.awaitTerminal(1); + makeSubagentToolResultFrame({ + parentToolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000322", + toolUseId: "toolu-early-bash", + }), + // A long early burst still reaches the subagent once it registers. + ...EARLY_BURST.flatMap((text, index) => + makeSubagentAssistantFrames({ + parentToolUseId: TOOL_USE_ID, + uuid: `00000000-0000-4000-8001-${String(index).padStart(12, "0")}`, + text, + }), + ), + makeSubagentTaskStartedFrame({ + taskId: TASK_ID, + toolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000323", + }), + ...makeSubagentAssistantFrames({ + parentToolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000324", + text: "Still working.", + }), + claudeSdkFrame({ + type: "system", + subtype: "task_progress", + task_id: TASK_ID, + description: "Checking the diffs", + uuid: "00000000-0000-4000-8000-000000000325", + session_id: WAKE_NATIVE_SESSION, + }), + ...makeSubagentAssistantFrames({ + parentToolUseId: TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000326", + text: FINAL_REPORT, + }), + makeSubagentNotificationFrame({ + taskId: TASK_ID, + toolUseId: TOOL_USE_ID, + summary: FINAL_REPORT, + uuid: "00000000-0000-4000-8000-000000000327", + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000328", + result: "The auditor finished.", + }), + ]; + for (const frame of frames) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(1); - const routing = subagentRouting(harness.events, ["toolu-early-bash"]); - assert.isDefined(routing.childThreadId); - assert.deepEqual( - [...(routing.toolThreadIds.get("toolu-early-bash") ?? [])], - [routing.childThreadId], - ); - assert.deepEqual(routing.assistantTexts(routing.childThreadId), [ - "Starting early.", - ...EARLY_BURST, - "Still working.", - FINAL_REPORT, - ]); - assert.deepEqual(routing.assistantTexts(harness.threadId), ["The auditor finished."]); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, + const routing = subagentRouting(harness.events, ["toolu-early-bash"]); + assert.isDefined(routing.childThreadId); + assert.deepEqual( + [...(routing.toolThreadIds.get("toolu-early-bash") ?? [])], + [routing.childThreadId], + ); + assert.deepEqual(routing.assistantTexts(routing.childThreadId), [ + "Starting early.", + ...EARLY_BURST.slice(0, kept), + "Still working.", + FINAL_REPORT, + ]); + assert.deepEqual(routing.assistantTexts(harness.threadId), ["The auditor finished."]); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), ), ), ), - ), ); it.effect.each([false, true])( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 78c6167e03232..1c83a5e0c9c2d 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -4551,6 +4551,52 @@ function claudeSubagentModelSelection( // Generous bounds on state for subagents that never register; overflow is logged, not silent. const PENDING_CLAUDE_SUBAGENT_CAP = 4096; const PENDING_CLAUDE_SUBAGENT_FRAME_CAP = 65_536; +/** Session-wide budget for early frames, measured as serialized JSON length. */ +const PENDING_CLAUDE_SUBAGENT_FRAME_BYTES = 64 * 1024 * 1024; + +interface PendingClaudeSubagentFrames { + readonly byToolUseId: Map; + bytes: number; +} + +/** Buffers a frame for an unregistered subagent; returns the tool use whose frames were dropped. */ +function bufferPendingClaudeSubagentFrame( + pending: PendingClaudeSubagentFrames, + toolUseId: string, + message: SDKMessage, +): string | null { + const bytes = JSON.stringify(message)?.length ?? 0; + const entry = pending.byToolUseId.get(toolUseId); + if ( + (entry?.frames.length ?? 0) >= PENDING_CLAUDE_SUBAGENT_FRAME_CAP || + pending.bytes + bytes > PENDING_CLAUDE_SUBAGENT_FRAME_BYTES + ) { + return toolUseId; + } + pending.bytes += bytes; + if (entry !== undefined) { + entry.frames.push(message); + entry.bytes += bytes; + return null; + } + pending.byToolUseId.set(toolUseId, { frames: [message], bytes }); + if (pending.byToolUseId.size <= PENDING_CLAUDE_SUBAGENT_CAP) return null; + const [oldestId, oldest] = pending.byToolUseId.entries().next().value!; + pending.byToolUseId.delete(oldestId); + pending.bytes -= oldest.bytes; + return oldestId; +} + +function takePendingClaudeSubagentFrames( + pending: PendingClaudeSubagentFrames, + toolUseId: string, +): ReadonlyArray { + const entry = pending.byToolUseId.get(toolUseId); + if (entry === undefined) return []; + pending.byToolUseId.delete(toolUseId); + pending.bytes -= entry.bytes; + return entry.frames; +} /** Returns the tool use whose launch details were evicted to stay within the cap. */ function rememberPendingClaudeSubagentLaunch( @@ -5281,7 +5327,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( // Buffered idle outcomes must not settle a resumed child again. const appliedSubagentOutcomes = new WeakSet(); // Subagent frames can precede the task_started that registers their owner. - const pendingSubagentFramesByToolUseId = yield* Ref.make(new Map()); + // Mutated in place: each session handles its SDK frames one at a time. + const pendingSubagentFrames: PendingClaudeSubagentFrames = { + byToolUseId: new Map(), + bytes: 0, + }; const warnEvictedSubagentLaunch = ( context: ActiveClaudeTurnContext, evictedToolUseId: string | null, @@ -9520,26 +9570,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( frameParentToolUseId !== null && (yield* resolveSubagentByToolUseId(context, frameParentToolUseId)) === undefined ) { - const droppedToolUseId = yield* Ref.modify( - pendingSubagentFramesByToolUseId, - (current) => { - const frames = current.get(frameParentToolUseId); - if (frames !== undefined) { - if (frames.length >= PENDING_CLAUDE_SUBAGENT_FRAME_CAP) { - return [frameParentToolUseId, current] as const; - } - // Appending in place keeps a long burst linear; the map is local to this session. - frames.push(message); - return [null, current] as const; - } - const next = new Map(current).set(frameParentToolUseId, [message]); - const oldest = next.keys().next(); - if (next.size > PENDING_CLAUDE_SUBAGENT_CAP && !oldest.done) { - next.delete(oldest.value); - return [oldest.value, next] as const; - } - return [null, next] as const; - }, + const droppedToolUseId = bufferPendingClaudeSubagentFrame( + pendingSubagentFrames, + frameParentToolUseId, + message, ); if (droppedToolUseId !== null) { yield* Effect.logWarning("orchestration-v2.claude-subagent-frames-dropped", { @@ -10224,15 +10258,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* Ref.update(sessionSubagentTaskIdsByToolUseId, (current) => current.get(toolUseId) === taskId ? current : new Map(current).set(toolUseId, taskId), ); - return yield* Ref.modify(pendingSubagentFramesByToolUseId, (current) => { - const frames = current.get(toolUseId); - if (frames === undefined) { - return [[] as ReadonlyArray, current] as const; - } - const next = new Map(current); - next.delete(toolUseId); - return [frames, next] as const; - }); + return takePendingClaudeSubagentFrames(pendingSubagentFrames, toolUseId); }); const handleRoutedSdkMessage = Effect.fnUntraced(function* (input: { From 14e3f5923bee227d9ae7586687ccbf54b27eb6e4 Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 13:23:22 +0100 Subject: [PATCH 13/13] fix(web): keep every saved draft's uploads alive while the app is in use The server keeps a pending upload for 30 days after a client last asked about it, but the web client only asked when a draft was opened or a stash restored. A draft left unopened for a month lost its uploaded files even while the app was used daily. On load, and then about once a day, the app now asks each connected environment about the uploads that saved drafts and stash entries reference, one at a time, which refreshes them on the server. The composer guide now says how long unsent draft uploads are kept. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/appInit.tsx | 2 + apps/web/src/lib/draftUploadKeepAlive.test.ts | 45 +++++++++++++ apps/web/src/lib/draftUploadKeepAlive.ts | 63 +++++++++++++++++++ docs/user/composer.md | 10 ++- 4 files changed, 117 insertions(+), 3 deletions(-) create mode 100644 apps/web/src/lib/draftUploadKeepAlive.test.ts create mode 100644 apps/web/src/lib/draftUploadKeepAlive.ts diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index 3be9175c4f2e4..eb1a5f56f3504 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -41,6 +41,7 @@ import { import { syncBrowserChromeTheme } from "./hooks/useTheme"; import { startThreadVisitedMigration } from "./hooks/useThreadVisitedMigration"; import { installDesktopPasteAsText } from "./lib/desktopPasteAsText"; +import { startDraftUploadKeepAlive } from "./lib/draftUploadKeepAlive"; import { syncDocumentElectronPlatformClasses, syncDocumentWindowControlsOverlayClass, @@ -182,6 +183,7 @@ export function startAppServices(): AppRouter { startClientAppearance(); startDocumentTitle(); startHostEnvironmentLookup(); + startDraftUploadKeepAlive(); startEnvironmentThemeRepaint(); startBrowserChromeThemeSync(router); startDefaultThemeAdoption(); diff --git a/apps/web/src/lib/draftUploadKeepAlive.test.ts b/apps/web/src/lib/draftUploadKeepAlive.test.ts new file mode 100644 index 0000000000000..28128a7eb91c5 --- /dev/null +++ b/apps/web/src/lib/draftUploadKeepAlive.test.ts @@ -0,0 +1,45 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { referencedDraftUploads } from "./draftUploadKeepAlive"; + +describe("referencedDraftUploads", () => { + it("collects uploads from saved drafts and stash entries by environment", () => { + const local = EnvironmentId.make("environment-local"); + const remote = EnvironmentId.make("environment-remote"); + const file = { id: "file", name: "notes.pdf", mimeType: "application/pdf", sizeBytes: 1 }; + const referenced = referencedDraftUploads({ + drafts: [ + { + files: [ + { + ...file, + type: "file", + file: null, + uploadedAttachmentId: "a", + uploadEnvironmentId: local, + }, + // Not uploaded yet, so the server holds nothing for it. + { ...file, type: "file", file: null }, + ], + }, + { + files: [ + { + ...file, + type: "file", + file: null, + uploadedAttachmentId: "a", + uploadEnvironmentId: local, + }, + ], + }, + ], + stashEntries: [{ files: [{ ...file, attachmentId: "b", environmentId: remote }] }, {}], + }); + expect(Object.fromEntries([...referenced].map(([id, ids]) => [id, [...ids]]))).toEqual({ + [local]: ["a"], + [remote]: ["b"], + }); + }); +}); diff --git a/apps/web/src/lib/draftUploadKeepAlive.ts b/apps/web/src/lib/draftUploadKeepAlive.ts new file mode 100644 index 0000000000000..c87f718271914 --- /dev/null +++ b/apps/web/src/lib/draftUploadKeepAlive.ts @@ -0,0 +1,63 @@ +import type { EnvironmentId } from "@t3tools/contracts"; + +import { useComposerDraftStore, type ComposerThreadDraftState } from "../composerDraftStore"; +import { usePromptStashStore, type PromptStashEntry } from "../promptStashStore"; +import { appAtomRegistry } from "../rpc/atomRegistry"; +import { environmentPresentations } from "../state/presentation"; +import { verifyStashedAttachmentUpload } from "./attachmentUploadQueue"; + +// The server deletes uploads no client has asked about for 30 days; a daily refresh keeps +// every draft and stash upload alive while the app is in use, even unopened ones. +const REFRESH_INTERVAL_MS = 24 * 60 * 60 * 1000; + +/** Uploaded attachment ids that saved drafts and stash entries still reference, by environment. */ +export function referencedDraftUploads(input: { + readonly drafts: Iterable>; + readonly stashEntries: ReadonlyArray>; +}): ReadonlyMap> { + const byEnvironment = new Map>(); + const add = (environmentId: EnvironmentId, attachmentId: string) => { + const ids = byEnvironment.get(environmentId) ?? new Set(); + ids.add(attachmentId); + byEnvironment.set(environmentId, ids); + }; + for (const draft of input.drafts) { + for (const file of draft.files) { + if (file.uploadedAttachmentId && file.uploadEnvironmentId) { + add(file.uploadEnvironmentId, file.uploadedAttachmentId); + } + } + } + for (const entry of input.stashEntries) { + for (const file of entry.files ?? []) add(file.environmentId, file.attachmentId); + } + return byEnvironment; +} + +/** Asks each connected environment about its draft uploads on load, then daily. */ +export function startDraftUploadKeepAlive(): void { + const refreshedAt = new Map(); + const refresh = () => { + const now = Date.now(); + const presentations = appAtomRegistry.get(environmentPresentations.presentationsAtom); + const referenced = referencedDraftUploads({ + drafts: Object.values(useComposerDraftStore.getState().draftsByThreadKey), + stashEntries: usePromptStashStore.getState().entries, + }); + for (const [environmentId, attachmentIds] of referenced) { + if (presentations.get(environmentId)?.connection.phase !== "connected") continue; + const last = refreshedAt.get(environmentId); + if (last !== undefined && now - last < REFRESH_INTERVAL_MS) continue; + refreshedAt.set(environmentId, now); + void (async () => { + // One at a time keeps the request burst small; failures wait for the next refresh. + for (const attachmentId of attachmentIds) { + await verifyStashedAttachmentUpload({ environmentId, attachmentId }).catch(() => {}); + } + })(); + } + }; + appAtomRegistry.subscribe(environmentPresentations.presentationsAtom, refresh); + window.setInterval(refresh, REFRESH_INTERVAL_MS); + refresh(); +} diff --git a/docs/user/composer.md b/docs/user/composer.md index 917480cbdb4e8..b50d3a092e15a 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -49,7 +49,11 @@ sends supported videos to Gemini models as video. Uploads begin when you add an attachment. All uploads must finish before the message can send. Retry or remove a failed upload. On web and desktop, reloading -before an upload finishes requires you to attach that file again. +before an upload finishes requires you to attach that file again. Files uploaded +to an unsent draft stay on the environment for 30 days from when the draft was last +opened. On web and desktop, the app also refreshes them about once a day while it is +connected to that environment, so an unopened draft keeps its files while you use +the app. You can drag or paste images into the web or desktop composer. HEIC and HEIF photos are converted to JPEG there and when selected from the mobile photo @@ -193,8 +197,8 @@ With an empty composer, the same shortcut restores a single stash or opens the stash menu when there are several. Stashes containing uploaded files must be restored in their original environment. -Those files are kept until 30 days pass without the stash or a draft using them. After an upload -expires, restore the prompt and use **Attach again** or remove the missing file before sending. +Those files are kept like draft uploads above. After an upload expires, restore the prompt and use +**Attach again** or remove the missing file before sending. ## Voice input on web and desktop