mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
perf(chat): eliminate activity_log seq scans, chat load waterfalls, and transcript storms (#23750)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Persistent agent chat pages (`/:companyPrefix/chats/:agentRef`) are a primary surface for collaborating with an agent across many tasks and turns. > - Opening an active agent chat page was slow: multiple endpoints scanned the full `activity_log` table, the page bypassed the single-request chat bootstrap, the native transcript hook aborted and retried historical run fetches across multiple waves, and pending task questions triggered N+1 per-task interaction requests. > - These bottlenecks blocked the initial chat reveal for several seconds and saturated server and database capacity during page open. > - This pull request eliminates the `activity_log` sequential scans with index-backed predicates (no schema migrations), batches pending-question interaction hydration, defers completed saved-reply run transcripts in persistent agent chats, stabilizes per-run transcript lifecycles, and enables parallel chat resolution and chat-bootstrap adoption on agent chat pages. > - The benefit is dramatically faster agent chat page loads with far fewer HTTP requests, zero `activity_log` full-table scans on hot chat paths, and no schema migrations. ## Linked Issues or Issue Description Related: #18461, #20355, #21650, #21671. **What happened?** Opening a persistent agent chat page with accumulated history and active tasks took multiple seconds before the conversation became visible and triggered dozens of concurrent API requests: 1. `decisionHistoryService.list` (`handledForBySource`) scanned all rows of `activity_log` because `(details ->> 'handledForUserId') IS NOT NULL` alone did not bind the second key of `activity_log_company_handled_for_created_idx`, and `decisions` used `NOT IN (SELECT id FROM issues ...)` which planned a full-company privacy subquery even when no settled decisions existed. 2. `activityService.forIssue` scanned all rows of `activity_log` because the `project.created` and `company.skill_created` branches omitted `entity_type`, preventing index scans. 3. `attentionService.taskQuestions` executed steady-state write transactions in `decision-retention` and unnecessary plan-document reads on read paths, and `CoordinatorChatPendingQuestion` mounted an `AttentionInteractionResolver` per question that fired one `GET /api/issues/:taskId/interactions` request per pending question. 4. `TaskChatThread` disabled saved-reply transcript deferral in `conversationMode`, fetching `/events` (and legacy `/log` fallbacks) for every historical completed run in the comment window, while `useNativeRunTranscripts` used a single shared `AbortController` that aborted and restarted in-flight sibling reads whenever run membership or live-stream state changed. 5. `AgentChat` waited serially for the agent roster and session before fetching the chat by `:agentRef`, `IssueDetail` skipped `startIssueChatBootstrap` for conversations, and the HTML preload plugin omitted the `AgentChat` chunk on `/chats/:ref` hard loads. **Expected behavior** Opening an agent chat page resolves the conversation and its first-frame data in parallel via `chat-bootstrap`, avoids sequential scans on `activity_log`, avoids fetching completed run transcripts when a saved reply is already visible, avoids aborting sibling in-flight transcript reads, and renders pending task questions without per-task N+1 interaction requests. **Steps to reproduce** 1. Create a company with a persistent agent chat that has 20+ historical replies from completed native runs, several hundred tasks assigned to that agent, pending `ask_user_questions` interactions across multiple tasks, and a large `activity_log` table. 2. Open `/:companyPrefix/chats/:agentRef` directly or from the sidebar and inspect the network waterfall and PostgreSQL query plans for `/activity`, `/decision-receipts`, `/pending-questions`, and `/heartbeat-runs/:id/events`. 3. Observe full-table `Seq Scan` plans on `activity_log`, bypassed `chat-bootstrap`, repeated aborted `/events` requests, and N+1 `/issues/:taskId/interactions` calls. **Paperclip version or commit** Reproduced on `ca21075837` (rebased onto `a3719da3ca`, final head `2995820afe`). ## What Changed - **Eliminate `activity_log` sequential scans (zero migrations)**: - `server/src/services/activity.ts`, `server/src/routes/activity.ts`, `server/src/routes/issues.ts`: Scope `forIssue` secondary branches by their canonical `entity_type` (`project` for `project.created`, `company_skill` for `company.skill_created`) and accept `companyId` from routes so PostgreSQL uses `BitmapOr` index scans instead of a full-table `Seq Scan`. - `server/src/services/decision-history.ts`: Add `(details ->> 'handledForUserId') >= ''` alongside `IS NOT NULL` in `handledForBySource` so PostgreSQL binds the partial index `activity_log_company_handled_for_created_idx`; replace `decision_target_issues.issue_id NOT IN (...)` with correlated `NOT EXISTS (...)`; add a `LIMIT 1` index probe before planning the full `decisions` privacy query when no settled decisions exist. - `server/src/services/conversation-decision-receipts.ts`, `server/src/routes/issues.ts`: Reuse the route's already-authorized conversation record instead of re-querying `source()`. - **Batch pending-question hydration and avoid steady-state retention writes**: - `packages/shared/src/types/attention.ts`, `server/src/services/issue-thread-interactions.ts`, `server/src/services/attention.ts`: Add optional `interaction?: IssueThreadInteraction | null` on `AttentionItem`, batch-hydrate interactions in `issueThreadInteractionService.listByIds` (grouping by `issueId` for acceptance readiness and skipping only `z.ZodError` legacy payloads), restrict `planDocumentMap` to actual plan confirmation interactions, and parallelize `decisionQueueItems` and `decisionTriage` reads in `enrichAttentionItems`. - `server/src/services/decision-retention.ts`: Add a read-only fast path in `syncItems` so steady-state reads skip opening a write transaction when retention rows are already current, while still syncing and bumping versions whenever `activityAt` changes. - `ui/src/components/AttentionInteractionResolver.tsx`, `ui/src/components/coordinator/CoordinatorChatPendingQuestions.tsx`: Accept optional `initialInteraction` so inline pending-question cards render immediately without N+1 `GET /issues/:taskId/interactions` requests while still honoring cache updates after mutations. - **Remove agent chat load waterfalls and transcript abort storms**: - `ui/src/components/TaskChatThread.tsx`, `ui/src/lib/run-answer-visibility.ts`: Defer completed `succeeded` run transcripts that already have a visible saved reply in `conversationMode` while preserving immediate hydration for live, failed, yielded, pending-interaction, and unanswered runs; precompute visible-answer lookups in linear time (`O(comments + runs)`) instead of quadratic scans. - `ui/src/components/transcript/useNativeRunTranscripts.ts`: Manage `AbortController`s and poll timers per run instead of one shared controller so adding sibling runs or transitioning stream health never aborts in-flight reads or refetches already-hydrated terminal runs; clear aborted in-flight tracking cleanly so expanding compact history refetches immediately. - `ui/src/pages/AgentChat.tsx`, `ui/src/pages/IssueDetail.tsx`, `ui/src/lib/vite-issue-detail-preload.ts`: Start `agentChatsApi.get` by `:agentRef` in parallel with roster/session reads on cold loads, enable `startIssueChatBootstrap` for conversations with an existing issue ID, and preload the `AgentChat` chunk alongside `IssueDetail` on `/chats/:ref` hard loads. - **Tests & SDK pin**: - Added/updated tests in `server/src/__tests__/activity-service.test.ts`, `server/src/__tests__/activity-routes.test.ts`, `server/src/__tests__/decision-history.test.ts`, `server/src/__tests__/issue-thread-interaction-routes.test.ts`, `ui/src/components/AttentionInteractionResolver.initial.test.tsx`, `ui/src/components/TaskChatThread.test.tsx`, `ui/src/components/transcript/useNativeRunTranscripts.test.tsx`, `ui/src/components/transcript/useNativeRunTranscripts.streaming.test.tsx`, and `ui/src/lib/vite-issue-detail-preload.test.ts`. - Updated `tests/runner-e2e/source-sdk-public-inputs.json` for `packages/shared/src/types/attention.ts`. ## Verification Local disposable PostgreSQL 18.1 benchmark (`200,000` `activity_log` rows, `455` tasks, `82` interactions, alternating baseline/treatment samples, `ANALYZE` run, positional `.values()` output equality verified on both empty and populated `handledForUserId` sets): | Caller/query | Before median | After median | Samples/spread | Complete output/contract check | Scope | | --- | --- | --- | --- | --- | --- | | `activityService.forIssue(50)` | `53.66 ms` (`50.78 ms` SQL exec, `11,147` buffers, `Seq Scan`) | `1.84 ms` (`0.31 ms` SQL exec, `23` buffers, `BitmapOr` index scans) | 7 alternating samples (before `48.03–62.79 ms`, after `1.34–3.18 ms`, `29.2x` speedup) | Pass (50 positional rows equal) | SQL | | `decisionHistory.handledForBySource` (40 ids, 0 rows) | `13.71 ms` (`11,193` buffers, `Seq Scan`) | `0.73 ms` (`2` buffers, `Bitmap Index Scan` on partial index) | 7 alternating samples (before `11.56–15.45 ms`, after `0.64–0.99 ms`, `18.8x` speedup) | Pass (empty + populated non-empty positional rows equal) | SQL | | `decisionHistory.handledForBySource` (40 ids, 1 matching row) | `40.35 ms` SQL exec (`11,193` buffers, `Seq Scan`) | `0.04 ms` SQL exec (`2` buffers, `Bitmap Index Scan` on partial index) | `EXPLAIN (ANALYZE, BUFFERS)` | Pass (1 positional row equal) | SQL | CI and reviews on final head `2995820afe`: - **GitHub Actions CI (`ci / verify`)**: **PASS** (all 86 check runs completed with 0 failures; `mergeStateStatus: CLEAN`). - **Greptile Review**: **5/5** (`SUCCESS`, 0 unresolved findings). - **Ponytail Paperclip Review**: **5/5** ("No actionable defects found in the reviewed paths. Verdict: Ship."). - **Feynman Nuclear Review**: **4/5** ("no confirmed defect in the new commits"). Tests and builds also verified locally: - `pnpm --filter @paperclipai/shared build` — pass - `cd server && node scripts/typecheck-layers.mjs` — pass (all 7 layers) - `pnpm --filter @paperclipai/ui typecheck` & `pnpm --filter @paperclipai/ui build` — pass - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/approval-queue-seeding-work.test.ts src/__tests__/decision-history.test.ts` — pass (28/28 and 14/14 on real embedded PostgreSQL) - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/activity-service.test.ts src/__tests__/openapi-routes.test.ts` — pass - Focused UI suites (`TaskChatThread.test.tsx`, `useNativeRunTranscripts.test.tsx`, `useNativeRunTranscripts.streaming.test.tsx`, `AttentionInteractionResolver.initial.test.tsx`, `AttentionInteractionResolver.replace.test.ts`, `IssueDetail.agentChatPanel.test.tsx`, `vite-issue-detail-preload.test.ts`) — pass ## Risks - **No schema migrations**: All SQL improvements use existing indexes. - **Completed chat run transcripts**: Persistent agent chats now defer completed `succeeded` runs that already have a visible saved reply, matching compact task behavior. Live, failed, yielded, pending-interaction, placeholder, progress-only, and hash-targeted runs still hydrate immediately. - **Inline interaction hydration**: `AttentionInteractionResolver` uses `initialInteraction` when provided and valid, skipping the mount-time `listInteractions` read; mutations and live updates continue to update/invalidate `queryKeys.issues.interactions(issueId)` and `["issues", "pending-questions"]`. Unparseable legacy interaction rows (`z.ZodError`) are omitted from the batch map and fall back cleanly to the per-issue read. - **Synthetic local proof vs production**: Local PostgreSQL benchmarks prove query plan and buffer reductions on synthetic data (`200k` rows); deployed latency improvements depend on production dataset size and cache warmth. ## Model Used Google Antigravity (Gemini) with tool use, terminal execution, and local embedded PostgreSQL profiling. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
c349b060db
commit
0960dd464d
29 files changed
+1206
-161
No files matched your search
@@ -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 {
|
||||
|
||||
@@ -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" }]);
|
||||
});
|
||||
|
||||
|
||||
@@ -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));
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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" }),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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));
|
||||
});
|
||||
|
||||
|
||||
@@ -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,
|
||||
}));
|
||||
});
|
||||
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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<string, AttentionQueueRef[]>();
|
||||
const retentionDaysBySource = new Map<string, number[]>();
|
||||
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<string, PlanDocumentSummary>())
|
||||
: planDocumentMap(db, companyId, visibleInteractionRows.map((row) => row.issueId), readCondition),
|
||||
planConfirmationIssueIds.length === 0
|
||||
? Promise.resolve(new Map<string, PlanDocumentSummary>())
|
||||
: 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<AttentionItem[]> => {
|
||||
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<AttentionListOptions, "userId" | "actor"> = {}): Promise<AttentionSummary> => {
|
||||
const { items: _items, nextCursor: _cursor, ...summary } = await list(companyId, {
|
||||
|
||||
@@ -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<AuthorizedConversation> {
|
||||
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<AttentionItem[]> {
|
||||
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<ConversationTaskHandoffPage> {
|
||||
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<DecisionHistoryQuery, "cursor" | "limit">): Promise<DecisionHistoryPage> {
|
||||
const conversation = await source(companyId, conversationId, options);
|
||||
const { handoffIds, directIds } = await taskScopes(companyId, conversation, options);
|
||||
|
||||
@@ -263,7 +263,12 @@ async function handledForBySource(db: Db, companyId: string, items: Array<Pick<D
|
||||
.from(activityLog)
|
||||
.where(and(
|
||||
eq(activityLog.companyId, companyId),
|
||||
// Match the partial index predicate AND bind the 2nd B-tree key of
|
||||
// `activity_log_company_handled_for_created_idx`; without `>= ''`,
|
||||
// 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<string>`${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,
|
||||
|
||||
@@ -140,10 +140,24 @@ export function decisionRetentionService(
|
||||
async function syncItems(companyId: string, items: readonly RetentionSource[]) {
|
||||
if (items.length === 0) return new Map<string, DecisionRetentionState>();
|
||||
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)));
|
||||
|
||||
@@ -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<string, IssueThreadInteraction>();
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(issueThreadInteractions)
|
||||
.where(and(
|
||||
eq(issueThreadInteractions.companyId, companyId),
|
||||
inArray(issueThreadInteractions.id, uniqueIds),
|
||||
));
|
||||
if (rows.length === 0) return new Map<string, IssueThreadInteraction>();
|
||||
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<string, IssueThreadInteraction[]>();
|
||||
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,
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 }) => (
|
||||
<div data-testid="interaction-card">{interaction.title ?? interaction.id}:{interaction.status}</div>
|
||||
),
|
||||
}));
|
||||
|
||||
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(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AttentionInteractionResolver
|
||||
companyId={QUESTION_INTERACTION.companyId}
|
||||
issueId={QUESTION_INTERACTION.issueId}
|
||||
interactionId={QUESTION_INTERACTION.id}
|
||||
initialInteraction={QUESTION_INTERACTION}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
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(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AttentionInteractionResolver
|
||||
companyId={QUESTION_INTERACTION.companyId}
|
||||
issueId={QUESTION_INTERACTION.issueId}
|
||||
interactionId={QUESTION_INTERACTION.id}
|
||||
initialInteraction={QUESTION_INTERACTION}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
expect(container.querySelector('[data-testid="interaction-card"]')?.textContent).toBe("Choose rollout strategy:pending");
|
||||
expect(listInteractionsMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -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<IssueThreadInteraction | null>(() => {
|
||||
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<IssueThreadInteraction | null>(() => {
|
||||
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 (
|
||||
<div className="space-y-3 py-3">
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
@@ -155,7 +165,7 @@ export function AttentionInteractionResolver({
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !interaction) {
|
||||
if (!interaction) {
|
||||
return (
|
||||
<div className="space-y-3 py-3">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
|
||||
@@ -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(<TaskChatThread {...savedProps} />);
|
||||
await settleThreadLayout();
|
||||
expect(container.textContent).toContain("Saved chat reply");
|
||||
expect(transcriptHookRuns.native.at(-1)).toEqual([]);
|
||||
expect(transcriptHookRuns.legacy.at(-1)).toEqual([]);
|
||||
render(<TaskChatThread {...savedProps} linkedRuns={[{ ...retryRun, runId: "live-chat-run", status: "running", startedAt: retryRun.createdAt }]} />);
|
||||
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(<TaskChatThread {...props} />);
|
||||
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(<TaskChatThread {...props} />);
|
||||
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 } }
|
||||
|
||||
@@ -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<TaskChatThreadProps["documents"]> = [];
|
||||
const EMPTY_WORK_PRODUCTS: NonNullable<TaskChatThreadProps["workProducts"]> = [];
|
||||
const EMPTY_ATTACHMENTS: NonNullable<TaskChatThreadProps["attachments"]> = [];
|
||||
const EMPTY_BLOCKED_BY: NonNullable<TaskChatThreadProps["blockedBy"]> = [];
|
||||
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<string>();
|
||||
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<string>();
|
||||
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]);
|
||||
|
||||
@@ -34,7 +34,7 @@ export function CoordinatorChatPendingQuestion({ item }: { item: AttentionItem }
|
||||
return <section data-testid="coordinator-chat-pending-question" className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">{item.originAgentName ?? "Your agent"} needs your input on {task.title ?? task.identifier ?? "this task"}.</p>
|
||||
<article className="coordinator-decision-card space-y-4 rounded-xl border border-border bg-card p-6">
|
||||
<AttentionInteractionResolver companyId={task.companyId} issueId={task.id} interactionId={item.subject.id} currentUserId={userId} presentation="coordinator-decision" footerSlot={<Link to={href} className="flex max-w-full items-center gap-2 text-sm text-muted-foreground hover:text-foreground">
|
||||
<AttentionInteractionResolver companyId={task.companyId} issueId={task.id} interactionId={item.subject.id} initialInteraction={item.interaction} currentUserId={userId} presentation="coordinator-decision" footerSlot={<Link to={href} className="flex max-w-full items-center gap-2 text-sm text-muted-foreground hover:text-foreground">
|
||||
<span className="shrink-0">{task.identifier ?? "Open task"}</span><span className="truncate">{task.title}</span><ArrowUpRight className="size-4 shrink-0" />
|
||||
</Link>} />
|
||||
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -225,7 +225,13 @@ describe("native history readiness and stable projection", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
let latest: ReturnType<typeof useNativeRunTranscripts>;
|
||||
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(<StateProbe runs={[one]} />); });
|
||||
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(<StateProbe runs={[one, { ...one, id: "two" }]} />); });
|
||||
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(<StateProbe runs={[one, { ...one, id: "two" }]} enabled={false} />); });
|
||||
expect(inFlightSignal.aborted).toBe(true);
|
||||
await act(async () => { root.render(<StateProbe runs={[one, { ...one, id: "two" }]} />); });
|
||||
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(<StateProbe runs={[compactRun]} />); });
|
||||
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(<StateProbe runs={[{ ...compactRun, conversationOnly: false }]} />); });
|
||||
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<string, unknown>; 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(<StateProbe runs={[liveRun]} />); });
|
||||
expect(eventsMock).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Run completes before the in-flight poll resolves.
|
||||
await act(async () => { root.render(<StateProbe runs={[{ ...liveRun, status: "succeeded" }]} />); });
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -81,18 +81,72 @@ export function useNativeRunTranscripts(runs: readonly NativeRunTranscriptSource
|
||||
};
|
||||
const gapPendingRef = useRef(new Set<string>());
|
||||
const historyReadsRef = useRef(new Map<string, AbortSignal>());
|
||||
const inFlightStatusByRunRef = useRef(new Map<string, string>());
|
||||
const latestRunByIdRef = useRef(new Map<string, NativeRunTranscriptSource>());
|
||||
const controllersByRunRef = useRef(new Map<string, AbortController>());
|
||||
const timersByRunRef = useRef(new Map<string, number>());
|
||||
const pendingRefreshRef = useRef(new Set<string>());
|
||||
const interruptedReadsRef = useRef(new Set<string>());
|
||||
const refreshByRunRef = useRef(new Map<string, (force?: boolean) => void>());
|
||||
const hydratedStatusByRunRef = useRef(new Map<string, string>());
|
||||
const errorsByRunRef = useRef(new Map<string, NativeRunTranscriptError>());
|
||||
const streamHealthyRef = useRef(false);
|
||||
const mountedRef = useRef(true);
|
||||
const previousCompanyRef = useRef(options.companyId);
|
||||
const refreshContextRef = useRef<readonly unknown[]>([]);
|
||||
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<string, NativeRunTranscriptSource>();
|
||||
for (const run of nativeRuns) nextLatestById.set(run.id, run);
|
||||
latestRunByIdRef.current = nextLatestById;
|
||||
const changedModes = new Set<string>();
|
||||
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<string, number>();
|
||||
const pendingRefresh = new Set<string>();
|
||||
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 = <T,>(previous: Map<string, T>) => {
|
||||
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<string, TranscriptEntry[]>();
|
||||
|
||||
@@ -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: {
|
||||
/**
|
||||
|
||||
@@ -38,16 +38,56 @@ export function semanticProgressCommentIds(value: unknown): Set<string> {
|
||||
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<RunAnswerVisibilityComment>,
|
||||
): Map<string, string[]> {
|
||||
const byRun = new Map<string, string[]>();
|
||||
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<string, readonly string[]>,
|
||||
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<RunAnswerVisibilityComment>,
|
||||
runId: string,
|
||||
resultJson: unknown,
|
||||
): boolean {
|
||||
|
||||
@@ -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"]);
|
||||
});
|
||||
@@ -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<string>();
|
||||
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<string>();
|
||||
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 });
|
||||
|
||||
@@ -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<Issue | null>(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<Issue[]>(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<Issue[]>(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);
|
||||
|
||||
@@ -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<Issue>(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.
|
||||
|
||||
Reference in new issue
Block a user