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
@@ -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[]>();
|
||||
|
||||
Reference in new issue
Block a user