diff --git a/server/src/__tests__/heartbeat-comment-wake-batching.test.ts b/server/src/__tests__/heartbeat-comment-wake-batching.test.ts index 855d99c4286..77a75841b62 100644 --- a/server/src/__tests__/heartbeat-comment-wake-batching.test.ts +++ b/server/src/__tests__/heartbeat-comment-wake-batching.test.ts @@ -2164,6 +2164,169 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => { } }, 120_000); + async function startAssignedRunWithDeferredChildCompletion(input: { + gateway: Awaited>; + title: string; + firstRunComment?: boolean; + }) { + const companyId = randomUUID(); + const agentId = randomUUID(); + const issueId = randomUUID(); + const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`; + const heartbeat = heartbeatService(db); + await db.insert(companies).values(wakeCompanyRow(companyId, issuePrefix)); + await grantFixtureWorkspaceAccess(companyId, ["responsible-user", "user-1"]); + await db.insert(agents).values(wakeGatewayAgentRow(agentId, companyId, "Gateway Agent", input.gateway)); + await db.insert(issues).values(wakeIssueRow(issueId, companyId, input.title, agentId, issuePrefix)); + + const firstRunComment = input.firstRunComment + ? await db.insert(issueComments) + .values(wakeUserCommentRow(companyId, issueId, "user-1", "Start with this instruction")) + .returning().then((rows) => rows[0]) + : null; + const firstRun = await heartbeat.wakeup(agentId, firstRunComment + ? { + source: "automation", triggerDetail: "system", reason: "issue_commented", + payload: { issueId, commentId: firstRunComment.id }, + contextSnapshot: { issueId, taskId: issueId, commentId: firstRunComment.id, wakeCommentId: firstRunComment.id, + wakeReason: "issue_commented" }, + requestedByActorType: "user", requestedByActorId: "user-1", + } + : { + source: "assignment", triggerDetail: "system", reason: "issue_assigned", + payload: { issueId }, contextSnapshot: { issueId, taskId: issueId, wakeReason: "issue_assigned" }, + requestedByActorType: "user", requestedByActorId: "user-1", + }); + expect(firstRun).not.toBeNull(); + await waitFor(async () => { + const run = await db.select({ status: heartbeatRuns.status }).from(heartbeatRuns) + .where(eq(heartbeatRuns.id, firstRun!.id)).then((rows) => rows[0] ?? null); + return run?.status === "running"; + }); + await waitFor(() => input.gateway.getAgentPayloads().length >= 1); + + const childCompletionIntentId = randomUUID(); + const childCompletionWakeId = randomUUID(); + const childCompletionContext = { issueId, taskId: issueId, wakeReason: "issue_children_completed" }; + await db.insert(agentWakeupRequests).values([{ + id: childCompletionIntentId, companyId, agentId, source: "automation", triggerDetail: "system", + reason: "issue_children_completed", status: "coalesced", + requestedByActorType: "system", requestedByActorId: "native-status-committer", + payload: { issueId, taskId: issueId }, finishedAt: new Date(), + }, { + id: childCompletionWakeId, companyId, agentId, source: "automation", triggerDetail: "system", + reason: "issue_execution_deferred", status: "deferred_issue_execution", + requestedByActorType: "system", requestedByActorId: `native-status-wake-dispatch:${childCompletionIntentId}`, + payload: { issueId, taskId: issueId, _paperclipWakeContext: childCompletionContext }, + }]); + return { companyId, agentId, issueId, heartbeat, firstRun: firstRun!, firstRunComment, childCompletionWakeId }; + } + + async function closeIssueAndFinishFirstRun( + gateway: Awaited>, + issueId: string, + firstRunId: string, + ) { + await db.update(issues).set({ + status: "done", completedAt: new Date(), executionRunId: null, executionAgentNameKey: null, + executionLockedAt: null, updatedAt: new Date(), + }).where(eq(issues.id, issueId)); + gateway.releaseFirstWait(); + await waitFor(async () => { + const run = await db.select({ status: heartbeatRuns.status }).from(heartbeatRuns) + .where(eq(heartbeatRuns.id, firstRunId)).then((rows) => rows[0] ?? null); + return run?.status === "succeeded"; + }, 90_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 { + const { companyId, agentId, issueId, heartbeat, firstRun, childCompletionWakeId } = + await startAssignedRunWithDeferredChildCompletion({ gateway, title: "Person comment behind a child result" }); + + const personComment = await db.insert(issueComments) + .values(wakeUserCommentRow(companyId, issueId, "user-1", "Additional requirement posted while the run was finishing")) + .returning().then((rows) => rows[0]); + const commentWake = 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", + }); + expect(commentWake).toBeNull(); + const merged = await selectDeferredWakeForAgent(companyId, agentId); + expect(merged).toMatchObject({ id: childCompletionWakeId, requestedByActorType: "system" }); + expect(JSON.stringify(merged?.payload)).toContain(personComment.id); + + await closeIssueAndFinishFirstRun(gateway, issueId, firstRun.id); + + await waitFor(async () => { + const wake = await db.select({ status: agentWakeupRequests.status }).from(agentWakeupRequests) + .where(eq(agentWakeupRequests.id, childCompletionWakeId)).then((rows) => rows[0] ?? null); + return wake?.status !== "deferred_issue_execution"; + }, 30_000); + const settledWake = await db.select({ status: agentWakeupRequests.status, error: agentWakeupRequests.error }) + .from(agentWakeupRequests).where(eq(agentWakeupRequests.id, childCompletionWakeId)).then((rows) => rows[0] ?? null); + expect(settledWake?.error).toBeNull(); + expect(settledWake?.status).not.toBe("cancelled"); + await waitFor(() => gateway.getAgentPayloads().length >= 2, 90_000); + const issueAfter = await db.select({ status: issues.status, completedAt: issues.completedAt }) + .from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null); + expect(issueAfter).toMatchObject({ status: "in_progress", completedAt: null }); + const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId)) + .orderBy(asc(heartbeatRuns.createdAt)); + expect(runs).toHaveLength(2); + expect(runs[1]?.wakeupRequestId).toBe(childCompletionWakeId); + expect(String(gateway.getAgentPayloads()[1]?.message ?? "")).toContain( + "Additional requirement posted while the run was finishing", + ); + } finally { + gateway.releaseFirstWait(); + await gateway.close(); + } + }, 120_000); + + it("keeps a finished task closed when the only person comment in a deferred system wake was the run's own input", async () => { + const gateway = await createControlledGatewayServer(); + try { + const { companyId, agentId, issueId, heartbeat, firstRun, firstRunComment, childCompletionWakeId } = + await startAssignedRunWithDeferredChildCompletion({ + gateway, title: "Delivered person comment behind a child result", firstRunComment: true, + }); + + const repeatedWake = await heartbeat.wakeup(agentId, { + source: "automation", triggerDetail: "system", reason: "issue_commented", + payload: { issueId, commentId: firstRunComment!.id }, + contextSnapshot: { issueId, taskId: issueId, commentId: firstRunComment!.id, wakeCommentId: firstRunComment!.id, + wakeReason: "issue_commented" }, + requestedByActorType: "user", requestedByActorId: "user-1", + }); + expect(repeatedWake).toBeNull(); + const merged = await selectDeferredWakeForAgent(companyId, agentId); + expect(merged?.id).toBe(childCompletionWakeId); + expect(JSON.stringify(merged?.payload)).toContain(firstRunComment!.id); + + await closeIssueAndFinishFirstRun(gateway, issueId, firstRun.id); + + await waitFor(async () => { + const wake = await db.select({ status: agentWakeupRequests.status }).from(agentWakeupRequests) + .where(eq(agentWakeupRequests.id, childCompletionWakeId)).then((rows) => rows[0] ?? null); + return wake?.status === "cancelled"; + }, 90_000); + const issueAfter = await db.select({ status: issues.status }).from(issues) + .where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null); + expect(issueAfter?.status).toBe("done"); + const runs = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId)); + expect(runs.map((run) => run.id)).toEqual([firstRun.id]); + expect(gateway.getAgentPayloads()).toHaveLength(1); + } finally { + gateway.releaseFirstWait(); + await gateway.close(); + } + }, 120_000); + it("cancels a deferred comment wake when its only queued comment is deleted before promotion", async () => { const gateway = await createControlledGatewayServer(); const companyId = randomUUID(); diff --git a/server/src/modules/wake-queue/adapters/postgres.ts b/server/src/modules/wake-queue/adapters/postgres.ts index 3d9a0ab20e1..1803aab486a 100644 --- a/server/src/modules/wake-queue/adapters/postgres.ts +++ b/server/src/modules/wake-queue/adapters/postgres.ts @@ -474,10 +474,18 @@ function buildTransaction(tx: Db, deps: WakeQueuePostgresAdapterDeps, db: Db, ru async getCommentSelfAuthorship({ companyId, issueId, finishingRunId, commentIds }) { const rows = await tx - .select({ createdByRunId: issueComments.createdByRunId }) + .select({ + createdByRunId: issueComments.createdByRunId, authorType: issueComments.authorType, + authorUserId: issueComments.authorUserId, authorAgentId: issueComments.authorAgentId, + derivedAuthorAgentId: issueComments.derivedAuthorAgentId, deletedAt: issueComments.deletedAt, + }) .from(issueComments) .where(and(eq(issueComments.companyId, companyId), eq(issueComments.issueId, issueId), inArray(issueComments.id, commentIds))); - return { allSelfAuthored: rows.length > 0 && rows.every((row) => row.createdByRunId === finishingRunId) }; + return { + allSelfAuthored: rows.length > 0 && rows.every((row) => row.createdByRunId === finishingRunId), + includesPersonComment: rows.some((row) => !row.deletedAt && row.authorUserId !== null && row.createdByRunId === null && + row.authorAgentId === null && row.derivedAuthorAgentId === null && (row.authorType === "user" || row.authorType === null)), + }; }, async isWatcherCommentDuringFinishingRun({ companyId, issueId, finishingRunId, commentIds }) { diff --git a/server/src/modules/wake-queue/application/ports.ts b/server/src/modules/wake-queue/application/ports.ts index ffda4692b36..2ee3256260f 100644 --- a/server/src/modules/wake-queue/application/ports.ts +++ b/server/src/modules/wake-queue/application/ports.ts @@ -178,7 +178,7 @@ export interface WakeQueueTransaction { issueId: string; finishingRunId: string; commentIds: string[]; - }): Promise<{ allSelfAuthored: boolean }>; + }): Promise<{ allSelfAuthored: boolean; includesPersonComment: boolean }>; /** Proves all candidate comments only report completed child work in the finishing parent's own run. */ isCompletedDelegationMention(input: { companyId: string; diff --git a/server/src/modules/wake-queue/application/use-cases.test.ts b/server/src/modules/wake-queue/application/use-cases.test.ts index f5c6999e852..8cf2e851f00 100644 --- a/server/src/modules/wake-queue/application/use-cases.test.ts +++ b/server/src/modules/wake-queue/application/use-cases.test.ts @@ -115,7 +115,7 @@ function createFakeTransaction(overrides: Partial = {}): W reason: null, releasePolicy: null, })), - getCommentSelfAuthorship: vi.fn(async () => ({ allSelfAuthored: false })), + getCommentSelfAuthorship: vi.fn(async () => ({ allSelfAuthored: false, includesPersonComment: false })), isWatcherCommentDuringFinishingRun: vi.fn(async () => false), owedInteractionAnswer: vi.fn(async (): Promise<"deliver" | "blocked" | null> => null), isCompletedDelegationMention: vi.fn(async () => false), @@ -681,7 +681,7 @@ describe("releaseIssueExecution", () => { liveNonSelfCommentIds: scenario === "done_missing" || scenario === "done_self" ? [] : commentIds, containedSelfAuthoredComment: scenario === "done_self", })), - getCommentSelfAuthorship: vi.fn(async () => ({ allSelfAuthored: scenario === "done_self" })), + getCommentSelfAuthorship: vi.fn(async () => ({ allSelfAuthored: scenario === "done_self", includesPersonComment: false })), isWatcherCommentDuringFinishingRun: vi.fn(async () => scenario === "done_watcher_during_run"), reopenIssue: vi.fn(async () => ({ ...ISSUE, status: "todo" })), }); diff --git a/server/src/modules/wake-queue/application/use-cases.ts b/server/src/modules/wake-queue/application/use-cases.ts index 70a4ad5732a..f10416fe4c8 100644 --- a/server/src/modules/wake-queue/application/use-cases.ts +++ b/server/src/modules/wake-queue/application/use-cases.ts @@ -392,6 +392,7 @@ async function promoteDeferredWake( shouldReopen = !selfAuthorship.allSelfAuthored && (workingCandidate.requestedByActorType === "user" || + selfAuthorship.includesPersonComment || workingCandidate.wakeReason === "issue_reopened_via_comment" || // The agent watching the task posted it while the run that closed the // task was active. That agent receives the completed result and can