mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
## 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>
421 lines
19 KiB
TypeScript
421 lines
19 KiB
TypeScript
import { TranscriptSequence } from "../../lib/transcript-sequence";
|
|
import { useTranscriptLiveStream } from "../../context/LiveUpdatesProvider";
|
|
import { usePageVisibility } from "../../lib/page-visibility";
|
|
import { liveRunEvent, mergeRunEvents } from "../../lib/live-run-event";
|
|
import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
|
|
import { QueryClientContext } from "@tanstack/react-query";
|
|
import type { HeartbeatRunEvent } from "@paperclipai/shared";
|
|
import type { TranscriptEntry } from "@/adapters";
|
|
import { heartbeatsApi } from "@/api/heartbeats";
|
|
import { nativeRunEventsToTranscript } from "./native-run-events";
|
|
import { readTranscriptRequest } from "./read-transcript-request";
|
|
|
|
const EVENT_PAGE_SIZE = 1_000;
|
|
const EVENT_POLL_INTERVAL_MS = 2_000;
|
|
|
|
interface SavedNativeHistory {
|
|
events: HeartbeatRunEvent[];
|
|
cursor: number;
|
|
}
|
|
|
|
const historyKey = (companyId: string, run: NativeRunTranscriptSource) =>
|
|
["native-run-transcript", companyId, run.id, Boolean(run.conversationOnly), run.status] as const;
|
|
|
|
export interface NativeRunTranscriptSource {
|
|
id: string;
|
|
status: string;
|
|
conversationOnly?: boolean;
|
|
runtimeMode?: "legacy" | "native";
|
|
}
|
|
|
|
export interface NativeRunTranscriptError {
|
|
message: string;
|
|
failedAt: string;
|
|
}
|
|
|
|
function isLive(status: string): boolean {
|
|
return status === "queued" || status === "running";
|
|
}
|
|
|
|
export function useNativeRunTranscripts(runs: readonly NativeRunTranscriptSource[], options: { companyId?: string | null; enabled?: boolean } = {}) {
|
|
const queryClient = useContext(QueryClientContext);
|
|
const { visible } = usePageVisibility();
|
|
const nativeRunsKey = runs
|
|
.filter((run) => run.runtimeMode === "native")
|
|
.map((run) => `${run.id}:${run.status}:${Boolean(run.conversationOnly)}`)
|
|
.sort()
|
|
.join(",");
|
|
const nativeRuns = useMemo(
|
|
() => runs.filter((run) => run.runtimeMode === "native").map((run) => ({ ...run })),
|
|
// The key carries every field this hook consumes.
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
[nativeRunsKey],
|
|
);
|
|
const savedHistory = useMemo(() => {
|
|
const saved = new Map<string, SavedNativeHistory>();
|
|
if (queryClient && options.companyId && options.enabled !== false) {
|
|
for (const run of nativeRuns) {
|
|
if (isLive(run.status)) continue;
|
|
const history = queryClient.getQueryData<SavedNativeHistory>(historyKey(options.companyId, run));
|
|
if (history) saved.set(run.id, history);
|
|
}
|
|
}
|
|
return saved;
|
|
}, [queryClient, options.companyId, options.enabled, nativeRuns]);
|
|
const [eventsByRun, setEventsByRun] = useState<Map<string, HeartbeatRunEvent[]>>(new Map());
|
|
const persistedEventsByRunRef = useRef(new Map<string, HeartbeatRunEvent[]>());
|
|
const [errorsByRun, setErrorsByRun] = useState<Map<string, NativeRunTranscriptError>>(new Map());
|
|
const [hydratedRunIds, setHydratedRunIds] = useState<ReadonlySet<string>>(new Set());
|
|
const [hydratedStatusByRun, setHydratedStatusByRun] = useState(new Map<string, string>());
|
|
const [retryGeneration, setRetryGeneration] = useState(0);
|
|
const retry = useCallback(() => setRetryGeneration((value) => value + 1), []);
|
|
const projectionCacheRef = useRef(new Map<string, { events: HeartbeatRunEvent[]; transcript: TranscriptEntry[] }>());
|
|
const cursorByRunRef = useRef(new Map<string, number>());
|
|
const conversationOnlyByRunRef = useRef(new Map<string, boolean>());
|
|
|
|
const sequencesRef = useRef(new Map<string, TranscriptSequence>());
|
|
const sequence = (id: string) => {
|
|
let value = sequencesRef.current.get(id);
|
|
if (!value) { value = new TranscriptSequence(); sequencesRef.current.set(id, value); }
|
|
return value;
|
|
};
|
|
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 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, 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;
|
|
if (event.type === "heartbeat.run.status" && typeof event.payload.status === "string" && !isLive(event.payload.status)) {
|
|
refreshByRunRef.current.get(runId)?.(true); return;
|
|
}
|
|
const row = liveRunEvent(event);
|
|
if (!row) return;
|
|
const cursor = sequence(runId);
|
|
const envelope = row.payload?.prpEvent;
|
|
const hasTranscriptBody = envelope !== null && typeof envelope === "object" && !Array.isArray(envelope);
|
|
if (!hasTranscriptBody) cursor.requireHistory(row.seq);
|
|
if (cursor.observe(row.seq) && !gapPendingRef.current.has(runId)) {
|
|
gapPendingRef.current.add(runId);
|
|
refreshByRunRef.current.get(runId)?.();
|
|
}
|
|
if (hasTranscriptBody) setEventsByRun(previous => new Map(previous).set(runId, mergeRunEvents(previous.get(runId) ?? [], [row])));
|
|
});
|
|
|
|
|
|
streamHealthyRef.current = stream.healthy;
|
|
|
|
useEffect(() => {
|
|
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);
|
|
}
|
|
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)));
|
|
return next.size === previous.size ? previous : next;
|
|
};
|
|
setEventsByRun(previous => {
|
|
let next = retainMap(previous);
|
|
for (const [id, saved] of savedHistory) {
|
|
if (!next.has(id) || changedModes.has(id)) {
|
|
if (next === previous) next = new Map(next);
|
|
next.set(id, mergeRunEvents(saved.events, next.get(id) ?? []));
|
|
}
|
|
}
|
|
return next;
|
|
});
|
|
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;
|
|
});
|
|
for (const id of cursorByRunRef.current.keys()) {
|
|
if (!retainedIds.has(id)) {
|
|
cursorByRunRef.current.delete(id); sequencesRef.current.delete(id); gapPendingRef.current.delete(id);
|
|
}
|
|
}
|
|
for (const id of persistedEventsByRunRef.current.keys()) {
|
|
if (!retainedIds.has(id)) persistedEventsByRunRef.current.delete(id);
|
|
}
|
|
|
|
const refreshRun = async (run: NativeRunTranscriptSource) => {
|
|
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);
|
|
let cursor = cursorByRunRef.current.get(run.id) ?? saved?.cursor ?? 0;
|
|
const observedBeforeRead = sequence(run.id).observed;
|
|
const incoming: HeartbeatRunEvent[] = [];
|
|
for (;;) {
|
|
const page = await readTranscriptRequest(
|
|
(signal) => (run.conversationOnly ? heartbeatsApi.conversationEvents : heartbeatsApi.events)(run.id, cursor, EVENT_PAGE_SIZE, { signal }),
|
|
controller.signal,
|
|
);
|
|
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));
|
|
if (page.length < EVENT_PAGE_SIZE || nextCursor === cursor) {
|
|
cursor = nextCursor;
|
|
break;
|
|
}
|
|
cursor = nextCursor;
|
|
}
|
|
// Commit this run's cursor with its rows. A slow sibling must neither
|
|
// hold its readiness hostage nor stall live polling for this run.
|
|
const coveredCursor = run.conversationOnly ? Math.max(cursor, observedBeforeRead) : cursor;
|
|
cursorByRunRef.current.set(run.id, coveredCursor);
|
|
sequence(run.id).confirm(coveredCursor);
|
|
failed = sequence(run.id).needsCatchup;
|
|
if (!failed) gapPendingRef.current.delete(run.id);
|
|
if (incoming.length > 0) setEventsByRun((previous) => {
|
|
const next = new Map(previous);
|
|
next.set(run.id, mergeRunEvents(previous.get(run.id) ?? saved?.events ?? [], incoming));
|
|
return next;
|
|
});
|
|
const previousEvents = persistedEventsByRunRef.current.get(run.id) ?? [];
|
|
const persistedEvents = incoming.length ? mergeRunEvents(previousEvents, incoming) : previousEvents;
|
|
persistedEventsByRunRef.current.set(run.id, persistedEvents);
|
|
if (!failed && !isLive(run.status) && queryClient && options.companyId) {
|
|
const key = historyKey(options.companyId, run);
|
|
queryClient.setQueryData<SavedNativeHistory>(key, {
|
|
events: persistedEvents,
|
|
cursor: coveredCursor,
|
|
});
|
|
}
|
|
setErrorsByRun((previous) => {
|
|
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;
|
|
const next = new Map(previous).set(run.id, run.status);
|
|
hydratedStatusByRunRef.current = next;
|
|
return next;
|
|
});
|
|
} catch (error) {
|
|
if (!mountedRef.current || controller.signal.aborted) return;
|
|
failed = true;
|
|
setErrorsByRun((previous) => {
|
|
if (previous.has(run.id)) return previous;
|
|
const next = new Map(previous);
|
|
next.set(run.id, {
|
|
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);
|
|
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]));
|
|
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(() => {
|
|
timersByRunRef.current.delete(run.id);
|
|
const currentRun = latestRunByIdRef.current.get(run.id);
|
|
if (currentRun) void refreshRun(currentRun);
|
|
}, EVENT_POLL_INTERVAL_MS);
|
|
timersByRunRef.current.set(run.id, timer);
|
|
}
|
|
};
|
|
for (const run of nativeRuns) {
|
|
refreshByRunRef.current.set(run.id, (force = false) => {
|
|
if (force) pendingRefreshRef.current.add(run.id);
|
|
void refreshRun(latestRunByIdRef.current.get(run.id) ?? run);
|
|
});
|
|
// 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);
|
|
}
|
|
}
|
|
}
|
|
}, [nativeRuns, retryGeneration, visible, options.enabled, options.companyId, stream.healthy, stream.epoch, queryClient, savedHistory, abortRun, abortAllRuns]);
|
|
|
|
const transcriptByRun = useMemo(() => {
|
|
const transcripts = new Map<string, TranscriptEntry[]>();
|
|
for (const run of nativeRuns) {
|
|
const events = eventsByRun.get(run.id) ?? savedHistory.get(run.id)?.events;
|
|
if (!events) continue;
|
|
let cached = projectionCacheRef.current.get(run.id);
|
|
if (!cached || cached.events !== events) {
|
|
cached = { events, transcript: nativeRunEventsToTranscript(events) };
|
|
projectionCacheRef.current.set(run.id, cached);
|
|
}
|
|
transcripts.set(run.id, cached.transcript);
|
|
}
|
|
for (const id of projectionCacheRef.current.keys()) {
|
|
if (!transcripts.has(id)) projectionCacheRef.current.delete(id);
|
|
}
|
|
return transcripts;
|
|
}, [eventsByRun, nativeRuns, savedHistory]);
|
|
|
|
const terminalHydratedRunIds = useMemo(() => new Set(nativeRuns
|
|
.filter((run) => !isLive(run.status) && hydratedStatusByRun.get(run.id) === run.status)
|
|
.map((run) => run.id)), [nativeRuns, hydratedStatusByRun]);
|
|
|
|
const availableRunIds = useMemo(() => new Set([...savedHistory.keys(), ...hydratedRunIds]), [savedHistory, hydratedRunIds]);
|
|
const availableTerminalRunIds = useMemo(() => new Set([...savedHistory.keys(), ...terminalHydratedRunIds]), [savedHistory, terminalHydratedRunIds]);
|
|
return {
|
|
transcriptByRun, errorsByRun, hydratedRunIds: availableRunIds, terminalHydratedRunIds: availableTerminalRunIds, retry,
|
|
isInitialHydrating: nativeRuns.some((run) => !availableRunIds.has(run.id)),
|
|
};
|
|
}
|