From f6db57a948256d166557e8131cfe546a937b3435 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:55:18 +0000 Subject: [PATCH 1/6] fix(server): wake threads when watches and waits go stale Model: gpt-6.2-sol Task: fix Agent: Codex Lane: codex --- apps/server/src/mcp/OrchestratorMcpService.ts | 36 ++ .../src/mcp/toolkits/orchestrator/handlers.ts | 1 + .../src/mcp/toolkits/orchestrator/tools.ts | 6 +- .../src/mcp/toolkits/pullRequests/handlers.ts | 21 +- .../src/mcp/toolkits/pullRequests/tools.ts | 8 +- .../Adapters/ClaudeAdapterV2.ts | 41 ++ .../src/orchestration-v2/ModelAlertReactor.ts | 28 +- .../src/orchestration-v2/Orchestrator.ts | 354 +++++++++++++++++- .../src/orchestration-v2/ProjectionStore.ts | 30 ++ .../ProviderTurnControlService.test.ts | 2 + .../PullRequestWatchReactor.ts | 101 ++++- .../src/orchestration-v2/ThreadEventAlerts.ts | 4 + .../ThreadManagementService.test.ts | 1 + .../ThreadManagementService.ts | 26 ++ .../orchestration-v2/pullRequestWatch.test.ts | 26 +- .../src/orchestration-v2/pullRequestWatch.ts | 77 +++- .../src/orchestration-v2/runtimeLayer.test.ts | 292 +++++++++++++++ .../src/orchestration-v2/waitStaleness.ts | 29 ++ apps/server/src/peer/RemoteDelegation.ts | 31 +- .../src/pullRequest/PullRequestService.ts | 3 + .../pullRequest/PullRequestWatchService.ts | 11 +- .../src/relay/AgentAwarenessRelay.test.ts | 1 + packages/contracts/src/index.ts | 1 + packages/contracts/src/orchestrationV2.ts | 43 +++ packages/contracts/src/orchestratorMcp.ts | 4 + packages/contracts/src/pullRequest.ts | 2 + packages/contracts/src/threadPullRequest.ts | 9 + packages/contracts/src/waitStaleness.ts | 19 + .../src/server/gitHubPullRequestJson.ts | 4 + 29 files changed, 1176 insertions(+), 35 deletions(-) create mode 100644 apps/server/src/orchestration-v2/waitStaleness.ts create mode 100644 packages/contracts/src/waitStaleness.ts diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index a50fa929ed04e..be5faaf8b530b 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -1,3 +1,9 @@ +import { BACKGROUND_WAIT_STALE_MINUTES } from "@t3tools/contracts"; +import { + staleTimeoutMs, + waitActivityMs, + waitIntentionallyHeld, +} from "../orchestration-v2/waitStaleness.ts"; import { CommandId, EnvironmentId, @@ -2876,6 +2882,14 @@ const make = Effect.gen(function* () { // delegations deliver through the blocking tool call until `awaitTask` // gives up the wait (timeout, cancelled call) and upgrades the wake. completionWake: input.mode === "wait" ? "settled_only" : "always", + ...(input.mode === "wait" + ? { + staleTimeoutMs: staleTimeoutMs( + input.staleTimeoutMinutes, + BACKGROUND_WAIT_STALE_MINUTES, + ), + } + : {}), }) .pipe( Effect.mapError((error) => @@ -3721,7 +3735,29 @@ const make = Effect.gen(function* () { : []; const wakesCaller = ownedTask && !childRequests.some((request) => request.status === "pending"); + const progressShell = + result.timedOut && input.untilDelegatedWorkSettled === true + ? yield* threadManagement + .getThreadShell(input.threadId) + .pipe(Effect.orElseSucceed(() => null)) + : null; + const progress = + progressShell === null + ? {} + : { + progressAtMs: Math.max( + waitActivityMs(progressShell), + yield* threadManagement + .getWaitActivityMs(progressShell.id, progressShell.latestRunId) + .pipe(Effect.orElseSucceed(() => 0)), + ), + intentionallyHeld: waitIntentionallyHeld( + progressShell, + yield* Clock.currentTimeMillis, + ), + }; return { + ...progress, threadId: input.threadId, runId: result.run?.id ?? null, status, diff --git a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts index 2827882f0a4a0..1a23b7af57aff 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts @@ -179,6 +179,7 @@ const handlers = { threadId: caller.thread.threadId, taskIds: input.taskIds, awaited: input.waiting ?? true, + staleTimeoutMinutes: input.staleTimeoutMinutes, }) .pipe( Effect.mapError( diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index a30d1152c60aa..d0744cbb004a0 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -1,4 +1,5 @@ import { + StaleTimeoutMinutes, OrchestratorMcpCapabilitiesInput, OrchestratorMcpCapabilitiesResult, OrchestrationV2StopWorkflowInput, @@ -90,7 +91,7 @@ const OrchestratorCapabilitiesTool = Tool.make("orchestrator_capabilities", { const DelegateTaskTool = Tool.make("delegate_task", { description: - "Start one child agent with only `task`. No parent history. Separate checkout or PR per child: `isolation:'worktree'`. Keep `taskId` for `task_status` and `task_cancel`. No secrets in `task`.", + "Start one child agent with only `task`. No parent history. Separate checkout or PR per child: `isolation:'worktree'`. Keep `taskId` for `task_status` and `task_cancel`. In `mode:'wait'`, T3 wakes the parent once per quiet period after 45 minutes without child activity. Change this with `staleTimeoutMinutes`. The separate `timeoutMs` limits only the tool call. No secrets in `task`.", parameters: OrchestratorMcpDelegateTaskInput, success: OrchestratorMcpDelegateTaskResult, failure: OrchestratorMcpFailure, @@ -147,13 +148,14 @@ const WorkflowStopTool = Tool.make("t3_workflow_stop", { const BackgroundWaitTool = Tool.make("t3_background_wait", { description: - "Keep this thread in Working while background work runs. Pass its task ID once started. Not for work left running (dev server, watcher). `waiting=false` clears. Doesn't stop tasks. Claude/OpenCode only.", + "Keep this thread in Working while background work runs. Pass its task ID once started. Not for work left running (dev server, watcher). `waiting=false` clears. Doesn't stop tasks. T3 wakes you once per quiet period after 45 minutes without progress. Set `staleTimeoutMinutes` to change the deadline. Claude/OpenCode only.", parameters: Schema.Struct({ taskIds: Schema.Array(TrimmedNonEmptyString).check( Schema.isMinLength(1), Schema.isMaxLength(20), ), waiting: Schema.optional(Schema.Boolean), + staleTimeoutMinutes: StaleTimeoutMinutes, }), success: Schema.Struct({ matched: Schema.Array(Schema.String), diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index 884dd09a3dea4..4704b62720d18 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -199,18 +199,25 @@ const make = Effect.gen(function* () { // The domain service owns the registration span. const setWatching = Effect.fnUntraced(function* ( - input: PullRequestTargetInput, + input: PullRequestTargetInput & { readonly staleTimeoutMinutes?: number | undefined }, watching: boolean, ) { const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests"); const threadId = input.threadId ?? scope.thread?.threadId; if (threadId === undefined) return yield* new PullRequestThreadRequiredError(); - return yield* watches.setWatching({ threadId, target: input, watching }).pipe( - Effect.catchTags({ - PullRequestWatchThreadNotFoundError: (error) => - threadNotFound(engine, scope, error.threadId, error.message), - }), - ); + return yield* watches + .setWatching({ + threadId, + target: input, + watching, + staleTimeoutMinutes: input.staleTimeoutMinutes, + }) + .pipe( + Effect.catchTags({ + PullRequestWatchThreadNotFoundError: (error) => + threadNotFound(engine, scope, error.threadId, error.message), + }), + ); }); const locateAll = Effect.fn("PullRequestsToolkit.locateAll")(function* ( diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 376817db10079..72513ef1a0808 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -1,4 +1,5 @@ import { + StaleTimeoutMinutes, McpCapabilityUnavailableError, OrchestratorMcpEnvironmentTarget, OrchestratorMcpFailure, @@ -326,8 +327,11 @@ const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", { const WatchPullRequestTool = Tool.make("watch_pull_request", { description: - "Watch an open PR for this thread, linking it first if needed. T3 wakes you on failed checks, passed required checks, new comments or reviews, or conflicts. Handle old comments first. Only later ones wake you. After this call, end your turn. The watch stays on after each wake, so do not call this again on a wake. A wake is not a merge decision. Check readiness yourself.", - parameters: PullRequestTargetInput, + "Watch an open PR for this thread, linking it first if needed. T3 wakes you on failed checks, passed required checks, new comments or reviews, or conflicts. Handle old comments first. Only later ones wake you. After this call, end your turn. The watch stays on after each wake, so do not call this again on a wake. A wake is not a merge decision. Check readiness yourself. T3 also wakes you once per quiet period after 30 minutes without progress. Set `staleTimeoutMinutes` to change that deadline.", + parameters: Schema.Struct({ + ...PullRequestTargetInput.fields, + staleTimeoutMinutes: StaleTimeoutMinutes, + }), success: WatchPullRequestResult, failure: PullRequestToolError, dependencies: watchDependencies, diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 7c4f6e1b7b29b..f5979d9b8389c 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -10633,6 +10633,40 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return subagent?.task.status === "running" ? settled : null; }); + const backgroundTaskProgress = new Map(); + const recordBackgroundTaskProgress = Effect.fnUntraced(function* ( + nativeThreadId: string, + message: Extract, + ) { + const signature = `${message.run_id ?? ""}:${message.usage.total_tokens}:${message.usage.tool_uses}:${message.summary ?? ""}`; + if (backgroundTaskProgress.get(message.task_id) === signature) return; + const now = DateTime.toEpochMillis(yield* DateTime.now); + const changed = yield* Ref.modify(pendingBackgroundTasksByNativeThread, (current) => { + const roster = current.get(nativeThreadId); + const task = roster?.get(message.task_id); + if (task === undefined) return [false, current] as const; + return [ + true, + new Map(current).set( + nativeThreadId, + new Map(roster).set(message.task_id, { ...task, progressAtMs: now }), + ), + ] as const; + }); + if (!changed) return; + backgroundTaskProgress.delete(message.task_id); + backgroundTaskProgress.set(message.task_id, signature); + for (const oldest of backgroundTaskProgress.keys()) { + if (backgroundTaskProgress.size <= 64) break; + backgroundTaskProgress.delete(oldest); + } + const active = yield* Ref.get(activeTurn); + yield* emitRosterUpdate( + nativeThreadId, + active?.nativeThreadId === nativeThreadId ? active : null, + ); + }); + const handleSdkMessageFrame = Effect.fnUntraced(function* (input: { readonly query: ClaudeAgentSdkQuerySession; readonly message: SDKMessage; @@ -10665,6 +10699,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } return; } + if ( + message.type === "system" && + message.subtype === "task_progress" && + input.replayed !== true + ) { + yield* recordBackgroundTaskProgress(liveQuery.nativeThreadId, message); + } // Track before routing: idle-wake Monitors report tasks before replaying their tool calls. yield* trackClaudeMonitorCalls(message); yield* trackClaudeScheduledWakeup(liveQuery.nativeThreadId, message); diff --git a/apps/server/src/orchestration-v2/ModelAlertReactor.ts b/apps/server/src/orchestration-v2/ModelAlertReactor.ts index e0cc3e0bc9e4c..d5d640e9708fc 100644 --- a/apps/server/src/orchestration-v2/ModelAlertReactor.ts +++ b/apps/server/src/orchestration-v2/ModelAlertReactor.ts @@ -1104,11 +1104,15 @@ export const make = Effect.gen(function* () { )), ) : null; + const hasStalenessWait = + trigger === "sweep" && + shell.activeRunId !== null && + ((yield* projections.getThread(shell.id)).stalenessWaits?.length ?? 0) > 0; if (trigger !== "sweep" || shell.activeRunId !== null || shell.activityRunStatus != null) { - return { remoteTaskCount, childActivityMs }; + return { remoteTaskCount, childActivityMs, hasStalenessWait }; } if (queuedThreads !== undefined && !queuedThreads.has(shell.id)) { - return { remoteTaskCount, childActivityMs, strandedQueue: null }; + return { remoteTaskCount, childActivityMs, hasStalenessWait, strandedQueue: null }; } const now = yield* DateTime.now; const { runs } = yield* projections.getThreadRecords(shell.id, ["runs"]); @@ -1138,7 +1142,7 @@ export const make = Effect.gen(function* () { (shell.lastErrorClass === "usage_limit" && latestRun?.providerInstanceId === oldest.providerInstanceId), }; - return { remoteTaskCount, childActivityMs, strandedQueue }; + return { remoteTaskCount, childActivityMs, hasStalenessWait, strandedQueue }; }); /** The watcher thread as one delivery needs it, or null when it cannot be read. */ @@ -1622,6 +1626,24 @@ export const make = Effect.gen(function* () { yield* sweepResumes.pipe( Effect.catchCause((cause) => Effect.logWarning("resume sweep failed", { cause })), ); + const now = yield* Clock.currentTimeMillis; + yield* Effect.forEach( + yield* projections.listStalenessWaitThreads, + (threadId) => + engine + .dispatch({ + type: "thread.wait-staleness.update", + commandId: CommandId.make(`server:wait-staleness:${threadId}:${now}`), + threadId, + operation: { type: "sweep" }, + }) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("wait staleness sweep failed", { threadId, cause }), + ), + ), + { discard: true }, + ); const index = yield* projections.listActiveShellIndex(); const queuedThreads = new Set(yield* projections.getRecoveryThreadIds("queued-runs")); // One scan of the delegated tasks for the whole sweep, not one per thread. diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index a3dbdb3942fea..594196d243e1e 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1,3 +1,4 @@ +import { waitActivityMs, waitIntentionallyHeld } from "./waitStaleness.ts"; import type { OrchestrationV2ThreadLinkMetadata, GuestShareId, @@ -34,12 +35,13 @@ import { ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE, type ChatAttachment, CommandId, + PR_WATCH_STALE_MINUTES, type GuestMessageId, isCompactionCommandMessage, isOrchestrationV2WorkActive, isProviderNativeSubagentThread, MessageId, - type NodeId, + NodeId, type ModelSelection, OrchestrationV2Command, type OrchestrationV2InternalCommand, @@ -48,6 +50,7 @@ import { type OrchestrationV2ServerCommand, type ThreadPullRequestLink, type ThreadPullRequestWatch, + ThreadStalenessWait, type OrchestrationV2AppThread, type OrchestrationV2ContextHandoff, type OrchestrationV2ContextSourcePoint, @@ -533,6 +536,10 @@ export interface OrchestratorV2Shape { Effect.Effect, OrchestratorV2Error >; + readonly getWaitActivityMs: ( + threadId: ThreadId, + runId: RunId | null, + ) => Effect.Effect; readonly getThreadShell: ( threadId: ThreadId, ) => Effect.Effect; @@ -660,6 +667,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId { case "thread.pull-request.unlink": case "thread.pull-request-link.sync": case "thread.pull-request.watch": + case "thread.wait-staleness.update": case "thread.pull-request-watch.sync": case "thread.pull-request-watch.checks-reopen": case "thread.pull-request.sync": @@ -1220,6 +1228,20 @@ function pullRequestSnapshotEndsWatch( ); } +const WaitStaleDiagnostic = Schema.Struct({ + type: Schema.Literal("wait_stale_timeout"), + waits: Schema.Array( + Schema.Struct({ + taskId: Schema.String, + kind: ThreadStalenessWait.fields.kind, + state: Schema.String, + childLink: Schema.optional(Schema.String), + idleMinutes: Schema.Int, + }), + ), +}); +const encodeWaitStaleDiagnostic = Schema.encodeEffect(Schema.fromJsonString(WaitStaleDiagnostic)); + type MonitorPullRequestStamp = NonNullable< Extract["pullRequest"] >; @@ -1240,6 +1262,11 @@ function isStalePullRequestWatchStamp( candidate.source !== "stack-dismissed" && threadPullRequestKeysEqual(candidate, stamp), ); if (link === undefined) return true; + if ( + stamp.staleProgressAt !== undefined && + link.watch?.staleness?.lastProgressAt !== stamp.staleProgressAt + ) + return true; if (stamp.watchEnded === true) { // The final notice outlives its watch, but a replacement watch supersedes it. const latestWatch = link.watch ?? link.endedWatch; @@ -1268,6 +1295,43 @@ function isStalePullRequestWatchStamp( ); } +function isStaleBackgroundWaitWake( + projection: OrchestrationV2ThreadProjection, + run: OrchestrationV2Run, +): boolean { + const source = projection.messages.find((message) => message.id === run.userMessageId) + ?.notification?.source; + if (source?.kind !== "monitor" || source.staleWaits === undefined) return false; + if (projection.thread.settledAt !== null || projection.thread.settledOverride === "settled") + return true; + return source.staleWaits.every((stamp) => { + const wait = projection.thread.stalenessWaits?.find( + (wait) => wait.kind === stamp.kind && wait.taskId === stamp.taskId, + ); + if (wait?.lastProgressAtMs !== stamp.lastProgressAtMs || wait.remoteHeld === true) return true; + if (wait.kind === "background") { + return !projection.providerThreads + .find((provider) => provider.id === projection.thread.activeProviderThreadId) + ?.pendingBackgroundTasks?.some( + (task) => + task.taskId === wait.taskId && + task.awaited === true && + (task.progressAtMs ?? 0) <= wait.lastProgressAtMs, + ); + } + const task = projection.subagents.find((task) => task.id === wait.taskId); + return ( + task === undefined || + task.result !== null || + task.completionDelivery?.state === "disposed" || + task.status === "completed" || + task.status === "failed" || + task.status === "cancelled" || + task.status === "interrupted" + ); + }); +} + function isStalePullRequestWatchWake( projection: Pick, run: OrchestrationV2Run, @@ -2635,7 +2699,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); while ( storedQueuedRun !== undefined && - isStalePullRequestWatchWake(projection, storedQueuedRun) + (isStalePullRequestWatchWake(projection, storedQueuedRun) || + isStaleBackgroundWaitWake(projection, storedQueuedRun)) ) { yield* writeSystemEvents( queuedRunCancellationEvents(projection, storedQueuedRun, yield* DateTime.now), @@ -4175,6 +4240,229 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); }); + const updateWaitStaleness = Effect.fn("Orchestrator.updateWaitStaleness")(function* ( + command: Extract, + events: Ref.Ref>, + effects: Ref.Ref>, + ) { + const now = yield* DateTime.now; + const nowMs = DateTime.toEpochMillis(now); + const { operation, threadId } = command; + const thread = yield* projectionStore.getThread(threadId).pipe(mapDispatchError(command)); + if (thread.deletedAt !== null) return; + const waits = thread.stalenessWaits ?? []; + let next = waits; + const stale: Array<{ + taskId: string; + kind: ThreadStalenessWait["kind"]; + state: string; + childLink?: string; + idleMinutes: number; + lastProgressAtMs: number; + }> = []; + switch (operation.type) { + case "register": { + const added = [...new Set(operation.taskIds)].filter( + (taskId) => !waits.some((wait) => wait.kind === operation.kind && wait.taskId === taskId), + ); + if (added.length > 0) { + next = [ + ...waits, + ...added.map((taskId) => ({ + kind: operation.kind, + taskId, + staleTimeoutMs: operation.staleTimeoutMs, + lastProgressAtMs: nowMs, + })), + ]; + } + break; + } + case "clear": + next = waits.filter( + (wait) => wait.kind !== operation.kind || !operation.taskIds.includes(wait.taskId), + ); + break; + case "remote-progress": + next = waits.map((wait) => { + const lastProgressAtMs = Math.min(operation.progressAtMs, nowMs); + if (wait.kind !== "delegate" || wait.taskId !== operation.taskId) return wait; + if (lastProgressAtMs <= wait.lastProgressAtMs) { + return operation.held === wait.remoteHeld || operation.held === undefined + ? wait + : { ...wait, remoteHeld: operation.held }; + } + const { alerted: _, ...rearmed } = wait; + return { + ...rearmed, + lastProgressAtMs, + ...(operation.held === undefined ? {} : { remoteHeld: operation.held }), + }; + }); + break; + case "sweep": { + if (waits.length === 0) return; + const shell = yield* projectionStore + .getThreadShell(threadId) + .pipe(mapDispatchError(command)); + if ( + shell === null || + shell.archivedAt !== null || + shell.settledAt !== null || + shell.settledOverride === "settled" + ) { + next = []; + break; + } + const tasks = yield* projectionStore + .getThreadRecords(threadId, ["subagents", "providerThreads"], { + subagentIds: waits.flatMap((wait) => + wait.kind === "delegate" ? [NodeId.make(wait.taskId)] : [], + ), + }) + .pipe(mapDispatchError(command)); + const parentHeld = waitIntentionallyHeld(shell, nowMs); + const retained: ThreadStalenessWait[] = []; + for (const wait of waits) { + let progressAtMs = wait.lastProgressAtMs; + let state = "pending"; + let childLink: string | undefined; + let held = parentHeld; + if (wait.kind === "background") { + const task = tasks.providerThreads + .find((provider) => provider.id === thread.activeProviderThreadId) + ?.pendingBackgroundTasks?.find( + (task) => task.taskId === wait.taskId && task.awaited === true, + ); + if (task === undefined) { + // The provider's roster event and the MCP registration can commit in either order. + if (nowMs < wait.lastProgressAtMs + 60_000) retained.push(wait); + continue; + } + state = task.kind; + const item = + task.itemId === undefined + ? null + : yield* projectionStore + .getTurnItem({ + threadId: task.sourceThreadId ?? threadId, + itemId: task.itemId, + }) + .pipe(mapDispatchError(command)); + progressAtMs = Math.max( + progressAtMs, + task.progressAtMs ?? 0, + item === null ? 0 : DateTime.toEpochMillis(item.updatedAt), + ); + } else { + const task = tasks.subagents.find( + (task) => task.id === wait.taskId && task.origin === "app_owned", + ); + if ( + task === undefined || + task.result !== null || + task.completionDelivery?.state === "disposed" || + task.status === "completed" || + task.status === "failed" || + task.status === "interrupted" || + task.status === "cancelled" + ) + continue; + state = task.status; + if (task.remoteChild !== undefined) { + childLink = formatThreadLink(task.remoteChild, task.remoteChild.title); + held ||= wait.remoteHeld === true; + } else if (task.childThreadId !== null) { + const child = yield* projectionStore + .getThreadShell(task.childThreadId) + .pipe(mapDispatchError(command)); + if ( + child === null || + child.deletedAt !== null || + child.archivedAt !== null || + child.settledOverride === "settled" + ) + continue; + childLink = formatThreadLink( + { environmentId: null, threadId: child.id }, + child.title, + ); + state = child.status; + held ||= waitIntentionallyHeld(child, nowMs); + const itemActivity = yield* projectionStore + .getWaitActivityMs(child.id, child.latestRunId) + .pipe(mapDispatchError(command)); + progressAtMs = Math.max(progressAtMs, waitActivityMs(child), itemActivity); + } + } + const rearmed = progressAtMs > wait.lastProgressAtMs; + const { alerted: _, ...registration } = wait; + const current = rearmed ? { ...registration, lastProgressAtMs: progressAtMs } : wait; + const idleMs = nowMs - current.lastProgressAtMs; + if (!held && !current.alerted && idleMs >= current.staleTimeoutMs) { + retained.push({ ...current, alerted: true }); + stale.push({ + taskId: wait.taskId, + kind: wait.kind, + state, + idleMinutes: Math.floor(idleMs / 60_000), + lastProgressAtMs: current.lastProgressAtMs, + ...(childLink === undefined ? {} : { childLink }), + }); + } else { + retained.push(current); + } + } + next = retained; + break; + } + } + if (next.length === waits.length && next.every((wait, index) => wait === waits[index])) return; + yield* emit( + events, + command, + )({ + type: "thread.metadata-updated", + occurredAt: now, + threadId, + providerInstanceId: thread.providerInstanceId, + payload: { ...thread, stalenessWaits: next }, + }); + if (stale.length === 0) return; + const diagnostic = yield* encodeWaitStaleDiagnostic({ + type: "wait_stale_timeout", + waits: stale.map(({ lastProgressAtMs: _, ...diagnostic }) => diagnostic), + }).pipe(Effect.orDie); + const text = `${diagnostic}\n\nCheck why this work is quiet. T3 Code keeps its normal completion wake armed and reports staleness again only after progress.`; + yield* dispatchMessage( + { + type: "message.dispatch", + commandId: command.commandId, + threadId, + messageId: MessageId.make(`message:${command.commandId}`), + text, + attachments: [], + notification: { + source: { + kind: "monitor", + staleWaits: stale.map(({ kind, taskId, lastProgressAtMs }) => ({ + kind, + taskId, + lastProgressAtMs, + })), + }, + outcome: "updated", + summary: `No progress on ${stale.length === 1 ? "one wait" : `${stale.length} waits`}`, + }, + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }, + events, + effects, + ); + }); + // Recheck under the lock after reading the host. Record the watch first so wake events carry it. const dispatchPullRequestWatchSync = Effect.fn("orchestrationV2.dispatch.pullRequestWatchSync")( function* ( @@ -4244,6 +4532,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio watchStartedAt: entry.startedAt, headSha: entry.includesRemarks === true ? null : (entry.watch?.headSha ?? null), ...(entry.watch === null ? { watchEnded: true } : {}), + ...(entry.staleProgressAt === undefined ? {} : { staleProgressAt: entry.staleProgressAt }), ...(entries.length > 1 && sections?.[index] !== undefined ? { section: sections[index] } : {}), @@ -5350,6 +5639,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? undefined : (existing.watch ?? { startedAt, + staleness: { + staleTimeoutMs: command.staleTimeoutMs ?? PR_WATCH_STALE_MINUTES * 60_000, + lastProgressAt: startedAt, + }, headSha: null, failedChecks: [], passed: false, @@ -9836,6 +10129,40 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* Ref.update(effects, (existing) => [...existing, pendingEffect]); }); + const recordDelegateDeadline = Effect.fn("Orchestrator.recordDelegateDeadline")(function* ( + command: Extract< + OrchestrationV2ServerCommand, + { type: "delegated_task.request" | "delegated_task.remote.request" } + >, + events: Ref.Ref>, + parent: OrchestrationV2ThreadProjection["thread"], + taskId: NodeId, + now: DateTime.Utc, + ) { + if (command.staleTimeoutMs === undefined) return; + yield* emit( + events, + command, + )({ + type: "thread.metadata-updated", + threadId: parent.id, + providerInstanceId: parent.providerInstanceId, + occurredAt: now, + payload: { + ...parent, + stalenessWaits: [ + ...(parent.stalenessWaits ?? []), + { + kind: "delegate", + taskId, + staleTimeoutMs: command.staleTimeoutMs, + lastProgressAtMs: DateTime.toEpochMillis(now), + }, + ], + }, + }); + }); + const dispatchDelegatedTaskRequest = Effect.fn("orchestrationV2.dispatch.delegatedTaskRequest")( function* ( command: Extract, @@ -9994,6 +10321,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio result: null, }; const emitEvent = emit(events, command); + yield* recordDelegateDeadline(command, events, parentProjection.thread, taskNodeId, now); yield* emitEvent({ type: "thread.created", @@ -10366,6 +10694,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio occurredAt: now, }; const emitEvent = emit(events, command); + yield* recordDelegateDeadline(command, events, parentProjection.thread, taskNodeId, now); yield* emitEvent({ ...common, type: "node.updated", @@ -15575,6 +15904,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "thread.pull-request-watch.checks-reopen": yield* dispatchThreadMutation(command, events, effects); break; + case "thread.wait-staleness.update": + yield* updateWaitStaleness(command, events, effects); + break; case "thread.pull-request-watch.sync": yield* dispatchPullRequestWatchSync(command, events, effects); break; @@ -15999,6 +16331,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.type === "thread.visit" || // A read can answer a watch again before a push's reopen lands; nothing is left to clear. command.type === "thread.pull-request-watch.checks-reopen" || + command.type === "thread.wait-staleness.update" || command.type === "thread.interrupt.unresponsive" || command.type === "thread.stop" || command.type === "subagent.stop" || @@ -16069,6 +16402,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); + if ( + plan.events.length === 0 && + command.type === "thread.wait-staleness.update" && + command.operation.type === "sweep" + ) { + // The periodic sweep has no caller to replay a no-op receipt for. + const sequence = yield* eventSink + .latestSequence({ threadId: command.threadId }) + .pipe(mapDispatchError(command)); + return { sequence, storedEvents: [] }; + } + if (plan.events.length === 0 && plan.effects.length === 0 && cancelledTask === undefined) { // A settle that ended nothing still records its receipt: a replayed Stop // effect then finds it instead of settling work that appeared since. @@ -16972,6 +17317,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio Effect.map(Effect.mapError(shellProjectionError)), ); }), + getWaitActivityMs: Effect.fn("OrchestratorV2.getWaitActivityMs")(function (threadId, runId) { + return projectionStore + .getWaitActivityMs(threadId, runId) + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); + }), getThreadShell: Effect.fn("OrchestratorV2.getThreadShell")(function (threadId) { return projectionStore .getThreadShell(threadId) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index e314acb6488ab..ee117f548070e 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -615,6 +615,11 @@ export interface ProjectionStoreV2Shape { readonly countThreads: () => Effect.Effect; readonly countActiveRunThreads: () => Effect.Effect; /** Every active thread, in shell order. */ + readonly listStalenessWaitThreads: Effect.Effect, ProjectionStoreV2Error>; + readonly getWaitActivityMs: ( + threadId: ThreadId, + runId: RunId | null, + ) => Effect.Effect; readonly listActiveShellIndex: () => Effect.Effect< ReadonlyArray, ProjectionStoreV2Error @@ -9234,6 +9239,29 @@ export const layer: Layer.Layer = return rows[0]?.count ?? 0; }, Effect.mapError(shellSnapshotReadError)); + const listStalenessWaitThreads = sql<{ readonly thread_id: string }>` + SELECT thread_id FROM orchestration_v2_projection_threads + WHERE deleted_at IS NULL AND json_extract(payload_json, '$.archivedAt') IS NULL + AND json_array_length(payload_json, '$.stalenessWaits') > 0 + `.pipe( + Effect.map((rows) => rows.map(({ thread_id }) => ThreadId.make(thread_id))), + Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })), + ); + + const getWaitActivityMs = Effect.fn("ProjectionStore.getWaitActivityMs")( + function* (threadId: ThreadId, runId: RunId | null) { + if (runId === null) return 0; + const rows = yield* sql<{ readonly activity: string | null }>` + SELECT max(updated_at) AS activity FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId} AND run_id = ${runId} + AND type NOT IN ('user_message', 'link_request') + `; + const activity = rows[0]?.activity; + return activity == null ? 0 : Date.parse(activity); + }, + (effect, threadId) => effect.pipe(Effect.mapError(controlReadError(threadId))), + ); + const listActiveShellIndex = Effect.fn("ProjectionStore.listActiveShellIndex")(function* () { const rows = yield* sql<{ readonly thread_id: string; @@ -9618,6 +9646,8 @@ export const layer: Layer.Layer = countThreads: readOnReader(countThreads), countActiveRunThreads: readOnReader(countActiveRunThreads), listActiveShellIndex: readOnReader(listActiveShellIndex), + listStalenessWaitThreads: NodeSqliteClient.readOnly(listStalenessWaitThreads), + getWaitActivityMs: readOnReader(getWaitActivityMs), listActiveThreads: readOnReader(listActiveThreads), readShellSnapshot: readOnReader(readShellSnapshot), listOlderSettledThreads: readOnReader(listOlderSettledThreads), diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index 88b72fdc54269..f2eaa26136940 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -210,6 +210,8 @@ it.effect( ProjectionStore.ProjectionStoreV2, ProjectionStore.ProjectionStoreV2.of({ apply: () => Effect.void, + listStalenessWaitThreads: Effect.succeed([]), + getWaitActivityMs: () => Effect.succeed(0), getLimitRecoveryCandidates: () => Effect.die("unused getLimitRecoveryCandidates"), getLimitRecoveryWakeAt: () => Effect.die("unused getLimitRecoveryWakeAt"), getOpenRemoteDelegatedTasks: Effect.die("unused getOpenRemoteDelegatedTasks"), diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index 3485765a0ed93..ef35265bcd5f1 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -42,6 +42,7 @@ import { evaluatePullRequestWatch, PULL_REQUEST_WATCH_NO_CHECKS_MS, pullRequestWatchMessage, + stalePullRequestWatch, } from "./pullRequestWatch.ts"; /** Checks take minutes; faster sweeps waste the account's shared host quota. */ @@ -103,6 +104,7 @@ interface Wake { readonly text: string; readonly notification: OrchestrationV2Notification; readonly includesRemarks?: boolean; + readonly staleProgressAt?: string; } /** A wake a pass holds back so each thread gets one for everything the pass found. */ @@ -204,6 +206,7 @@ const checksPendingBeforeOf = ({ watch }: WatchTarget) => function watchesEqual(left: ThreadPullRequestWatch, right: ThreadPullRequestWatch): boolean { return ( left.startedAt === right.startedAt && + JSON.stringify(left.staleness) === JSON.stringify(right.staleness) && left.headSha === right.headSha && left.failedChecks.join("\n") === right.failedChecks.join("\n") && left.passed === right.passed && @@ -332,7 +335,19 @@ export const make = Effect.gen(function* () { ...(endedWatch === undefined ? {} : { endedWatch }), ...(wake === undefined ? {} - : { wake: { ...wake, messageId: MessageId.make(`message:pr-watch:${uuid}`) } }), + : { + ...(wake.staleProgressAt === undefined + ? {} + : { staleProgressAt: wake.staleProgressAt }), + wake: { + text: wake.text, + notification: wake.notification, + ...(wake.includesRemarks === undefined + ? {} + : { includesRemarks: wake.includesRemarks }), + messageId: MessageId.make(`message:pr-watch:${uuid}`), + }, + }), }); }); @@ -470,12 +485,18 @@ export const make = Effect.gen(function* () { ...identityOf(first.target.link), startedAt: first.target.watch.startedAt, watch: first.next, + ...(first.wake.staleProgressAt === undefined + ? {} + : { staleProgressAt: first.wake.staleProgressAt }), ...checksPendingBeforeOf(first.target), ...(first.endedWatch === undefined ? {} : { endedWatch: first.endedWatch }), others: rest.map((item) => ({ ...identityOf(item.target.link), startedAt: item.target.watch.startedAt, watch: item.next, + ...(item.wake.staleProgressAt === undefined + ? {} + : { staleProgressAt: item.wake.staleProgressAt }), ...checksPendingBeforeOf(item.target), ...(item.endedWatch === undefined ? {} : { endedWatch: item.endedWatch }), ...(item.wake.includesRemarks === true ? { includesRemarks: true } : {}), @@ -586,6 +607,41 @@ export const make = Effect.gen(function* () { ), ); + const holdStale = ( + group: WatchGroup, + target: WatchTarget, + watch: ThreadPullRequestWatch, + now: number, + hostObservation: "current" | "unavailable", + ) => { + if (target.link.snapshot?.state === "closed") return Effect.succeed(false); + const stale = stalePullRequestWatch( + watch, + target.link.url, + target.link.number, + now, + hostObservation, + ); + return stale === undefined + ? Effect.succeed(false) + : hold({ + groupKey: group.key, + target, + ...stale, + wake: { + ...stale.wake, + ...(stale.next.staleness === undefined + ? {} + : { staleProgressAt: stale.next.staleness.lastProgressAt }), + }, + }).pipe(Effect.as(true)); + }; + + const checkStaleness = (group: WatchGroup, now: number, observation: "current" | "unavailable") => + eachTarget(group, (target) => + holdStale(group, target, target.watch, now, observation).pipe(Effect.asVoid), + ); + const readGroup = Effect.fn("PullRequestWatchReactor.readGroup")(function* ( group: WatchGroup, fingerprint: ProviderChangeRequestWatchFingerprint | null, @@ -593,7 +649,7 @@ export const make = Effect.gen(function* () { const now = yield* Clock.currentTimeMillis; const last = lastReads.get(group.key); const plan = planRead(group, last, fingerprint, now); - if (!plan.detail) return; + if (!plan.detail) return yield* checkStaleness(group, now, "current"); if ( last === undefined || group.targets.some((target) => !last.watches.has(watchKey(target))) || @@ -621,7 +677,7 @@ export const make = Effect.gen(function* () { return yield* Effect.failCause(detailRead.cause); lastReads.delete(group.key); const reason = providerFailureReason(detailRead.cause); - if (reason === "rate-limited") return; + if (reason === "rate-limited") return yield* checkStaleness(group, now, "unavailable"); // Transport and host failures can outlast the failure limit; keep the watch for recovery. if (reason === "failed") { readFailures.delete(group.key); @@ -697,7 +753,15 @@ export const make = Effect.gen(function* () { remarks: fingerprint?.remarks ?? null, }); yield* eachTarget(group, (target) => { - const report = evaluatePullRequestWatch(target.watch, detail, remarks, now); + const report = evaluatePullRequestWatch( + target.watch, + detail, + remarks, + now, + detail.reviewDecision === undefined + ? target.link.snapshot?.reviewDecision + : detail.reviewDecision, + ); if (report.changes.length > 0) { const wake = { ...pullRequestWatchMessage({ @@ -723,7 +787,13 @@ export const make = Effect.gen(function* () { : { groupKey: group.key, target, next: report.next, wake }, ); } - return watchesEqual(report.next, target.watch) ? Effect.void : record(target, report.next); + return holdStale(group, target, report.next, now, "current").pipe( + Effect.flatMap((held) => + held || watchesEqual(report.next, target.watch) + ? Effect.void + : record(target, report.next), + ), + ); }); }); @@ -797,7 +867,12 @@ export const make = Effect.gen(function* () { ? Effect.void : pullRequests.invalidate({ reference: referenceOf(group) }) ).pipe( - Effect.andThen(fingerprintOf(group)), + Effect.andThen( + fingerprintOf(group).pipe( + Effect.timeoutOption("30 seconds"), + Effect.map(Option.getOrElse(() => "paused" as const)), + ), + ), Effect.tap((fingerprint) => { const last = lastReads.get(group.key); // Open pull request views refresh only when the host state moved. @@ -812,11 +887,19 @@ export const make = Effect.gen(function* () { }), Effect.flatMap((fingerprint) => fingerprint === "paused" - ? Effect.void + ? Clock.currentTimeMillis.pipe( + Effect.flatMap((now) => checkStaleness(group, now, "unavailable")), + ) : reads.withPermit( readGroup(group, fingerprint).pipe( - Effect.catchCause( - logFailure("pull request watch check failed", { pullRequest: group.key }), + Effect.timeout("60 seconds"), + Effect.catchCause((cause) => + logFailure("pull request watch check failed", { pullRequest: group.key })( + cause, + ).pipe( + Effect.andThen(Clock.currentTimeMillis), + Effect.flatMap((now) => checkStaleness(group, now, "unavailable")), + ), ), ), ), diff --git a/apps/server/src/orchestration-v2/ThreadEventAlerts.ts b/apps/server/src/orchestration-v2/ThreadEventAlerts.ts index 34f0bf2dee6bf..a8c71720980bd 100644 --- a/apps/server/src/orchestration-v2/ThreadEventAlerts.ts +++ b/apps/server/src/orchestration-v2/ThreadEventAlerts.ts @@ -176,6 +176,7 @@ export function judgeThread(input: { readonly remoteTaskCount?: number; /** The latest activity among the children this thread waits on. */ readonly childActivityMs?: number | null; + readonly hasStalenessWait?: boolean; /** A model alert for the run already reported a usage limit, so a failure adds nothing. */ readonly usageLimitReported?: boolean; }): { readonly evaluated: ReadonlyArray; readonly findings: ThreadFinding[] } { @@ -295,6 +296,7 @@ export function judgeThread(input: { quiet && shell.activeRunId !== null && shell.blockedOnThreadWait !== true && + input.hasStalenessWait !== true && shell.pendingRuntimeRequest === null ) { findings.push({ @@ -406,6 +408,7 @@ export function threadEventStillHolds(input: { readonly strandedQueue?: StrandedQueue | null; readonly remoteTaskCount?: number; readonly childActivityMs?: number | null; + readonly hasStalenessWait?: boolean; }): boolean { const { alert } = input; const firedMs = Date.parse(alert.occurredAt); @@ -416,6 +419,7 @@ export function threadEventStillHolds(input: { nowMs: firedMs, stuckMinutes: input.stuckMinutes, ...(input.strandedQueue === undefined ? {} : { strandedQueue: input.strandedQueue }), + ...(input.hasStalenessWait === undefined ? {} : { hasStalenessWait: input.hasStalenessWait }), ...(input.remoteTaskCount === undefined ? {} : { remoteTaskCount: input.remoteTaskCount }), ...(input.childActivityMs === undefined ? {} : { childActivityMs: input.childActivityMs }), }); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index 4dba426ab9975..8dbbadba2dffb 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -701,6 +701,7 @@ it.effect.each([ Layer.provide( Layer.mergeAll( Layer.mock(Orchestrator.OrchestratorV2)({ + dispatch: () => Effect.succeed({ sequence: 0, storedEvents: [] }), getThreadRecords: () => Effect.succeed({ thread: { diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 53e69c1c29e0f..c7760456a60b4 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1,3 +1,6 @@ +import * as SecureRandom from "effect/crypto/SecureRandom"; +import { BACKGROUND_WAIT_STALE_MINUTES } from "@t3tools/contracts"; +import { staleTimeoutMs } from "./waitStaleness.ts"; import type { OrchestrationV2SearchThreadInput, OrchestrationV2SearchThreadResult, @@ -491,6 +494,7 @@ export interface ThreadManagementServiceShape { Effect.Effect, Orchestrator.OrchestratorV2Error >; + readonly getWaitActivityMs: Orchestrator.OrchestratorV2["Service"]["getWaitActivityMs"]; readonly getThreadShell: Orchestrator.OrchestratorV2["Service"]["getThreadShell"]; readonly listAppOwnedChildThreadIds: Orchestrator.OrchestratorV2["Service"]["listAppOwnedChildThreadIds"]; readonly getThreadLinkMetadata: Orchestrator.OrchestratorV2["Service"]["getThreadLinkMetadata"]; @@ -568,6 +572,7 @@ export interface ThreadManagementServiceShape { readonly threadId: ThreadId; readonly taskIds: ReadonlyArray; readonly awaited: boolean; + readonly staleTimeoutMinutes?: number | undefined; }) => Effect.Effect< { readonly matched: ReadonlyArray; readonly unmatched: ReadonlyArray }, ThreadManagementBackgroundWaitError @@ -1761,6 +1766,26 @@ const make = Effect.gen(function* () { reason: "unmatched", }); } + const taskIds = input.awaited ? matched : input.taskIds; + const uuid = SecureRandom.uuidV4Unsafe(); + yield* orchestrator + .dispatch({ + type: "thread.wait-staleness.update", + commandId: CommandId.make(`server:background-wait:${uuid}`), + threadId: input.threadId, + operation: input.awaited + ? { + type: "register", + kind: "background", + taskIds, + staleTimeoutMs: staleTimeoutMs( + input.staleTimeoutMinutes, + BACKGROUND_WAIT_STALE_MINUTES, + ), + } + : { type: "clear", kind: "background", taskIds }, + }) + .pipe(Effect.mapError(unavailable)); const matchedIds = new Set(matched); return { matched, unmatched: input.taskIds.filter((taskId) => !matchedIds.has(taskId)) }; }); @@ -1910,6 +1935,7 @@ const make = Effect.gen(function* () { listActiveShellIndex: orchestrator.listActiveShellIndex, listOlderSettledThreads: orchestrator.listOlderSettledThreads, readShellSnapshot: orchestrator.readShellSnapshot, + getWaitActivityMs: orchestrator.getWaitActivityMs, getThreadShell: orchestrator.getThreadShell, listAppOwnedChildThreadIds: Effect.fn("ThreadManagementService.listAppOwnedChildThreadIds")( function (threadId) { diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts index 7275fd845b373..adff61b3e05fb 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts @@ -13,8 +13,10 @@ import { // These cases read the head once or at one moment, so the no-checks notice never comes due. const evaluatePullRequestWatch = ( - ...args: Parameters extends [...infer Head, number] ? Head : never -) => evaluate(...args, 0); + watch: Parameters[0], + detail: Parameters[1], + remarks: Parameters[2], +) => evaluate(watch, detail, remarks, 0); const STARTED = "2026-10-02T12:00:00.000Z"; @@ -81,6 +83,26 @@ const remark = ( const noRemarks: ReadonlyArray = []; describe("evaluatePullRequestWatch", () => { + it("resets staleness only on observed progress, then rearms after a check transition", () => { + const start = Date.parse(STARTED); + const initial = evaluate(watch(), detail(), [], start + 60_000).next; + assert.equal(initial.staleness?.lastProgressAt, STARTED); + const unchanged = evaluate( + initial, + detail({ checks: [...detail().checks].reverse() }), + [], + start + 120_000, + ).next; + assert.deepEqual(unchanged.staleness, initial.staleness); + const progressed = evaluate( + unchanged, + detail({ checks: [check("lint", "success"), check("test", "success")] }), + [], + start + 180_000, + ).next; + assert.equal(progressed.staleness?.lastProgressAt, "2026-10-02T12:03:00.000Z"); + }); + it.each(["pending", "success"] as const)( "reports a required rebase once with %s CI", (status) => { diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.ts b/apps/server/src/orchestration-v2/pullRequestWatch.ts index e4a00f0624244..f8ecddd114c74 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.ts @@ -1,9 +1,10 @@ -import type { - OrchestrationV2Notification, - PullRequestCheck, - PullRequestComment, - PullRequestDetail, - ThreadPullRequestWatch, +import { + PR_WATCH_STALE_MINUTES, + type OrchestrationV2Notification, + type PullRequestCheck, + type PullRequestComment, + type PullRequestDetail, + type ThreadPullRequestWatch, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -37,6 +38,41 @@ const isFailedCheck = (check: PullRequestCheck) => const workflowRunOf = (url: string | null) => url?.match(/^.*\/actions\/runs\/\d+/)?.[0] ?? null; const approvalKey = (check: PullRequestCheck) => workflowRunOf(check.url) ?? check.name; +const stalenessOf = (watch: ThreadPullRequestWatch) => + watch.staleness ?? { + staleTimeoutMs: PR_WATCH_STALE_MINUTES * 60_000, + lastProgressAt: watch.startedAt, + }; + +export function stalePullRequestWatch( + watch: ThreadPullRequestWatch, + url: string, + number: number, + now: number, + hostObservation: "current" | "unavailable", +): { readonly next: ThreadPullRequestWatch; readonly wake: PullRequestWatchWake } | undefined { + const staleness = stalenessOf(watch); + const idleMs = now - Date.parse(staleness.lastProgressAt); + if (staleness.alerted || idleMs < staleness.staleTimeoutMs) return; + const idleMinutes = Math.floor(idleMs / 60_000); + const counts: Record = {}; + for (const entry of staleness.checks ?? []) { + const status = entry.slice(entry.lastIndexOf("\t") + 1); + counts[status] = (counts[status] ?? 0) + 1; + } + return { + next: { ...watch, staleness: { ...staleness, alerted: true } }, + wake: { + text: `${JSON.stringify({ type: "pull_request_watch_stale_timeout", url, idleMinutes, headSha: watch.headSha, checks: staleness.checks === undefined ? null : counts, reviewDecision: staleness.reviewDecision ?? null, hostObservation })}\n\nT3 Code still watches this PR. Check why progress stopped (for example, queued checks or a review hold). A new progress event re-arms the timeout.`, + notification: { + source: { kind: "monitor" }, + outcome: "updated", + summary: `#${number}: no observed progress for ${idleMinutes} minutes`, + }, + }, + }; +} + export function evaluatePullRequestWatch( watch: ThreadPullRequestWatch, detail: Pick< @@ -52,6 +88,7 @@ export function evaluatePullRequestWatch( >, remarks: ReadonlyArray | null, now: number, + reviewDecision?: NonNullable["reviewDecision"], ): PullRequestWatchReport { const changes: Array = []; // A read without a head says nothing about pushes, so it keeps the last known one. @@ -232,10 +269,38 @@ export function evaluatePullRequestWatch( const commentsOnly = changes.length > 0 && changes.every((change) => change.kind === "remarks"); const progress = headMoved || (changes.length > 0 && !commentsOnly); const wakes = (progress ? 0 : watch.wakes) + (commentsOnly ? 1 : 0); + const previous = stalenessOf(watch); + const checkState = + unread || (checks.length === 0 && !headMoved && previous.checks?.length) + ? previous.checks + : checks + .map(({ name, status, pendingPhase }) => `${name}\t${pendingPhase ?? status}`) + .toSorted(); + const progressed = + headMoved || + (previous.checks !== undefined && + checkState !== undefined && + previous.checks.join("\n") !== checkState.join("\n")) || + (reviewDecision !== undefined && + previous.reviewDecision !== undefined && + reviewDecision !== previous.reviewDecision) || + changes.some((change) => change.kind !== "no-checks"); + const staleness = { + ...(progressed + ? { + staleTimeoutMs: previous.staleTimeoutMs, + lastProgressAt: DateTime.formatIso(DateTime.makeUnsafe(now)), + } + : previous), + ...(checkState === undefined ? {} : { checks: checkState }), + ...(reviewDecision === undefined ? {} : { reviewDecision }), + }; + return { changes, next: { startedAt: watch.startedAt, + staleness, headSha, failedChecks, passed, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 94a2bf650fb23..6c8c271f75a50 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -4739,6 +4739,298 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect("uses native task progress and clears the deadline when background work ends", () => + Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const { threadId } = yield* createWatchedThread("background-stale"); + yield* engine.dispatch({ + type: "message.dispatch", + createdBy: "agent", + creationSource: "mcp", + commandId: CommandId.make(`${threadId}:start`), + threadId, + messageId: MessageId.make(`${threadId}:start`), + text: "Run background checks.", + attachments: [], + dispatchMode: { type: "start_immediately" }, + }); + const provider = (yield* engine.getThreadRecords(threadId, ["providerThreads"])) + .providerThreads[0]!; + const roster = Effect.fnUntraced(function* (suffix: string, active: boolean) { + const now = yield* DateTime.now; + yield* sink.write({ + events: [ + { + id: EventId.make(`${threadId}:${suffix}`), + type: "provider-thread.updated", + threadId, + driver: provider.driver, + providerInstanceId: provider.providerInstanceId, + occurredAt: now, + payload: { + ...provider, + updatedAt: now, + pendingBackgroundTasks: active + ? [ + { + taskId: "tests", + kind: "monitor", + awaited: true, + progressAtMs: DateTime.toEpochMillis(now), + }, + ] + : [], + }, + }, + ], + effects: [], + }); + }); + yield* roster("pending", true); + yield* engine.dispatch({ + type: "thread.wait-staleness.update", + threadId, + commandId: CommandId.make(`${threadId}:register`), + operation: { + type: "register", + kind: "background", + taskIds: ["tests"], + staleTimeoutMs: 5 * 60_000, + }, + }); + const sweep = (suffix: string) => + engine.dispatch({ + type: "thread.wait-staleness.update", + threadId, + commandId: CommandId.make(`${threadId}:${suffix}`), + operation: { type: "sweep" }, + }); + const notices = engine + .getThreadRecords(threadId, ["messages"]) + .pipe( + Effect.map(({ messages }) => + messages.filter((message) => message.text.includes('"type":"wait_stale_timeout"')), + ), + ); + yield* TestClock.adjust("4 minutes"); + yield* roster("progress", true); + yield* TestClock.adjust("1 minute"); + yield* sweep("early"); + assert.lengthOf(yield* notices, 0); + yield* TestClock.adjust("4 minutes"); + yield* sweep("due"); + assert.include((yield* notices)[0]?.text, '"taskId":"tests","kind":"background"'); + assert.include((yield* notices)[0]?.text, '"idleMinutes":5'); + yield* roster("completed", false); + yield* TestClock.adjust("1 hour"); + yield* sweep("ended"); + assert.lengthOf(yield* notices, 1); + assert.deepEqual((yield* engine.getThreadRecords(threadId, [])).thread.stalenessWaits, []); + }), + ); + + it.effect( + "retains an awaited child deadline across replay and alerts once per quiet period", + () => + Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const projection = yield* ProjectionStore.ProjectionStoreV2; + const maintenance = yield* ProjectionReplay.ProjectionReplay; + const { threadId } = yield* createWatchedThread("delegate-stale"); + yield* engine.dispatch({ + type: "message.dispatch", + createdBy: "agent", + creationSource: "mcp", + commandId: CommandId.make(`${threadId}:start`), + threadId, + messageId: MessageId.make(`${threadId}:start`), + text: "Delegate the work.", + attachments: [], + dispatchMode: { type: "start_immediately" }, + }); + const parentRun = (yield* engine.getThreadRecords(threadId, ["runs"])).runs[0]!; + yield* engine.dispatch({ + type: "delegated_task.remote.request", + commandId: CommandId.make(`${threadId}:delegate`), + parentThreadId: threadId, + parentRunId: parentRun.id, + parentNodeId: parentRun.rootNodeId!, + task: "Work in the linked environment.", + driver: ProviderDriverKind.make("remote"), + modelSelection, + completionWake: "settled_only", + staleTimeoutMs: 45 * 60_000, + remoteChild: { + environmentId: EnvironmentId.make("remote-env"), + threadId: ThreadId.make("remote-thread"), + title: "Child", + label: "Test peer", + }, + }); + const task = (yield* engine.getThreadRecords(threadId, ["subagents"])).subagents[0]!; + const sweep = (suffix: string) => + engine.dispatch({ + type: "thread.wait-staleness.update", + commandId: CommandId.make(`${threadId}:${suffix}`), + threadId, + operation: { type: "sweep" }, + }); + const notices = engine + .getThreadRecords(threadId, ["messages"]) + .pipe( + Effect.map(({ messages }) => + messages.filter((message) => message.text.includes('"type":"wait_stale_timeout"')), + ), + ); + yield* TestClock.adjust("44 minutes"); + yield* sweep("early"); + assert.lengthOf(yield* notices, 0); + assert.include(yield* projection.listStalenessWaitThreads, threadId); + assert.isTrue((yield* maintenance.rebuild).valid); + yield* TestClock.adjust("1 minute"); + yield* sweep("due"); + const [notice] = yield* notices; + assert.include(notice?.text, task.id); + assert.include( + notice?.text, + '"childLink":"[Child](t3-thread://v2/remote-env/remote-thread)"', + ); + assert.include(notice?.text, '"idleMinutes":45'); + yield* TestClock.adjust("1 hour"); + yield* sweep("quiet"); + assert.lengthOf(yield* notices, 1); + const progressAtMs = DateTime.toEpochMillis(yield* DateTime.now); + yield* engine.dispatch({ + type: "thread.wait-staleness.update", + commandId: CommandId.make(`${threadId}:progress`), + threadId, + operation: { type: "remote-progress", taskId: task.id, progressAtMs, held: true }, + }); + yield* TestClock.adjust("45 minutes"); + yield* sweep("deliberate-hold"); + assert.lengthOf(yield* notices, 1); + yield* engine.dispatch({ + type: "delegated_task.remote.complete", + commandId: CommandId.make(`${threadId}:done`), + parentThreadId: threadId, + taskId: task.id, + status: "completed", + result: "Done.", + }); + yield* sweep("completed"); + assert.notInclude(yield* projection.listStalenessWaitThreads, threadId); + assert.lengthOf(yield* notices, 1); + }), + ); + + it.effect.each([undefined, 5] as const)( + "wakes a quiet PR watch after its persisted deadline (%s minutes)", + (customMinutes) => + Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const maintenance = yield* ProjectionReplay.ProjectionReplay; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = ThreadId.make(`pr-stale-${customMinutes}`); + const projectId = ProjectId.make(`pr-stale-project-${customMinutes}`); + const url = "https://github.com/pingdotgg/t3code/pull/12"; + const key = { host: "github.com", repository: "pingdotgg/t3code", number: 12 }; + yield* engine.dispatch({ + type: "thread.create", + createdBy: "agent", + creationSource: "mcp", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId, + title: "Stale watch", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + yield* engine.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make(`${threadId}:watch`), + threadId, + ...key, + watching: true, + link: { url, source: "agent" }, + ...(customMinutes === undefined ? {} : { staleTimeoutMs: customMinutes * 60_000 }), + }); + let status: PullRequestCheck["status"] = "pending"; + const provider = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(PullRequestService.PullRequestService)({ + detail: () => + Effect.sync(() => ({ + ...watchedPullRequestDetail({ + projectId, + number: 12, + at: "2026-10-02T12:00:00.000Z", + }), + reviewDecision: "review-required" as const, + checks: [{ name: "CI", status, description: null, url: null, required: false }], + })), + activity: () => + Effect.succeed({ + comments: [], + commentCount: 0, + commentsTruncated: false, + reviewThreads: [], + commits: [], + }), + watchFingerprint: () => Effect.succeed(null), + }), + ); + const makeReactor = PullRequestWatchReactor.make.pipe(Effect.provide(provider)); + const readTimeouts = engine + .getThreadRecords(threadId, ["messages"]) + .pipe( + Effect.map(({ messages }) => + messages.filter((message) => + message.text.includes('"type":"pull_request_watch_stale_timeout"'), + ), + ), + ); + const first = yield* makeReactor; + yield* first.sweep; + const timeout = customMinutes ?? 30; + yield* TestClock.adjust(`${timeout - 1} minutes`); + yield* first.sweep; + assert.lengthOf(yield* readTimeouts, 0); + assert.isTrue((yield* maintenance.rebuild).valid); + const restarted = yield* makeReactor; + yield* TestClock.adjust("1 minute"); + yield* restarted.sweep; + yield* worker.drain(); + const [notice] = yield* readTimeouts; + assert.include(notice?.text, `"url":"${url}"`); + assert.include(notice?.text, `"idleMinutes":${timeout}`); + assert.include(notice?.text, '"checks":{"pending":1}'); + assert.include(notice?.text, '"reviewDecision":"review-required"'); + const restartedAgain = yield* makeReactor; + yield* TestClock.adjust("1 hour"); + yield* restartedAgain.sweep; + assert.lengthOf(yield* readTimeouts, 1); + status = "neutral"; + yield* TestClock.adjust("10 minutes"); + yield* restartedAgain.sweep; + assert.lengthOf(yield* readTimeouts, 1); + yield* engine.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make(`${threadId}:unwatch`), + threadId, + ...key, + watching: false, + }); + yield* TestClock.adjust("1 hour"); + yield* restartedAgain.sweep; + assert.lengthOf(yield* readTimeouts, 1); + }), + ); + it.effect.each([ ["an idle", false], ["a busy", true], diff --git a/apps/server/src/orchestration-v2/waitStaleness.ts b/apps/server/src/orchestration-v2/waitStaleness.ts new file mode 100644 index 0000000000000..5b2c2bb8c19f8 --- /dev/null +++ b/apps/server/src/orchestration-v2/waitStaleness.ts @@ -0,0 +1,29 @@ +import type { OrchestrationV2ThreadShell } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; + +export function staleTimeoutMs(minutes: number | undefined, defaultMinutes: number): number { + return Math.round(Math.max(5, Math.min(1440, minutes ?? defaultMinutes)) * 60_000); +} + +export function waitActivityMs(shell: OrchestrationV2ThreadShell): number { + const timestamp = (value: DateTime.Utc | null | undefined) => + value == null ? 0 : DateTime.toEpochMillis(value); + return Math.max( + timestamp(shell.latestRunRequestedAt), + timestamp(shell.latestRunStartedAt), + timestamp(shell.latestRunCompletedAt), + shell.latestVisibleMessage?.role === "assistant" + ? timestamp(shell.latestVisibleMessage.updatedAt) + : 0, + ); +} + +export function waitIntentionallyHeld(shell: OrchestrationV2ThreadShell, now: number): boolean { + return ( + shell.pendingRuntimeRequest !== null || + shell.inbox?.decisionRequest !== undefined || + shell.latestRunStopRequested === true || + (shell.snoozedUntil != null && DateTime.toEpochMillis(shell.snoozedUntil) > now) || + (shell.limitRecovery != null && Date.parse(shell.limitRecovery.resetAt) > now) + ); +} diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index 4104e659cc5ce..e657e59ab4450 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -1,3 +1,5 @@ +import { BACKGROUND_WAIT_STALE_MINUTES } from "@t3tools/contracts"; +import { staleTimeoutMs } from "../orchestration-v2/waitStaleness.ts"; import { CommandId, DEFAULT_AUTOMATIC_PLACEMENT_HOSTS, @@ -1031,6 +1033,14 @@ const make = Effect.gen(function* () { modelSelection: launched.modelSelection, remoteChild, completionWake: input.mode === "wait" ? "settled_only" : "always", + ...(input.mode === "wait" + ? { + staleTimeoutMs: staleTimeoutMs( + input.staleTimeoutMinutes, + BACKGROUND_WAIT_STALE_MINUTES, + ), + } + : {}), }) .pipe( // The cause goes to the log; the caller learns only that recording failed. @@ -1471,7 +1481,26 @@ const make = Effect.gen(function* () { .pipe(Effect.raceFirst(endedHere)); // The next look reads the result and stops it there. if ("endedHere" in waited) return false; - if (waited.timedOut) return false; + if (waited.timedOut) { + if (waited.progressAtMs !== undefined) { + yield* threads + .dispatch({ + type: "thread.wait-staleness.update", + commandId: CommandId.make( + `server:remote-wait-progress:${taskId}:${waited.progressAtMs}:${waited.intentionallyHeld}:${sequence}`, + ), + threadId: parentThreadId, + operation: { + type: "remote-progress", + taskId, + progressAtMs: waited.progressAtMs, + ...(waited.intentionallyHeld === undefined ? {} : { held: waited.intentionallyHeld }), + }, + }) + .pipe(Effect.ignoreCause({ log: true })); + } + return false; + } // A task recorded without its run waits on the thread's latest; a // thread there with none has nothing left to wait for. if (waited.runId === null) { diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 592bfb92ce7cd..5f5ce37c93f59 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -1929,6 +1929,9 @@ export const make = Effect.gen(function* () { observedAt, mergedAt: changeRequest.mergedAt, closedAt: changeRequest.closedAt, + ...(changeRequest.reviewDecision === undefined + ? {} + : { reviewDecision: changeRequest.reviewDecision }), reviewers: changeRequest.reviewers, labels: changeRequest.labels, checks: changeRequest.checks, diff --git a/apps/server/src/pullRequest/PullRequestWatchService.ts b/apps/server/src/pullRequest/PullRequestWatchService.ts index 6ed736075c018..23e808c58f555 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.ts @@ -1,5 +1,6 @@ import { CommandId, + PR_WATCH_STALE_MINUTES, ThreadId, type OrchestrationV2ThreadShell, type PullRequestUnavailableError, @@ -12,6 +13,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; +import { staleTimeoutMs } from "../orchestration-v2/waitStaleness.ts"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as PullRequestService from "./PullRequestService.ts"; @@ -69,6 +71,7 @@ export class PullRequestWatchService extends Context.Service< readonly threadId: ThreadId; readonly target: PullRequestTarget; readonly watching: boolean; + readonly staleTimeoutMinutes?: number | undefined; }) => Effect.Effect< ResolvedTarget & { readonly watching: boolean; readonly wasWatching: boolean }, | PullRequestWatchFailedError @@ -104,6 +107,7 @@ const make = Effect.gen(function* () { readonly threadId: ThreadId; readonly target: PullRequestTarget; readonly watching: boolean; + readonly staleTimeoutMinutes?: number | undefined; }) { const { watching } = input; const thread = yield* requireThread(input.threadId); @@ -157,7 +161,12 @@ const make = Effect.gen(function* () { repository: target.repository, number: target.number, watching, - ...(watching ? { link: { url: target.url, source: "agent" as const } } : {}), + ...(watching + ? { + link: { url: target.url, source: "agent" as const }, + staleTimeoutMs: staleTimeoutMs(input.staleTimeoutMinutes, PR_WATCH_STALE_MINUTES), + } + : {}), }) .pipe( Effect.catchCause((cause) => diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts index b46c0dde4e86d..d0dfff1fd9768 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.test.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts @@ -208,6 +208,7 @@ const makeTestRelay = Effect.fnUntraced(function* ( const shellReads: ThreadId[] = []; const catchUp = { activitySnapshotReads: 0 }; const threads = ThreadManagementService.ThreadManagementService.of({ + getWaitActivityMs: () => Effect.succeed(0), getThreadShell: unused, getShellSnapshot: unused, getAgentAwarenessSnapshot: (threadId) => diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 4a7fe499f9b0b..5f2800e5cb26e 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -47,6 +47,7 @@ export * from "./peerLink.ts"; export * from "./linkedSidebar.ts"; export * from "./threadMetadataMcp.ts"; export * from "./threadPullRequest.ts"; +export * from "./waitStaleness.ts"; export * from "./threadSearch.ts"; export * from "./threadTags.ts"; export * from "./threadStanding.ts"; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 13659ac2700fb..6c968b99ee630 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1,3 +1,4 @@ +import { ThreadStalenessWait } from "./waitStaleness.ts"; import { OrchestrationMessageContext } from "./composerContext.ts"; import { withRecordIdTable } from "./orchestrationV2IdTable.ts"; import * as DateTime from "effect/DateTime"; @@ -521,6 +522,7 @@ export const OrchestrationV2AppThread = Schema.Struct({ worktreePath: Schema.NullOr(TrimmedNonEmptyString), linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)), pullRequests: Schema.optional(Schema.Array(ThreadPullRequestLink)), + stalenessWaits: Schema.optional(Schema.Array(ThreadStalenessWait)), branchPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)), activeProviderThreadId: Schema.NullOr(ProviderThreadId), historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin), @@ -1226,6 +1228,7 @@ const PendingBackgroundTaskFields = { itemId: Schema.optional(TurnItemId), sourceThreadId: Schema.optional(ThreadId), taskId: TrimmedNonEmptyString, + progressAtMs: Schema.optional(Schema.Finite), description: Schema.optional(TrimmedNonEmptyString), /** The subagent task that started this work and waits on it. */ parentTaskId: Schema.optional(TrimmedNonEmptyString), @@ -1503,6 +1506,7 @@ const MonitorPullRequestStamp = Schema.Struct({ /** Null when the wake is not about one head, so a newer push does not outdate it. */ headSha: Schema.NullOr(TrimmedNonEmptyString), watchEnded: Schema.optional(Schema.Boolean), + staleProgressAt: Schema.optional(IsoDateTime), /** Set on a wake covering several pull requests. */ section: Schema.optional(PullRequestWakeSection), }); @@ -1539,6 +1543,15 @@ export const OrchestrationV2NotificationSource = kindUnionWithFallback( Schema.Struct({ kind: Schema.Literal("monitor"), pullRequest: Schema.optional(MonitorPullRequestStamp), + staleWaits: Schema.optional( + Schema.Array( + Schema.Struct({ + kind: ThreadStalenessWait.fields.kind, + taskId: ThreadStalenessWait.fields.taskId, + lastProgressAtMs: ThreadStalenessWait.fields.lastProgressAtMs, + }), + ), + ), /** The other pull requests one wake covers; outdated ones leave it before it starts. */ otherPullRequests: Schema.optional(Schema.Array(MonitorPullRequestStamp)), }), @@ -3572,6 +3585,7 @@ export const OrchestrationV2Command = Schema.Union([ threadId: ThreadId, ...ThreadPullRequestKey.fields, watching: Schema.Boolean, + staleTimeoutMs: Schema.optional(PositiveInt), link: Schema.optional( Schema.Struct({ url: TrimmedNonEmptyString, @@ -3831,6 +3845,7 @@ export const OrchestrationV2Command = Schema.Union([ runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, workspaceStrategy: Schema.optional(OrchestrationV2ThreadLaunchWorkspaceStrategy), + staleTimeoutMs: Schema.optional(PositiveInt), // Defaults to settled_only; fire-and-forget wakes require always. completionWake: Schema.optional(Schema.Literals(["always", "settled_only"])), createdAt: Schema.optional(Schema.DateTimeUtc), @@ -3876,6 +3891,31 @@ export type OrchestrationV2Command = typeof OrchestrationV2Command.Type; // Excluded from dispatchCommand so only the server can send these. const OrchestrationV2InternalCommand = Schema.Union([ + Schema.Struct({ + type: Schema.Literal("thread.wait-staleness.update"), + commandId: CommandId, + threadId: ThreadId, + operation: Schema.Union([ + Schema.Struct({ + type: Schema.Literal("register"), + kind: ThreadStalenessWait.fields.kind, + taskIds: Schema.Array(Schema.String), + staleTimeoutMs: PositiveInt, + }), + Schema.Struct({ + type: Schema.Literal("clear"), + kind: ThreadStalenessWait.fields.kind, + taskIds: Schema.Array(Schema.String), + }), + Schema.Struct({ + type: Schema.Literal("remote-progress"), + taskId: NodeId, + progressAtMs: Schema.Finite, + held: Schema.optional(Schema.Boolean), + }), + Schema.Struct({ type: Schema.Literal("sweep") }), + ]), + }), // Guest share commands the server issues after checking T3 Connect and the guest token. Schema.Struct({ type: Schema.Literal("thread.guest-share.open"), @@ -3929,6 +3969,7 @@ const OrchestrationV2InternalCommand = Schema.Union([ * makes the read's answer describe the old head, so the cleared answer stays. */ checksPendingBefore: Schema.optional(Schema.Boolean), + staleProgressAt: Schema.optional(IsoDateTime), /** With `watch: null`, the state the ended watch keeps instead of its last saved one. */ endedWatch: Schema.optional(ThreadPullRequestWatch), /** More watches of this thread recorded together, which `wake` also reports on. */ @@ -3939,6 +3980,7 @@ const OrchestrationV2InternalCommand = Schema.Union([ startedAt: IsoDateTime, watch: Schema.NullOr(ThreadPullRequestWatch), checksPendingBefore: Schema.optional(Schema.Boolean), + staleProgressAt: Schema.optional(IsoDateTime), endedWatch: Schema.optional(ThreadPullRequestWatch), includesRemarks: Schema.optional(Schema.Boolean), }), @@ -3973,6 +4015,7 @@ const OrchestrationV2InternalCommand = Schema.Union([ driver: ProviderDriverKind, modelSelection: ModelSelection, remoteChild: OrchestrationV2RemoteTaskChild, + staleTimeoutMs: Schema.optional(PositiveInt), completionWake: Schema.optional(Schema.Literals(["always", "settled_only"])), }), /** diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index b7278fc9c9984..5bc58006fa696 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -1,3 +1,4 @@ +import { StaleTimeoutMinutes } from "./waitStaleness.ts"; import * as Effect from "effect/Effect"; import { HostResourcesSnapshot } from "./resourceTelemetry.ts"; import * as Schema from "effect/Schema"; @@ -201,6 +202,7 @@ export const OrchestratorMcpDelegateTaskInput = Schema.Struct({ timeoutMs: Schema.optional(Schema.Finite).annotate({ description: "Mode 'wait' only. At most 45 s. A timeout does not cancel the child.", }), + staleTimeoutMinutes: StaleTimeoutMinutes, clientRequestId: Schema.optional(OrchestratorMcpClientRequestId), runtimeMode: Schema.optional( OrchestratorMcpRuntimeMode.annotate({ @@ -632,6 +634,8 @@ export const OrchestratorMcpThreadWaitInput = Schema.Struct({ export type OrchestratorMcpThreadWaitInput = typeof OrchestratorMcpThreadWaitInput.Type; export const OrchestratorMcpThreadWaitResult = Schema.Struct({ + progressAtMs: Schema.optional(Schema.Finite), + intentionallyHeld: Schema.optional(Schema.Boolean), threadId: ThreadId, runId: Schema.NullOr(RunId), status: OrchestratorMcpThreadStatus, diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts index d438080369a40..6f34959069bf2 100644 --- a/packages/contracts/src/pullRequest.ts +++ b/packages/contracts/src/pullRequest.ts @@ -113,6 +113,7 @@ export type PullRequestCheckStatus = typeof PullRequestCheckStatus.Type; export const PullRequestCheck = Schema.Struct({ name: TrimmedNonEmptyString, status: PullRequestCheckStatus, + pendingPhase: Schema.optional(Schema.Literals(["queued", "in-progress"])), description: Schema.NullOr(Schema.String), url: Schema.NullOr(Schema.String), required: Schema.optional(Schema.Boolean), @@ -668,6 +669,7 @@ export const PullRequestDetail = Schema.Struct({ observedAt: Schema.optional(Schema.Finite), mergedAt: Schema.NullOr(IsoDateTime), closedAt: Schema.NullOr(IsoDateTime), + reviewDecision: Schema.optional(Schema.NullOr(PullRequestReviewDecision)), reviewers: Schema.Array(PullRequestActor), labels: Schema.Array(PullRequestLabel), checks: Schema.Array(PullRequestCheck), diff --git a/packages/contracts/src/threadPullRequest.ts b/packages/contracts/src/threadPullRequest.ts index 0c8d7a61fe92d..dcefa5316c5f3 100644 --- a/packages/contracts/src/threadPullRequest.ts +++ b/packages/contracts/src/threadPullRequest.ts @@ -82,6 +82,15 @@ export type ThreadPullRequestKey = typeof ThreadPullRequestKey.Type; export const ThreadPullRequestWatch = Schema.Struct({ startedAt: IsoDateTime, + staleness: Schema.optional( + Schema.Struct({ + staleTimeoutMs: PositiveInt, + lastProgressAt: IsoDateTime, + checks: Schema.optional(Schema.Array(Schema.String)), + reviewDecision: Schema.optional(Schema.NullOr(PullRequestReviewDecision)), + alerted: Schema.optional(Schema.Literal(true)), + }), + ), headSha: Schema.NullOr(TrimmedNonEmptyString), failedChecks: Schema.Array(TrimmedNonEmptyString), passed: Schema.Boolean, diff --git a/packages/contracts/src/waitStaleness.ts b/packages/contracts/src/waitStaleness.ts new file mode 100644 index 0000000000000..73c05194c1a11 --- /dev/null +++ b/packages/contracts/src/waitStaleness.ts @@ -0,0 +1,19 @@ +import * as Schema from "effect/Schema"; + +export const StaleTimeoutMinutes = Schema.optional(Schema.Finite).annotate({ + description: "Idle timeout in minutes. Clamped to 5–1440 minutes.", +}); + +export const PR_WATCH_STALE_MINUTES = 30; +export const BACKGROUND_WAIT_STALE_MINUTES = 45; + +// Stored on the owning application thread, independent of provider process lifetime. +export const ThreadStalenessWait = Schema.Struct({ + kind: Schema.Literals(["background", "delegate"]), + taskId: Schema.String, + staleTimeoutMs: Schema.Int, + lastProgressAtMs: Schema.Finite, + remoteHeld: Schema.optional(Schema.Boolean), + alerted: Schema.optional(Schema.Literal(true)), +}); +export type ThreadStalenessWait = typeof ThreadStalenessWait.Type; diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts index a2b3f3c2c3edd..afb1280ca9a73 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts @@ -627,11 +627,15 @@ function toCheckEntries(raw: ReadonlyArray | null | undefined): Rea const name = trimmed(check.name) ?? trimmed(check.context); if (name === null) return []; const status = toCheckStatus(check); + const phase = check.status?.trim().toUpperCase(); + const pendingPhase = + phase === "IN_PROGRESS" ? "in-progress" : phase === "QUEUED" ? "queued" : undefined; return [ { check: { name, status, + ...(pendingPhase === undefined ? {} : { pendingPhase }), description: trimmed(check.description), url: trimmed(check.detailsUrl) ?? trimmed(check.targetUrl), ...(typeof check.isRequired === "boolean" ? { required: check.isRequired } : {}), From 89fe5665ad3188feeda2b04551dc6b4c7cf812a2 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:59:53 +0000 Subject: [PATCH 2/6] fix(server): apply the wait deadline to native monitors Model: gpt-6.2-sol Task: fix Agent: Codex Lane: codex --- .../Adapters/ClaudeAdapterV2.ts | 3 +- .../src/orchestration-v2/ModelAlertReactor.ts | 23 ++- .../src/orchestration-v2/Orchestrator.ts | 58 ++++-- .../src/orchestration-v2/ProjectionStore.ts | 19 +- .../src/orchestration-v2/ThreadEventAlerts.ts | 2 +- .../src/orchestration-v2/runtimeLayer.test.ts | 181 +++++++++--------- .../src/orchestration-v2/waitStaleness.ts | 1 + packages/contracts/src/orchestratorMcp.ts | 2 +- 8 files changed, 171 insertions(+), 118 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index f5979d9b8389c..2e204fb7318c5 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -6936,13 +6936,14 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeThreadId: string, task: OrchestrationV2PendingBackgroundTask, ) { + const now = yield* Clock.currentTimeMillis; const startedMonitor = yield* Ref.modify( pendingBackgroundTasksByNativeThread, (current) => { const roster = new Map(rosterForNativeThread(current, nativeThreadId)); const startedMonitor = task.kind === "monitor" && roster.get(task.taskId)?.kind !== "monitor"; - roster.set(task.taskId, task); + roster.set(task.taskId, startedMonitor ? { ...task, progressAtMs: now } : task); return [startedMonitor, new Map(current).set(nativeThreadId, roster)] as const; }, ); diff --git a/apps/server/src/orchestration-v2/ModelAlertReactor.ts b/apps/server/src/orchestration-v2/ModelAlertReactor.ts index d5d640e9708fc..4caf9fc02821e 100644 --- a/apps/server/src/orchestration-v2/ModelAlertReactor.ts +++ b/apps/server/src/orchestration-v2/ModelAlertReactor.ts @@ -1057,6 +1057,7 @@ export const make = Effect.gen(function* () { const shell = yield* projections.getThreadShell(ThreadId.make(alert.threadId)); if (shell === null) return null; const holds = threadEventStillHolds({ + hasStalenessWait: yield* hasActiveStalenessWait(shell, REJUDGE_TRIGGER[alert.kind]), alert, shell, stuckMinutes: (yield* settings.getSettings).watcherStuckMinutes, @@ -1068,6 +1069,17 @@ export const make = Effect.gen(function* () { }); /** What the shell does not carry: open delegated tasks elsewhere, and children's last activity. */ + const hasActiveStalenessWait = Effect.fnUntraced(function* ( + shell: OrchestrationV2ThreadShell, + trigger: ThreadEventTrigger, + ) { + return ( + trigger === "sweep" && + shell.activeRunId !== null && + ((yield* projections.getThread(shell.id)).stalenessWaits?.length ?? 0) > 0 + ); + }); + const judgeContext = Effect.fnUntraced(function* ( shell: OrchestrationV2ThreadShell, trigger: ThreadEventTrigger, @@ -1104,15 +1116,11 @@ export const make = Effect.gen(function* () { )), ) : null; - const hasStalenessWait = - trigger === "sweep" && - shell.activeRunId !== null && - ((yield* projections.getThread(shell.id)).stalenessWaits?.length ?? 0) > 0; if (trigger !== "sweep" || shell.activeRunId !== null || shell.activityRunStatus != null) { - return { remoteTaskCount, childActivityMs, hasStalenessWait }; + return { remoteTaskCount, childActivityMs }; } if (queuedThreads !== undefined && !queuedThreads.has(shell.id)) { - return { remoteTaskCount, childActivityMs, hasStalenessWait, strandedQueue: null }; + return { remoteTaskCount, childActivityMs, strandedQueue: null }; } const now = yield* DateTime.now; const { runs } = yield* projections.getThreadRecords(shell.id, ["runs"]); @@ -1142,7 +1150,7 @@ export const make = Effect.gen(function* () { (shell.lastErrorClass === "usage_limit" && latestRun?.providerInstanceId === oldest.providerInstanceId), }; - return { remoteTaskCount, childActivityMs, hasStalenessWait, strandedQueue }; + return { remoteTaskCount, childActivityMs, strandedQueue }; }); /** The watcher thread as one delivery needs it, or null when it cannot be read. */ @@ -1478,6 +1486,7 @@ export const make = Effect.gen(function* () { const nowMs = yield* Clock.currentTimeMillis; const context = yield* judgeContext(shell, trigger, remoteTasks, queuedThreads); const judged = judgeThread({ + hasStalenessWait: yield* hasActiveStalenessWait(shell, trigger), shell, trigger, nowMs, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 594196d243e1e..a3f6498700947 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -35,6 +35,7 @@ import { ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE, type ChatAttachment, CommandId, + BACKGROUND_WAIT_STALE_MINUTES, PR_WATCH_STALE_MINUTES, type GuestMessageId, isCompactionCommandMessage, @@ -4265,17 +4266,21 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const added = [...new Set(operation.taskIds)].filter( (taskId) => !waits.some((wait) => wait.kind === operation.kind && wait.taskId === taskId), ); - if (added.length > 0) { - next = [ - ...waits, - ...added.map((taskId) => ({ - kind: operation.kind, - taskId, - staleTimeoutMs: operation.staleTimeoutMs, - lastProgressAtMs: nowMs, - })), - ]; - } + next = [ + ...waits.map((wait) => + wait.kind === operation.kind && + operation.taskIds.includes(wait.taskId) && + wait.staleTimeoutMs !== operation.staleTimeoutMs + ? { ...wait, staleTimeoutMs: operation.staleTimeoutMs } + : wait, + ), + ...added.map((taskId) => ({ + kind: operation.kind, + taskId, + staleTimeoutMs: operation.staleTimeoutMs, + lastProgressAtMs: nowMs, + })), + ]; break; } case "clear": @@ -4301,7 +4306,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); break; case "sweep": { - if (waits.length === 0) return; const shell = yield* projectionStore .getThreadShell(threadId) .pipe(mapDispatchError(command)); @@ -4322,18 +4326,36 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }) .pipe(mapDispatchError(command)); const parentHeld = waitIntentionallyHeld(shell, nowMs); + const provider = tasks.providerThreads.find( + (provider) => provider.id === thread.activeProviderThreadId, + ); + const roster = provider?.pendingBackgroundTasks ?? []; + const registrations = [...waits]; + for (const task of roster) { + if ( + task.kind !== "monitor" || + task.awaited !== true || + waits.some((wait) => wait.kind === "background" && wait.taskId === task.taskId) + ) + continue; + registrations.push({ + kind: "background", + taskId: task.taskId, + staleTimeoutMs: BACKGROUND_WAIT_STALE_MINUTES * 60_000, + lastProgressAtMs: + task.progressAtMs ?? DateTime.toEpochMillis(provider?.updatedAt ?? now), + }); + } const retained: ThreadStalenessWait[] = []; - for (const wait of waits) { + for (const wait of registrations) { let progressAtMs = wait.lastProgressAtMs; let state = "pending"; let childLink: string | undefined; let held = parentHeld; if (wait.kind === "background") { - const task = tasks.providerThreads - .find((provider) => provider.id === thread.activeProviderThreadId) - ?.pendingBackgroundTasks?.find( - (task) => task.taskId === wait.taskId && task.awaited === true, - ); + const task = roster.find( + (task) => task.taskId === wait.taskId && task.awaited === true, + ); if (task === undefined) { // The provider's roster event and the MCP registration can commit in either order. if (nowMs < wait.lastProgressAtMs + 60_000) retained.push(wait); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index ee117f548070e..9e222c698e31b 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -9240,9 +9240,22 @@ export const layer: Layer.Layer = }, Effect.mapError(shellSnapshotReadError)); const listStalenessWaitThreads = sql<{ readonly thread_id: string }>` - SELECT thread_id FROM orchestration_v2_projection_threads - WHERE deleted_at IS NULL AND json_extract(payload_json, '$.archivedAt') IS NULL - AND json_array_length(payload_json, '$.stalenessWaits') > 0 + SELECT t.thread_id FROM orchestration_v2_projection_threads t + WHERE t.deleted_at IS NULL AND json_extract(t.payload_json, '$.archivedAt') IS NULL + AND ( + json_array_length(t.payload_json, '$.stalenessWaits') > 0 + OR ( + json_extract(t.payload_json, '$.settledAt') IS NULL + AND json_extract(t.payload_json, '$.settledOverride') IS NOT 'settled' + AND EXISTS ( + SELECT 1 FROM orchestration_v2_projection_provider_threads p, + json_each(p.payload_json, '$.pendingBackgroundTasks') task + WHERE p.provider_thread_id = t.active_provider_thread_id + AND json_extract(task.value, '$.kind') = 'monitor' + AND json_extract(task.value, '$.awaited') = 1 + ) + ) + ) `.pipe( Effect.map((rows) => rows.map(({ thread_id }) => ThreadId.make(thread_id))), Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })), diff --git a/apps/server/src/orchestration-v2/ThreadEventAlerts.ts b/apps/server/src/orchestration-v2/ThreadEventAlerts.ts index a8c71720980bd..ecf01ad685a43 100644 --- a/apps/server/src/orchestration-v2/ThreadEventAlerts.ts +++ b/apps/server/src/orchestration-v2/ThreadEventAlerts.ts @@ -414,12 +414,12 @@ export function threadEventStillHolds(input: { const firedMs = Date.parse(alert.occurredAt); if (!Number.isFinite(firedMs)) return true; const { findings } = judgeThread({ + ...(input.hasStalenessWait === undefined ? {} : { hasStalenessWait: input.hasStalenessWait }), shell: input.shell, trigger: REJUDGE_TRIGGER[alert.kind], nowMs: firedMs, stuckMinutes: input.stuckMinutes, ...(input.strandedQueue === undefined ? {} : { strandedQueue: input.strandedQueue }), - ...(input.hasStalenessWait === undefined ? {} : { hasStalenessWait: input.hasStalenessWait }), ...(input.remoteTaskCount === undefined ? {} : { remoteTaskCount: input.remoteTaskCount }), ...(input.childActivityMs === undefined ? {} : { childActivityMs: input.childActivityMs }), }); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 6c8c271f75a50..0c1c42eac2e94 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -4739,95 +4739,102 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); - it.effect("uses native task progress and clears the deadline when background work ends", () => - Effect.gen(function* () { - const engine = yield* Orchestrator.OrchestratorV2; - const sink = yield* EventSink.EventSinkV2; - const { threadId } = yield* createWatchedThread("background-stale"); - yield* engine.dispatch({ - type: "message.dispatch", - createdBy: "agent", - creationSource: "mcp", - commandId: CommandId.make(`${threadId}:start`), - threadId, - messageId: MessageId.make(`${threadId}:start`), - text: "Run background checks.", - attachments: [], - dispatchMode: { type: "start_immediately" }, - }); - const provider = (yield* engine.getThreadRecords(threadId, ["providerThreads"])) - .providerThreads[0]!; - const roster = Effect.fnUntraced(function* (suffix: string, active: boolean) { - const now = yield* DateTime.now; - yield* sink.write({ - events: [ - { - id: EventId.make(`${threadId}:${suffix}`), - type: "provider-thread.updated", - threadId, - driver: provider.driver, - providerInstanceId: provider.providerInstanceId, - occurredAt: now, - payload: { - ...provider, - updatedAt: now, - pendingBackgroundTasks: active - ? [ - { - taskId: "tests", - kind: "monitor", - awaited: true, - progressAtMs: DateTime.toEpochMillis(now), - }, - ] - : [], - }, - }, - ], - effects: [], - }); - }); - yield* roster("pending", true); - yield* engine.dispatch({ - type: "thread.wait-staleness.update", - threadId, - commandId: CommandId.make(`${threadId}:register`), - operation: { - type: "register", - kind: "background", - taskIds: ["tests"], - staleTimeoutMs: 5 * 60_000, - }, - }); - const sweep = (suffix: string) => - engine.dispatch({ - type: "thread.wait-staleness.update", + it.effect.each([5, undefined])( + "uses native task progress and clears the deadline when background work ends (%s minutes)", + (customMinutes) => + Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const projection = yield* ProjectionStore.ProjectionStoreV2; + const { threadId } = yield* createWatchedThread(`background-stale-${customMinutes}`); + yield* engine.dispatch({ + type: "message.dispatch", + createdBy: "agent", + creationSource: "mcp", + commandId: CommandId.make(`${threadId}:start`), threadId, - commandId: CommandId.make(`${threadId}:${suffix}`), - operation: { type: "sweep" }, + messageId: MessageId.make(`${threadId}:start`), + text: "Run background checks.", + attachments: [], + dispatchMode: { type: "start_immediately" }, }); - const notices = engine - .getThreadRecords(threadId, ["messages"]) - .pipe( - Effect.map(({ messages }) => - messages.filter((message) => message.text.includes('"type":"wait_stale_timeout"')), - ), - ); - yield* TestClock.adjust("4 minutes"); - yield* roster("progress", true); - yield* TestClock.adjust("1 minute"); - yield* sweep("early"); - assert.lengthOf(yield* notices, 0); - yield* TestClock.adjust("4 minutes"); - yield* sweep("due"); - assert.include((yield* notices)[0]?.text, '"taskId":"tests","kind":"background"'); - assert.include((yield* notices)[0]?.text, '"idleMinutes":5'); - yield* roster("completed", false); - yield* TestClock.adjust("1 hour"); - yield* sweep("ended"); - assert.lengthOf(yield* notices, 1); - assert.deepEqual((yield* engine.getThreadRecords(threadId, [])).thread.stalenessWaits, []); - }), + const provider = (yield* engine.getThreadRecords(threadId, ["providerThreads"])) + .providerThreads[0]!; + const roster = Effect.fnUntraced(function* (suffix: string, active: boolean) { + const now = yield* DateTime.now; + yield* sink.write({ + events: [ + { + id: EventId.make(`${threadId}:${suffix}`), + type: "provider-thread.updated", + threadId, + driver: provider.driver, + providerInstanceId: provider.providerInstanceId, + occurredAt: now, + payload: { + ...provider, + updatedAt: now, + pendingBackgroundTasks: active + ? [ + { + taskId: "tests", + kind: "monitor", + awaited: true, + progressAtMs: DateTime.toEpochMillis(now), + }, + ] + : [], + }, + }, + ], + effects: [], + }); + }); + yield* roster("pending", true); + if (customMinutes !== undefined) { + yield* engine.dispatch({ + type: "thread.wait-staleness.update", + threadId, + commandId: CommandId.make(`${threadId}:register`), + operation: { + type: "register", + kind: "background", + taskIds: ["tests"], + staleTimeoutMs: customMinutes * 60_000, + }, + }); + } + const minutes = customMinutes ?? 45; + assert.include(yield* projection.listStalenessWaitThreads, threadId); + const sweep = (suffix: string) => + engine.dispatch({ + type: "thread.wait-staleness.update", + threadId, + commandId: CommandId.make(`${threadId}:${suffix}`), + operation: { type: "sweep" }, + }); + const notices = engine + .getThreadRecords(threadId, ["messages"]) + .pipe( + Effect.map(({ messages }) => + messages.filter((message) => message.text.includes('"type":"wait_stale_timeout"')), + ), + ); + yield* TestClock.adjust(`${minutes - 1} minutes`); + yield* roster("progress", true); + yield* TestClock.adjust("1 minute"); + yield* sweep("early"); + assert.lengthOf(yield* notices, 0); + yield* TestClock.adjust(`${minutes - 1} minutes`); + yield* sweep("due"); + assert.include((yield* notices)[0]?.text, '"taskId":"tests","kind":"background"'); + assert.include((yield* notices)[0]?.text, `"idleMinutes":${minutes}`); + yield* roster("completed", false); + yield* TestClock.adjust("1 hour"); + yield* sweep("ended"); + assert.lengthOf(yield* notices, 1); + assert.deepEqual((yield* engine.getThreadRecords(threadId, [])).thread.stalenessWaits, []); + }), ); it.effect( diff --git a/apps/server/src/orchestration-v2/waitStaleness.ts b/apps/server/src/orchestration-v2/waitStaleness.ts index 5b2c2bb8c19f8..737b6423b9c35 100644 --- a/apps/server/src/orchestration-v2/waitStaleness.ts +++ b/apps/server/src/orchestration-v2/waitStaleness.ts @@ -24,6 +24,7 @@ export function waitIntentionallyHeld(shell: OrchestrationV2ThreadShell, now: nu shell.inbox?.decisionRequest !== undefined || shell.latestRunStopRequested === true || (shell.snoozedUntil != null && DateTime.toEpochMillis(shell.snoozedUntil) > now) || + shell.limitRecovery?.autoResume === true || (shell.limitRecovery != null && Date.parse(shell.limitRecovery.resetAt) > now) ); } diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index 5bc58006fa696..23ff97996775c 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -1,4 +1,3 @@ -import { StaleTimeoutMinutes } from "./waitStaleness.ts"; import * as Effect from "effect/Effect"; import { HostResourcesSnapshot } from "./resourceTelemetry.ts"; import * as Schema from "effect/Schema"; @@ -38,6 +37,7 @@ import { import { secretRequestPageUrl } from "./secretRequest.ts"; import { hasOnlyPairedSurrogates } from "./threadMetadataMcp.ts"; import { LastThreadTitleRegeneration, ThreadTitleRegeneration } from "./threadTitle.ts"; +import { StaleTimeoutMinutes } from "./waitStaleness.ts"; import { OrchestrationV2Actor, OrchestrationV2CreationSource, From c0420e9abfed62a38b1ebc7022e8cf52c81d6f77 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:01:32 +0000 Subject: [PATCH 3/6] test(server): use the current event sink fixture shape Model: gpt-6.2-sol Task: fix Agent: Codex Lane: codex --- apps/server/src/orchestration-v2/runtimeLayer.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 0c1c42eac2e94..ed6fca25d602a 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -4787,7 +4787,6 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }, }, ], - effects: [], }); }); yield* roster("pending", true); From dd8ca0c8e423762d3d00d9e377ba3635cd305c99 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 23 Nov 2026 00:31:40 +0000 Subject: [PATCH 4/6] fix(server): deliver wait deadlines safely and preserve their state Persist background wait deadlines before provider enrollment and recover older awaited work. Deliver active-run diagnostics through system notices, refresh queued groups at delivery, and keep PR watch overrides and intentional holds intact. Model: gpt-6.2-sol Task: fix Agent: Codex Lane: codex Harness: t3/codex --- .../src/orchestration-v2/ModelAlertReactor.ts | 8 +- .../src/orchestration-v2/Orchestrator.ts | 723 ++++++++++++------ .../src/orchestration-v2/ProjectionStore.ts | 24 +- .../ProviderRuntimeRecoveryService.ts | 7 +- .../PullRequestWatchReactor.ts | 36 +- .../ThreadManagementService.test.ts | 24 +- .../ThreadManagementService.ts | 78 +- .../src/orchestration-v2/pullRequestWatch.ts | 6 +- .../src/orchestration-v2/runtimeLayer.test.ts | 592 +++++++++++++- .../pullRequest/PullRequestWatchService.ts | 9 +- packages/contracts/src/orchestrationV2.ts | 4 + packages/contracts/src/waitStaleness.ts | 4 + 12 files changed, 1227 insertions(+), 288 deletions(-) diff --git a/apps/server/src/orchestration-v2/ModelAlertReactor.ts b/apps/server/src/orchestration-v2/ModelAlertReactor.ts index 4caf9fc02821e..f9dc7e4f08068 100644 --- a/apps/server/src/orchestration-v2/ModelAlertReactor.ts +++ b/apps/server/src/orchestration-v2/ModelAlertReactor.ts @@ -1076,7 +1076,13 @@ export const make = Effect.gen(function* () { return ( trigger === "sweep" && shell.activeRunId !== null && - ((yield* projections.getThread(shell.id)).stalenessWaits?.length ?? 0) > 0 + ((yield* projections.getThread(shell.id)).stalenessWaits ?? []).some( + (wait) => + wait.kind === "delegate" || + shell.pendingBackgroundTasks?.some( + (task) => task.taskId === wait.taskId && task.awaited === true, + ), + ) ); }); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index a3f6498700947..e989099361d17 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -98,7 +98,11 @@ import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { modelSelectionsEqual } from "@t3tools/shared/model"; import { modelSwitchSince } from "./modelSwitch.ts"; import { isPlaceholderThreadTitle } from "./placeholderThreadTitle.ts"; -import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts"; +import { + combinePullRequestWatchWakes, + pullRequestWatchStaleness, + type PullRequestWatchWake, +} from "./pullRequestWatch.ts"; import { recordThreadOpen } from "@t3tools/shared/paletteSearch"; import { formatThreadLink } from "@t3tools/shared/threadLinks"; import { @@ -929,9 +933,20 @@ function syncedPullRequestWatch( if (command.watch === null) return undefined; // A push cleared the answer while this read was in flight, so its answer is the old head's. if (command.checksPendingBefore === undefined || existing?.checksPending !== undefined) { - return command.watch; + return withCurrentWatchTimeout(existing, command.watch); } - return withoutChecksAnswer(command.watch); + return withoutChecksAnswer(withCurrentWatchTimeout(existing, command.watch)); +} + +function withCurrentWatchTimeout( + existing: ThreadPullRequestWatch | undefined, + incoming: ThreadPullRequestWatch, +) { + if (incoming.staleness === undefined || existing?.staleness === undefined) return incoming; + return { + ...incoming, + staleness: { ...incoming.staleness, staleTimeoutMs: existing.staleness.staleTimeoutMs }, + }; } const withoutChecksAnswer = ({ @@ -1257,6 +1272,7 @@ function monitorPullRequestStamps( function isStalePullRequestWatchStamp( projection: Pick, stamp: MonitorPullRequestStamp, + held = false, ): boolean { const link = threadPullRequestsOf(projection.thread).find( (candidate) => @@ -1265,7 +1281,7 @@ function isStalePullRequestWatchStamp( if (link === undefined) return true; if ( stamp.staleProgressAt !== undefined && - link.watch?.staleness?.lastProgressAt !== stamp.staleProgressAt + (held || link.watch?.staleness?.lastProgressAt !== stamp.staleProgressAt) ) return true; if (stamp.watchEnded === true) { @@ -1296,52 +1312,59 @@ function isStalePullRequestWatchStamp( ); } -function isStaleBackgroundWaitWake( - projection: OrchestrationV2ThreadProjection, - run: OrchestrationV2Run, -): boolean { - const source = projection.messages.find((message) => message.id === run.userMessageId) - ?.notification?.source; - if (source?.kind !== "monitor" || source.staleWaits === undefined) return false; - if (projection.thread.settledAt !== null || projection.thread.settledOverride === "settled") - return true; - return source.staleWaits.every((stamp) => { - const wait = projection.thread.stalenessWaits?.find( - (wait) => wait.kind === stamp.kind && wait.taskId === stamp.taskId, - ); - if (wait?.lastProgressAtMs !== stamp.lastProgressAtMs || wait.remoteHeld === true) return true; - if (wait.kind === "background") { - return !projection.providerThreads - .find((provider) => provider.id === projection.thread.activeProviderThreadId) - ?.pendingBackgroundTasks?.some( - (task) => - task.taskId === wait.taskId && - task.awaited === true && - (task.progressAtMs ?? 0) <= wait.lastProgressAtMs, - ); - } - const task = projection.subagents.find((task) => task.id === wait.taskId); - return ( - task === undefined || - task.result !== null || - task.completionDelivery?.state === "disposed" || - task.status === "completed" || - task.status === "failed" || - task.status === "cancelled" || - task.status === "interrupted" - ); - }); +type StaleWait = { + taskId: string; + kind: ThreadStalenessWait["kind"]; + state: string; + childLink?: string; + idleMinutes: number; + lastProgressAtMs: number; +}; + +const waitStaleNotice = Effect.fn("Orchestrator.waitStaleNotice")(function* ( + stale: ReadonlyArray, +) { + const diagnostic = yield* encodeWaitStaleDiagnostic({ + type: "wait_stale_timeout", + waits: stale.map(({ lastProgressAtMs: _, ...entry }) => entry), + }).pipe(Effect.orDie); + return { + text: `${diagnostic}\n\nCheck why this work is quiet. T3 Code keeps its normal completion wake armed and reports staleness again only after progress.`, + notification: { + source: { + kind: "monitor", + staleWaits: stale.map(({ kind, taskId, lastProgressAtMs }) => ({ + kind, + taskId, + lastProgressAtMs, + })), + }, + outcome: "updated", + summary: `No progress on ${stale.length === 1 ? "one wait" : `${stale.length} waits`}`, + } satisfies OrchestrationV2Notification, + }; +}); + +function isOpenStalenessDelegate(task: OrchestrationV2Subagent): boolean { + return ( + task.origin === "app_owned" && + task.result === null && + task.completionDelivery?.state !== "disposed" && + (task.status === "pending" || task.status === "running" || task.status === "waiting") + ); } function isStalePullRequestWatchWake( projection: Pick, run: OrchestrationV2Run, + held: boolean, ): boolean { const stamps = monitorPullRequestStamps( projection.messages.find((message) => message.id === run.userMessageId)?.notification?.source, ); return ( - stamps.length > 0 && stamps.every((stamp) => isStalePullRequestWatchStamp(projection, stamp)) + stamps.length > 0 && + stamps.every((stamp) => isStalePullRequestWatchStamp(projection, stamp, held)) ); } @@ -1352,11 +1375,12 @@ function isStalePullRequestWatchWake( function currentPullRequestWatchWake( projection: Pick, run: OrchestrationV2Run, + held: boolean, ): OrchestrationV2ConversationMessage | undefined { const message = projection.messages.find((candidate) => candidate.id === run.userMessageId); const stamps = monitorPullRequestStamps(message?.notification?.source); if (message === undefined || stamps.length < 2) return undefined; - const current = stamps.filter((stamp) => !isStalePullRequestWatchStamp(projection, stamp)); + const current = stamps.filter((stamp) => !isStalePullRequestWatchStamp(projection, stamp, held)); const [first, ...rest] = current; if (first === undefined || rest.length === stamps.length - 1) return undefined; const sections = current.flatMap(({ section }) => (section === undefined ? [] : [section])); @@ -2639,6 +2663,98 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); }); + const revalidateQueuedDeadline = Effect.fn("Orchestrator.revalidateQueuedDeadline")(function* ( + projection: OrchestrationV2ThreadProjection, + run: OrchestrationV2Run, + ) { + const message = projection.messages.find((message) => message.id === run.userMessageId); + const source = message?.notification?.source; + const prStamps = monitorPullRequestStamps(source).filter( + (stamp) => stamp.staleProgressAt !== undefined, + ); + if ( + message === undefined || + source?.kind !== "monitor" || + (source.staleWaits === undefined && prStamps.length === 0) + ) + return { type: "keep" } as const; + const thread = projection.thread; + const shell = yield* projectionStore.getThreadShell(thread.id); + if (shell === null || shell.settledAt !== null || shell.settledOverride === "settled") + return { type: "cancel" } as const; + const now = yield* DateTime.now; + const nowMs = DateTime.toEpochMillis(now); + const held = waitIntentionallyHeld(shell, nowMs); + if (source.staleWaits === undefined) { + if (!held) return { type: "keep" } as const; + const links = threadPullRequestsOf(thread).map((link) => { + if ( + !prStamps.some( + (stamp) => + threadPullRequestKeysEqual(stamp, link) && + stamp.watchStartedAt === link.watch?.startedAt && + stamp.staleProgressAt === link.watch?.staleness?.lastProgressAt, + ) || + link.watch?.staleness === undefined + ) + return link; + const { alerted: _, ...progress } = link.watch.staleness; + return { ...link, watch: { ...link.watch, staleness: progress } }; + }); + return { type: "keep", prHeld: true, thread: { ...thread, pullRequests: links } } as const; + } + const tasks = yield* projectionStore.getThreadRecords( + thread.id, + ["subagents", "providerThreads"], + { + subagentIds: source.staleWaits + .filter((stamp) => stamp.kind === "delegate") + .map((stamp) => NodeId.make(stamp.taskId)), + }, + ); + const provider = tasks.providerThreads.find( + (provider) => provider.id === thread.activeProviderThreadId, + ); + const current: StaleWait[] = []; + const rearmed = new Set(); + for (const stamp of source.staleWaits) { + const wait = thread.stalenessWaits?.find( + (wait) => wait.kind === stamp.kind && wait.taskId === stamp.taskId, + ); + if (wait?.lastProgressAtMs !== stamp.lastProgressAtMs || wait.alerted !== true) continue; + const observation = yield* observeStalenessWait( + thread.id, + wait, + provider, + tasks.subagents, + nowMs, + ); + if (observation === null || observation.current.lastProgressAtMs !== stamp.lastProgressAtMs) + continue; + if (held || observation.held || observation.diagnostic === undefined) rearmed.add(wait); + else current.push(observation.diagnostic); + } + const updated = + rearmed.size === 0 + ? undefined + : { + ...thread, + stalenessWaits: + thread.stalenessWaits?.map((wait) => { + if (!rearmed.has(wait)) return wait; + const { alerted: _, ...next } = wait; + return next; + }) ?? [], + }; + return current.length === 0 + ? ({ type: "cancel", thread: updated } as const) + : ({ + type: "replace", + thread: updated, + message: { ...message, ...(yield* waitStaleNotice(current)) }, + } as const); + }); + const startNextQueuedRun = Effect.fn("Orchestrator.startNextQueuedRun")( function* ( threadId: ThreadId, @@ -2698,22 +2814,39 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : projection.runs.find( (run) => run.id === options.queuedRunId && run.status === "queued", ); - while ( - storedQueuedRun !== undefined && - (isStalePullRequestWatchWake(projection, storedQueuedRun) || - isStaleBackgroundWaitWake(projection, storedQueuedRun)) - ) { + let currentWake: OrchestrationV2ConversationMessage | undefined; + while (storedQueuedRun !== undefined) { + const deadline = yield* revalidateQueuedDeadline(projection, storedQueuedRun).pipe( + Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })), + ); + if ("thread" in deadline && deadline.thread !== undefined) { + yield* writeSystemEvents([ + { + type: "thread.metadata-updated", + threadId, + occurredAt: checkedAt, + providerInstanceId: deadline.thread.providerInstanceId, + payload: deadline.thread, + }, + ]); + } + const prHeld = "prHeld" in deadline && deadline.prHeld; + if ( + deadline.type !== "cancel" && + !isStalePullRequestWatchWake(projection, storedQueuedRun, prHeld) + ) { + currentWake = + deadline.type === "replace" + ? deadline.message + : currentPullRequestWatchWake(projection, storedQueuedRun, prHeld); + break; + } yield* writeSystemEvents( - queuedRunCancellationEvents(projection, storedQueuedRun, yield* DateTime.now), + queuedRunCancellationEvents(projection, storedQueuedRun, checkedAt), ); projection = yield* readCommandProjection(threadId); storedQueuedRun = nextQueuedRun(projection); } - // A wake that outlived some of its pull requests tells only the current ones. - const currentWake = - storedQueuedRun === undefined - ? undefined - : currentPullRequestWatchWake(projection, storedQueuedRun); if (storedQueuedRun !== undefined && currentWake !== undefined) { const now = yield* DateTime.now; yield* writeSystemEvents([ @@ -4241,6 +4374,137 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); }); + const emitDeadlineNotice = Effect.fn("Orchestrator.emitDeadlineNotice")(function* ( + command: Extract< + OrchestrationV2ServerCommand, + { type: "thread.wait-staleness.update" | "thread.pull-request-watch.sync" } + >, + events: Ref.Ref>, + runId: RunId, + now: DateTime.Utc, + title: string, + message: string, + ) { + const run = yield* projectionStore + .getRun(command.threadId, runId) + .pipe(mapDispatchError(command)); + if (run === undefined) + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "Deadline notice run disappeared.", + }); + yield* emit( + events, + command, + )({ + type: "turn-item.updated", + threadId: run.threadId, + runId, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { + type: "system_notice", + id: TurnItemId.make(`item:deadline:${command.commandId}`), + threadId: run.threadId, + runId, + nodeId: run.rootNodeId, + providerThreadId: run.providerThreadId, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "completed", + title, + message, + startedAt: now, + completedAt: now, + updatedAt: now, + }, + }); + }); + + const observeStalenessWait = Effect.fn("Orchestrator.observeStalenessWait")(function* ( + threadId: ThreadId, + wait: ThreadStalenessWait, + provider: OrchestrationV2ProviderThread | undefined, + subagents: ReadonlyArray, + nowMs: number, + ) { + let progressAtMs = wait.lastProgressAtMs; + let state: string; + let childLink: string | undefined; + let held = false; + let observed = wait; + if (wait.kind === "background") { + if (wait.providerThreadId !== undefined && wait.providerThreadId !== provider?.id) + return null; + const task = provider?.pendingBackgroundTasks?.find((task) => task.taskId === wait.taskId); + if (task?.awaited !== true || provider === undefined) { + return wait.backgroundObserved === true || wait.providerThreadId === undefined + ? null + : { current: wait, held: false, diagnostic: undefined }; + } + if (wait.backgroundObserved !== true && provider !== undefined) { + const { registeredBy: _, ...registration } = wait; + observed = { ...registration, providerThreadId: provider.id, backgroundObserved: true }; + } + state = task.kind; + const item = + task.itemId === undefined + ? null + : yield* projectionStore.getTurnItem({ + threadId: task.sourceThreadId ?? threadId, + itemId: task.itemId, + }); + progressAtMs = Math.max( + progressAtMs, + task.progressAtMs ?? 0, + item === null ? 0 : DateTime.toEpochMillis(item.updatedAt), + ); + } else { + const task = subagents.find((task) => task.id === wait.taskId); + if (task === undefined || !isOpenStalenessDelegate(task)) return null; + state = task.status; + if (task.remoteChild !== undefined) { + childLink = formatThreadLink(task.remoteChild, task.remoteChild.title); + held = wait.remoteHeld === true; + } else if (task.childThreadId !== null) { + const child = yield* projectionStore.getThreadShell(task.childThreadId); + if ( + child === null || + child.deletedAt !== null || + child.archivedAt !== null || + child.settledOverride === "settled" + ) + return null; + state = child.status; + childLink = formatThreadLink({ environmentId: null, threadId: child.id }, child.title); + held = waitIntentionallyHeld(child, nowMs); + const itemActivity = yield* projectionStore.getWaitActivityMs(child.id, child.latestRunId); + progressAtMs = Math.max(progressAtMs, waitActivityMs(child), itemActivity); + } + } + const { alerted: _, ...rearmed } = observed; + const current = + progressAtMs > wait.lastProgressAtMs + ? { ...rearmed, lastProgressAtMs: progressAtMs } + : observed; + const idleMs = nowMs - current.lastProgressAtMs; + const diagnostic: StaleWait | undefined = + idleMs < current.staleTimeoutMs + ? undefined + : { + taskId: current.taskId, + kind: current.kind, + state, + idleMinutes: Math.floor(idleMs / 60_000), + lastProgressAtMs: current.lastProgressAtMs, + ...(childLink === undefined ? {} : { childLink }), + }; + return { current, held, diagnostic }; + }); + const updateWaitStaleness = Effect.fn("Orchestrator.updateWaitStaleness")(function* ( command: Extract, events: Ref.Ref>, @@ -4253,39 +4517,55 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (thread.deletedAt !== null) return; const waits = thread.stalenessWaits ?? []; let next = waits; - const stale: Array<{ - taskId: string; - kind: ThreadStalenessWait["kind"]; - state: string; - childLink?: string; - idleMinutes: number; - lastProgressAtMs: number; - }> = []; + const stale: Array = []; + let activeRunId: RunId | null = null; switch (operation.type) { case "register": { + const providerThreadId = + operation.kind === "background" + ? (operation.providerThreadId ?? thread.activeProviderThreadId ?? undefined) + : undefined; + if ( + operation.providerThreadId !== undefined && + operation.providerThreadId !== thread.activeProviderThreadId + ) + return; + const matches = (wait: ThreadStalenessWait, taskId: string) => + wait.kind === operation.kind && wait.taskId === taskId; + const current = (wait: ThreadStalenessWait) => + wait.providerThreadId === undefined || + operation.providerThreadId === undefined || + wait.providerThreadId === operation.providerThreadId; const added = [...new Set(operation.taskIds)].filter( - (taskId) => !waits.some((wait) => wait.kind === operation.kind && wait.taskId === taskId), + (taskId) => !waits.some((wait) => matches(wait, taskId) && current(wait)), ); next = [ - ...waits.map((wait) => - wait.kind === operation.kind && - operation.taskIds.includes(wait.taskId) && - wait.staleTimeoutMs !== operation.staleTimeoutMs - ? { ...wait, staleTimeoutMs: operation.staleTimeoutMs } - : wait, - ), + ...waits + .filter((wait) => current(wait) || !operation.taskIds.some((id) => matches(wait, id))) + .map((wait) => + operation.onlyIfMissing !== true && + operation.taskIds.some((id) => matches(wait, id)) && + wait.staleTimeoutMs !== operation.staleTimeoutMs + ? { ...wait, staleTimeoutMs: operation.staleTimeoutMs } + : wait, + ), ...added.map((taskId) => ({ kind: operation.kind, taskId, staleTimeoutMs: operation.staleTimeoutMs, lastProgressAtMs: nowMs, + ...(providerThreadId === undefined ? {} : { providerThreadId }), + ...(operation.onlyIfMissing === true ? { registeredBy: command.commandId } : {}), })), ]; break; } case "clear": next = waits.filter( - (wait) => wait.kind !== operation.kind || !operation.taskIds.includes(wait.taskId), + (wait) => + wait.kind !== operation.kind || + !operation.taskIds.includes(wait.taskId) || + (operation.registeredBy !== undefined && wait.registeredBy !== operation.registeredBy), ); break; case "remote-progress": @@ -4318,119 +4598,64 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio next = []; break; } + activeRunId = shell.activeRunId; const tasks = yield* projectionStore - .getThreadRecords(threadId, ["subagents", "providerThreads"], { - subagentIds: waits.flatMap((wait) => - wait.kind === "delegate" ? [NodeId.make(wait.taskId)] : [], - ), - }) + .getThreadRecords(threadId, ["subagents", "providerThreads"], { openSubagentsOnly: true }) .pipe(mapDispatchError(command)); const parentHeld = waitIntentionallyHeld(shell, nowMs); const provider = tasks.providerThreads.find( (provider) => provider.id === thread.activeProviderThreadId, ); - const roster = provider?.pendingBackgroundTasks ?? []; const registrations = [...waits]; - for (const task of roster) { + for (const task of provider?.pendingBackgroundTasks ?? []) { if ( - task.kind !== "monitor" || + provider === undefined || task.awaited !== true || - waits.some((wait) => wait.kind === "background" && wait.taskId === task.taskId) + waits.some( + (wait) => + wait.kind === "background" && + wait.taskId === task.taskId && + (wait.providerThreadId ?? provider.id) === provider.id, + ) ) continue; registrations.push({ kind: "background", taskId: task.taskId, staleTimeoutMs: BACKGROUND_WAIT_STALE_MINUTES * 60_000, - lastProgressAtMs: - task.progressAtMs ?? DateTime.toEpochMillis(provider?.updatedAt ?? now), + lastProgressAtMs: task.progressAtMs ?? DateTime.toEpochMillis(provider.updatedAt), + providerThreadId: provider.id, + backgroundObserved: true, + }); + } + for (const task of tasks.subagents) { + if ( + !isOpenStalenessDelegate(task) || + (task.completionWake !== "settled_only" && task.waitedBeforeRecovery !== true) || + waits.some((wait) => wait.kind === "delegate" && wait.taskId === task.id) + ) + continue; + registrations.push({ + kind: "delegate", + taskId: task.id, + staleTimeoutMs: BACKGROUND_WAIT_STALE_MINUTES * 60_000, + lastProgressAtMs: DateTime.toEpochMillis(task.startedAt ?? task.updatedAt), }); } const retained: ThreadStalenessWait[] = []; for (const wait of registrations) { - let progressAtMs = wait.lastProgressAtMs; - let state = "pending"; - let childLink: string | undefined; - let held = parentHeld; - if (wait.kind === "background") { - const task = roster.find( - (task) => task.taskId === wait.taskId && task.awaited === true, - ); - if (task === undefined) { - // The provider's roster event and the MCP registration can commit in either order. - if (nowMs < wait.lastProgressAtMs + 60_000) retained.push(wait); - continue; - } - state = task.kind; - const item = - task.itemId === undefined - ? null - : yield* projectionStore - .getTurnItem({ - threadId: task.sourceThreadId ?? threadId, - itemId: task.itemId, - }) - .pipe(mapDispatchError(command)); - progressAtMs = Math.max( - progressAtMs, - task.progressAtMs ?? 0, - item === null ? 0 : DateTime.toEpochMillis(item.updatedAt), - ); - } else { - const task = tasks.subagents.find( - (task) => task.id === wait.taskId && task.origin === "app_owned", - ); - if ( - task === undefined || - task.result !== null || - task.completionDelivery?.state === "disposed" || - task.status === "completed" || - task.status === "failed" || - task.status === "interrupted" || - task.status === "cancelled" - ) - continue; - state = task.status; - if (task.remoteChild !== undefined) { - childLink = formatThreadLink(task.remoteChild, task.remoteChild.title); - held ||= wait.remoteHeld === true; - } else if (task.childThreadId !== null) { - const child = yield* projectionStore - .getThreadShell(task.childThreadId) - .pipe(mapDispatchError(command)); - if ( - child === null || - child.deletedAt !== null || - child.archivedAt !== null || - child.settledOverride === "settled" - ) - continue; - childLink = formatThreadLink( - { environmentId: null, threadId: child.id }, - child.title, - ); - state = child.status; - held ||= waitIntentionallyHeld(child, nowMs); - const itemActivity = yield* projectionStore - .getWaitActivityMs(child.id, child.latestRunId) - .pipe(mapDispatchError(command)); - progressAtMs = Math.max(progressAtMs, waitActivityMs(child), itemActivity); - } - } - const rearmed = progressAtMs > wait.lastProgressAtMs; - const { alerted: _, ...registration } = wait; - const current = rearmed ? { ...registration, lastProgressAtMs: progressAtMs } : wait; - const idleMs = nowMs - current.lastProgressAtMs; - if (!held && !current.alerted && idleMs >= current.staleTimeoutMs) { + const observation = yield* observeStalenessWait( + threadId, + wait, + provider, + tasks.subagents, + nowMs, + ).pipe(mapDispatchError(command)); + if (observation === null) continue; + const { current, diagnostic, held } = observation; + if (!parentHeld && !held && !current.alerted && diagnostic !== undefined) { retained.push({ ...current, alerted: true }); - stale.push({ - taskId: wait.taskId, - kind: wait.kind, - state, - idleMinutes: Math.floor(idleMs / 60_000), - lastProgressAtMs: current.lastProgressAtMs, - ...(childLink === undefined ? {} : { childLink }), - }); + stale.push(diagnostic); } else { retained.push(current); } @@ -4451,11 +4676,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio payload: { ...thread, stalenessWaits: next }, }); if (stale.length === 0) return; - const diagnostic = yield* encodeWaitStaleDiagnostic({ - type: "wait_stale_timeout", - waits: stale.map(({ lastProgressAtMs: _, ...diagnostic }) => diagnostic), - }).pipe(Effect.orDie); - const text = `${diagnostic}\n\nCheck why this work is quiet. T3 Code keeps its normal completion wake armed and reports staleness again only after progress.`; + const { text, notification } = yield* waitStaleNotice(stale); + if (activeRunId !== null) { + yield* emitDeadlineNotice(command, events, activeRunId, now, notification.summary, text); + return; + } yield* dispatchMessage( { type: "message.dispatch", @@ -4464,18 +4689,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio messageId: MessageId.make(`message:${command.commandId}`), text, attachments: [], - notification: { - source: { - kind: "monitor", - staleWaits: stale.map(({ kind, taskId, lastProgressAtMs }) => ({ - kind, - taskId, - lastProgressAtMs, - })), - }, - outcome: "updated", - summary: `No progress on ${stale.length === 1 ? "one wait" : `${stale.length} waits`}`, - }, + notification, dispatchMode: { type: "queue_after_active" }, createdBy: "agent", creationSource: "server", @@ -4543,11 +4757,62 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: "The pull request watch ended or its thread settled while it was read.", }); } - for (const { entry } of entries) { + const hasDeadline = entries.some(({ entry }) => entry.staleProgressAt !== undefined); + const shell = hasDeadline + ? yield* projectionStore.getThreadShell(thread.id).pipe(mapDispatchError(command)) + : null; + const now = yield* DateTime.now; + const nowMs = DateTime.toEpochMillis(now); + let suppressDeadline = false; + for (const { entry, link } of entries) { const { includesRemarks: _, ...mutation } = entry; - yield* dispatchThreadMutation(mutation, events, effects); + if ( + entry.staleProgressAt === undefined || + link?.watch === undefined || + entry.watch?.staleness === undefined + ) { + yield* dispatchThreadMutation(mutation, events, effects); + continue; + } + const existing = pullRequestWatchStaleness(link.watch); + const { alerted: _mark, ...progress } = entry.watch.staleness; + if (existing.lastProgressAt !== entry.staleProgressAt) { + suppressDeadline = true; + continue; + } + const held = + shell === null || + waitIntentionallyHeld(shell, nowMs) || + outdated[0] || + nowMs - Date.parse(progress.lastProgressAt) < existing.staleTimeoutMs; + suppressDeadline ||= held || existing.alerted === true; + yield* dispatchThreadMutation( + { + ...mutation, + watch: { + ...entry.watch, + staleness: { + ...progress, + ...(existing.alerted === true || !held ? { alerted: true } : {}), + }, + }, + }, + events, + effects, + ); + } + if (wake === undefined || outdated[0] || suppressDeadline) return; + if (hasDeadline && shell?.activeRunId != null) { + yield* emitDeadlineNotice( + command, + events, + shell.activeRunId, + now, + wake.notification.summary, + wake.text, + ); + return; } - if (wake === undefined || outdated[0]) return; const { sections, ...wakeMessage } = wake; const stamps = entries.map(({ entry, key }, index) => ({ ...key, @@ -5659,47 +5924,57 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : existing.watch : !command.watching ? undefined - : (existing.watch ?? { - startedAt, - staleness: { - staleTimeoutMs: command.staleTimeoutMs ?? PR_WATCH_STALE_MINUTES * 60_000, - lastProgressAt: startedAt, - }, - headSha: null, - failedChecks: [], - passed: false, - passedChecks: [], - conflicting: false, - // Watching again must not repeat check or conflict news the last watch told. - ...(existing.endedWatch && { - headSha: existing.endedWatch.headSha, - failedChecks: existing.endedWatch.failedChecks, - passed: existing.endedWatch.passed, - passedChecks: existing.endedWatch.passedChecks, - conflicting: existing.endedWatch.conflicting, - rebaseRequired: existing.endedWatch.rebaseRequired, - }), - awaitingBaseline: existing.endedWatch - ? existing.endedWatch.awaitingBaseline - : "all", - ...(existing.endedWatch?.owedChecks !== undefined && { - owedChecks: existing.endedWatch.owedChecks, - }), - ...(existing.endedWatch?.awaitingApproval !== undefined && { - awaitingApproval: existing.endedWatch.awaitingApproval, - }), - ...(existing.endedWatch?.approvalAnnounced !== undefined && { - approvalAnnounced: existing.endedWatch.approvalAnnounced, - }), - // A finished-checks answer may be an older head's; a fresh read decides. - ...(existing.endedWatch?.checksPending === true && { checksPending: true }), - ...(existing.endedWatch?.checksAwaitedSince !== undefined && { - checksAwaitedSince: existing.endedWatch.checksAwaitedSince, - }), - remarksThrough: startedAt, - remarkIds: [], - wakes: 0, - }); + : existing.watch !== undefined + ? command.staleTimeoutMs === undefined + ? existing.watch + : { + ...existing.watch, + staleness: { + ...pullRequestWatchStaleness(existing.watch), + staleTimeoutMs: command.staleTimeoutMs, + }, + } + : { + startedAt, + staleness: { + staleTimeoutMs: command.staleTimeoutMs ?? PR_WATCH_STALE_MINUTES * 60_000, + lastProgressAt: startedAt, + }, + headSha: null, + failedChecks: [], + passed: false, + passedChecks: [], + conflicting: false, + // Watching again must not repeat check or conflict news the last watch told. + ...(existing.endedWatch && { + headSha: existing.endedWatch.headSha, + failedChecks: existing.endedWatch.failedChecks, + passed: existing.endedWatch.passed, + passedChecks: existing.endedWatch.passedChecks, + conflicting: existing.endedWatch.conflicting, + rebaseRequired: existing.endedWatch.rebaseRequired, + }), + awaitingBaseline: existing.endedWatch + ? existing.endedWatch.awaitingBaseline + : "all", + ...(existing.endedWatch?.owedChecks !== undefined && { + owedChecks: existing.endedWatch.owedChecks, + }), + ...(existing.endedWatch?.awaitingApproval !== undefined && { + awaitingApproval: existing.endedWatch.awaitingApproval, + }), + ...(existing.endedWatch?.approvalAnnounced !== undefined && { + approvalAnnounced: existing.endedWatch.approvalAnnounced, + }), + // A finished-checks answer may be an older head's; a fresh read decides. + ...(existing.endedWatch?.checksPending === true && { checksPending: true }), + ...(existing.endedWatch?.checksAwaitedSince !== undefined && { + checksAwaitedSince: existing.endedWatch.checksAwaitedSince, + }), + remarksThrough: startedAt, + remarkIds: [], + wakes: 0, + }; if (watch === existing.watch && links === linked) return thread; const final = command.type === "thread.pull-request-watch.sync" && watch === undefined @@ -16353,6 +16628,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.type === "thread.visit" || // A read can answer a watch again before a push's reopen lands; nothing is left to clear. command.type === "thread.pull-request-watch.checks-reopen" || + (command.type === "thread.pull-request-watch.sync" && + command.staleProgressAt !== undefined) || command.type === "thread.wait-staleness.update" || command.type === "thread.interrupt.unresponsive" || command.type === "thread.stop" || diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 9e222c698e31b..54489aaa3ab89 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -383,6 +383,7 @@ export interface ProjectionRecordFilter { readonly runtimeRequestStatuses?: ReadonlyArray; readonly contextTransferStatuses?: ReadonlyArray; readonly subagentIds?: ReadonlyArray; + readonly openSubagentsOnly?: true; readonly subagentRunIds?: ReadonlyArray; readonly subagentChildThreadIds?: ReadonlyArray; readonly nodeIds?: ReadonlyArray; @@ -4160,6 +4161,7 @@ export const layer: Layer.Layer = SELECT payload_json FROM orchestration_v2_projection_subagents AS subagent WHERE ${threadColumn(filter?.subagentIds ?? filter?.subagentChildThreadIds)} = ${threadId} + ${filter?.openSubagentsOnly === true ? sql`AND subagent.status IN ('pending', 'running', 'waiting')` : sql``} ${filter?.subagentIds === undefined ? sql`` : sql`AND subagent_id IN (SELECT value FROM json_each(${encodeIdList(filter.subagentIds)}))`} ${filter?.subagentChildThreadIds === undefined ? sql`` : sql`AND child_thread_id IN (SELECT value FROM json_each(${encodeIdList(filter.subagentChildThreadIds)}))`} ${filter?.subagentRunIds === undefined ? sql`` : sql`AND run_id IN (SELECT value FROM json_each(${encodeIdList(filter.subagentRunIds)}))`} @@ -9247,12 +9249,21 @@ export const layer: Layer.Layer = OR ( json_extract(t.payload_json, '$.settledAt') IS NULL AND json_extract(t.payload_json, '$.settledOverride') IS NOT 'settled' - AND EXISTS ( - SELECT 1 FROM orchestration_v2_projection_provider_threads p, - json_each(p.payload_json, '$.pendingBackgroundTasks') task - WHERE p.provider_thread_id = t.active_provider_thread_id - AND json_extract(task.value, '$.kind') = 'monitor' - AND json_extract(task.value, '$.awaited') = 1 + AND ( + EXISTS ( + SELECT 1 FROM orchestration_v2_projection_provider_threads p, + json_each(p.payload_json, '$.pendingBackgroundTasks') task + WHERE p.provider_thread_id = t.active_provider_thread_id + AND json_extract(task.value, '$.awaited') = 1 + ) OR EXISTS ( + SELECT 1 FROM orchestration_v2_projection_subagents task + WHERE task.thread_id = t.thread_id AND task.origin = 'app_owned' + AND task.status IN ('pending', 'running', 'waiting') + AND task.completion_delivery_state IS NOT 'disposed' + AND json_extract(task.payload_json, '$.result') IS NULL + AND (json_extract(task.payload_json, '$.completionWake') = 'settled_only' + OR json_extract(task.payload_json, '$.waitedBeforeRecovery') = 1) + ) ) ) ) @@ -9268,6 +9279,7 @@ export const layer: Layer.Layer = SELECT max(updated_at) AS activity FROM orchestration_v2_projection_turn_items WHERE thread_id = ${threadId} AND run_id = ${runId} AND type NOT IN ('user_message', 'link_request') + AND turn_item_id NOT LIKE 'item:deadline:%' `; const activity = rows[0]?.activity; return activity == null ? 0 : Date.parse(activity); diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts index ac93bbad696b8..fb43028a88891 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts @@ -833,7 +833,12 @@ export const make = Effect.gen(function* () { driver: task.driver, providerInstanceId: task.providerInstanceId, occurredAt: now, - payload: { ...task, completionWake: "always", updatedAt: now }, + payload: { + ...task, + completionWake: "always", + waitedBeforeRecovery: true, + updatedAt: now, + }, }); } const recoveredNonterminalRunIds = new Set(runs.map((run) => run.id)); diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index ef35265bcd5f1..183a4d2f977cf 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -43,6 +43,7 @@ import { PULL_REQUEST_WATCH_NO_CHECKS_MS, pullRequestWatchMessage, stalePullRequestWatch, + pullRequestWatchStaleness, } from "./pullRequestWatch.ts"; /** Checks take minutes; faster sweeps waste the account's shared host quota. */ @@ -324,7 +325,7 @@ export const make = Effect.gen(function* () { endedWatch?: ThreadPullRequestWatch, ) { const uuid = yield* random.uuidV4(); - yield* engine.dispatch({ + return yield* engine.dispatch({ type: "thread.pull-request-watch.sync", commandId: CommandId.make(`server:pr-watch:${target.thread.id}:${uuid}`), threadId: target.thread.id, @@ -607,8 +608,7 @@ export const make = Effect.gen(function* () { ), ); - const holdStale = ( - group: WatchGroup, + const sendStale = ( target: WatchTarget, watch: ThreadPullRequestWatch, now: number, @@ -624,22 +624,24 @@ export const make = Effect.gen(function* () { ); return stale === undefined ? Effect.succeed(false) - : hold({ - groupKey: group.key, - target, - ...stale, - wake: { - ...stale.wake, - ...(stale.next.staleness === undefined - ? {} - : { staleProgressAt: stale.next.staleness.lastProgressAt }), - }, - }).pipe(Effect.as(true)); + : record(target, stale.next, { + ...stale.wake, + staleProgressAt: pullRequestWatchStaleness(stale.next).lastProgressAt, + }).pipe( + Effect.tap(({ storedEvents }) => + storedEvents.some( + ({ event }) => event.type === "message.updated" || event.type === "turn-item.updated", + ) + ? woke(target) + : Effect.void, + ), + Effect.as(true), + ); }; const checkStaleness = (group: WatchGroup, now: number, observation: "current" | "unavailable") => eachTarget(group, (target) => - holdStale(group, target, target.watch, now, observation).pipe(Effect.asVoid), + sendStale(target, target.watch, now, observation).pipe(Effect.asVoid), ); const readGroup = Effect.fn("PullRequestWatchReactor.readGroup")(function* ( @@ -787,11 +789,11 @@ export const make = Effect.gen(function* () { : { groupKey: group.key, target, next: report.next, wake }, ); } - return holdStale(group, target, report.next, now, "current").pipe( + return sendStale(target, report.next, now, "current").pipe( Effect.flatMap((held) => held || watchesEqual(report.next, target.watch) ? Effect.void - : record(target, report.next), + : record(target, report.next).pipe(Effect.asVoid), ), ); }); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index 8dbbadba2dffb..8be40b9fb8f29 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -643,6 +643,7 @@ it.effect("waitForThread returns the cut run once its continuation is declined", it.effect.each([ "live", "no-match", + "provider-failed", "no-match-clear", "no-session", "unsupported-runtime", @@ -676,6 +677,7 @@ it.effect.each([ updatedAt: now, }; const calls: Array<{ providerThreadId: ProviderThreadId; awaited: boolean }> = []; + const order: string[] = []; const runtime = { driver, providerSessionId, @@ -687,11 +689,18 @@ it.effect.each([ readonly taskIds: ReadonlyArray; readonly awaited: boolean; }) => - Effect.sync(() => { + Effect.gen(function* () { + order.push("provider"); calls.push({ providerThreadId: input.providerThread.id, awaited: input.awaited, }); + if (state === "provider-failed") { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver, + detail: "Enrollment unavailable", + }); + } return { matched: input.taskIds.filter((taskId) => taskId === "tests") }; }), }), @@ -701,7 +710,12 @@ it.effect.each([ Layer.provide( Layer.mergeAll( Layer.mock(Orchestrator.OrchestratorV2)({ - dispatch: () => Effect.succeed({ sequence: 0, storedEvents: [] }), + dispatch: (command) => + Effect.sync(() => { + if (command.type === "thread.wait-staleness.update") + order.push(command.operation.type); + return { sequence: 0, storedEvents: [] }; + }), getThreadRecords: () => Effect.succeed({ thread: { @@ -728,16 +742,22 @@ it.effect.each([ threadId, taskIds: state.startsWith("no-match") ? ["finished"] : ["tests", "finished"], awaited: state !== "no-match-clear", + staleTimeoutMinutes: 7, }) .pipe(Effect.result); }).pipe(Effect.provide(Layer.merge(layerTest, ThreadCommandExecutor.layer))); if (state === "live") { + expect(order.slice(0, 2)).toEqual(["register", "provider"]); expect(result).toMatchObject({ success: { matched: ["tests"], unmatched: ["finished"] }, }); expect(calls).toEqual([{ providerThreadId, awaited: true }]); + } else if (state === "provider-failed") { + expect(order).toEqual(["register", "provider", "clear"]); + expect(result).toMatchObject({ failure: { reason: "failed" } }); } else if (state === "no-match") { + expect(order).toEqual(["register", "provider", "clear"]); expect(result).toMatchObject({ failure: { _tag: "ThreadManagementBackgroundWaitError", reason: "unmatched" }, }); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index c7760456a60b4..4e43c231c683e 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1747,7 +1747,35 @@ const make = Effect.gen(function* () { reason: "unsupported", }); } - const { matched } = yield* runtime.value + const uuid = SecureRandom.uuidV4Unsafe(); + const registrationId = CommandId.make(`server:background-wait:${uuid}:prepare`); + const dispatchWait = ( + commandId: CommandId, + operation: Extract< + OrchestrationV2ServerCommand, + { type: "thread.wait-staleness.update" } + >["operation"], + ) => + orchestrator + .dispatch({ + type: "thread.wait-staleness.update", + commandId, + threadId: input.threadId, + operation, + }) + .pipe(Effect.mapError(unavailable)); + const timeout = staleTimeoutMs(input.staleTimeoutMinutes, BACKGROUND_WAIT_STALE_MINUTES); + if (input.awaited) { + yield* dispatchWait(registrationId, { + type: "register", + kind: "background", + taskIds: input.taskIds, + staleTimeoutMs: timeout, + providerThreadId: providerThread.id, + onlyIfMissing: true, + }); + } + const result = yield* runtime.value .awaitBackgroundTasks({ providerThread, taskIds: input.taskIds, awaited: input.awaited }) .pipe( Effect.timeout("15 seconds"), @@ -1759,35 +1787,39 @@ const make = Effect.gen(function* () { cause, }), ), + Effect.result, ); + const matched = result._tag === "Success" ? result.success.matched : []; + const matchedIds = new Set(matched); + const unmatched = input.taskIds.filter((taskId) => !matchedIds.has(taskId)); + if (input.awaited && unmatched.length > 0) { + yield* dispatchWait(CommandId.make(`${registrationId}:reconcile`), { + type: "clear", + kind: "background", + taskIds: unmatched, + registeredBy: registrationId, + }); + } + if (result._tag === "Failure") return yield* result.failure; if (input.awaited && matched.length === 0) { return yield* new ThreadManagementBackgroundWaitError({ threadId: input.threadId, reason: "unmatched", }); } - const taskIds = input.awaited ? matched : input.taskIds; - const uuid = SecureRandom.uuidV4Unsafe(); - yield* orchestrator - .dispatch({ - type: "thread.wait-staleness.update", - commandId: CommandId.make(`server:background-wait:${uuid}`), - threadId: input.threadId, - operation: input.awaited - ? { - type: "register", - kind: "background", - taskIds, - staleTimeoutMs: staleTimeoutMs( - input.staleTimeoutMinutes, - BACKGROUND_WAIT_STALE_MINUTES, - ), - } - : { type: "clear", kind: "background", taskIds }, - }) - .pipe(Effect.mapError(unavailable)); - const matchedIds = new Set(matched); - return { matched, unmatched: input.taskIds.filter((taskId) => !matchedIds.has(taskId)) }; + yield* dispatchWait( + CommandId.make(`${registrationId}:finish`), + input.awaited + ? { + type: "register", + kind: "background", + taskIds: matched, + staleTimeoutMs: timeout, + providerThreadId: providerThread.id, + } + : { type: "clear", kind: "background", taskIds: input.taskIds }, + ); + return { matched, unmatched }; }); const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = Effect.fn( diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.ts b/apps/server/src/orchestration-v2/pullRequestWatch.ts index f8ecddd114c74..806ad311f6841 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.ts @@ -38,7 +38,7 @@ const isFailedCheck = (check: PullRequestCheck) => const workflowRunOf = (url: string | null) => url?.match(/^.*\/actions\/runs\/\d+/)?.[0] ?? null; const approvalKey = (check: PullRequestCheck) => workflowRunOf(check.url) ?? check.name; -const stalenessOf = (watch: ThreadPullRequestWatch) => +export const pullRequestWatchStaleness = (watch: ThreadPullRequestWatch) => watch.staleness ?? { staleTimeoutMs: PR_WATCH_STALE_MINUTES * 60_000, lastProgressAt: watch.startedAt, @@ -51,7 +51,7 @@ export function stalePullRequestWatch( now: number, hostObservation: "current" | "unavailable", ): { readonly next: ThreadPullRequestWatch; readonly wake: PullRequestWatchWake } | undefined { - const staleness = stalenessOf(watch); + const staleness = pullRequestWatchStaleness(watch); const idleMs = now - Date.parse(staleness.lastProgressAt); if (staleness.alerted || idleMs < staleness.staleTimeoutMs) return; const idleMinutes = Math.floor(idleMs / 60_000); @@ -269,7 +269,7 @@ export function evaluatePullRequestWatch( const commentsOnly = changes.length > 0 && changes.every((change) => change.kind === "remarks"); const progress = headMoved || (changes.length > 0 && !commentsOnly); const wakes = (progress ? 0 : watch.wakes) + (commentsOnly ? 1 : 0); - const previous = stalenessOf(watch); + const previous = pullRequestWatchStaleness(watch); const checkState = unread || (checks.length === 0 && !headMoved && previous.checks?.length) ? previous.checks diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index ed6fca25d602a..ef1127644d182 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -1,3 +1,15 @@ +import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts"; +import { makeThreadInbox } from "@t3tools/contracts"; +import * as HttpClient from "effect/http/HttpClient"; +import * as ModelAlertReactor from "./ModelAlertReactor.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as PeerMcpClient from "../peer/PeerMcpClient.ts"; +import * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; +import * as McpToolAccess from "../mcp/McpToolAccess.ts"; +import * as McpToolAccessTestkit from "../mcp/McpToolAccess.testkit.ts"; +import * as PullRequestsHandlers from "../mcp/toolkits/pullRequests/handlers.ts"; +import { PullRequestsToolkit } from "../mcp/toolkits/pullRequests/tools.ts"; +import * as PullRequestWatchService from "../pullRequest/PullRequestWatchService.ts"; import { PullRequestProviderError } from "@t3tools/source-control-core/server/PullRequestProvider"; import { SourceControlProviderKind } from "@t3tools/contracts"; import { limitRecoveryCommand } from "./UsageLimitRecoveryWorker.ts"; @@ -4739,6 +4751,554 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + const makeDeadlineSweep = ModelAlertReactor.make.pipe( + Effect.provide( + Layer.mergeAll( + layerServerConfig, + ServerSettings.layerTest(), + Layer.mock(ServerEnvironment.ServerEnvironment)({ + getEnvironmentId: Effect.succeed(EnvironmentId.make("deadline-test")), + }), + Layer.mock(PeerMcpClient.PeerMcpClient)({}), + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected webhook")), + ), + ).pipe(Layer.provideMerge(Layer.merge(NodeServices.layer, NodeCrypto.layer))), + ), + ); + + const startDeadlineParent = Effect.fnUntraced(function* (name: string) { + const engine = yield* Orchestrator.OrchestratorV2; + const { threadId, key, watch } = yield* createWatchedThread(name); + yield* engine.dispatch({ + type: "message.dispatch", + createdBy: "agent", + creationSource: "mcp", + commandId: CommandId.make(`${threadId}:start`), + threadId, + messageId: MessageId.make(`${threadId}:start`), + text: "Wait for work.", + attachments: [], + dispatchMode: { type: "start_immediately" }, + }); + const { + runs: [run], + providerThreads: [provider], + } = yield* engine.getThreadRecords(threadId, ["runs", "providerThreads"]); + assert.isDefined(run); + assert.isDefined(provider); + return { threadId, key, watch, run, provider }; + }); + + it.effect( + "delivers a deadline notice to a permanently active parent through the real sweep", + () => + Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const { threadId, run } = yield* startDeadlineParent("hung-deadline"); + const now = yield* DateTime.now; + yield* sink.write({ + events: [ + { + id: EventId.make(`${threadId}:running`), + type: "run.updated", + threadId, + runId: run.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...run, status: "running", startedAt: now }, + }, + ], + }); + yield* engine.dispatch({ + type: "delegated_task.remote.request", + commandId: CommandId.make(`${threadId}:delegate`), + parentThreadId: threadId, + parentRunId: run.id, + parentNodeId: run.rootNodeId!, + task: "Work in the linked environment.", + driver: ProviderDriverKind.make("remote"), + modelSelection, + completionWake: "settled_only", + staleTimeoutMs: 5 * 60_000, + remoteChild: { + environmentId: EnvironmentId.make("child-env"), + threadId: ThreadId.make("child-thread"), + label: "Child", + }, + }); + const reactor = yield* makeDeadlineSweep; + yield* TestClock.adjust("5 minutes"); + const afterSequence = yield* engine.getThreadEventSequence(threadId); + yield* reactor.sweep; + const read = yield* engine.getThreadRecords(threadId, ["runs", "turnItems", "messages"]); + assert.deepEqual( + read.runs.map(({ id, status }) => [id, status]), + [[run.id, "running"]], + ); + const notices = read.turnItems.filter( + (item) => item.type === "system_notice" && item.message.includes("wait_stale_timeout"), + ); + assert.lengthOf(notices, 1); + const timeline = yield* engine.getTimelinePage(threadId, { view: "activity", limit: 20 }); + assert.isTrue(timeline.items.some(({ item }) => item.id === notices[0]?.id)); + const delivered = yield* sink.stream({ threadId, afterSequence }).pipe( + Stream.filter( + (stored) => + stored.event.type === "turn-item.updated" && + stored.event.payload.id === notices[0]?.id, + ), + Stream.take(1), + Stream.runCollect, + ); + assert.lengthOf(delivered, 1); + assert.lengthOf(read.messages, 1); + yield* TestClock.adjust("1 hour"); + yield* reactor.sweep; + assert.lengthOf( + (yield* engine.getThreadRecords(threadId, ["turnItems"])).turnItems.filter( + (item) => item.type === "system_notice" && item.message.includes("wait_stale_timeout"), + ), + 1, + ); + }), + ); + + it.effect.each(["claudeAgent", "opencode"] as const)( + "discovers legacy ordinary %s background work and preserves a delayed explicit deadline across replay", + (driver) => + Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const projection = yield* ProjectionStore.ProjectionStoreV2; + const replay = yield* ProjectionReplay.ProjectionReplay; + const { threadId, provider } = yield* startDeadlineParent(`legacy-${driver}`); + const now = yield* DateTime.now; + const roster = (suffix: string, tasks: typeof provider.pendingBackgroundTasks) => + sink.write({ + events: [ + { + id: EventId.make(`${threadId}:${suffix}`), + type: "provider-thread.updated", + threadId, + driver: ProviderDriverKind.make(driver), + providerInstanceId: provider.providerInstanceId, + occurredAt: now, + payload: { + ...provider, + driver: ProviderDriverKind.make(driver), + ...(tasks === undefined ? {} : { pendingBackgroundTasks: tasks }), + }, + }, + ], + }); + const legacy = { taskId: "legacy", kind: "command", awaited: true } as const; + yield* roster("legacy", [legacy]); + assert.include(yield* projection.listStalenessWaitThreads, threadId); + const sweep = yield* makeDeadlineSweep; + yield* sweep.sweep; + const prepare = { + type: "thread.wait-staleness.update", + threadId, + commandId: CommandId.make(`${threadId}:prepare`), + operation: { + type: "register", + kind: "background", + taskIds: ["delayed"], + staleTimeoutMs: 5 * 60_000, + }, + } as const; + // The same command can be replayed after the provider call did not return to MCP. + yield* engine.dispatch(prepare); + assert.isTrue((yield* replay.rebuild).valid); + yield* engine.dispatch(prepare); + yield* TestClock.adjust("2 minutes"); + yield* sweep.sweep; + yield* roster("delayed", [legacy, { taskId: "delayed", kind: "command", awaited: true }]); + yield* TestClock.adjust("3 minutes"); + yield* sweep.sweep; + const read = yield* engine.getThreadRecords(threadId, ["turnItems"]); + assert.deepEqual( + read.thread.stalenessWaits?.map(({ taskId, staleTimeoutMs, alerted }) => [ + taskId, + staleTimeoutMs, + alerted, + ]), + [ + ["legacy", 45 * 60_000, undefined], + ["delayed", 5 * 60_000, true], + ], + ); + assert.include( + read.turnItems + .flatMap((item) => (item.type === "system_notice" ? [item.message] : [])) + .join(" "), + '"taskId":"delayed"', + ); + yield* roster("cancelled", []); + yield* TestClock.adjust("1 minute"); + yield* sweep.sweep; + assert.deepEqual((yield* engine.getThreadRecords(threadId, [])).thread.stalenessWaits, []); + }), + ); + + it.effect("rebuilds a queued group from the children still stale at delivery", () => + Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const { threadId, run } = yield* startDeadlineParent("queued-stale-group"); + for (const name of ["done", "held", "progress", "quiet"]) { + const child = yield* createWatchedThread(`queued-child-${name}`); + yield* engine.dispatch({ + type: "delegated_task.remote.request", + commandId: CommandId.make(`${threadId}:${name}`), + parentThreadId: threadId, + parentRunId: run.id, + parentNodeId: run.rootNodeId!, + task: name, + driver: ProviderDriverKind.make("remote"), + modelSelection, + completionWake: "settled_only", + staleTimeoutMs: 5 * 60_000, + remoteChild: { + environmentId: EnvironmentId.make("child-env"), + threadId: child.threadId, + label: name, + }, + }); + } + const { thread, subagents } = yield* engine.getThreadRecords(threadId, ["subagents"]); + const waits = thread.stalenessWaits!; + yield* TestClock.adjust("5 minutes"); + const now = yield* DateTime.now; + yield* sink.write({ + events: [ + { + id: EventId.make(`${threadId}:marks`), + type: "thread.metadata-updated", + threadId, + occurredAt: now, + providerInstanceId: thread.providerInstanceId, + payload: { + ...thread, + stalenessWaits: waits.map((wait) => ({ ...wait, alerted: true })), + }, + }, + ...subagents.map((task): OrchestrationV2DomainEvent => ({ + id: EventId.make(`${task.id}:local`), + type: "subagent.updated", + threadId, + runId: run.id, + nodeId: task.id, + providerInstanceId: task.providerInstanceId, + driver: task.driver, + occurredAt: now, + payload: + task.prompt === "done" + ? { ...task, result: "done", status: "completed" } + : { ...task, remoteChild: undefined, childThreadId: task.remoteChild!.threadId }, + })), + ], + }); + const messageId = MessageId.make(`${threadId}:queued`); + yield* engine.dispatch({ + type: "message.dispatch", + createdBy: "agent", + creationSource: "server", + commandId: CommandId.make(`${threadId}:queued`), + threadId, + messageId, + text: "Original grouped notice: done, held, progress, quiet", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + notification: { + source: { + kind: "monitor", + staleWaits: waits.map(({ taskId, kind, lastProgressAtMs }) => ({ + taskId, + kind, + lastProgressAtMs, + })), + }, + outcome: "updated", + summary: "No progress on 4 waits", + }, + }); + const childId = (name: string) => + subagents.find((task) => task.prompt === name)!.remoteChild!.threadId; + yield* engine.dispatch({ + type: "thread.snooze", + commandId: CommandId.make(`${threadId}:snooze`), + threadId: childId("held"), + snoozedUntil: DateTime.formatIso(DateTime.add(now, { hours: 1 })), + }); + yield* engine.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${threadId}:child-progress`), + threadId: childId("progress"), + messageId: MessageId.make(`${threadId}:child-progress`), + text: "Child resumes work.", + attachments: [], + dispatchMode: { type: "start_immediately" }, + }); + const afterSequence = yield* engine.getThreadEventSequence(threadId); + yield* sink.write({ + events: [ + { + id: EventId.make(`${threadId}:end`), + type: "run.updated", + threadId, + runId: run.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...run, status: "completed", completedAt: now }, + }, + ], + }); + yield* sink.stream({ threadId, afterSequence }).pipe( + Stream.filter( + ({ event }) => + event.type === "run.updated" && + event.payload.userMessageId === messageId && + event.payload.status === "starting", + ), + Stream.take(1), + Stream.runDrain, + ); + const { messages } = yield* engine.getThreadRecords(threadId, ["messages"]); + const delivered = messages.find((message) => message.id === messageId); + assert.equal(delivered?.notification?.summary, "No progress on one wait"); + assert.include(delivered?.text, subagents.find((task) => task.prompt === "quiet")!.id); + for (const task of subagents.filter((task) => task.prompt !== "quiet")) + assert.notInclude(delivered?.text, task.id); + }), + ); + + it.effect.each([false, true])( + "updates an existing PR watch timeout through MCP (legacy=%s)", + (legacy) => + Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const { threadId, key, watch } = yield* createWatchedThread(`repeat-watch-${legacy}`); + const { staleness: _, ...oldWatch } = watch; + const baseline = { + ...oldWatch, + headSha: "head-offline", + failedChecks: ["test"], + remarkIds: ["remark-offline"], + }; + const staleness = { + staleTimeoutMs: 17 * 60_000, + lastProgressAt: watch.startedAt, + alerted: true as const, + }; + yield* engine.dispatch({ + type: "thread.pull-request-watch.sync", + commandId: CommandId.make(`${threadId}:baseline`), + threadId, + ...key, + startedAt: watch.startedAt, + watch: legacy ? baseline : { ...baseline, staleness }, + }); + const read = engine + .getThreadShell(threadId) + .pipe(Effect.map((shell) => shell?.pullRequests?.[0]?.watch)); + const dependencies = Layer.mergeAll( + Layer.succeed(Orchestrator.OrchestratorV2, engine), + Layer.mock(ProjectService.ProjectService)({ getShell: () => Effect.succeedNone }), + Layer.mock(PullRequestService.PullRequestService)({}), + Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}), + McpToolAccessTestkit.liveThreadsLayer, + NodeCrypto.layer, + ); + const watchDependencies = PullRequestWatchService.layer.pipe( + Layer.provideMerge(dependencies), + ); + const toolkit = yield* PullRequestsToolkit.pipe( + Effect.provide( + McpToolAccess.HandlersLayer.layer(PullRequestsHandlers.layer).pipe( + Layer.provide(watchDependencies), + ), + ), + ); + const call = (minutes?: number) => + toolkit + .handle("watch_pull_request", { + threadId, + url: `https://github.com/${key.repository}/pull/${key.number}`, + ...(minutes === undefined ? {} : { staleTimeoutMinutes: minutes }), + }) + .pipe( + Stream.unwrap, + Stream.runCollect, + Effect.provideService(McpInvocationContext.McpInvocationContext, { + environmentId: EnvironmentId.make("repeat-watch"), + requestNamespace: "repeat-watch", + capabilities: new Set(["pull-requests"]), + issuedAt: 0, + thread: { + threadId, + providerSessionId: "test", + providerInstanceId: modelSelection.instanceId, + }, + client: undefined, + }), + Effect.provide(watchDependencies), + ); + yield* call(8); + const expected = { + ...baseline, + staleness: { + lastProgressAt: watch.startedAt, + staleTimeoutMs: 8 * 60_000, + ...(legacy ? {} : { alerted: true as const }), + }, + }; + assert.deepEqual(yield* read, expected); + yield* call(); + assert.deepEqual(yield* read, expected); + }), + ); + + it.effect.each(["snooze", "decision"] as const)( + "continues PR tracking during %s and sends other due notices before a slow probe", + (hold) => + Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const delayed = yield* createWatchedThread(`slow-${hold}`); + const quiet = yield* createWatchedThread(`held-${hold}`); + const fast = yield* createWatchedThread(`fast-${hold}`); + for (const { threadId, key, watch } of [delayed, quiet, fast]) { + // Use independent host groups with recognizable, negative-free fixtures. + yield* engine.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make(`${threadId}:unwatch`), + threadId, + ...key, + watching: false, + }); + const number = threadId === delayed.threadId ? 21 : threadId === quiet.threadId ? 22 : 23; + yield* engine.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make(`${threadId}:rewatch`), + threadId, + ...key, + number, + watching: true, + link: { url: `https://github.com/${key.repository}/pull/${number}`, source: "agent" }, + staleTimeoutMs: 5 * 60_000, + }); + yield* engine.dispatch({ + type: "thread.pull-request-watch.sync", + commandId: CommandId.make(`${threadId}:baseline`), + threadId, + ...key, + number, + startedAt: watch.startedAt, + watch: { + ...watch, + awaitingBaseline: "checks", + failedChecks: ["lint"], + headSha: "abc1234def", + staleness: { staleTimeoutMs: 5 * 60_000, lastProgressAt: watch.startedAt }, + }, + }); + } + yield* TestClock.adjust("5 minutes"); + const entered = yield* Deferred.make(); + const releaseHeldRead = yield* Deferred.make(); + const releaseSlow = yield* Deferred.make(); + const host = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(PullRequestService.PullRequestService)({ + watchFingerprint: (input) => + (input.number === 21 ? Deferred.await(releaseSlow) : Effect.void).pipe( + Effect.as(null), + ), + detail: (input) => + (input.number === 22 + ? Deferred.succeed(entered, undefined).pipe( + Effect.andThen(Deferred.await(releaseHeldRead)), + ) + : Effect.void + ).pipe( + Effect.as( + watchedPullRequestDetail({ + projectId: input.projectId, + number: input.number, + at: quiet.watch.startedAt, + }), + ), + ), + activity: () => + Effect.succeed({ + comments: [], + commentCount: 0, + commentsTruncated: false, + reviewThreads: [], + commits: [], + }), + }), + ); + const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host)); + const pass = yield* reactor.sweep.pipe(Effect.forkChild); + yield* Deferred.await(entered); + const now = yield* DateTime.now; + if (hold === "snooze") { + yield* engine.dispatch({ + type: "thread.snooze", + commandId: CommandId.make(`${quiet.threadId}:hold`), + threadId: quiet.threadId, + snoozedUntil: DateTime.formatIso(DateTime.add(now, { hours: 1 })), + }); + } else { + const { thread } = yield* engine.getThreadRecords(quiet.threadId, []); + yield* sink.write({ + events: [ + { + id: EventId.make(`${quiet.threadId}:hold`), + type: "thread.metadata-updated", + threadId: quiet.threadId, + providerInstanceId: thread.providerInstanceId, + occurredAt: now, + payload: { + ...thread, + inbox: { + ...(thread.inbox ?? makeThreadInbox({ actor: null })), + decisionRequest: { + founder: "kameron", + kind: "decision", + question: "Waiting for a decision", + requestedAt: DateTime.formatIso(now), + }, + }, + }, + }, + ], + }); + } + yield* Deferred.succeed(releaseHeldRead, undefined); + yield* TestClock.adjust("1 second"); + const seenBeforeSlow = (yield* engine.getThreadRecords(fast.threadId, ["messages"])) + .messages; + yield* Deferred.succeed(releaseSlow, undefined); + yield* Fiber.join(pass); + const seen = yield* engine.getThreadRecords(quiet.threadId, ["messages"]); + assert.lengthOf(seen.messages, 0); + const tracked = seen.thread.pullRequests?.find((link) => link.number === 22)?.watch + ?.staleness; + assert.isDefined(tracked?.checks); + assert.isUndefined(tracked?.alerted); + assert.include(seenBeforeSlow[0]?.text, "pull_request_watch_stale_timeout"); + }), + ); + it.effect.each([5, undefined])( "uses native task progress and clears the deadline when background work ends (%s minutes)", (customMinutes) => @@ -4813,10 +5373,15 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { operation: { type: "sweep" }, }); const notices = engine - .getThreadRecords(threadId, ["messages"]) + .getThreadRecords(threadId, ["messages", "turnItems"]) .pipe( - Effect.map(({ messages }) => - messages.filter((message) => message.text.includes('"type":"wait_stale_timeout"')), + Effect.map(({ messages, turnItems }) => + [ + ...messages, + ...turnItems.flatMap((item) => + item.type === "system_notice" ? [{ text: item.message }] : [], + ), + ].filter((message) => message.text.includes('"type":"wait_stale_timeout"')), ), ); yield* TestClock.adjust(`${minutes - 1} minutes`); @@ -4836,14 +5401,14 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); - it.effect( - "retains an awaited child deadline across replay and alerts once per quiet period", - () => + it.effect.each([false, true])( + "retains an awaited child deadline across replay and alerts once per quiet period (legacy=%s)", + (legacy) => Effect.gen(function* () { const engine = yield* Orchestrator.OrchestratorV2; const projection = yield* ProjectionStore.ProjectionStoreV2; const maintenance = yield* ProjectionReplay.ProjectionReplay; - const { threadId } = yield* createWatchedThread("delegate-stale"); + const { threadId } = yield* createWatchedThread(`delegate-stale-${legacy}`); yield* engine.dispatch({ type: "message.dispatch", createdBy: "agent", @@ -4866,7 +5431,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { driver: ProviderDriverKind.make("remote"), modelSelection, completionWake: "settled_only", - staleTimeoutMs: 45 * 60_000, + ...(legacy ? {} : { staleTimeoutMs: 45 * 60_000 }), remoteChild: { environmentId: EnvironmentId.make("remote-env"), threadId: ThreadId.make("remote-thread"), @@ -4883,10 +5448,15 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { operation: { type: "sweep" }, }); const notices = engine - .getThreadRecords(threadId, ["messages"]) + .getThreadRecords(threadId, ["messages", "turnItems"]) .pipe( - Effect.map(({ messages }) => - messages.filter((message) => message.text.includes('"type":"wait_stale_timeout"')), + Effect.map(({ messages, turnItems }) => + [ + ...messages, + ...turnItems.flatMap((item) => + item.type === "system_notice" ? [{ text: item.message }] : [], + ), + ].filter((message) => message.text.includes('"type":"wait_stale_timeout"')), ), ); yield* TestClock.adjust("44 minutes"); diff --git a/apps/server/src/pullRequest/PullRequestWatchService.ts b/apps/server/src/pullRequest/PullRequestWatchService.ts index 23e808c58f555..525a979764641 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.ts @@ -164,7 +164,14 @@ const make = Effect.gen(function* () { ...(watching ? { link: { url: target.url, source: "agent" as const }, - staleTimeoutMs: staleTimeoutMs(input.staleTimeoutMinutes, PR_WATCH_STALE_MINUTES), + ...(input.staleTimeoutMinutes === undefined + ? {} + : { + staleTimeoutMs: staleTimeoutMs( + input.staleTimeoutMinutes, + PR_WATCH_STALE_MINUTES, + ), + }), } : {}), }) diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 6c968b99ee630..50221005b49d2 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1110,6 +1110,7 @@ export const OrchestrationV2Subagent = Schema.Struct({ /** Set from the run that produced `result`; informs the parent and takes no action. */ workerAlert: Schema.optional(OrchestrationV2WorkerAlert), completionWake: Schema.optional(Schema.Literals(["always", "settled_only"])), + waitedBeforeRecovery: Schema.optional(Schema.Literal(true)), completionDelivery: Schema.optional(OrchestrationV2DelegatedCompletionTaskDelivery), // The run whose unfinished task was cancelled, committed with its Stop. cancelledRunId: Schema.optional(RunId), @@ -3901,11 +3902,14 @@ const OrchestrationV2InternalCommand = Schema.Union([ kind: ThreadStalenessWait.fields.kind, taskIds: Schema.Array(Schema.String), staleTimeoutMs: PositiveInt, + providerThreadId: Schema.optional(ProviderThreadId), + onlyIfMissing: Schema.optional(Schema.Literal(true)), }), Schema.Struct({ type: Schema.Literal("clear"), kind: ThreadStalenessWait.fields.kind, taskIds: Schema.Array(Schema.String), + registeredBy: Schema.optional(CommandId), }), Schema.Struct({ type: Schema.Literal("remote-progress"), diff --git a/packages/contracts/src/waitStaleness.ts b/packages/contracts/src/waitStaleness.ts index 73c05194c1a11..754784ad5bb1c 100644 --- a/packages/contracts/src/waitStaleness.ts +++ b/packages/contracts/src/waitStaleness.ts @@ -1,4 +1,5 @@ import * as Schema from "effect/Schema"; +import { CommandId, ProviderThreadId } from "./baseSchemas.ts"; export const StaleTimeoutMinutes = Schema.optional(Schema.Finite).annotate({ description: "Idle timeout in minutes. Clamped to 5–1440 minutes.", @@ -13,6 +14,9 @@ export const ThreadStalenessWait = Schema.Struct({ taskId: Schema.String, staleTimeoutMs: Schema.Int, lastProgressAtMs: Schema.Finite, + providerThreadId: Schema.optional(ProviderThreadId), + backgroundObserved: Schema.optional(Schema.Literal(true)), + registeredBy: Schema.optional(CommandId), remoteHeld: Schema.optional(Schema.Boolean), alerted: Schema.optional(Schema.Literal(true)), }); From 419438752a0faf31dccff836c2d8d96582ef0fc2 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 23 Nov 2026 00:34:36 +0000 Subject: [PATCH 5/6] fix(server): compose deadline revalidation with snoozed queues Place the deadline helper with the staleness handlers so the sibling snooze-queue repair applies cleanly. Model: gpt-6.2-sol Task: fix Agent: Codex Lane: codex Harness: t3/codex --- .../src/orchestration-v2/Orchestrator.ts | 184 +++++++++--------- 1 file changed, 92 insertions(+), 92 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index e989099361d17..26eca7bf4c939 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -2663,98 +2663,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); }); - const revalidateQueuedDeadline = Effect.fn("Orchestrator.revalidateQueuedDeadline")(function* ( - projection: OrchestrationV2ThreadProjection, - run: OrchestrationV2Run, - ) { - const message = projection.messages.find((message) => message.id === run.userMessageId); - const source = message?.notification?.source; - const prStamps = monitorPullRequestStamps(source).filter( - (stamp) => stamp.staleProgressAt !== undefined, - ); - if ( - message === undefined || - source?.kind !== "monitor" || - (source.staleWaits === undefined && prStamps.length === 0) - ) - return { type: "keep" } as const; - const thread = projection.thread; - const shell = yield* projectionStore.getThreadShell(thread.id); - if (shell === null || shell.settledAt !== null || shell.settledOverride === "settled") - return { type: "cancel" } as const; - const now = yield* DateTime.now; - const nowMs = DateTime.toEpochMillis(now); - const held = waitIntentionallyHeld(shell, nowMs); - if (source.staleWaits === undefined) { - if (!held) return { type: "keep" } as const; - const links = threadPullRequestsOf(thread).map((link) => { - if ( - !prStamps.some( - (stamp) => - threadPullRequestKeysEqual(stamp, link) && - stamp.watchStartedAt === link.watch?.startedAt && - stamp.staleProgressAt === link.watch?.staleness?.lastProgressAt, - ) || - link.watch?.staleness === undefined - ) - return link; - const { alerted: _, ...progress } = link.watch.staleness; - return { ...link, watch: { ...link.watch, staleness: progress } }; - }); - return { type: "keep", prHeld: true, thread: { ...thread, pullRequests: links } } as const; - } - const tasks = yield* projectionStore.getThreadRecords( - thread.id, - ["subagents", "providerThreads"], - { - subagentIds: source.staleWaits - .filter((stamp) => stamp.kind === "delegate") - .map((stamp) => NodeId.make(stamp.taskId)), - }, - ); - const provider = tasks.providerThreads.find( - (provider) => provider.id === thread.activeProviderThreadId, - ); - const current: StaleWait[] = []; - const rearmed = new Set(); - for (const stamp of source.staleWaits) { - const wait = thread.stalenessWaits?.find( - (wait) => wait.kind === stamp.kind && wait.taskId === stamp.taskId, - ); - if (wait?.lastProgressAtMs !== stamp.lastProgressAtMs || wait.alerted !== true) continue; - const observation = yield* observeStalenessWait( - thread.id, - wait, - provider, - tasks.subagents, - nowMs, - ); - if (observation === null || observation.current.lastProgressAtMs !== stamp.lastProgressAtMs) - continue; - if (held || observation.held || observation.diagnostic === undefined) rearmed.add(wait); - else current.push(observation.diagnostic); - } - const updated = - rearmed.size === 0 - ? undefined - : { - ...thread, - stalenessWaits: - thread.stalenessWaits?.map((wait) => { - if (!rearmed.has(wait)) return wait; - const { alerted: _, ...next } = wait; - return next; - }) ?? [], - }; - return current.length === 0 - ? ({ type: "cancel", thread: updated } as const) - : ({ - type: "replace", - thread: updated, - message: { ...message, ...(yield* waitStaleNotice(current)) }, - } as const); - }); - const startNextQueuedRun = Effect.fn("Orchestrator.startNextQueuedRun")( function* ( threadId: ThreadId, @@ -4699,6 +4607,98 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); }); + const revalidateQueuedDeadline = Effect.fn("Orchestrator.revalidateQueuedDeadline")(function* ( + projection: OrchestrationV2ThreadProjection, + run: OrchestrationV2Run, + ) { + const message = projection.messages.find((message) => message.id === run.userMessageId); + const source = message?.notification?.source; + const prStamps = monitorPullRequestStamps(source).filter( + (stamp) => stamp.staleProgressAt !== undefined, + ); + if ( + message === undefined || + source?.kind !== "monitor" || + (source.staleWaits === undefined && prStamps.length === 0) + ) + return { type: "keep" } as const; + const thread = projection.thread; + const shell = yield* projectionStore.getThreadShell(thread.id); + if (shell === null || shell.settledAt !== null || shell.settledOverride === "settled") + return { type: "cancel" } as const; + const now = yield* DateTime.now; + const nowMs = DateTime.toEpochMillis(now); + const held = waitIntentionallyHeld(shell, nowMs); + if (source.staleWaits === undefined) { + if (!held) return { type: "keep" } as const; + const links = threadPullRequestsOf(thread).map((link) => { + if ( + !prStamps.some( + (stamp) => + threadPullRequestKeysEqual(stamp, link) && + stamp.watchStartedAt === link.watch?.startedAt && + stamp.staleProgressAt === link.watch?.staleness?.lastProgressAt, + ) || + link.watch?.staleness === undefined + ) + return link; + const { alerted: _, ...progress } = link.watch.staleness; + return { ...link, watch: { ...link.watch, staleness: progress } }; + }); + return { type: "keep", prHeld: true, thread: { ...thread, pullRequests: links } } as const; + } + const tasks = yield* projectionStore.getThreadRecords( + thread.id, + ["subagents", "providerThreads"], + { + subagentIds: source.staleWaits + .filter((stamp) => stamp.kind === "delegate") + .map((stamp) => NodeId.make(stamp.taskId)), + }, + ); + const provider = tasks.providerThreads.find( + (provider) => provider.id === thread.activeProviderThreadId, + ); + const current: StaleWait[] = []; + const rearmed = new Set(); + for (const stamp of source.staleWaits) { + const wait = thread.stalenessWaits?.find( + (wait) => wait.kind === stamp.kind && wait.taskId === stamp.taskId, + ); + if (wait?.lastProgressAtMs !== stamp.lastProgressAtMs || wait.alerted !== true) continue; + const observation = yield* observeStalenessWait( + thread.id, + wait, + provider, + tasks.subagents, + nowMs, + ); + if (observation === null || observation.current.lastProgressAtMs !== stamp.lastProgressAtMs) + continue; + if (held || observation.held || observation.diagnostic === undefined) rearmed.add(wait); + else current.push(observation.diagnostic); + } + const updated = + rearmed.size === 0 + ? undefined + : { + ...thread, + stalenessWaits: + thread.stalenessWaits?.map((wait) => { + if (!rearmed.has(wait)) return wait; + const { alerted: _, ...next } = wait; + return next; + }) ?? [], + }; + return current.length === 0 + ? ({ type: "cancel", thread: updated } as const) + : ({ + type: "replace", + thread: updated, + message: { ...message, ...(yield* waitStaleNotice(current)) }, + } as const); + }); + // Recheck under the lock after reading the host. Record the watch first so wake events carry it. const dispatchPullRequestWatchSync = Effect.fn("orchestrationV2.dispatch.pullRequestWatchSync")( function* ( From ff0a5ac16be359b36645e535221609a730bb128f Mon Sep 17 00:00:00 2001 From: Kameron Smith Date: Mon, 23 Nov 2026 23:43:12 -0500 Subject: [PATCH 6/6] test(server): expect the stale-watch notice when the host stays unreadable The repeated-host-read-failures cases keep a watch unreadable for exactly the 30 minute stale window. The watch now wakes the thread once about the missing progress, so these cases expect that notice before the recovery summaries. Model: claude-sonnet-5-5 Task: test Agent: Claude Code Co-Authored-By: Claude Sonnet 5.5 --- apps/server/src/orchestration-v2/runtimeLayer.test.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index ef1127644d182..d34a456a4686f 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -4545,15 +4545,19 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { return; } assert.isDefined(thread?.pullRequests?.[0]?.watch); - assert.deepEqual(yield* summaries, []); + // The host stayed unreadable for the whole stale window, so the watch wakes the thread + // once about the missing progress while it keeps watching. + const stale = "#8: no observed progress for 30 minutes"; + assert.deepEqual(yield* summaries, [stale]); disconnected = false; genericFailure = false; passed = true; yield* sweep; - assert.deepEqual(yield* summaries, ["#8: checks passed"]); + const settled = [stale, "#8: checks passed"].toSorted(); + assert.deepEqual((yield* summaries).toSorted(), settled); yield* TestClock.adjust("10 minutes"); yield* sweep; - assert.deepEqual(yield* summaries, ["#8: checks passed"]); + assert.deepEqual((yield* summaries).toSorted(), settled); yield* orchestrator.dispatch({ type: "thread.pull-request.watch", commandId: CommandId.make(`pr-watch-unreadable-stop-${reason}-${activityFails}`),