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/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 4550692f3e18a..1327d6e62aa87 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -15092,99 +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 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", - }), - 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); + 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-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({ + 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.", - "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 4a252d6092edb..1c83a5e0c9c2d 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -4548,22 +4548,70 @@ 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; +/** 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( 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 +4621,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 +4636,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 +5327,21 @@ 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, + ) => + 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 +9545,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({ @@ -9509,21 +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.length >= PENDING_CLAUDE_SUBAGENT_FRAME_CAP) { - return [frameParentToolUseId, current] as const; - } - const next = new Map(current).set(frameParentToolUseId, [...frames, 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", { @@ -9788,13 +9838,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; } @@ -10205,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: { @@ -10406,13 +10451,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({ 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.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..775ca94485a91 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -628,6 +628,16 @@ 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; 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(EffectOutbox.BACKGROUND_EFFECT_TYPES); +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 +656,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 +800,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 +832,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 +855,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) { 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; diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index f5e4336fec045..094d4a5fe0e54 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"; @@ -45,7 +46,11 @@ 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; +/** 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. */ @@ -93,6 +98,13 @@ 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; +} + interface ReadPlan { readonly detail: boolean; readonly activity: boolean; @@ -100,7 +112,14 @@ interface ReadPlan { const watchKey = ({ thread, watch }: WatchTarget) => `${thread.id} ${watch.startedAt}`; -type WatchEndReason = "merged" | "closed" | "unreadable" | "comment-limit" | "subagent" | "stopped"; +type WatchEndReason = "merged" | "closed" | "not-found" | "comment-limit" | "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; @@ -246,7 +265,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. @@ -295,20 +314,83 @@ export const make = Effect.gen(function* () { }); }); - const giveUp = (target: WatchTarget) => + 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", + summary: `#${target.link.number}: cannot read it, still watching`, + }, + }).pipe(Effect.tap(() => woke(target))); + + 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" }, + outcome: "updated", + summary: `#${target.link.number}: readable again`, + }, + }).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 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.`, + 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, could not read it`, + summary: `#${target.link.number}: stopped watching, not found`, }, }).pipe( Effect.tap(() => woke(target)), - Effect.catch(() => record(target, null)), - Effect.tap(() => ended(target, "unreadable")), + 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, @@ -458,9 +540,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); @@ -498,19 +581,28 @@ 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. + // Transport and host failures can outlast an outage; they do not count toward the notice. if (reason === "failed") { 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 = (readFailures.get(group.key)?.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), + ); + 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); } 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); @@ -615,6 +707,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, @@ -644,7 +737,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/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"); + }); }); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index d32800e34268b..188bbee1c2280 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -3251,6 +3251,17 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { ); assert.isNull(woken.thread.settledOverride); assert.isNull(woken.thread.settledAt); + // Later tests sweep every watch in this shared database, and failing reads keep one alive. + for (const number of [7, 8]) { + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make(`pr-watch-settle-stop-${mode}-${number}`), + threadId, + ...key, + number, + watching: false, + }); + } }), ); @@ -3360,6 +3371,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({ @@ -3372,7 +3385,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, @@ -3380,29 +3393,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( @@ -3420,36 +3439,64 @@ 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"]), - ({ messages }) => messages.flatMap((message) => message.notification?.summary ?? []), + ({ messages }) => + messages.flatMap((message) => message.notification?.summary ?? []).toSorted(), ); yield* sweep; assert.deepEqual(yield* summaries, []); disconnected = true; - for (let pass = 0; pass < 15; pass += 1) { + passesRead.clear(); + 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); - if (reason !== "failed") { - assert.isUndefined(thread?.pullRequests?.[0]?.watch); - assert.deepEqual(yield* summaries, ["#8: stopped watching, could not read it"]); + 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 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; } - assert.isDefined(thread?.pullRequests?.[0]?.watch); - assert.deepEqual(yield* summaries, []); 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/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..62139f611b457 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,76 @@ it.effect( }).pipe(Effect.provide(ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies)))); }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); + +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 }, + ); + 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, 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 4fd59e610f0f3..b4dfe71e62585 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, @@ -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, @@ -1111,29 +1116,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 +1143,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 }), ), 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/components/chat/useComposerStash.ts b/apps/web/src/components/chat/useComposerStash.ts index b390858d684f8..fa7f8e745a074 100644 --- a/apps/web/src/components/chat/useComposerStash.ts +++ b/apps/web/src/components/chat/useComposerStash.ts @@ -394,7 +394,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/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 67fc0c9a3ebc8..89e553c467906 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -51,7 +51,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 @@ -202,8 +206,8 @@ the stash would use more than about 60% of that space, so drafts keep room to sa If drafts cannot be saved, T3 Code tells you. 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 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 diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 62ef90b1dfe32..1b895db296fbd 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -329,8 +329,11 @@ 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, 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. Archiving a thread also ends all its watches. Settling keeps them, and a wake moves the thread back to active work. 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;