diff --git a/server/src/__tests__/chat-channels/github-review-finding-threads.integration.test.ts b/server/src/__tests__/chat-channels/github-review-finding-threads.integration.test.ts index 5835d799848..8dabea865ef 100644 --- a/server/src/__tests__/chat-channels/github-review-finding-threads.integration.test.ts +++ b/server/src/__tests__/chat-channels/github-review-finding-threads.integration.test.ts @@ -339,7 +339,8 @@ describeEmbeddedPostgres("chat channels: github review finding threads and fallb const posts = f.runtime.endpoints.get(f.endpoint.id)?.posts ?? []; expect(posts).toHaveLength(0); expect(f.responseWrites).toHaveLength(expected === "none" ? 2 : 1); - if (expected === "none") expect(f.responseWrites[1]).toMatchObject({ method: "PATCH", body: expect.stringContaining("stopped before completing this turn") }); + if (expected === "none") expect(f.responseWrites[1]).toMatchObject({ method: "PATCH", body: expect.stringContaining( + scenario === "different_run" ? "See the [latest response](https://github.com/paperclipai/paperclip/issues/418)" : "stopped before completing this turn") }); const [fallback] = await db.select().from(chatPublications).where(and(eq(chatPublications.endpointId, f.endpoint.id), eq(chatPublications.idempotencyKey, `run:${f.run.id}:failed:${f.endpoint.id}`))); expect(fallback.state).toBe(expected === "none" ? "published" : "cancelled"); diff --git a/server/src/__tests__/chat-channels/github-review-response-maintenance.integration.test.ts b/server/src/__tests__/chat-channels/github-review-response-maintenance.integration.test.ts index 617290c3ce7..8d20974043c 100644 --- a/server/src/__tests__/chat-channels/github-review-response-maintenance.integration.test.ts +++ b/server/src/__tests__/chat-channels/github-review-response-maintenance.integration.test.ts @@ -129,6 +129,29 @@ describeEmbeddedPostgres("chat channels: github review response maintenance", () await responses.processPending(); expect(f.responseWrites).toHaveLength(writes); }); + it.each(["in_progress", "blocked"] as const)("links the latest response when a request's run ends without its own reply: %s", + async issueStatus => { + const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100"); + await db.update(issues).set({ status: issueStatus }).where(eq(issues.id, f.conversation.issueId!)); + const [firstId] = [...f.responseComments.keys()]; + const [main] = await db.insert(chatConversations).values({ companyId: f.companyId, endpointId: f.endpoint.id, + issueId: f.conversation.issueId, externalConversationId: "github:paperclipai/paperclip", + externalLabel: "paperclipai/paperclip", externalThreadId: "github:paperclipai/paperclip:418" }).returning(); + await db.insert(chatActions).values({ companyId: f.companyId, endpointId: f.endpoint.id, conversationId: main.id, + kind: "github_review_publication", providerActionId: `github_publication:${randomUUID()}`, status: "processed", + payload: { operation: "assessment", session: { companyId: f.companyId, issueId: f.conversation.issueId, runId: randomUUID(), agentId: f.assignedAgentId } }, + result: { summaryUrl: "https://github.com/paperclipai/paperclip/pull/418#issuecomment-1" } }); + await db.update(heartbeatRuns).set({ status: "succeeded", runtimeMode: "native", nativePhase: "committed", resultJson: { + finalizationPhase: "committed", finalizationReasonCode: "completion_claim_policy_accepted", + nativeResult: { schema: "paperclip.run_result.v1", reportedWorkDisposition: "done" }, + presentationDecision: { schema: "paperclip.run_presentation_decision.v1", chosenSource: "none", commentAction: "create" } } }) + .where(eq(heartbeatRuns.id, f.run.id)); + await githubResponseCommentService(db, f.providerFetch).failRun({ companyId: f.companyId, endpointId: f.endpoint.id, + issueId: f.conversation.issueId!, runId: f.run.id, + body: "This turn ended without publishing a final response. See the Paperclip task for details." }); + expect(f.responseComments.get(firstId)?.body).toContain("See the [latest response](https://github.com/paperclipai/paperclip/pull/418)"); + expect(f.responseComments.get(firstId)?.body).not.toContain("ended without publishing"); + }); it("links a GitHub thread whose run waited to the response a later run published", async () => { const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100"); const [firstId] = [...f.responseComments.keys()]; @@ -143,7 +166,7 @@ describeEmbeddedPostgres("chat channels: github review response maintenance", () externalLabel: "paperclipai/paperclip", externalThreadId: "github:paperclipai/paperclip:4180" }).returning(); await db.insert(chatActions).values({ companyId: f.companyId, endpointId: f.endpoint.id, conversationId: other.id, kind: "github_review_publication", providerActionId: `github_publication:${randomUUID()}`, status: "processed", - payload: { operation: "comment", session: { companyId: f.companyId, issueId: f.conversation.issueId, runId: f.run.id } }, + payload: { operation: "comment", session: { companyId: f.companyId, issueId: f.conversation.issueId, runId: randomUUID(), agentId: f.assignedAgentId } }, result: { id: "77", url: "https://github.com/paperclipai/paperclip/pull/4180#issuecomment-77" } }); await db.update(issues).set({ status: "in_progress" }).where(eq(issues.id, f.conversation.issueId!)); await responses.processPending(); @@ -176,7 +199,7 @@ describeEmbeddedPostgres("chat channels: github review response maintenance", () url: "https://github.com/paperclipai/paperclip/pull/418#discussion_r88", digest: "d" } } }); await db.insert(chatActions).values({ companyId: f.companyId, endpointId: f.endpoint.id, conversationId: f.conversation.id, kind: "github_review_publication", providerActionId: `github_publication:${randomUUID()}`, status: "processed", - payload: { operation: "assessment", reviewId, session: { companyId: f.companyId, issueId: f.conversation.issueId, runId: f.run.id } }, + payload: { operation: "assessment", reviewId, session: { companyId: f.companyId, issueId: f.conversation.issueId, runId: f.run.id, agentId: f.assignedAgentId } }, result: { reviewId, summaryUrl: null } }); await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.conversation.issueId!)); await responses.processPending(); diff --git a/server/src/services/chat-channels/github/response-execution.ts b/server/src/services/chat-channels/github/response-execution.ts index 8156dae9561..c1033f3b38f 100644 --- a/server/src/services/chat-channels/github/response-execution.ts +++ b/server/src/services/chat-channels/github/response-execution.ts @@ -34,6 +34,15 @@ export function settlesFromRequestRun(state: GitHubResponseRunState, issueStatus issueStatus !== "blocked" && !!state.finishedRequestRun; } +/** The notice that points a request at the latest response its agent published + * on the same pull request or issue after the request arrived, if any. */ +export async function latestResponseNotice(db: Db, + input: { companyId: string; endpointId: string; issueId: string; since: Date; threadId: string }) { + const url = await githubLatestTaskResponseUrl(db, { companyId: input.companyId, endpointId: input.endpointId, + issueId: input.issueId, since: input.since, baseThreadId: baseThreadId(input.threadId) }); + return url ? `See the [latest response](${url}).` : null; +} + /** `read` is this request's state from a batched page read, if the caller has it. */ export async function githubResponseExecution(db: Db, input: GitHubResponseExecutionInput, read?: GitHubResponseRunRead) { const state = read ?? await readGitHubResponseRun(db, input); @@ -55,8 +64,8 @@ export async function githubResponseExecution(db: Db, input: GitHubResponseExecu const presentationPending = !!run && answersRequest && run.nativePresentationPending && reply === "none"; const passiveResponseWait = !!run && answersRequest && run.passiveResponseWait && reply === "none"; const unanswered = !!run && !presentationPending && reply === "none" && !paused; - const latestResponse = unanswered ? await githubLatestTaskResponseUrl(db, { companyId: input.companyId, - endpointId: input.endpointId, issueId: input.issueId, since: input.deliveryCreatedAt, baseThreadId: baseThreadId(input.threadId) }) + const latestResponse = unanswered ? await latestResponseNotice(db, { companyId: input.companyId, + endpointId: input.endpointId, issueId: input.issueId, since: input.deliveryCreatedAt, threadId: input.threadId }) : null; const taskFinished = ["done", "cancelled"].includes(input.issueStatus); // Precedence: a later published response is more useful to the reader than @@ -71,7 +80,7 @@ export async function githubResponseExecution(db: Db, input: GitHubResponseExecu : run.responsePublicationFailed ? "publish_failed" : run.status === "succeeded" ? "ended" : "stopped"; const body = outcome === null || outcome === "waiting" ? undefined - : outcome === "link" ? `See the [latest response](${latestResponse}).` : STATUS_TEXT[outcome]; + : outcome === "link" ? latestResponse! : STATUS_TEXT[outcome]; return { body, outcome, paused, reply, running: requestRunning, presentationPending, passiveResponseWait, versionAt: run ? new Date(Math.max(run.updatedAt.getTime(), input.deliveryCreatedAt.getTime())) diff --git a/server/src/services/chat-github-response-comments.ts b/server/src/services/chat-github-response-comments.ts index c72c135f4b1..f4c3300e0f7 100644 --- a/server/src/services/chat-github-response-comments.ts +++ b/server/src/services/chat-github-response-comments.ts @@ -6,7 +6,7 @@ import { type Db, } from "@paperclipai/db"; import { registerGitHubTerminalResponseWork } from "./chat-channels/github/terminal-response-work.js"; -import { githubResponseExecution, githubResponseRunColumns as responseRunColumns } from "./chat-channels/github/response-execution.js"; +import { githubResponseExecution, githubResponseRunColumns as responseRunColumns, latestResponseNotice } from "./chat-channels/github/response-execution.js"; import { FINISHED_RUN_STATUSES, finishedRunStatusSql, runBoundToIssue, runWokeForComment } from "./chat-channels/github/response-run-state.js"; import { notifyChatResponseAvailability } from "./chat-response-availability.js"; import { registerGitHubAcknowledgementWork } from "./chat-channels/github/acknowledgement-work.js"; @@ -427,7 +427,10 @@ export function githubResponseCommentService(db: Db, fetchImpl = fetch) { if (isMainPullResponse(source) && current.passiveResponseWait) throw forbidden("GitHub run intentionally yielded without a new response"); if (await githubRunReplyState(db, input) !== "none") throw conflict("GitHub reply is still being resolved"); }; - receipt = await acknowledge(link.deliveryId, input.body, assertRun); + const source = await context(link.deliveryId); + const notice = await latestResponseNotice(db, { companyId: input.companyId, + endpointId: input.endpointId, issueId: input.issueId, since: source.delivery.createdAt, threadId: source.conversation.externalThreadId }); + receipt = await acknowledge(link.deliveryId, notice ?? input.body, assertRun); } if (!receipt) throw forbidden("GitHub failure has no request binding"); return receipt; diff --git a/server/src/services/chat-run-publications.ts b/server/src/services/chat-run-publications.ts index 6ee49861800..5e4664f16dd 100644 --- a/server/src/services/chat-run-publications.ts +++ b/server/src/services/chat-run-publications.ts @@ -135,6 +135,8 @@ export async function githubLatestTaskResponseUrl( eq(chatActions.status, "processed"), sql`${chatActions.payload}->'session'->>'companyId' = ${input.companyId}`, sql`${chatActions.payload}->'session'->>'issueId' = ${input.issueId}`, + sql`${chatActions.payload}->'session'->>'agentId' = (select ${chatEndpoints.assignedAgentId}::text from ${chatEndpoints} + where ${chatEndpoints.id} = ${input.endpointId}::uuid and ${chatEndpoints.companyId} = ${input.companyId}::uuid)`, sql`${chatActions.payload}->>'operation' in ('comment', 'formal_review', 'assessment')`, sql`${url} like 'https://github.com/%'`, sql`${chatActions.updatedAt} > ${input.since.toISOString()}::timestamptz`,