diff --git a/server/src/__tests__/heartbeat-comment-wake-batching.test.ts b/server/src/__tests__/heartbeat-comment-wake-batching.test.ts index 77a75841b62..2e7c35ed30b 100644 --- a/server/src/__tests__/heartbeat-comment-wake-batching.test.ts +++ b/server/src/__tests__/heartbeat-comment-wake-batching.test.ts @@ -33,6 +33,7 @@ import { } from "@paperclipai/db"; import { runningProcesses } from "../adapters/index.js"; import { heartbeatService } from "../services/heartbeat.ts"; +import { hasPendingNativeChildCompletion } from "../services/native-runtime/native-child-completion-delivery.js"; import { issueThreadInteractionService } from "../services/issue-thread-interactions.js"; import { isRetiredExternalChatQuestionSource, questionResponseDeliveryService } from "../services/question-response-delivery.js"; import { SUCCESSFUL_RUN_HANDOFF_REQUIRED_NOTICE_BODY } from "../services/recovery/index.ts"; @@ -2207,7 +2208,8 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => { const childCompletionIntentId = randomUUID(); const childCompletionWakeId = randomUUID(); - const childCompletionContext = { issueId, taskId: issueId, wakeReason: "issue_children_completed" }; + const childCompletionContext = { issueId, taskId: issueId, wakeReason: "issue_children_completed", + nativeChildCompletionDecisionId: randomUUID(), completedChildIssueId: randomUUID() }; await db.insert(agentWakeupRequests).values([{ id: childCompletionIntentId, companyId, agentId, source: "automation", triggerDetail: "system", reason: "issue_children_completed", status: "coalesced", @@ -2239,6 +2241,47 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => { }, 90_000); } + it("keeps a pending child completion visible to the finish gate after a person's comment merges into its deferred wake", async () => { + const gateway = await createControlledGatewayServer(); + try { + const { companyId, agentId, issueId, heartbeat, firstRun, childCompletionWakeId } = + await startAssignedRunWithDeferredChildCompletion({ gateway, title: "Child result and person comment behind a run" }); + const pendingChildCompletion = () => hasPendingNativeChildCompletion(db, { + companyId, issueId, agentId, runId: firstRun.id, sourceIntentId: null, + }); + expect(await pendingChildCompletion()).toBe(true); + + const personComment = await db.insert(issueComments) + .values(wakeUserCommentRow(companyId, issueId, "user-1", "Also include the summary table")) + .returning().then((rows) => rows[0]); + expect(await heartbeat.wakeup(agentId, { + source: "automation", triggerDetail: "system", reason: "issue_commented", + payload: { issueId, commentId: personComment.id }, + contextSnapshot: { issueId, taskId: issueId, commentId: personComment.id, wakeCommentId: personComment.id, + wakeReason: "issue_commented" }, + requestedByActorType: "user", requestedByActorId: "user-1", + })).toBeNull(); + const merged = await selectDeferredWakeForAgent(companyId, agentId); + expect(merged?.id).toBe(childCompletionWakeId); + expect((merged?.payload as Record)._paperclipWakeContext).toMatchObject({ + wakeReason: "issue_commented", + wakeReasons: ["issue_children_completed", "issue_commented"], + wakeCommentIds: [personComment.id], + }); + expect(await pendingChildCompletion()).toBe(true); + + await closeIssueAndFinishFirstRun(gateway, issueId, firstRun.id); + await waitFor(() => gateway.getAgentPayloads().length >= 2, 90_000); + const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId)) + .orderBy(asc(heartbeatRuns.createdAt)); + expect(runs[1]?.wakeupRequestId).toBe(childCompletionWakeId); + expect(String(gateway.getAgentPayloads()[1]?.message ?? "")).toContain("Also include the summary table"); + } finally { + gateway.releaseFirstWait(); + await gateway.close(); + } + }, 120_000); + it("reopens a finished task when a person's comment joined a deferred system wake during the run", async () => { const gateway = await createControlledGatewayServer(); try { diff --git a/server/src/modules/wake-queue/application/use-cases.ts b/server/src/modules/wake-queue/application/use-cases.ts index f10416fe4c8..fb6a31c0f61 100644 --- a/server/src/modules/wake-queue/application/use-cases.ts +++ b/server/src/modules/wake-queue/application/use-cases.ts @@ -1,5 +1,5 @@ import { readWakeChatConversationId } from "../../run-dispatch/index.js"; -import { enrichPromotedWakeContext, wakeMustNotJoinActiveRun } from "../domain/context.js"; +import { enrichPromotedWakeContext, wakeMustNotJoinActiveRun, withMergedWakeReasons } from "../domain/context.js"; import { QUEUED_MESSAGES_DELIVERED_REASON } from "../domain/policy.js"; import { decideQueuedCommentAction, @@ -979,12 +979,16 @@ export function createAdmitWakeBehindIssueExecution(deps: { }); if (existingDeferred && !existingDeferred.payload?.interactionId && !existingDeferred.deferredContext.interactionId) { - const mergedDeferredContext = deps.helpers.mergeCoalescedContextSnapshot( + const mergedDeferredContext = withMergedWakeReasons( + deps.helpers.mergeCoalescedContextSnapshot( + existingDeferred.deferredContext, + input.contextSnapshot, + { + preserveExistingInteractionContinuation: true, + }, + ), existingDeferred.deferredContext, input.contextSnapshot, - { - preserveExistingInteractionContinuation: true, - }, ); const mergedPayload = { ...existingDeferred.payload, diff --git a/server/src/modules/wake-queue/domain/context.ts b/server/src/modules/wake-queue/domain/context.ts index 7ce30654bdd..51a7c6e91f7 100644 --- a/server/src/modules/wake-queue/domain/context.ts +++ b/server/src/modules/wake-queue/domain/context.ts @@ -89,6 +89,23 @@ export function wakeMustNotJoinActiveRun( wakeChatConversationsConflict(activeRunContext, wakeContext); } +const WAKE_REASONS_KEY = "wakeReasons"; + +function readWakeReasons(context: unknown): string[] { + const parsed = parseObject(context); + const listed = Array.isArray(parsed[WAKE_REASONS_KEY]) ? parsed[WAKE_REASONS_KEY] as unknown[] : []; + return [...listed, parsed.wakeReason].flatMap((value) => readNonEmptyString(value) ?? []); +} + +export function withMergedWakeReasons( + merged: Record, + existing: unknown, + incoming: unknown, +): Record { + const reasons = [...new Set([...readWakeReasons(existing), ...readWakeReasons(incoming)])]; + return reasons.length > 1 ? { ...merged, [WAKE_REASONS_KEY]: reasons } : merged; +} + export function hasRetainedExternalChatRetry(context: unknown): boolean { const active = parseObject(context); const activeSource = readNonEmptyString(active.source); diff --git a/server/src/services/native-runtime/native-child-completion-delivery.ts b/server/src/services/native-runtime/native-child-completion-delivery.ts index 0ae2377fd5c..7d367edfa59 100644 --- a/server/src/services/native-runtime/native-child-completion-delivery.ts +++ b/server/src/services/native-runtime/native-child-completion-delivery.ts @@ -34,7 +34,8 @@ export async function hasPendingNativeChildCompletion(db: Db, input: NativeChild eq(agentWakeupRequests.agentId, input.agentId), or(eq(agentWakeupRequests.reason, "issue_children_completed"), and(eq(agentWakeupRequests.reason, "issue_execution_deferred"), - sql`${agentWakeupRequests.payload}->'_paperclipWakeContext'->>'wakeReason' = 'issue_children_completed'`)), + sql`(${agentWakeupRequests.payload}->'_paperclipWakeContext'->>'wakeReason' = 'issue_children_completed' + or ${agentWakeupRequests.payload}->'_paperclipWakeContext'->'wakeReasons' @> '["issue_children_completed"]'::jsonb)`)), eq(agentWakeupRequests.requestedByActorType, "system"), or(eq(agentWakeupRequests.requestedByActorId, "native-status-committer"), sql`${agentWakeupRequests.requestedByActorId} like 'native-status-wake-dispatch:%'`),