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..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; }, ); @@ -10633,6 +10634,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 +10700,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..f9dc7e4f08068 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,23 @@ 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 ?? []).some( + (wait) => + wait.kind === "delegate" || + shell.pendingBackgroundTasks?.some( + (task) => task.taskId === wait.taskId && task.awaited === true, + ), + ) + ); + }); + const judgeContext = Effect.fnUntraced(function* ( shell: OrchestrationV2ThreadShell, trigger: ThreadEventTrigger, @@ -1474,6 +1492,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, @@ -1622,6 +1641,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..26eca7bf4c939 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,14 @@ import { ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE, type ChatAttachment, CommandId, + BACKGROUND_WAIT_STALE_MINUTES, + PR_WATCH_STALE_MINUTES, type GuestMessageId, isCompactionCommandMessage, isOrchestrationV2WorkActive, isProviderNativeSubagentThread, MessageId, - type NodeId, + NodeId, type ModelSelection, OrchestrationV2Command, type OrchestrationV2InternalCommand, @@ -48,6 +51,7 @@ import { type OrchestrationV2ServerCommand, type ThreadPullRequestLink, type ThreadPullRequestWatch, + ThreadStalenessWait, type OrchestrationV2AppThread, type OrchestrationV2ContextHandoff, type OrchestrationV2ContextSourcePoint, @@ -94,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 { @@ -533,6 +541,10 @@ export interface OrchestratorV2Shape { Effect.Effect, OrchestratorV2Error >; + readonly getWaitActivityMs: ( + threadId: ThreadId, + runId: RunId | null, + ) => Effect.Effect; readonly getThreadShell: ( threadId: ThreadId, ) => Effect.Effect; @@ -660,6 +672,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": @@ -920,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 = ({ @@ -1220,6 +1244,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"] >; @@ -1234,12 +1272,18 @@ function monitorPullRequestStamps( function isStalePullRequestWatchStamp( projection: Pick, stamp: MonitorPullRequestStamp, + held = false, ): boolean { const link = threadPullRequestsOf(projection.thread).find( (candidate) => candidate.source !== "stack-dismissed" && threadPullRequestKeysEqual(candidate, stamp), ); if (link === undefined) return true; + if ( + stamp.staleProgressAt !== undefined && + (held || 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,15 +1312,59 @@ function isStalePullRequestWatchStamp( ); } +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)) ); } @@ -1287,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])); @@ -2633,21 +2722,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) - ) { + 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([ @@ -4175,6 +4282,423 @@ 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>, + 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 = []; + 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) => matches(wait, taskId) && current(wait)), + ); + next = [ + ...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) || + (operation.registeredBy !== undefined && wait.registeredBy !== operation.registeredBy), + ); + 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": { + const shell = yield* projectionStore + .getThreadShell(threadId) + .pipe(mapDispatchError(command)); + if ( + shell === null || + shell.archivedAt !== null || + shell.settledAt !== null || + shell.settledOverride === "settled" + ) { + next = []; + break; + } + activeRunId = shell.activeRunId; + const tasks = yield* projectionStore + .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 registrations = [...waits]; + for (const task of provider?.pendingBackgroundTasks ?? []) { + if ( + provider === undefined || + task.awaited !== true || + 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), + 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) { + 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(diagnostic); + } 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 { text, notification } = yield* waitStaleNotice(stale); + if (activeRunId !== null) { + yield* emitDeadlineNotice(command, events, activeRunId, now, notification.summary, text); + return; + } + yield* dispatchMessage( + { + type: "message.dispatch", + commandId: command.commandId, + threadId, + messageId: MessageId.make(`message:${command.commandId}`), + text, + attachments: [], + notification, + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }, + events, + effects, + ); + }); + + 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* ( @@ -4233,17 +4757,69 @@ 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, 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] } : {}), @@ -5348,43 +5924,57 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : existing.watch : !command.watching ? undefined - : (existing.watch ?? { - 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 @@ -9836,6 +10426,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 +10618,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 +10991,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 +16201,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 +16628,9 @@ 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" || command.type === "subagent.stop" || @@ -16069,6 +16701,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 +17616,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..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; @@ -615,6 +616,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 @@ -4155,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)}))`} @@ -9234,6 +9241,52 @@ export const layer: Layer.Layer = return rows[0]?.count ?? 0; }, Effect.mapError(shellSnapshotReadError)); + const listStalenessWaitThreads = sql<{ readonly thread_id: string }>` + 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, '$.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) + ) + ) + ) + ) + `.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') + AND turn_item_id NOT LIKE 'item:deadline:%' + `; + 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 +9671,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/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/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..183a4d2f977cf 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -42,6 +42,8 @@ import { evaluatePullRequestWatch, PULL_REQUEST_WATCH_NO_CHECKS_MS, pullRequestWatchMessage, + stalePullRequestWatch, + pullRequestWatchStaleness, } from "./pullRequestWatch.ts"; /** Checks take minutes; faster sweeps waste the account's shared host quota. */ @@ -103,6 +105,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 +207,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 && @@ -321,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, @@ -332,7 +336,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 +486,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 +608,42 @@ export const make = Effect.gen(function* () { ), ); + const sendStale = ( + 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) + : 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) => + sendStale(target, target.watch, now, observation).pipe(Effect.asVoid), + ); + const readGroup = Effect.fn("PullRequestWatchReactor.readGroup")(function* ( group: WatchGroup, fingerprint: ProviderChangeRequestWatchFingerprint | null, @@ -593,7 +651,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 +679,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 +755,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 +789,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 sendStale(target, report.next, now, "current").pipe( + Effect.flatMap((held) => + held || watchesEqual(report.next, target.watch) + ? Effect.void + : record(target, report.next).pipe(Effect.asVoid), + ), + ); }); }); @@ -797,7 +869,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 +889,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..ecf01ad685a43 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,11 +408,13 @@ 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); 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, diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index 4dba426ab9975..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,6 +710,12 @@ it.effect.each([ Layer.provide( Layer.mergeAll( Layer.mock(Orchestrator.OrchestratorV2)({ + dispatch: (command) => + Effect.sync(() => { + if (command.type === "thread.wait-staleness.update") + order.push(command.operation.type); + return { sequence: 0, storedEvents: [] }; + }), getThreadRecords: () => Effect.succeed({ thread: { @@ -727,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 53e69c1c29e0f..4e43c231c683e 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 @@ -1742,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"), @@ -1754,15 +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 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( @@ -1910,6 +1967,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..806ad311f6841 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; +export const pullRequestWatchStaleness = (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 = pullRequestWatchStaleness(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 = pullRequestWatchStaleness(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..d34a456a4686f 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"; @@ -4533,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}`), @@ -4739,6 +4755,862 @@ 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) => + 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, + 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), + }, + ] + : [], + }, + }, + ], + }); + }); + 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", "turnItems"]) + .pipe( + 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`); + 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.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-${legacy}`); + 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", + ...(legacy ? {} : { 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", "turnItems"]) + .pipe( + 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"); + 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..737b6423b9c35 --- /dev/null +++ b/apps/server/src/orchestration-v2/waitStaleness.ts @@ -0,0 +1,30 @@ +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?.autoResume === true || + (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..525a979764641 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,19 @@ 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 }, + ...(input.staleTimeoutMinutes === undefined + ? {} + : { + 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..50221005b49d2 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), @@ -1108,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), @@ -1226,6 +1229,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 +1507,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 +1544,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 +3586,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 +3846,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 +3892,34 @@ 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, + 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"), + 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 +3973,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 +3984,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 +4019,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..23ff97996775c 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -37,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, @@ -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..754784ad5bb1c --- /dev/null +++ b/packages/contracts/src/waitStaleness.ts @@ -0,0 +1,23 @@ +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.", +}); + +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, + 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)), +}); +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 } : {}),