diff --git a/packages/shared/src/types/attention.ts b/packages/shared/src/types/attention.ts index ac112c8e57d..ec310599deb 100644 --- a/packages/shared/src/types/attention.ts +++ b/packages/shared/src/types/attention.ts @@ -4,6 +4,7 @@ import type { IssueThreadInteractionResolverPolicyProvenance, } from "../constants.js"; import type { InboxDismissalKind } from "./inbox-dismissal.js"; +import type { IssueThreadInteraction } from "./issue.js"; export const ATTENTION_SOURCE_KINDS = [ "approval", @@ -673,6 +674,11 @@ export interface AttentionItem { * kind, whose decisions are not governed by a resolver policy. */ resolverAudience?: AttentionResolverAudience | null; + /** + * Optional hydrated interaction record attached by task-question projections + * so inline cards can render immediately without per-task interaction fetches. + */ + interaction?: IssueThreadInteraction | null; } export interface AttentionFeed { diff --git a/server/src/__tests__/activity-routes.test.ts b/server/src/__tests__/activity-routes.test.ts index 99509006d12..f085b1ab337 100644 --- a/server/src/__tests__/activity-routes.test.ts +++ b/server/src/__tests__/activity-routes.test.ts @@ -151,7 +151,7 @@ describe("activity routes", () => { expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({ action: "issue:read", resource: expect.objectContaining({ companyId: "company-1", issueId: "issue-1" }), })); - expect(mockActivityService.forIssue).toHaveBeenCalledWith("issue-1"); + expect(mockActivityService.forIssue).toHaveBeenCalledWith("issue-1", undefined, "company-1"); expect(res.body).toEqual([{ action: "issue.recovery_action_resolved", actorType: "system" }]); }); diff --git a/server/src/__tests__/activity-service.test.ts b/server/src/__tests__/activity-service.test.ts index 0798e853388..ec79ab95555 100644 --- a/server/src/__tests__/activity-service.test.ts +++ b/server/src/__tests__/activity-service.test.ts @@ -947,4 +947,75 @@ describeEmbeddedPostgres("activity service", () => { await waitForLiveness(service, companyId, issueId, [runId]); }); }); + + describe("forIssue", () => { + it("returns issue events plus source-issue project and skill creations with company scoping", async () => { + const companyId = randomUUID(); + const otherCompanyId = randomUUID(); + const issueId = randomUUID(); + const projectId = randomUUID(); + const skillId = randomUUID(); + await db.insert(companies).values([ + { id: companyId, name: "Activity Co", issuePrefix: `A${companyId.slice(0, 4).toUpperCase()}` }, + { id: otherCompanyId, name: "Other Co", issuePrefix: `B${otherCompanyId.slice(0, 4).toUpperCase()}` }, + ]); + await db.insert(issues).values({ + id: issueId, + companyId, + title: "Activity test issue", + }); + await db.insert(activityLog).values([ + { + companyId, + actorType: "user", + actorId: "user-1", + action: "issue.updated", + entityType: "issue", + entityId: issueId, + details: { field: "title" }, + createdAt: new Date("2026-12-04T10:00:00Z"), + }, + { + companyId, + actorType: "agent", + actorId: randomUUID(), + action: "project.created", + entityType: "project", + entityId: projectId, + details: { sourceIssueId: issueId }, + createdAt: new Date("2026-12-04T10:01:00Z"), + }, + { + companyId, + actorType: "agent", + actorId: randomUUID(), + action: "company.skill_created", + entityType: "company_skill", + entityId: skillId, + details: { sourceIssueId: issueId }, + createdAt: new Date("2026-12-04T10:02:00Z"), + }, + { + companyId: otherCompanyId, + actorType: "agent", + actorId: randomUUID(), + action: "project.created", + entityType: "project", + entityId: randomUUID(), + details: { sourceIssueId: issueId }, + createdAt: new Date("2026-12-04T10:03:00Z"), + }, + ]); + + const service = activityService(db); + const scoped = await service.forIssue(issueId, undefined, companyId); + const inferred = await service.forIssue(issueId); + expect(scoped.map((row) => row.action)).toEqual([ + "company.skill_created", + "project.created", + "issue.updated", + ]); + expect(inferred.map((row) => row.id)).toEqual(scoped.map((row) => row.id)); + }); + }); }); diff --git a/server/src/__tests__/decision-history.test.ts b/server/src/__tests__/decision-history.test.ts index fec042bc192..16e071af5ba 100644 --- a/server/src/__tests__/decision-history.test.ts +++ b/server/src/__tests__/decision-history.test.ts @@ -3,6 +3,8 @@ import { sql } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { activityLog, agents, approvals, budgetIncidents, budgetPolicies, companies, createDb, decisions, decisionTargetIssues, heartbeatRuns, issueApprovals, issues, issueThreadInteractions, projects } from "@paperclipai/db"; import { approvalHistoryAction, decisionHistoryAction, decisionHistoryService, decodeDecisionHistoryCursor, decisionHistoryHref, decisionHistoryTarget, interactionHistoryAction, itemVerdictsHistoryLabel } from "../services/decision-history.js"; +import { conversationDecisionReceiptsService } from "../services/conversation-decision-receipts.js"; +import { decisionRetentionService } from "../services/decision-retention.js"; import { documentService } from "../services/documents.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; @@ -374,4 +376,84 @@ const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTes const secured = await service.list(companyId, { ...options, limit: 100 }); expect(secured.items.map((item) => item.sourceId)).not.toContain(visual); }); + + it("hydrates valid pending-question interactions in one batch and skips unparseable legacy payloads", async () => { + const companyId = randomUUID(), agentId = randomUUID(), conversationId = randomUUID(), taskId = randomUUID(); + const userId = "owner-user"; + await db.insert(companies).values({ id: companyId, name: "Chat Perf", issuePrefix: "CHP" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Codie", role: "engineer", adapterType: "codex_local" }); + await db.insert(issues).values([ + { + id: conversationId, companyId, identifier: "CHP-1", title: "Chat with Codie", + assigneeAgentId: agentId, conversationAgentId: agentId, conversationUserId: userId, + conversationState: "waiting", conversationSessionGeneration: 0, status: "in_review", createdByUserId: userId, + }, + { + id: taskId, companyId, identifier: "CHP-2", title: "Follow up", + assigneeAgentId: agentId, createdByUserId: userId, status: "in_progress", + }, + ]); + const validId = randomUUID(), legacyId = randomUUID(); + await db.insert(issueThreadInteractions).values([ + { + id: validId, companyId, issueId: taskId, kind: "ask_user_questions", status: "pending", + title: "Valid question", createdByAgentId: agentId, addresseeUserId: userId, + payload: { + version: 1, + questions: [{ id: "q1", prompt: "Ship now?", selectionMode: "single", options: [{ id: "yes", label: "Yes" }] }], + }, + }, + { + id: legacyId, companyId, issueId: taskId, kind: "ask_user_questions", status: "pending", + title: "Legacy question", createdByAgentId: agentId, addresseeUserId: userId, + payload: { questions: [{ id: "q1", prompt: "Legacy shape without version" }] } as never, + }, + ]); + const receipts = conversationDecisionReceiptsService(db); + const items = await receipts.listPendingQuestions(companyId, conversationId, { + actor: { type: "board", userId, source: "cloud_tenant", isInstanceAdmin: false }, + userId, + }); + expect(items.map((item) => item.subject.id)).toEqual(expect.arrayContaining([validId, legacyId])); + expect(items.find((item) => item.subject.id === validId)?.interaction).toMatchObject({ + id: validId, + kind: "ask_user_questions", + title: "Valid question", + }); + expect(items.find((item) => item.subject.id === legacyId)?.interaction).toBeUndefined(); + }); + + it("syncItems skips the write transaction in steady state and still updates when activityAt changes", async () => { + const companyId = randomUUID(); + const sourceId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "RetentionFastPath", issuePrefix: `RF${companyId.slice(0, 4).toUpperCase()}` }); + const retention = decisionRetentionService(db); + const initialAt = "2026-12-04T12:00:00.000Z"; + const first = await retention.syncItems(companyId, [ + { sourceKind: "issue_thread_interaction", subject: { id: sourceId }, activityAt: initialAt }, + ]); + const key = `issue_thread_interaction:${sourceId}`; + const created = first.get(key); + expect(created).toBeDefined(); + expect(created?.version).toBe(1); + + const txSpy = vi.spyOn(db, "transaction"); + try { + const steady = await retention.syncItems(companyId, [ + { sourceKind: "issue_thread_interaction", subject: { id: sourceId }, activityAt: initialAt }, + ]); + expect(txSpy).not.toHaveBeenCalled(); + expect(steady.get(key)).toEqual(created); + + const updatedAt = "2026-12-04T12:05:00.000Z"; + const updated = await retention.syncItems(companyId, [ + { sourceKind: "issue_thread_interaction", subject: { id: sourceId }, activityAt: updatedAt }, + ]); + expect(txSpy).toHaveBeenCalledTimes(1); + expect(updated.get(key)?.version).toBe(2); + expect(updated.get(key)?.sourceActivityAt.toISOString()).toBe(updatedAt); + } finally { + txSpy.mockRestore(); + } + }); }); diff --git a/server/src/__tests__/issue-thread-interaction-routes.test.ts b/server/src/__tests__/issue-thread-interaction-routes.test.ts index 97fd780be56..911ea8c022c 100644 --- a/server/src/__tests__/issue-thread-interaction-routes.test.ts +++ b/server/src/__tests__/issue-thread-interaction-routes.test.ts @@ -639,6 +639,7 @@ describe("issue thread interaction routes", () => { })); expect(list).toHaveBeenCalledWith("company-1", ISSUE_ID, { actor: owner, userId: owner.userId, cursor: "prior-page", limit: 100, + conversation: expect.objectContaining({ id: ISSUE_ID, companyId: "company-1" }), }); expect(mockLogActivity).not.toHaveBeenCalled(); expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled(); @@ -649,6 +650,7 @@ describe("issue thread interaction routes", () => { expect(response.status).toBe(200); expect(list).toHaveBeenCalledWith("company-1", ISSUE_ID, { actor: owner, userId: owner.userId, + conversation: expect.objectContaining({ id: ISSUE_ID, companyId: "company-1" }), }); }); diff --git a/server/src/__tests__/issue-thread-interactions-service.test.ts b/server/src/__tests__/issue-thread-interactions-service.test.ts index 49daac5b40b..7eda1ece555 100644 --- a/server/src/__tests__/issue-thread-interactions-service.test.ts +++ b/server/src/__tests__/issue-thread-interactions-service.test.ts @@ -4841,5 +4841,190 @@ describeEmbeddedPostgres("issueThreadInteractionService", () => { status: "accepted", }); }); + + it("listByIds evaluates acceptance readiness per issue, expires terminal issues, and skips ZodError legacy rows", async () => { + const { + companyId, + projectId, + executionWorkspaceId: unfinalizedWorkspaceId, + issueId: unfinalizedIssueId, + goalId, + interactionId: unfinalizedInteractionId, + sourceRunId, + } = await seedAcceptGateFixture({ sourceRunStatus: "running" }); + + const finalizedWorkspaceId = randomUUID(); + const finalizedIssueId = randomUUID(); + const noWorkspaceIssueId = randomUUID(); + const closedIssueId = randomUUID(); + const [projectWorkspace] = await db + .select({ id: projectWorkspaces.id }) + .from(projectWorkspaces) + .where(eq(projectWorkspaces.companyId, companyId)); + + await db.insert(executionWorkspaces).values({ + id: finalizedWorkspaceId, + companyId, + projectId, + projectWorkspaceId: projectWorkspace!.id, + mode: "isolated_workspace", + strategyType: "git_worktree", + name: "exec-finalized", + status: "active", + providerType: "git_worktree", + }); + + await db.insert(issues).values([ + { + id: finalizedIssueId, + companyId, + projectId, + goalId, + title: "Issue with finalized workspace", + status: "in_progress", + priority: "medium", + executionWorkspaceId: finalizedWorkspaceId, + }, + { + id: noWorkspaceIssueId, + companyId, + projectId, + goalId, + title: "Issue without workspace", + status: "in_progress", + priority: "medium", + executionWorkspaceId: null, + }, + { + id: closedIssueId, + companyId, + projectId, + goalId, + title: "Closed issue", + status: "done", + priority: "medium", + executionWorkspaceId: null, + }, + ]); + + // Same sourceRunId is unfinalized on unfinalizedWorkspaceId, but finalized on finalizedWorkspaceId. + await db.insert(workspaceOperations).values([ + { + companyId, + executionWorkspaceId: unfinalizedWorkspaceId, + heartbeatRunId: sourceRunId!, + phase: "worktree_prepare", + status: "succeeded", + }, + { + companyId, + executionWorkspaceId: finalizedWorkspaceId, + heartbeatRunId: sourceRunId!, + phase: "worktree_prepare", + status: "succeeded", + }, + { + companyId, + executionWorkspaceId: finalizedWorkspaceId, + heartbeatRunId: sourceRunId!, + phase: "workspace_finalize", + status: "succeeded", + }, + ]); + + const finalizedInteraction = await interactionsSvc.create( + { id: finalizedIssueId, companyId }, + { + kind: "request_confirmation", + continuationPolicy: "wake_assignee", + sourceRunId: sourceRunId!, + payload: { version: 1, prompt: "Accept finalized workspace card?" }, + }, + { userId: "local-board" }, + ); + const noWorkspaceInteraction = await interactionsSvc.create( + { id: noWorkspaceIssueId, companyId }, + { + kind: "request_confirmation", + continuationPolicy: "wake_assignee", + sourceRunId: sourceRunId!, + payload: { version: 1, prompt: "Accept workspace-less card?" }, + }, + { userId: "local-board" }, + ); + const [closedIssueInteraction] = await db + .insert(issueThreadInteractions) + .values({ + companyId, + issueId: closedIssueId, + kind: "request_confirmation", + status: "pending", + payload: { version: 1, prompt: "Stale card on closed issue?" }, + }) + .returning(); + const [malformedLegacyRow] = await db + .insert(issueThreadInteractions) + .values({ + companyId, + issueId: unfinalizedIssueId, + kind: "request_confirmation", + status: "pending", + // Missing required prompt -> triggers z.ZodError during hydration. + payload: { version: 1 } as unknown as IssueThreadInteractionPayload, + }) + .returning(); + + const allIds = [ + finalizedInteraction.id, + unfinalizedInteractionId, + noWorkspaceInteraction.id, + closedIssueInteraction!.id, + malformedLegacyRow!.id, + ]; + + for (const orderedIds of [allIds, [...allIds].reverse()]) { + const result = await interactionsSvc.listByIds(companyId, orderedIds); + expect(result.get(unfinalizedInteractionId)).toMatchObject({ + id: unfinalizedInteractionId, + status: "pending", + acceptanceBlocker: "workspace_sync_pending", + }); + expect(result.get(finalizedInteraction.id)?.acceptanceBlocker).toBeUndefined(); + expect(result.get(noWorkspaceInteraction.id)?.acceptanceBlocker).toBeUndefined(); + expect(result.get(closedIssueInteraction!.id)).toMatchObject({ + id: closedIssueInteraction!.id, + status: "expired", + result: { outcome: "issue_closed" }, + }); + expect(result.has(malformedLegacyRow!.id)).toBe(false); + } + }); + + it("listByIds rethrows non-ZodError hydration failures instead of swallowing them", async () => { + const { companyId, issueId } = await seedConfirmationIssue("listByIds non-Zod rethrow"); + const valid = await interactionsSvc.create( + { id: issueId, companyId }, + { + kind: "request_confirmation", + continuationPolicy: "wake_assignee", + payload: { version: 1, prompt: "Valid card" }, + }, + { userId: "local-board" }, + ); + const [unknownKindRow] = await db + .insert(issueThreadInteractions) + .values({ + companyId, + issueId, + kind: "unknown_future_kind", + status: "pending", + payload: { version: 1 } as unknown as IssueThreadInteractionPayload, + }) + .returning(); + + await expect( + interactionsSvc.listByIds(companyId, [valid.id, unknownKindRow!.id]), + ).rejects.toThrow("Unknown interaction kind: unknown_future_kind"); + }); }); }); diff --git a/server/src/routes/activity.ts b/server/src/routes/activity.ts index 67ff20fe94f..c122afe8e01 100644 --- a/server/src/routes/activity.ts +++ b/server/src/routes/activity.ts @@ -377,7 +377,7 @@ export function activityRoutes(db: Db) { res.json(await svc.inputFactsForIssue(issue.companyId, issue.id, parsed.data)); return; } - const result = await (req.query.view === "recent" ? svc.forIssue(issue.id, 50) : svc.forIssue(issue.id)); + const result = await (req.query.view === "recent" ? svc.forIssue(issue.id, 50, issue.companyId) : svc.forIssue(issue.id, undefined, issue.companyId)); res.json(await svc.withActorNames(result)); }); diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 2b268742e8e..46f7037532c 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -8719,7 +8719,7 @@ export function issueRoutes( recentComments.comments.map((comment) => comment.id).sort(), ), })), - activitySvc.forIssue(issue.id, 50).then(rows => activitySvc.withActorNames(rows)), + activitySvc.forIssue(issue.id, 50, issue.companyId).then(rows => activitySvc.withActorNames(rows)), activitySvc.runsForIssue(issue.companyId, issue.id, viewerUserId, 2, undefined, { skipLivenessBackfill: true }), issueThreadInteractionService(db).listForIssue(issue.id), svc.listAttachments(issue.id).then((rows) => rows.map(withContentPath)), @@ -18507,7 +18507,7 @@ export function issueRoutes( }).strict().safeParse(req.query); if (!query.success) throw badRequest("Invalid chat handoff filters"); res.json(await conversationDecisionReceiptsService(db).listCreatedTasks(issue.companyId, issue.id, { - ...query.data, actor: req.actor, userId: req.actor.userId, + ...query.data, actor: req.actor, userId: req.actor.userId, conversation: issue, })); }); @@ -18522,7 +18522,7 @@ export function issueRoutes( } if (!z.object({}).strict().safeParse(req.query).success) throw badRequest("Invalid pending question filters"); res.json(await conversationDecisionReceiptsService(db).listPendingQuestions(issue.companyId, issue.id, { - actor: req.actor, userId: req.actor.userId, + actor: req.actor, userId: req.actor.userId, conversation: issue, })); }); @@ -18541,7 +18541,7 @@ export function issueRoutes( }).strict().safeParse(req.query); if (!query.success) throw badRequest("Invalid decision receipt filters"); res.json(await conversationDecisionReceiptsService(db).list(issue.companyId, issue.id, { - ...query.data, actor: req.actor, userId: req.actor.userId, + ...query.data, actor: req.actor, userId: req.actor.userId, conversation: issue, })); }); diff --git a/server/src/services/activity.ts b/server/src/services/activity.ts index 6b433c3e7e8..eb37a639b5d 100644 --- a/server/src/services/activity.ts +++ b/server/src/services/activity.ts @@ -496,15 +496,32 @@ export function activityService(db: Db) { : row.actorType === "user" ? userNames.get(row.actorId) : undefined) ?? activityActorFallbackName(row.actorType, row.actorId) })); }, - forIssue: (issueId: string, limit?: number) => { + forIssue: (issueId: string, limit?: number, companyId?: string) => { + const companyPredicate = companyId + ? eq(activityLog.companyId, companyId) + : sql`${activityLog.companyId} = (select company_id from issues where id = ${issueId})`; const query = db .select() .from(activityLog) .where( or( - and(eq(activityLog.entityType, "issue"), eq(activityLog.entityId, issueId)), - and(or(eq(activityLog.action, "project.created"), eq(activityLog.action, "company.skill_created")), sql`${activityLog.details}->>'sourceIssueId' = ${issueId}`, - sql`${activityLog.companyId} = (select company_id from issues where id = ${issueId})`), + and( + ...(companyId ? [eq(activityLog.companyId, companyId)] : []), + eq(activityLog.entityType, "issue"), + eq(activityLog.entityId, issueId), + ), + and( + companyPredicate, + eq(activityLog.entityType, "project"), + eq(activityLog.action, "project.created"), + sql`${activityLog.details}->>'sourceIssueId' = ${issueId}`, + ), + and( + companyPredicate, + eq(activityLog.entityType, "company_skill"), + eq(activityLog.action, "company.skill_created"), + sql`${activityLog.details}->>'sourceIssueId' = ${issueId}`, + ), ), ) .orderBy(desc(activityLog.createdAt), desc(activityLog.id)); diff --git a/server/src/services/attention.ts b/server/src/services/attention.ts index e5ce678848f..98e873c309b 100644 --- a/server/src/services/attention.ts +++ b/server/src/services/attention.ts @@ -80,7 +80,7 @@ import { authorizationService, canActorReadApproval, issueReadSqlCondition, type import { humanCreatedIssueCondition } from "./issue-participation.js"; import { attentionAlreadyClosedError } from "./attention-already-closed.js"; import { inboxDismissalService } from "./inbox-dismissals.js"; -import { assertInteractionRoutingRecipientAllowed } from "./issue-thread-interactions.js"; +import { assertInteractionRoutingRecipientAllowed, issueThreadInteractionService } from "./issue-thread-interactions.js"; import { resolvableApprovalStatuses } from "../lib/approval-records.js"; import { activeIssueInteractionCondition, deferrableInteractionCondition } from "./issue-question-context.js"; import { evaluateAgentInvokability, type AgentOrgRow } from "./agent-invokability.js"; @@ -658,24 +658,33 @@ async function enrichAttentionItems( ) { if (items.length === 0) return items; const sourceIds = [...new Set(items.map((item) => item.subject.id))]; - const queueRows = !includeQueues ? [] : await db - .select({ - sourceKind: decisionQueueItems.sourceKind, - sourceId: decisionQueueItems.sourceId, - key: decisionQueues.key, - title: decisionQueues.title, - retentionDays: decisionQueues.retentionDays, - }) - .from(decisionQueueItems) - .innerJoin(decisionQueues, and( - eq(decisionQueueItems.queueId, decisionQueues.id), - eq(decisionQueues.companyId, companyId), - )) - .where(and( - eq(decisionQueueItems.companyId, companyId), - inArray(decisionQueueItems.sourceId, sourceIds), - )) - .orderBy(asc(decisionQueues.title), asc(decisionQueues.key)); + const [queueRows, triageRows] = await Promise.all([ + !includeQueues ? Promise.resolve([]) : db + .select({ + sourceKind: decisionQueueItems.sourceKind, + sourceId: decisionQueueItems.sourceId, + key: decisionQueues.key, + title: decisionQueues.title, + retentionDays: decisionQueues.retentionDays, + }) + .from(decisionQueueItems) + .innerJoin(decisionQueues, and( + eq(decisionQueueItems.queueId, decisionQueues.id), + eq(decisionQueues.companyId, companyId), + )) + .where(and( + eq(decisionQueueItems.companyId, companyId), + inArray(decisionQueueItems.sourceId, sourceIds), + )) + .orderBy(asc(decisionQueues.title), asc(decisionQueues.key)), + db + .select() + .from(decisionTriage) + .where(and( + eq(decisionTriage.companyId, companyId), + inArray(decisionTriage.sourceId, sourceIds), + )), + ]); const queuesBySource = new Map(); const retentionDaysBySource = new Map(); for (const row of queueRows) { @@ -689,14 +698,6 @@ async function enrichAttentionItems( retentionDaysBySource.set(key, values); } } - - const triageRows = await db - .select() - .from(decisionTriage) - .where(and( - eq(decisionTriage.companyId, companyId), - inArray(decisionTriage.sourceId, sourceIds), - )); const triageBySource = new Map(triageRows.map((row) => [ sourceKey(row.sourceKind as AttentionSourceKind, row.sourceId), row, @@ -1901,13 +1902,19 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions const visibleInteractionRows = collapsePendingConfirmationsToNewest(boardInteractionRows, await loadNewestSettledConfirmationAt( db, companyId, boardInteractionRows.filter((row) => row.kind === "request_confirmation").map((row) => row.issueId), )).filter(row => row.active); + const planConfirmationIssueIds = summaryOnly + ? [] + : visibleInteractionRows + .filter((row) => row.kind === "request_confirmation" && isPlanDocumentTarget(readRecord(row.payload))) + .map((row) => row.issueId); const [interactionIssueMap, interactionImageMap, interactionPlanDocumentMap] = await Promise.all([ // A pending human request remains actionable in a persistent chat even // though its idle container is intentionally absent from work queues. loadIssues(visibleInteractionRows.map((row) => row.issueId), true), loadImages(db, companyId, visibleInteractionRows.map((row) => row.issueId), readCondition), - summaryOnly ? Promise.resolve(new Map()) - : planDocumentMap(db, companyId, visibleInteractionRows.map((row) => row.issueId), readCondition), + planConfirmationIssueIds.length === 0 + ? Promise.resolve(new Map()) + : planDocumentMap(db, companyId, planConfirmationIssueIds, readCondition), ]); for (const interaction of visibleInteractionRows) { @@ -2938,7 +2945,15 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions taskQuestions: async (companyId: string, issueIds: readonly string[], options: { actor: AuthorizationActor; userId: string }): Promise => { if (issueIds.length === 0) return []; const feed = await list(companyId, { ...options, all: true, allowUnscopedAll: true }, issueIds); - return feed.items; + if (feed.items.length === 0) return []; + const interactionById = await issueThreadInteractionService(db).listByIds( + companyId, + feed.items.map((item) => item.subject.id), + ); + return feed.items.map((item) => { + const interaction = interactionById.get(item.subject.id); + return interaction ? { ...item, interaction } : item; + }); }, summary: async (companyId: string, options: Pick = {}): Promise => { const { items: _items, nextCursor: _cursor, ...summary } = await list(companyId, { diff --git a/server/src/services/conversation-decision-receipts.ts b/server/src/services/conversation-decision-receipts.ts index ae12b3f94dd..d747b0c481f 100644 --- a/server/src/services/conversation-decision-receipts.ts +++ b/server/src/services/conversation-decision-receipts.ts @@ -14,14 +14,31 @@ const handoffCursorIdSchema = z.uuid(); * Both the source chat's current audience and every task's current access are * checked on every read, including history pagination after a chat reset. */ export function conversationDecisionReceiptsService(db: Db) { - async function source(companyId: string, conversationId: string, options: { actor: AuthorizationActor; userId: string }) { + type AuthorizedConversation = Pick< + typeof issues.$inferSelect, + "id" | "companyId" | "conversationAgentId" | "conversationUserId" | "conversationSessionGeneration" | "conversationBoundaryCommentId" | "createdAt" + >; + async function source( + companyId: string, + conversationId: string, + options: { actor: AuthorizationActor; userId: string; conversation?: AuthorizedConversation }, + ): Promise { + if ( + options.conversation && + options.conversation.id === conversationId && + options.conversation.companyId === companyId && + options.conversation.conversationAgentId && + options.conversation.conversationUserId === options.userId + ) { + return options.conversation; + } const readable = await issueReadSqlCondition(db, options.actor); const [conversation] = await db.select().from(issues).where(and(eq(issues.id, conversationId), eq(issues.companyId, companyId), isNotNull(issues.conversationAgentId), eq(issues.conversationUserId, options.userId), readable)); if (!conversation) throw notFound("Conversation not found"); return conversation; } - async function taskScopes(companyId: string, conversation: typeof issues.$inferSelect, options: { + async function taskScopes(companyId: string, conversation: AuthorizedConversation, options: { actor: AuthorizationActor; userId: string; }) { const readable = await issueReadSqlCondition(db, options.actor); @@ -47,7 +64,7 @@ export function conversationDecisionReceiptsService(db: Db) { } return { async listPendingQuestions(companyId: string, conversationId: string, options: { - actor: AuthorizationActor; userId: string; + actor: AuthorizationActor; userId: string; conversation?: AuthorizedConversation; }): Promise { const conversation = await source(companyId, conversationId, options); const { handoffIds, directIds } = await taskScopes(companyId, conversation, options); @@ -59,7 +76,7 @@ export function conversationDecisionReceiptsService(db: Db) { return attentionService(db).taskQuestions(companyId, [...taskIds], options); }, async listCreatedTasks(companyId: string, conversationId: string, options: { - actor: AuthorizationActor; userId: string; cursor?: string; limit?: number; + actor: AuthorizationActor; userId: string; cursor?: string; limit?: number; conversation?: AuthorizedConversation; }): Promise { const conversation = await source(companyId, conversationId, options); const limit = Math.max(1, Math.min(options.limit ?? 40, 100)); @@ -103,6 +120,7 @@ export function conversationDecisionReceiptsService(db: Db) { async list(companyId: string, conversationId: string, options: { actor: AuthorizationActor; userId: string; + conversation?: AuthorizedConversation; } & Pick): Promise { const conversation = await source(companyId, conversationId, options); const { handoffIds, directIds } = await taskScopes(companyId, conversation, options); diff --git a/server/src/services/decision-history.ts b/server/src/services/decision-history.ts index 3bc225723cc..de6eb7a4454 100644 --- a/server/src/services/decision-history.ts +++ b/server/src/services/decision-history.ts @@ -263,7 +263,12 @@ async function handledForBySource(db: Db, companyId: string, items: Array= ''`, + // PostgreSQL estimates high selectivity for `IS NOT NULL` and falls back + // to a full-table Seq Scan of `activity_log`. sql`(${activityLog.details} ->> 'handledForUserId') IS NOT NULL`, + sql`(${activityLog.details} ->> 'handledForUserId') >= ''`, inArray(sql`${activityLog.details} -> 'receipt' ->> 'sourceId'`, sourceIds), )) .orderBy(desc(activityLog.createdAt)); @@ -287,7 +292,6 @@ export function decisionHistoryService(db: Db) { const since = options.since ? new Date(options.since) : null; if (since && !Number.isFinite(since.getTime())) throw badRequest("Invalid decision history date"); const readable = await issueReadSqlCondition(db, options.actor); - const readableIssues = db.select({ id: issues.id }).from(issues).where(and(eq(issues.companyId, companyId), readable)); const [company] = await db.select({ prefix: companies.issuePrefix }).from(companies).where(eq(companies.id, companyId)); if (!company) return { items: [], nextCursor: null }; // Cursor timestamps use the JSON/Date millisecond precision. Normalize SQL @@ -400,7 +404,7 @@ export function decisionHistoryService(db: Db) { .leftJoin(agents, and(eq(agents.id, decisions.originAgentId), eq(agents.companyId, companyId))) .leftJoin(projects, and(eq(projects.id, issues.projectId), eq(projects.companyId, companyId))) .where(and(eq(decisions.companyId, companyId), readable, notInArray(decisions.status, ["open"]), - sql`not exists (select 1 from ${decisionTargetIssues} where ${decisionTargetIssues.decisionId} = ${decisions.id} and (${decisionTargetIssues.companyId} <> ${companyId} or ${decisionTargetIssues.issueId} not in (${readableIssues})))`, + sql`not exists (select 1 from ${decisionTargetIssues} where ${decisionTargetIssues.decisionId} = ${decisions.id} and (${decisionTargetIssues.companyId} <> ${companyId} or not exists (select 1 from ${issues} where ${issues.companyId} = ${companyId} and ${issues.id} = ${decisionTargetIssues.issueId} and ${readable})))`, decisionOutcome, decisionScope, options.handledForMe ? handledForUserSourceCondition(companyId, options.userId, "decision", decisions.id) : undefined, options.agentId ? eq(decisions.originAgentId, options.agentId) : undefined, diff --git a/server/src/services/decision-retention.ts b/server/src/services/decision-retention.ts index 4ff2b094416..79cfadc70ac 100644 --- a/server/src/services/decision-retention.ts +++ b/server/src/services/decision-retention.ts @@ -140,10 +140,24 @@ export function decisionRetentionService( async function syncItems(companyId: string, items: readonly RetentionSource[]) { if (items.length === 0) return new Map(); const unique = [...new Map(items.map(item => [itemSourceKey(item), item])).values()]; + const sourceIds = unique.map(item => item.subject.id); + // Read-only fast path: in the steady state where every item already has a + // matching retention row with the same activity timestamp, avoid opening a + // write transaction on every read. + const initialRows = await db.select().from(decisionRetention).where(and( + eq(decisionRetention.companyId, companyId), + inArray(decisionRetention.sourceId, sourceIds), + )); + const initialByKey = new Map(initialRows.map(row => [sourceKey(row.sourceKind, row.sourceId), row])); + const needsSync = unique.some((item) => { + const row = initialByKey.get(itemSourceKey(item)); + return !row || row.sourceActivityAt.getTime() !== new Date(item.activityAt).getTime(); + }); + if (!needsSync) return initialByKey; return db.transaction(async tx => { const select = () => tx.select().from(decisionRetention).where(and( eq(decisionRetention.companyId, companyId), - inArray(decisionRetention.sourceId, unique.map(item => item.subject.id)), + inArray(decisionRetention.sourceId, sourceIds), )); let rows = await select(); const existing = new Set(rows.map(row => sourceKey(row.sourceKind, row.sourceId))); diff --git a/server/src/services/issue-thread-interactions.ts b/server/src/services/issue-thread-interactions.ts index 0ca10249139..dfa5473eb32 100644 --- a/server/src/services/issue-thread-interactions.ts +++ b/server/src/services/issue-thread-interactions.ts @@ -766,6 +766,25 @@ const storedRequestConfirmationPayloadSchema = requestConfirmationPayloadSchema. ]).nullable().optional(), }); +function hydrateInteractionForIssue( + row: IssueThreadInteractionRow, + issue?: { status: string }, +): IssueThreadInteraction { + return hydrateInteraction( + issue && + isTerminalIssueStatus(issue.status) && + row.status === "pending" && + !staysOpenOnTerminalIssue(row, issue.status) + ? { + ...row, + status: "expired", + result: buildAdministrativeOutcomeResult(row, "issue_closed"), + resolvedAt: row.updatedAt, + } + : row, + ); +} + function hydrateInteraction( row: IssueThreadInteractionRow, ): IssueThreadInteraction { @@ -4827,21 +4846,9 @@ export function issueThreadInteractionService( .then((issueRows) => issueRows[0]), ]); - const interactions = rows.filter((row) => !isHeldRoutineSuggestion(row, issue?.status)).map((row) => - hydrateInteraction( - issue && - isTerminalIssueStatus(issue.status) && - row.status === "pending" && - !staysOpenOnTerminalIssue(row, issue.status) - ? { - ...row, - status: "expired", - result: buildAdministrativeOutcomeResult(row, "issue_closed"), - resolvedAt: row.updatedAt, - } - : row, - ), - ); + const interactions = rows + .filter((row) => !isHeldRoutineSuggestion(row, issue?.status)) + .map((row) => hydrateInteractionForIssue(row, issue)); return withAcceptanceReadiness(interactions, issue); }, @@ -4855,6 +4862,51 @@ export function issueThreadInteractionService( return row ? (await withAcceptanceReadiness([hydrateInteraction(row)]))[0] : null; }, + listByIds: async (companyId: string, interactionIds: readonly string[]) => { + const uniqueIds = [...new Set(interactionIds.filter(Boolean))]; + if (uniqueIds.length === 0) return new Map(); + const rows = await db + .select() + .from(issueThreadInteractions) + .where(and( + eq(issueThreadInteractions.companyId, companyId), + inArray(issueThreadInteractions.id, uniqueIds), + )); + if (rows.length === 0) return new Map(); + const issueIds = [...new Set(rows.map((row) => row.issueId))]; + const issueRows = await db + .select({ + id: issues.id, + status: issues.status, + companyId: issues.companyId, + executionWorkspaceId: issues.executionWorkspaceId, + }) + .from(issues) + .where(and(eq(issues.companyId, companyId), inArray(issues.id, issueIds))); + const issueById = new Map(issueRows.map((row) => [row.id, row])); + const hydratedByIssue = new Map(); + for (const row of rows) { + const issue = issueById.get(row.issueId); + if (isHeldRoutineSuggestion(row, issue?.status)) continue; + try { + const item = hydrateInteractionForIssue(row, issue); + const group = hydratedByIssue.get(row.issueId); + if (group) group.push(item); + else hydratedByIssue.set(row.issueId, [item]); + } catch (error) { + if (!(error instanceof z.ZodError)) throw error; + // Skip unparseable legacy rows rather than failing the whole batch; + // callers fall back to per-issue reads when an inline interaction is absent. + } + } + const readyGroups = await Promise.all( + [...hydratedByIssue.entries()].map(([issueId, group]) => + withAcceptanceReadiness(group, issueById.get(issueId)), + ), + ); + return new Map(readyGroups.flat().map((item) => [item.id, item])); + }, + recordSecretProposalExecutionResult: async ( issue: { id: string; companyId: string }, interactionId: string, diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index effbcd51b0c..0006e79e72b 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -431,7 +431,7 @@ "packages/shared/src/types/approval.ts": "4554d36f804cb74b825b29711ed4c622df07ff6d", "packages/shared/src/types/artifact.ts": "6d022d34a718196df5c109a6164e7a70ede287e8", "packages/shared/src/types/asset.ts": "d148d6cba0e9a8d2e3aa6cb9182df6f59f909fba", - "packages/shared/src/types/attention.ts": "ac112c8e57d853ebdb739e459b7acb41313947ad", + "packages/shared/src/types/attention.ts": "ec310599deb773488593db9c62c4e0af173e16a5", "packages/shared/src/types/board-bootstrap.ts": "8eb0e0ec4c91369d12b268b9411ed512c8d1e8b1", "packages/shared/src/types/budget.ts": "7b3fe924d571008d67093c051a13d2c7e67f3ebe", "packages/shared/src/types/chat-channels.ts": "103eb76c5c517102e999b49b4bb726e0ea228902", diff --git a/ui/src/components/AttentionInteractionResolver.initial.test.tsx b/ui/src/components/AttentionInteractionResolver.initial.test.tsx new file mode 100644 index 00000000000..de37c00adee --- /dev/null +++ b/ui/src/components/AttentionInteractionResolver.initial.test.tsx @@ -0,0 +1,147 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { IssueThreadInteraction } from "@paperclipai/shared"; +import { queryKeys } from "../lib/queryKeys"; + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const listInteractionsMock = vi.fn(); + +vi.mock("../api/issues", () => ({ + issuesApi: { + listInteractions: (...args: unknown[]) => listInteractionsMock(...args), + acceptInteraction: vi.fn(), + rejectInteraction: vi.fn(), + respondToInteraction: vi.fn(), + submitInteractionVerdicts: vi.fn(), + }, +})); + +vi.mock("./AttentionCloseMenu", () => ({ + useAttentionActionConfirmation: () => async () => {}, +})); + +vi.mock("./IssueThreadInteractionCard", () => ({ + IssueThreadInteractionCard: ({ interaction }: { interaction: IssueThreadInteraction }) => ( +
{interaction.title ?? interaction.id}:{interaction.status}
+ ), +})); + +import { AttentionInteractionResolver } from "./AttentionInteractionResolver"; + +const QUESTION_INTERACTION: IssueThreadInteraction = { + id: "11111111-1111-4111-8111-111111111111", + companyId: "22222222-2222-4222-8222-222222222222", + issueId: "33333333-3333-4333-8333-333333333333", + kind: "ask_user_questions", + status: "pending", + title: "Choose rollout strategy", + summary: null, + continuationPolicy: "wake_assignee", + requestedResolverPolicy: "human_only", + effectiveResolverPolicy: "human_only", + resolverPolicy: "human_only", + legacyResolverPolicyAliases: { requested: null, effective: null }, + resolverPolicyProvenance: "explicit", + effectiveResolverPolicySource: "requested", + addresseeAgentId: null, + addresseeUserId: "user-1", + createdByAgentId: null, + createdByUserId: null, + sourceRunId: null, + sourceCommentId: null, + resolvedByAgentId: null, + resolvedByUserId: null, + resolvedAt: null, + dismissedAt: null, + dismissedByUserId: null, + payload: { + version: 1, + questions: [ + { + id: "q1", + prompt: "Which rollout?", + selectionMode: "single", + options: [{ id: "a", label: "Canary" }], + }, + ], + }, + result: null, + createdAt: new Date("2026-12-04T15:00:00Z"), + updatedAt: new Date("2026-12-04T15:00:00Z"), +}; + +describe("AttentionInteractionResolver initialInteraction", () => { + let container: HTMLDivElement; + let root: Root; + let queryClient: QueryClient; + + beforeEach(() => { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + listInteractionsMock.mockReset(); + }); + + afterEach(() => { + act(() => root.unmount()); + container.remove(); + }); + + it("renders immediately from initialInteraction without fetching listInteractions and prefers cache updates", async () => { + await act(async () => { + root.render( + + + , + ); + }); + expect(container.querySelector('[data-testid="interaction-card"]')?.textContent).toBe("Choose rollout strategy:pending"); + expect(listInteractionsMock).not.toHaveBeenCalled(); + + const answered: IssueThreadInteraction = { + ...QUESTION_INTERACTION, + status: "answered", + resolvedByUserId: "user-1", + resolvedAt: new Date("2026-12-04T15:05:00Z"), + }; + await act(async () => { + queryClient.setQueryData(queryKeys.issues.interactions(QUESTION_INTERACTION.issueId), [answered]); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + expect(container.querySelector('[data-testid="interaction-card"]')?.textContent).toBe("Choose rollout strategy:answered"); + }); + + it("still renders initialInteraction when the shared interactions query holds a stale cached error", async () => { + listInteractionsMock.mockRejectedValueOnce(new Error("previous fetch failed")); + await queryClient.prefetchQuery({ + queryKey: queryKeys.issues.interactions(QUESTION_INTERACTION.issueId), + queryFn: () => listInteractionsMock(QUESTION_INTERACTION.issueId), + }).catch(() => {}); + listInteractionsMock.mockReset(); + + await act(async () => { + root.render( + + + , + ); + }); + expect(container.querySelector('[data-testid="interaction-card"]')?.textContent).toBe("Choose rollout strategy:pending"); + expect(listInteractionsMock).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/src/components/AttentionInteractionResolver.tsx b/ui/src/components/AttentionInteractionResolver.tsx index 2eb0da2ad22..4da037aec1a 100644 --- a/ui/src/components/AttentionInteractionResolver.tsx +++ b/ui/src/components/AttentionInteractionResolver.tsx @@ -40,6 +40,8 @@ interface AttentionInteractionResolverProps { audienceStated?: boolean; /** Successful updates include partial item reviews; inspect status before settling the whole card. */ onResolved?: (interaction?: IssueThreadInteraction) => void; + /** Optional hydrated interaction already loaded by a batched endpoint (e.g. pending-questions). */ + initialInteraction?: IssueThreadInteraction | null; } export function replaceResolvedInteraction( @@ -77,21 +79,29 @@ export function AttentionInteractionResolver({ artifactRow, shareReviseDraft, onResolved, + initialInteraction, }: AttentionInteractionResolverProps) { const queryClient = useQueryClient(); const confirmAction = useAttentionActionConfirmation(); - const { data: interactions, isLoading, error } = useQuery({ + const hydratedInitialInteraction = useMemo(() => { + return initialInteraction && initialInteraction.id === interactionId && isIssueThreadInteraction(initialInteraction) + ? initialInteraction + : null; + }, [initialInteraction, interactionId]); + + const { data: interactions, isLoading } = useQuery({ queryKey: queryKeys.issues.interactions(issueId), queryFn: () => issuesApi.listInteractions(issueId), - enabled: !!issueId, + enabled: !!issueId && !hydratedInitialInteraction, refetchInterval: (query) => interactionReadinessRefetchInterval(query.state.data), }); const interaction = useMemo(() => { const match = (interactions ?? []).find((entry) => entry.id === interactionId); - return match && isIssueThreadInteraction(match) ? match : null; - }, [interactions, interactionId]); + if (match && isIssueThreadInteraction(match)) return match; + return hydratedInitialInteraction; + }, [interactions, interactionId, hydratedInitialInteraction]); const invalidate = (resolvedInteraction?: IssueThreadInteraction) => { // Cancel old reads before publishing the write's canonical response. @@ -144,7 +154,7 @@ export function AttentionInteractionResolver({ onSuccess: invalidate, }); - if (isLoading) { + if (!interaction && isLoading) { return (
@@ -155,7 +165,7 @@ export function AttentionInteractionResolver({ ); } - if (error || !interaction) { + if (!interaction) { return (

diff --git a/ui/src/components/TaskChatThread.test.tsx b/ui/src/components/TaskChatThread.test.tsx index 9a1dad60d4b..1c6b3da2d1d 100644 --- a/ui/src/components/TaskChatThread.test.tsx +++ b/ui/src/components/TaskChatThread.test.tsx @@ -33,6 +33,7 @@ import type { HeartbeatRunEvent } from "@paperclipai/shared"; import type { HeartbeatRun } from "@paperclipai/shared"; import { waitForStoppedRuns } from "@/lib/wait-for-stopped-runs"; import { ApiError } from "@/api/api-error"; +import * as runAnswerVisibility from "@/lib/run-answer-visibility"; const transcriptState = vi.hoisted(() => ({ transcriptByRun: new Map(), @@ -955,10 +956,77 @@ describe.each(["legacy", "native"] as const)("%s task history readiness", (runti expect(editor?.textContent).toBe("Keep this draft"); }); - it.each(["running", "failed", "no-reply", "placeholder", "chat", "yielded", "no-presentation", "progress"])("hydrates compact output when it is required (%s)", (scenario) => { + it("defers completed saved-reply runs in persistent agent chats while still hydrating required chat runs", async () => { + const savedProps = { + issueId: "saved-chat", compactHistory: true, conversationMode: true, onAdd: async () => {}, + linkedRuns: [{ ...retryRun, runId: "saved-run", status: "succeeded", startedAt: retryRun.createdAt }], + comments: [{ ...createLongThreadComments()[3], id: "saved-answer", authorType: "agent" as const, + authorAgentId: "agent-1", body: "Saved chat reply", runId: "saved-run" }], + }; + render(); + await settleThreadLayout(); + expect(container.textContent).toContain("Saved chat reply"); + expect(transcriptHookRuns.native.at(-1)).toEqual([]); + expect(transcriptHookRuns.legacy.at(-1)).toEqual([]); + render(); + expect((runtimeMode === "native" ? transcriptHookRuns.native : transcriptHookRuns.legacy).at(-1)).toMatchObject([{ id: "live-chat-run" }]); + }); + + it("defers 300 completed chat runs with linear indexing and no extra work on unchanged re-render", async () => { + const baseComment = createLongThreadComments()[3]; + const runCount = 300; + const linkedRuns = Array.from({ length: runCount }, (_, index) => { + const ts = new Date(Date.UTC(2026, 7, 25, 18, 0, index)).toISOString(); + return { + ...retryRun, + runId: `bulk-run-${index}`, + status: "succeeded", + createdAt: ts, + startedAt: ts, + }; + }); + const comments = Array.from({ length: runCount }, (_, index) => ({ + ...baseComment, + id: `bulk-answer-${index}`, + authorType: "agent" as const, + authorAgentId: "agent-1", + body: `Saved reply ${index}`, + runId: `bulk-run-${index}`, + createdAt: new Date(Date.UTC(2026, 7, 25, 18, 0, index)), + updatedAt: new Date(Date.UTC(2026, 7, 25, 18, 0, index)), + })); + const onAdd = async () => {}; + const indexSpy = vi.spyOn(runAnswerVisibility, "indexVisibleAgentCommentIdsByRun"); + const lookupSpy = vi.spyOn(runAnswerVisibility, "hasIndexedVisibleRunAnswer"); + try { + const props = { + issueId: "bulk-saved-chat", + compactHistory: true, + conversationMode: true, + onAdd, + linkedRuns, + comments, + }; + render(); + await settleThreadLayout(); + expect(transcriptHookRuns.native.at(-1)).toEqual([]); + expect(transcriptHookRuns.legacy.at(-1)).toEqual([]); + expect(indexSpy).toHaveBeenCalledTimes(1); + expect(lookupSpy).toHaveBeenCalledTimes(runCount); + + // An unchanged re-render must reuse the memoized deferral result. + render(); + expect(indexSpy).toHaveBeenCalledTimes(1); + expect(lookupSpy).toHaveBeenCalledTimes(runCount); + } finally { + indexSpy.mockRestore(); + lookupSpy.mockRestore(); + } + }); + + it.each(["running", "failed", "no-reply", "placeholder", "yielded", "no-presentation", "progress"])("hydrates compact output when it is required (%s)", (scenario) => { const props = { issueId: "required-output", compactHistory: true, onAdd: async () => {}, onExpandHistory: vi.fn(), - conversationMode: scenario === "chat", linkedRuns: [{ ...retryRun, runId: "saved-run", status: ["running", "failed"].includes(scenario) ? scenario : "succeeded", startedAt: retryRun.createdAt, resultJson: scenario === "yielded" ? { nativeResult: { schema: "paperclip.run_result.v1", reportedWorkDisposition: "yielded" } } : scenario === "no-presentation" ? { presentationDecision: { schema: "paperclip.run_presentation_decision.v1", commentId: null } } diff --git a/ui/src/components/TaskChatThread.tsx b/ui/src/components/TaskChatThread.tsx index aeb0c61225c..6f040a42e1e 100644 --- a/ui/src/components/TaskChatThread.tsx +++ b/ui/src/components/TaskChatThread.tsx @@ -1,5 +1,6 @@ import { - hasVisibleRunAnswer, + hasIndexedVisibleRunAnswer, + indexVisibleAgentCommentIdsByRun, LEGACY_WITHHELD_RUN_COMMENT, presentationDecisionCommentId, semanticProgressCommentIds, @@ -167,6 +168,10 @@ import { isRunStopConfirmed } from "@/lib/wait-for-stopped-runs"; import { safeNavigableUrl } from "@/lib/safe-url"; const EMPTY_BROWSERS: TaskBrowser[] = []; +const EMPTY_DOCUMENTS: NonNullable = []; +const EMPTY_WORK_PRODUCTS: NonNullable = []; +const EMPTY_ATTACHMENTS: NonNullable = []; +const EMPTY_BLOCKED_BY: NonNullable = []; const COMPACT_RUN_LOG_READ_LIMIT_BYTES = 32_000; /** Mirrors task-interruption-presentation.ts: a swarm-route failure needs the person when Antigravity says so. */ @@ -511,9 +516,9 @@ export function TaskChatThread(props: TaskChatThreadProps) { onRetryInitialHistory, comments, interactions: storedInteractions, - documents = [], - workProducts = [], - attachments = [], + documents = EMPTY_DOCUMENTS, + workProducts = EMPTY_WORK_PRODUCTS, + attachments = EMPTY_ATTACHMENTS, timelineEvents, issueId = null, agentMap, @@ -577,7 +582,7 @@ export function TaskChatThread(props: TaskChatThreadProps) { onSteerQueuedComment, queuedMessageAutoSteerDelayMs = QUEUED_MESSAGE_AUTO_STEER_DELAY_MS, onDiscardQueuedComment, - blockedBy = [], + blockedBy = EMPTY_BLOCKED_BY, blockerAttention, liveIssueIds, onResumeAssignee, @@ -1014,25 +1019,42 @@ export function TaskChatThread(props: TaskChatThreadProps) { const slowTranscriptRunIds = slowTranscriptsForIssue?.ids ?? EMPTY_RUN_IDS; const slowSettledTranscriptRunIds = slowTranscriptsForIssue?.deferred ?? EMPTY_RUN_IDS; const compactTranscriptDeferral = Boolean(props.compactHistory && !conversationMode && props.onExpandHistory && !scrollNavigation.hash); + // Persistent agent chats also open with a bounded comment window whose older + // completed turns already have saved replies; skip fetching their historical + // run transcripts on open just like compact task opens do. + const deferSavedCompletedTranscripts = Boolean( + props.compactHistory && (conversationMode || props.onExpandHistory) && !scrollNavigation.hash, + ); const deferredTranscriptRunIds = useMemo(() => { const deferred = new Set(); - if (!compactTranscriptDeferral) return deferred; - for (const run of runs) if (slowSettledTranscriptRunIds.has(run.id)) deferred.add(run.id); + if (!deferSavedCompletedTranscripts) return deferred; + if (compactTranscriptDeferral) { + for (const run of runs) if (slowSettledTranscriptRunIds.has(run.id)) deferred.add(run.id); + } + const pendingInteractionRunIds = new Set(); + if (interactions) { + for (const interaction of interactions) { + if (interaction.status === "pending" && interaction.sourceRunId) { + pendingInteractionRunIds.add(interaction.sourceRunId); + } + } + } + const visibleAgentCommentIdsByRun = indexVisibleAgentCommentIdsByRun(projectedComments); for (const run of runs) { if (requestedTranscripts.current.ids.has(run.id) || run.status !== "succeeded" || !run.createdAt || toMs(run.createdAt) > openedAt) continue; const meta = linkedRunMetaById.get(run.id); if (acceptedSemanticResultDisposition(meta?.resultJson) === "yielded" || - interactions?.some(interaction => interaction.sourceRunId === run.id && interaction.status === "pending")) continue; - if (hasVisibleRunAnswer(projectedComments, run.id, meta?.resultJson)) deferred.add(run.id); + pendingInteractionRunIds.has(run.id)) continue; + if (hasIndexedVisibleRunAnswer(visibleAgentCommentIdsByRun, run.id, meta?.resultJson)) deferred.add(run.id); } return deferred; - }, [issueId, runs, projectedComments, linkedRunMetaById, interactions, compactTranscriptDeferral, slowSettledTranscriptRunIds, openedAt]); + }, [issueId, runs, projectedComments, linkedRunMetaById, interactions, compactTranscriptDeferral, deferSavedCompletedTranscripts, slowSettledTranscriptRunIds, openedAt]); const transcriptRuns = useMemo(() => runs.filter(run => !deferredTranscriptRunIds.has(run.id) && - !(props.compactHistory && !conversationMode && props.onExpandHistory && !scrollNavigation.hash && + !(deferSavedCompletedTranscripts && initialHistoryPending && isTerminalRunStatus(run.status) && !requestedTranscripts.current.ids.has(run.id)), - ), [issueId, runs, deferredTranscriptRunIds, props.compactHistory, conversationMode, props.onExpandHistory, scrollNavigation.hash, initialHistoryPending]); + ), [issueId, runs, deferredTranscriptRunIds, deferSavedCompletedTranscripts, initialHistoryPending]); useLayoutEffect(() => { for (const run of transcriptRuns) requestedTranscripts.current.ids.add(run.id); }, [transcriptRuns]); diff --git a/ui/src/components/coordinator/CoordinatorChatPendingQuestions.tsx b/ui/src/components/coordinator/CoordinatorChatPendingQuestions.tsx index 3332309b6ed..5d6eee3dc9e 100644 --- a/ui/src/components/coordinator/CoordinatorChatPendingQuestions.tsx +++ b/ui/src/components/coordinator/CoordinatorChatPendingQuestions.tsx @@ -34,7 +34,7 @@ export function CoordinatorChatPendingQuestion({ item }: { item: AttentionItem } return

{item.originAgentName ?? "Your agent"} needs your input on {task.title ?? task.identifier ?? "this task"}.

- + {task.identifier ?? "Open task"}{task.title} } /> diff --git a/ui/src/components/transcript/useNativeRunTranscripts.streaming.test.tsx b/ui/src/components/transcript/useNativeRunTranscripts.streaming.test.tsx index 23324b27bb5..47c224fa34b 100644 --- a/ui/src/components/transcript/useNativeRunTranscripts.streaming.test.tsx +++ b/ui/src/components/transcript/useNativeRunTranscripts.streaming.test.tsx @@ -288,3 +288,15 @@ it("does not skip compact conversation rows committed during an older catch-up", await act(async () => vi.advanceTimersByTimeAsync(90_000)); expect(conversationEvents).toHaveBeenCalledTimes(settledReads); }); + +it("does not refetch already-hydrated terminal runs when the live stream reconnects", async () => { + events.mockResolvedValue([]); + await render("company-1", true, true); + await negotiate(); + const olderCallsBeforeReconnect = events.mock.calls.filter(([id]) => id === "older").length; + expect(olderCallsBeforeReconnect).toBe(1); + await act(async () => store.close()); + await negotiate(); + const olderCallsAfterReconnect = events.mock.calls.filter(([id]) => id === "older").length; + expect(olderCallsAfterReconnect).toBe(1); +}); diff --git a/ui/src/components/transcript/useNativeRunTranscripts.test.tsx b/ui/src/components/transcript/useNativeRunTranscripts.test.tsx index 633a3c16ac3..81fb3fcce69 100644 --- a/ui/src/components/transcript/useNativeRunTranscripts.test.tsx +++ b/ui/src/components/transcript/useNativeRunTranscripts.test.tsx @@ -225,7 +225,13 @@ describe("native history readiness and stable projection", () => { let container: HTMLDivElement; let root: Root; let latest: ReturnType; - function StateProbe({ runs = [{ id: "one", status: "running", runtimeMode: "native" as const }], enabled = true }) { + function StateProbe({ + runs = [{ id: "one", status: "running", runtimeMode: "native" as const }], + enabled = true, + }: { + runs?: Array<{ id: string; status: string; runtimeMode: "native"; conversationOnly?: boolean }>; + enabled?: boolean; + }) { latest = useNativeRunTranscripts(runs, { enabled }); return null; } @@ -268,15 +274,19 @@ describe("native history readiness and stable projection", () => { expect(eventsMock.mock.calls.map(([id]) => id)).toEqual(["one", "two", "one", "two"]); }); - it("restarts an interrupted explicit refresh when history membership changes", async () => { + it("keeps an in-flight explicit refresh alive when history membership changes, and restarts reads interrupted by disabling", async () => { eventsMock.mockResolvedValueOnce([]).mockImplementationOnce(() => new Promise(() => {})).mockResolvedValue([]); const one = { id: "one", status: "succeeded", runtimeMode: "native" as const }; await act(async () => { root.render(); }); await act(async () => { latest.retry(); }); - const interruptedSignal = eventsMock.mock.calls[1][3].signal; + const inFlightSignal = eventsMock.mock.calls[1][3].signal; await act(async () => { root.render(); }); - expect(interruptedSignal.aborted).toBe(true); - expect(eventsMock.mock.calls.map(([id]) => id)).toEqual(["one", "one", "one", "two"]); + expect(inFlightSignal.aborted).toBe(false); + expect(eventsMock.mock.calls.map(([id]) => id)).toEqual(["one", "one", "two"]); + await act(async () => { root.render(); }); + expect(inFlightSignal.aborted).toBe(true); + await act(async () => { root.render(); }); + expect(eventsMock.mock.calls.map(([id]) => id)).toEqual(["one", "one", "two", "one", "two"]); }); it("revalidates settled history after a disabled view resumes", async () => { @@ -363,4 +373,55 @@ describe("native history readiness and stable projection", () => { expect(eventsMock.mock.calls.filter(([id]) => id === "one").map(([, cursor]) => cursor)).toEqual([0, 7]); expect(latest.isInitialHydrating).toBe(false); }); + + it("restarts with full events immediately when conversationOnly toggles off during an in-flight read", async () => { + conversationEventsMock.mockImplementation(() => new Promise(() => {})); + eventsMock.mockResolvedValue([{ seq: 3, payload: {}, eventType: "log" }]); + const compactRun = { id: "expand-run", status: "succeeded", runtimeMode: "native" as const, conversationOnly: true }; + await act(async () => { root.render(); }); + expect(conversationEventsMock).toHaveBeenCalledTimes(1); + const compactSignal = conversationEventsMock.mock.calls[0][3].signal as AbortSignal; + expect(compactSignal.aborted).toBe(false); + expect(eventsMock).not.toHaveBeenCalled(); + + await act(async () => { root.render(); }); + expect(compactSignal.aborted).toBe(true); + expect(eventsMock).toHaveBeenCalledTimes(1); + expect(eventsMock.mock.calls[0][0]).toBe("expand-run"); + expect(latest.hydratedRunIds.has("expand-run")).toBe(true); + expect(latest.transcriptByRun.has("expand-run")).toBe(true); + }); + + it("finishes terminal hydration and stops polling when a live run succeeds during an in-flight poll", async () => { + vi.useFakeTimers(); + try { + let resolveFirstRead!: (rows: Array<{ seq: number; payload: Record; eventType: string }>) => void; + eventsMock + .mockImplementationOnce(() => new Promise((resolve) => { resolveFirstRead = resolve; })) + .mockResolvedValueOnce([{ seq: 2, payload: {}, eventType: "log" }]); + + const liveRun = { id: "finishing-run", status: "running", runtimeMode: "native" as const }; + await act(async () => { root.render(); }); + expect(eventsMock).toHaveBeenCalledTimes(1); + + // Run completes before the in-flight poll resolves. + await act(async () => { root.render(); }); + expect(eventsMock).toHaveBeenCalledTimes(1); + + // Resolving the first read must trigger one final terminal catchup read and then stop polling. + await act(async () => { + resolveFirstRead([{ seq: 1, payload: {}, eventType: "log" }]); + await Promise.resolve(); + await Promise.resolve(); + }); + expect(eventsMock).toHaveBeenCalledTimes(2); + expect(eventsMock.mock.calls[1][1]).toBe(1); + expect(latest.terminalHydratedRunIds.has("finishing-run")).toBe(true); + + await act(async () => { await vi.advanceTimersByTimeAsync(10_000); }); + expect(eventsMock).toHaveBeenCalledTimes(2); + } finally { + vi.useRealTimers(); + } + }); }); diff --git a/ui/src/components/transcript/useNativeRunTranscripts.ts b/ui/src/components/transcript/useNativeRunTranscripts.ts index fc1c0ceaa87..89a3c61de94 100644 --- a/ui/src/components/transcript/useNativeRunTranscripts.ts +++ b/ui/src/components/transcript/useNativeRunTranscripts.ts @@ -81,18 +81,72 @@ export function useNativeRunTranscripts(runs: readonly NativeRunTranscriptSource }; const gapPendingRef = useRef(new Set()); const historyReadsRef = useRef(new Map()); + const inFlightStatusByRunRef = useRef(new Map()); + const latestRunByIdRef = useRef(new Map()); + const controllersByRunRef = useRef(new Map()); + const timersByRunRef = useRef(new Map()); + const pendingRefreshRef = useRef(new Set()); const interruptedReadsRef = useRef(new Set()); const refreshByRunRef = useRef(new Map void>()); + const hydratedStatusByRunRef = useRef(new Map()); + const errorsByRunRef = useRef(new Map()); + const streamHealthyRef = useRef(false); + const mountedRef = useRef(true); const previousCompanyRef = useRef(options.companyId); - const refreshContextRef = useRef([]); + const previousContextRef = useRef<{ + retryGeneration: number; + visible: boolean; + enabled: boolean | undefined; + companyId: string | null | undefined; + streamHealthy: boolean; + streamEpoch: number; + } | null>(null); + + const abortRun = useCallback((runId: string, markInterrupted: boolean) => { + const timer = timersByRunRef.current.get(runId); + if (timer !== undefined) { + window.clearTimeout(timer); + timersByRunRef.current.delete(runId); + } + const controller = controllersByRunRef.current.get(runId); + if (controller) { + if (historyReadsRef.current.get(runId) === controller.signal) { + if (markInterrupted) interruptedReadsRef.current.add(runId); + historyReadsRef.current.delete(runId); + inFlightStatusByRunRef.current.delete(runId); + } + controllersByRunRef.current.delete(runId); + controller.abort(); + } + pendingRefreshRef.current.delete(runId); + refreshByRunRef.current.delete(runId); + }, []); + + const abortAllRuns = useCallback((markInterrupted: boolean) => { + for (const runId of [...new Set([...controllersByRunRef.current.keys(), ...timersByRunRef.current.keys(), ...refreshByRunRef.current.keys()])]) { + abortRun(runId, markInterrupted); + } + }, [abortRun]); + + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + abortAllRuns(false); + }; + }, [abortAllRuns]); + useEffect(() => { if (previousCompanyRef.current === options.companyId) return; previousCompanyRef.current = options.companyId; + abortAllRuns(false); setEventsByRun(new Map()); setErrorsByRun(new Map()); setHydratedRunIds(new Set()); setHydratedStatusByRun(new Map()); + hydratedStatusByRunRef.current.clear(); errorsByRunRef.current.clear(); + inFlightStatusByRunRef.current.clear(); latestRunByIdRef.current.clear(); projectionCacheRef.current.clear(); cursorByRunRef.current.clear(); conversationOnlyByRunRef.current.clear(); persistedEventsByRunRef.current.clear(); sequencesRef.current.clear(); gapPendingRef.current.clear(); interruptedReadsRef.current.clear(); - }, [options.companyId]); + }, [options.companyId, abortAllRuns]); const stream = useTranscriptLiveStream(nativeRuns.filter(run => isLive(run.status)).map(run => run.id), options, event => { const runId = typeof event.payload.runId === "string" ? event.payload.runId : null; if (!runId || !nativeRuns.some(run => run.id === runId)) return; @@ -113,27 +167,50 @@ export function useNativeRunTranscripts(runs: readonly NativeRunTranscriptSource }); + streamHealthyRef.current = stream.healthy; + useEffect(() => { - const context = [retryGeneration, visible, options.enabled, options.companyId, stream.healthy, stream.epoch]; - const refreshExisting = context.some((value, index) => value !== refreshContextRef.current[index]); - refreshContextRef.current = context; - if (!visible || options.enabled === false) return; + const prev = previousContextRef.current; + const retryChanged = prev !== null && prev.retryGeneration !== retryGeneration; + const companyChanged = prev !== null && prev.companyId !== options.companyId; + const becameActive = prev !== null && ((!prev.visible && visible) || (prev.enabled === false && options.enabled !== false)); + previousContextRef.current = { + retryGeneration, + visible, + enabled: options.enabled, + companyId: options.companyId, + streamHealthy: stream.healthy, + streamEpoch: stream.epoch, + }; + if (!visible || options.enabled === false) { + abortAllRuns(true); + return; + } + const nextLatestById = new Map(); + for (const run of nativeRuns) nextLatestById.set(run.id, run); + latestRunByIdRef.current = nextLatestById; const changedModes = new Set(); for (const run of nativeRuns) { const mode = Boolean(run.conversationOnly); if (conversationOnlyByRunRef.current.get(run.id) !== mode) { changedModes.add(run.id); cursorByRunRef.current.delete(run.id); sequencesRef.current.delete(run.id); + abortRun(run.id, false); } if (changedModes.has(run.id) || !persistedEventsByRunRef.current.has(run.id)) { persistedEventsByRunRef.current.set(run.id, savedHistory.get(run.id)?.events ?? []); } conversationOnlyByRunRef.current.set(run.id, mode); } - let cancelled = false; - const controller = new AbortController(); - const timers = new Map(); - const pendingRefresh = new Set(); const retainedIds = new Set(nativeRuns.map((run) => run.id)); + for (const id of [...controllersByRunRef.current.keys()]) { + if (!retainedIds.has(id)) abortRun(id, false); + } + for (const id of [...timersByRunRef.current.keys()]) { + if (!retainedIds.has(id)) abortRun(id, false); + } + for (const id of [...refreshByRunRef.current.keys()]) { + if (!retainedIds.has(id)) refreshByRunRef.current.delete(id); + } for (const id of interruptedReadsRef.current) if (!retainedIds.has(id)) interruptedReadsRef.current.delete(id); const retainMap = (previous: Map) => { const next = new Map([...previous].filter(([id]) => retainedIds.has(id))); @@ -149,8 +226,16 @@ export function useNativeRunTranscripts(runs: readonly NativeRunTranscriptSource } return next; }); - setErrorsByRun(retainMap); - setHydratedStatusByRun(retainMap); + setErrorsByRun((previous) => { + const next = retainMap(previous); + errorsByRunRef.current = next; + return next; + }); + setHydratedStatusByRun((previous) => { + const next = retainMap(previous); + hydratedStatusByRunRef.current = next; + return next; + }); setHydratedRunIds((previous) => { const next = new Set([...previous].filter((id) => retainedIds.has(id))); return next.size === previous.size ? previous : next; @@ -165,11 +250,17 @@ export function useNativeRunTranscripts(runs: readonly NativeRunTranscriptSource } const refreshRun = async (run: NativeRunTranscriptSource) => { - if (cancelled || historyReadsRef.current.has(run.id)) return; - pendingRefresh.delete(run.id); - window.clearTimeout(timers.get(run.id)); - timers.delete(run.id); + if (!mountedRef.current || historyReadsRef.current.has(run.id)) return; + pendingRefreshRef.current.delete(run.id); + const existingTimer = timersByRunRef.current.get(run.id); + if (existingTimer !== undefined) { + window.clearTimeout(existingTimer); + timersByRunRef.current.delete(run.id); + } + const controller = new AbortController(); + controllersByRunRef.current.set(run.id, controller); historyReadsRef.current.set(run.id, controller.signal); + inFlightStatusByRunRef.current.set(run.id, run.status); let failed = false; try { const saved = savedHistory.get(run.id); @@ -181,7 +272,7 @@ export function useNativeRunTranscripts(runs: readonly NativeRunTranscriptSource (signal) => (run.conversationOnly ? heartbeatsApi.conversationEvents : heartbeatsApi.events)(run.id, cursor, EVENT_PAGE_SIZE, { signal }), controller.signal, ); - if (cancelled) return; + if (!mountedRef.current || controller.signal.aborted) return; const last = page.at(-1); const nextCursor = last ? Math.max(cursor, last.seq) : cursor; incoming.push(...page.filter((event) => event.seq > cursor)); @@ -217,15 +308,18 @@ export function useNativeRunTranscripts(runs: readonly NativeRunTranscriptSource if (!previous.has(run.id)) return previous; const next = new Map(previous); next.delete(run.id); + errorsByRunRef.current = next; return next; }); interruptedReadsRef.current.delete(run.id); setHydratedStatusByRun((previous) => { if (previous.get(run.id) === run.status) return previous; - return new Map(previous).set(run.id, run.status); + const next = new Map(previous).set(run.id, run.status); + hydratedStatusByRunRef.current = next; + return next; }); } catch (error) { - if (cancelled) return; + if (!mountedRef.current || controller.signal.aborted) return; failed = true; setErrorsByRun((previous) => { if (previous.has(run.id)) return previous; @@ -234,41 +328,66 @@ export function useNativeRunTranscripts(runs: readonly NativeRunTranscriptSource message: error instanceof Error ? error.message : "Native run activity could not be loaded", failedAt: new Date().toISOString(), }); + errorsByRunRef.current = next; return next; }); } - if (historyReadsRef.current.get(run.id) === controller.signal) historyReadsRef.current.delete(run.id); - if (cancelled) return; + if (historyReadsRef.current.get(run.id) === controller.signal) { + historyReadsRef.current.delete(run.id); + inFlightStatusByRunRef.current.delete(run.id); + } + if (controllersByRunRef.current.get(run.id) === controller) controllersByRunRef.current.delete(run.id); + if (!mountedRef.current || controller.signal.aborted) return; setHydratedRunIds((previous) => previous.has(run.id) ? previous : new Set([...previous, run.id])); - if (pendingRefresh.has(run.id)) { - void refreshRun(run); - } else if ((isLive(run.status) && !stream.healthy) || failed) { + const latestRun = latestRunByIdRef.current.get(run.id); + if (!latestRun) return; + if (pendingRefreshRef.current.has(run.id)) { + void refreshRun(latestRun); + } else if ((isLive(latestRun.status) && !streamHealthyRef.current) || failed) { const timer = window.setTimeout(() => { - timers.delete(run.id); - void refreshRun(run); + timersByRunRef.current.delete(run.id); + const currentRun = latestRunByIdRef.current.get(run.id); + if (currentRun) void refreshRun(currentRun); }, EVENT_POLL_INTERVAL_MS); - timers.set(run.id, timer); + timersByRunRef.current.set(run.id, timer); } }; for (const run of nativeRuns) { refreshByRunRef.current.set(run.id, (force = false) => { - if (force) pendingRefresh.add(run.id); - void refreshRun(run); + if (force) pendingRefreshRef.current.add(run.id); + void refreshRun(latestRunByIdRef.current.get(run.id) ?? run); }); - if (refreshExisting || changedModes.has(run.id) || interruptedReadsRef.current.has(run.id) || isLive(run.status) - || hydratedStatusByRun.get(run.id) !== run.status || errorsByRun.has(run.id) || sequence(run.id).needsCatchup) void refreshRun(run); - } - return () => { - cancelled = true; - refreshByRunRef.current.clear(); - controller.abort(); - for (const [id, signal] of historyReadsRef.current) if (signal === controller.signal) { - interruptedReadsRef.current.add(id); - historyReadsRef.current.delete(id); + // Do not abort sibling in-flight reads or re-fetch already-hydrated + // terminal runs merely because another run arrived or the live stream + // transitioned state; only live/unhydrated/errored/explicitly-retried + // runs need a fetch. + const needsRefresh = + retryChanged || + companyChanged || + becameActive || + changedModes.has(run.id) || + interruptedReadsRef.current.has(run.id) || + isLive(run.status) || + hydratedStatusByRunRef.current.get(run.id) !== run.status || + errorsByRunRef.current.has(run.id) || + sequence(run.id).needsCatchup; + if (needsRefresh) { + if (historyReadsRef.current.has(run.id)) { + if ( + retryChanged || + companyChanged || + becameActive || + inFlightStatusByRunRef.current.get(run.id) !== run.status || + sequence(run.id).needsCatchup + ) { + pendingRefreshRef.current.add(run.id); + } + } else { + void refreshRun(run); + } } - for (const timer of timers.values()) window.clearTimeout(timer); - }; - }, [nativeRuns, retryGeneration, visible, options.enabled, options.companyId, stream.healthy, stream.epoch, queryClient, savedHistory]); + } + }, [nativeRuns, retryGeneration, visible, options.enabled, options.companyId, stream.healthy, stream.epoch, queryClient, savedHistory, abortRun, abortAllRuns]); const transcriptByRun = useMemo(() => { const transcripts = new Map(); diff --git a/ui/src/lib/queryKeys.ts b/ui/src/lib/queryKeys.ts index 7e2b4baea21..fa284935f9f 100644 --- a/ui/src/lib/queryKeys.ts +++ b/ui/src/lib/queryKeys.ts @@ -20,6 +20,8 @@ export const queryKeys = { ["agent-chats", companyId, userId] as const, detail: (companyId: string | null, userId: string | null, agentId: string | undefined) => ["agent-chat", companyId, userId, agentId] as const, + byRef: (companyId: string | null, agentRef: string | undefined) => + ["agent-chat", "by-ref", companyId, agentRef] as const, }, companies: { /** diff --git a/ui/src/lib/run-answer-visibility.ts b/ui/src/lib/run-answer-visibility.ts index 06b41578277..ba60103cfd5 100644 --- a/ui/src/lib/run-answer-visibility.ts +++ b/ui/src/lib/run-answer-visibility.ts @@ -38,16 +38,56 @@ export function semanticProgressCommentIds(value: unknown): Set { return ids; } +export interface RunAnswerVisibilityComment { + id: string; + authorType: string; + body: string; + deletedAt?: Date | string | null; + runId?: string | null; + createdByRunId?: string | null; + derivedCreatedByRunId?: string | null; +} + +export function indexVisibleAgentCommentIdsByRun( + comments: ReadonlyArray, +): Map { + const byRun = new Map(); + for (const comment of comments) { + if ( + comment.authorType !== "agent" || + comment.deletedAt || + !comment.body.trim() || + comment.body === LEGACY_WITHHELD_RUN_COMMENT + ) { + continue; + } + const runId = comment.runId ?? comment.createdByRunId ?? comment.derivedCreatedByRunId; + if (!runId) continue; + const list = byRun.get(runId); + if (list) list.push(comment.id); + else byRun.set(runId, [comment.id]); + } + return byRun; +} + +export function hasIndexedVisibleRunAnswer( + commentIdsByRun: ReadonlyMap, + runId: string, + resultJson: unknown, +): boolean { + const commentIds = commentIdsByRun.get(runId); + if (!commentIds || commentIds.length === 0) return false; + const presentationCommentId = presentationDecisionCommentId(resultJson); + const progressCommentIds = semanticProgressCommentIds(resultJson); + return commentIds.some( + (commentId) => + !progressCommentIds.has(commentId) && + (presentationCommentId === undefined || presentationCommentId === commentId), + ); +} + export function hasVisibleRunAnswer( - comments: ReadonlyArray<{ - id: string; - authorType: string; - body: string; - deletedAt?: Date | string | null; - runId?: string | null; - createdByRunId?: string | null; - derivedCreatedByRunId?: string | null; - }>, + comments: ReadonlyArray, runId: string, resultJson: unknown, ): boolean { diff --git a/ui/src/lib/vite-issue-detail-preload.test.ts b/ui/src/lib/vite-issue-detail-preload.test.ts index 712d4b64d46..92d1aa697a6 100644 --- a/ui/src/lib/vite-issue-detail-preload.test.ts +++ b/ui/src/lib/vite-issue-detail-preload.test.ts @@ -94,3 +94,27 @@ it.each(["/PAP/chats/helper", "/PAP/issues", "/PAP/issues/all", "/PAP/inbox/mine expect(page.fetches.filter(([url]) => String(url).includes("chat-bootstrap"))).toEqual([]); expect(page.win[EARLY_CHAT_BOOTSTRAP_GLOBAL]).toBeUndefined(); }); + +it("preloads the AgentChat chunk alongside IssueDetail on a hard load of /chats/:ref", () => { + const hook = preloadIssueDetail().transformIndexHtml; + if (typeof hook !== "function") throw new Error("Missing HTML transform"); + const tags = hook.call({} as never, "", { + bundle: { + detail: { type: "chunk", fileName: "assets/issue-detail-fixture.js", moduleIds: ["/app/src/pages/IssueDetail.tsx"], imports: ["assets/shared.js"] }, + chat: { type: "chunk", fileName: "assets/agent-chat-fixture.js", moduleIds: ["/app/src/pages/AgentChat.tsx"], imports: ["assets/issue-detail-fixture.js"] }, + shared: { type: "chunk", fileName: "assets/shared.js", moduleIds: [], imports: [] }, + }, + } as never) as { tag: string; children: string }[]; + const run = (pathname: string) => { + const links: { rel: string; href: string; crossOrigin: string }[] = []; + runInNewContext(tags[0].children, { + location: { pathname, origin: "https://board.example" }, + fetch: () => Promise.resolve({ ok: true, headers: { get: () => "" }, json: () => Promise.resolve(null), arrayBuffer: () => Promise.resolve(new ArrayBuffer(0)) }), + window: { addEventListener: () => {} }, + document: { createElement: () => ({}), head: { appendChild: (link: typeof links[number]) => links.push(link) }, addEventListener: () => {} }, + }); + return links.map((link) => link.href); + }; + expect(run("/PAP/chats/codie")).toEqual(["/assets/agent-chat-fixture.js", "/assets/issue-detail-fixture.js", "/assets/shared.js"]); + expect(run("/PAP/issues/PAP-1")).toEqual(["/assets/issue-detail-fixture.js", "/assets/shared.js"]); +}); diff --git a/ui/src/lib/vite-issue-detail-preload.ts b/ui/src/lib/vite-issue-detail-preload.ts index e8f0b64d4e5..08384ab6aaf 100644 --- a/ui/src/lib/vite-issue-detail-preload.ts +++ b/ui/src/lib/vite-issue-detail-preload.ts @@ -10,22 +10,34 @@ export function preloadIssueDetail(): Plugin { chunk.type === "chunk" && chunk.moduleIds.some((id) => id.endsWith("/src/pages/IssueDetail.tsx")), ); if (!issueDetail) return []; + const agentChat = Object.values(bundle ?? {}).find((chunk) => + chunk.type === "chunk" && chunk.moduleIds.some((id) => id.endsWith("/src/pages/AgentChat.tsx")), + ); const chunks = new Map(Object.values(bundle ?? {}).filter(chunk => chunk.type === "chunk").map(chunk => [chunk.fileName, chunk])); - const dependencies = new Set(); - const visit = (fileName: string) => { - if (!chunks.has(fileName) || dependencies.has(fileName)) return; - dependencies.add(fileName); - for (const imported of chunks.get(fileName)?.imports ?? []) visit(imported); + const collectDependencies = (rootFileName: string) => { + const deps = new Set(); + const visit = (fileName: string) => { + if (!chunks.has(fileName) || deps.has(fileName)) return; + deps.add(fileName); + for (const imported of chunks.get(fileName)?.imports ?? []) visit(imported); + }; + visit(rootFileName); + return [...deps].map(fileName => `/${fileName}`); }; - visit(issueDetail.fileName); + const issueDependencies = collectDependencies(issueDetail.fileName); + const chatDependencies = agentChat + ? [...new Set([...collectDependencies(agentChat.fileName), ...issueDependencies])] + : issueDependencies; return [{ tag: "script", injectTo: "head-prepend", children: `(() => { - const isDetail = pathname => { + const detailRoute = pathname => { const parts = pathname.split("/").filter(Boolean); const route = parts.length === 3 ? parts[1] : parts.length === 2 ? parts[0] : null; - return route === "chats" || (route === "issues" && !["all", "active", "backlog", "done", "recent"].includes(parts[parts.length - 1])); + if (route === "chats") return "chats"; + if (route === "issues" && !["all", "active", "backlog", "done", "recent"].includes(parts[parts.length - 1])) return "issues"; + return null; }; const append = href => { const link = document.createElement("link"); @@ -35,7 +47,7 @@ export function preloadIssueDetail(): Plugin { document.head.appendChild(link); }; let requested = false; - const preload = (speculative = false) => { + const preload = (speculative = false, kind = "issues") => { if (requested) return; requested = true; if (speculative) { @@ -45,10 +57,11 @@ export function preloadIssueDetail(): Plugin { }).catch(() => {}); return; } - for (const href of ${JSON.stringify([...dependencies].map(fileName => `/${fileName}`))}) append(href); + for (const href of kind === "chats" ? ${JSON.stringify(chatDependencies)} : ${JSON.stringify(issueDependencies)}) append(href); }; - if (isDetail(location.pathname)) { - preload(); + const currentRoute = detailRoute(location.pathname); + if (currentRoute) { + preload(false, currentRoute); // A hard load of a task starts the chat's first-frame data now, in // parallel with the app's JavaScript; the page adopts this answer. const parts = location.pathname.split("/").filter(Boolean); @@ -66,7 +79,7 @@ export function preloadIssueDetail(): Plugin { window.addEventListener(${JSON.stringify(TASK_COLLECTION_PAINTED_EVENT)}, () => preload(true), { once: true }); const onIntent = event => { const link = event.target.closest?.("a[href]"); - if (link?.origin === location.origin && isDetail(link.pathname)) preload(true); + if (link?.origin === location.origin && detailRoute(link.pathname)) preload(true); }; document.addEventListener("pointerover", onIntent, { passive: true }); document.addEventListener("pointerdown", onIntent, { passive: true }); diff --git a/ui/src/pages/AgentChat.tsx b/ui/src/pages/AgentChat.tsx index 916083bf8e5..408c346dc35 100644 --- a/ui/src/pages/AgentChat.tsx +++ b/ui/src/pages/AgentChat.tsx @@ -7,6 +7,7 @@ import { QueryErrorState, useQueryView } from "@/components/QueryView"; import { useCompany } from "@/context/CompanyContext"; import { useAgentChatEnabled } from "@/hooks/useAgentChatEnabled"; import { recordAgentChatVisit } from "@/lib/recent-agent-chats"; +import { startIssueChatBootstrap } from "@/lib/issue-chat-bootstrap"; import { queryKeys } from "@/lib/queryKeys"; import { Link, useLocation, useParams } from "@/lib/router"; import { agentRouteRef } from "@/lib/utils"; @@ -44,20 +45,77 @@ export function AgentChat() { && !rosterAgent && isUuidLike(agentRef), }); const agent = rosterAgent ?? (historyAgent.data?.companyId === selectedCompanyId ? historyAgent.data : undefined); + // Start resolving the chat by route ref immediately in parallel with the + // agent roster and session reads so cold opens avoid a serial waterfall. + // Seed the canonical detail cache entry instead of keeping a second live + // useQuery source that could diverge on invalidation. + useEffect(() => { + if (!enabled || !selectedCompanyId || !agentRef || (agent && session.isFetched)) return; + let cancelled = false; + const byRefKey = queryKeys.agentChats.byRef(selectedCompanyId, agentRef); + void client + .fetchQuery({ + queryKey: byRefKey, + queryFn: () => agentChatsApi.get(selectedCompanyId, agentRef), + staleTime: 0, + gcTime: 0, + }) + .then((prefetched) => { + if (cancelled || !prefetched || prefetched.companyId !== selectedCompanyId) return; + if (prefetched.id) { + startIssueChatBootstrap(client, selectedCompanyId, prefetched.id, [ + prefetched.id, + prefetched.identifier, + ]); + } + if (prefetched.conversationAgentId) { + const detailKey = queryKeys.agentChats.detail( + selectedCompanyId, + prefetched.conversationUserId ?? null, + prefetched.conversationAgentId, + ); + if (client.getQueryState(detailKey)?.data === undefined) { + client.setQueryData(detailKey, prefetched); + } + } + }) + .catch(() => { + // Ignore speculative prefetch errors; the canonical chat query handles + // error rendering and retries once agent + session settle. + }); + return () => { + cancelled = true; + }; + }, [enabled, selectedCompanyId, agentRef, agent, session.isFetched, client]); const chatKey = queryKeys.agentChats.detail(selectedCompanyId, userId, agent?.id); const chat = useQuery({ queryKey: chatKey, queryFn: () => agentChatsApi.get(selectedCompanyId!, agent!.id), - initialData: () => enabled && agent && session.isSuccess - ? client.getQueryData(queryKeys.agentChats.list(selectedCompanyId, userId)) - ?.find(issue => issue.companyId === selectedCompanyId && issue.conversationAgentId === agent?.id) - : undefined, + initialData: () => { + if (!enabled || !agent || !session.isSuccess) return undefined; + return client.getQueryData(queryKeys.agentChats.list(selectedCompanyId, userId)) + ?.find(issue => issue.companyId === selectedCompanyId && issue.conversationAgentId === agent?.id); + }, initialDataUpdatedAt: () => { - const state = client.getQueryState(queryKeys.agentChats.list(selectedCompanyId, userId)); - return state?.isInvalidated ? 0 : state?.dataUpdatedAt; + const listState = client.getQueryState(queryKeys.agentChats.list(selectedCompanyId, userId)); + return listState?.isInvalidated ? 0 : listState?.dataUpdatedAt; }, enabled: enabled && !!agent && session.isFetched, }); + // As soon as the conversation issue id is known, start the single + // chat-bootstrap request so TaskDetailSurface's first-frame reads share it + // instead of fanning out individually. + if ( + enabled && + selectedCompanyId && + chat.data?.id && + chat.data.companyId === selectedCompanyId + ) { + startIssueChatBootstrap(client, selectedCompanyId, chat.data.id, [ + chat.data.id, + chat.data.identifier, + ]); + } const sessionView = useQueryView(session); const historyView = useQueryView(historyAgent); const chatView = useQueryView(chat); diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index 20fd12b5f30..a2e67aa9b0d 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -3461,10 +3461,13 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS // chat history saved, so it opens like a cold one. const bootstrapCompanyId = companies.find((company) => company.issuePrefix === companyPrefix?.toUpperCase())?.id ?? selectedCompanyId; const coreIssueKey = issueId ? [...queryKeys.issues.detail(issueId), "core"] : null; - if (issueId && coreIssueKey && !conversation + if (issueId && coreIssueKey && (queryClient.getQueryData(coreIssueKey) === undefined || isRestoredSavedRead(queryClient, coreIssueKey))) { const restoredIssue = queryClient.getQueryData(coreIssueKey); - startIssueChatBootstrap(queryClient, bootstrapCompanyId, issueId, [restoredIssue?.id, restoredIssue?.identifier]); + startIssueChatBootstrap(queryClient, bootstrapCompanyId, issueId, [ + restoredIssue?.id ?? conversation?.issue?.id, + restoredIssue?.identifier ?? conversation?.issue?.identifier, + ]); } // The core issue keeps its own small, fast read so the header never waits // for the larger chat bootstrap; a preloaded task already has it cached.