Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Keep Patrol finding reviews in place across refreshes

rcourtmanc46dd92777e7
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 29601a17e8..3208ee20d1 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -5069,6 +5069,14 @@ consumer renders that failure as it renders any other (the Proxmox Replication
table shows its error and Retry; workload sparklines keep retained series). A
transport that always takes longer than that deadline plus one poll interval
never publishes.
+`pollMs` may also be an accessor, for a cadence that follows state (23 October
+2026): a Patrol finding review re-reads its investigation every 5 seconds while
+the run is active and every 30 seconds otherwise, and its thread only while the
+run is live or after a failed read. A new cadence restarts the interval, a read
+already in flight keeps its protection, and an accessor that returns undefined
+stops polling. A consumer that needs two cadences uses one accessor rather than
+a second timer that calls `refetch`, because a refetch and a poll replace each
+other's slow reads.
The settings reporting shell now also owns a deliberate split between
historical performance reports and current-state VM inventory export.
`frontend-modern/src/components/Settings/ReportingPanel.tsx`,
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index 3a6e1f4648..eeb7f788b5 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -840,6 +840,7 @@ attention`, `approval needed`, `outcome verified`, `no active work`) instead
3. Letting the Patrol page, local store, and findings UI drift into separate shadow truths for the same Patrol status or finding lifecycle state
4. Recreating Patrol run-history, status-bar, runtime-summary, or workspace-tab status/metadata badge shells locally instead of composing `StatusIndicatorBadge` and `MetadataBadge`
5. Recreating border-based Patrol or AI finding loading spinner shells locally instead of composing `LoadingSpinner`
+6. Reading finding-review or run-history data with `createResource`, or any read that suspends, instead of `createNonSuspendingQuery`: the nearest Suspense boundary is the app's route boundary, whose fallback replaces the page and loses the reader's place. Rebuilding findings rows or an open review for a refresh that returned the same findings is forbidden for the same reason
## Completion Obligations
@@ -2832,3 +2833,55 @@ for an interrupted run, because the queued fix is what the operator acts on.
Once core reconciles the plan's approval, rejection or expiry, the outcome
changes and the usual rules apply again. Proof:
`frontend-modern/src/components/patrol/__tests__/InvestigationSection.test.tsx`.
+
+### Finding reviews keep their place across refreshes (23 October 2026)
+
+The app shell re-reads Patrol findings every 30 seconds and the Patrol page
+every 60. Each read parsed new objects, so `FindingsPanel` rebuilt every row
+and remounted an open finding review. The remounted review read its
+investigation with `createResource`, and that read suspended the nearest
+Suspense boundary, the app's route boundary. Its "Loading view..." fallback
+replaced the whole page, so someone reading a review on the Activity tab was
+thrown back to the top. The same happened on opening a review or its thread,
+on Re-investigate, and on every 5-second poll of a running investigation.
+Now:
+
+- `aiIntelligenceStore` keeps the object of every finding a read returns
+ unchanged, and keeps the list when nothing changed.
+- `FindingsPanel` keeps a display group while its findings are the same
+ objects (`reuseIdenticalPatrolFindingDisplayGroups`). It settles sort ties by
+ finding id, because the API returns tied findings in no fixed order and a
+ Patrol run stamps one time on every finding it sees. The open review reads
+ its related findings through a getter, so it is redrawn only when its own
+ finding changes.
+- `InvestigationSection`, `ApprovalSection` and `InvestigationMessages` read
+ through `createNonSuspendingQuery`. The last answer stays on screen while
+ the next loads, and a remounted review shows the retained answer at once.
+ `RunToolCallTrace` moves to the same query. It did not suspend before, but
+ only because each of its reads checked `loading` first.
+- The remounts had also re-read the review every 30 seconds. The mounted
+ review now does that itself through the query's own poll, which never
+ replaces a slow read still in flight: the investigation and its governed
+ action re-read every 30 seconds, and the investigation every 5 seconds while
+ it runs (`pollMs` takes an accessor for that). A failed read keeps the last
+ answer instead of replacing it with "none"; only a 404 means the finding has
+ no investigation. The thread belongs to its run's session id, so a new run
+ reads its own thread and a re-read of the same run leaves it alone. It is
+ read again every 5 seconds while the run is live, once more when the run
+ finishes, and 30 seconds after a failed read; a message that comes back
+ unchanged keeps its row, and any tool output expanded in it. Re-investigate
+ stays hidden until the first read answers, because until then a running
+ investigation or a queued fix looks like none.
+- Rebuilding rows on every refresh had also kept their ages current. Rows and
+ the review now stay mounted, so their ages (last seen, acknowledged, last
+ investigated, regressions, lifecycle, an investigation's start and its
+ thread's messages) read the shared relative-time clock.
+
+A change to the open finding itself still redraws the review, which closes
+its thread, but the page does not move. Proofs:
+`frontend-modern/src/components/AI/__tests__/FindingsPanel.refresh.test.tsx`,
+`frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts`,
+`frontend-modern/src/stores/__tests__/aiIntelligence.test.ts`,
+`frontend-modern/src/hooks/__tests__/createNonSuspendingQuery.test.tsx`, and the
+`InvestigationSection`, `ApprovalSection`, `InvestigationMessages` and
+`RunToolCallTrace` tests under `frontend-modern/src/components/patrol/__tests__/`.
diff --git a/frontend-modern/browser-verification/14b0b05ccd7e4c6f.json b/frontend-modern/browser-verification/14b0b05ccd7e4c6f.json
new file mode 100644
index 0000000000..9a864d96c5
--- /dev/null
+++ b/frontend-modern/browser-verification/14b0b05ccd7e4c6f.json
@@ -0,0 +1,64 @@
+{
+ "version": 1,
+ "base_sha": "7b39194ae2fc921e91b98259d0e1679c67541430",
+ "verified_at": "2026-10-23T22:08:07Z",
+ "result": "passed",
+ "changed_paths": [
+ "frontend-modern/src/components/AI/FindingsPanel.tsx",
+ "frontend-modern/src/components/patrol/ApprovalSection.tsx",
+ "frontend-modern/src/components/patrol/InvestigationMessages.tsx",
+ "frontend-modern/src/components/patrol/InvestigationSection.tsx",
+ "frontend-modern/src/components/patrol/RunToolCallTrace.tsx",
+ "frontend-modern/src/hooks/createNonSuspendingQuery.ts",
+ "frontend-modern/src/stores/aiIntelligence.ts",
+ "frontend-modern/src/utils/aiFindingPresentation.ts"
+ ],
+ "content_sha256": {
+ "frontend-modern/src/components/AI/FindingsPanel.tsx": "ec6ad2732f705f14f2dfda0471b056e605eab18e709360f9c277d5385626c676",
+ "frontend-modern/src/components/patrol/ApprovalSection.tsx": "6c7dac44ca991fe99e55ae38ea7cb4f60e5de58ae83ca7163ca6706893971d2f",
+ "frontend-modern/src/components/patrol/InvestigationMessages.tsx": "dceb6715810bf20a5d31caf68ad3c6ac1cb8a0a98990bbc0b7ecd18ae044467b",
+ "frontend-modern/src/components/patrol/InvestigationSection.tsx": "73a2e84a34426d1bb9bb2fb9e8214c190502b57a132bbe0cf02d0a388f84df1f",
+ "frontend-modern/src/components/patrol/RunToolCallTrace.tsx": "d0f982e6a3e954421b6a5a99d1b1605885523044e5cdf5dc3aaf62312e8b35fe",
+ "frontend-modern/src/hooks/createNonSuspendingQuery.ts": "7e24f7f22de510e32c53c7165c0e2b009e88293ee5f340ca5d4c1082868512d9",
+ "frontend-modern/src/stores/aiIntelligence.ts": "b3e6b1e5d61e493796f117f334a8bc9af8689d1e6087561780edd4d7dd6fb849",
+ "frontend-modern/src/utils/aiFindingPresentation.ts": "d4396dd219ac518b23cf7c9fecd2bebb2f7545927e066ee6261bae3eebc590ed"
+ },
+ "routes": [
+ "/patrol/activity"
+ ],
+ "viewports": [
+ {
+ "width": 1024,
+ "height": 768
+ },
+ {
+ "width": 1440,
+ "height": 900
+ },
+ {
+ "width": 390,
+ "height": 844
+ }
+ ],
+ "states": [
+ "Private Pulse Pro stack: the enterprise binary built on pulse-dev from main 15ea29fe2b (pulse and pulse-enterprise), Vite dev server of this change, small mock estate, seeded Patrol findings and orchestrator investigation sessions; compared with main's frontend sources on the same backend",
+ "Before (main) at 1024x768: opening a finding's review moved the page from 1389px to 0; opening its thread and each 30s and 60s findings reload flashed the route's Loading view fallback and dropped a reader at 2715px to 0; the open row and the review's content were rebuilt three times in 70 seconds, which closed the thread and reset the review's inner scroll",
+ "After at 1024x768, 1440x900 and 390x844: opening the review kept the page where it was (1584, 1417 and 2525px); over 70 seconds (two 30s reloads, one 60s reload and a 30s re-read of the investigation) the page stayed at 3050, 1585 and 4483px with no Loading view fallback, no row or review content rebuilt, rows in the same order, the thread still open and the review's inner scroll unchanged",
+ "A 150-second watch at 1024x768 with unchanged findings: no row moved or was rebuilt",
+ "History: with the runs list fulfilled to carry tool calls, expanding a run's tool calls kept the page at 1024x768 and 390x844 and listed the three calls",
+ "Ages in the open review and rows read the shared clock (last seen, started); the review's investigation, Patrol record, summary and Re-investigate render as on main",
+ "No Loading view fallback in any run; the only console error was the rig's 500 for seeded investigation messages, which the thread shows as No investigation messages available"
+ ],
+ "interactions": [
+ "Opened the Activity tab and Finding options and history",
+ "Opened a finding's review from mid-page, opened its investigation thread, scrolled the review into view and scrolled inside the review",
+ "Kept the review open for 70 seconds (150 seconds once) while the app's 30s and the page's 60s findings reloads ran",
+ "Opened History, selected a run, returned to History, opened Technical details and expanded the run's tool calls"
+ ],
+ "browser": {
+ "client": "playwright 1.62.1",
+ "engine": "Chromium",
+ "version": "151.0.7922.34 headless"
+ },
+ "scope": "Pulse Pro binary on a mock estate with seeded Patrol findings and investigation sessions; mock data, not live provider connections."
+}
diff --git a/frontend-modern/src/components/AI/FindingsPanel.tsx b/frontend-modern/src/components/AI/FindingsPanel.tsx
index cffb83f578..e4ab96878d 100644
--- a/frontend-modern/src/components/AI/FindingsPanel.tsx
+++ b/frontend-modern/src/components/AI/FindingsPanel.tsx
@@ -83,6 +83,8 @@ import {
getInvestigationStatusBadgeTone,
getPatrolFindingActionableState,
getPatrolFindingQueueSummary,
+ reuseIdenticalPatrolFindingDisplayGroups,
+ type PatrolFindingDisplayGroup,
} from '@/utils/aiFindingPresentation';
import { copyToClipboard } from '@/utils/clipboard';
@@ -384,7 +386,14 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
const aRecency = getFindingRecencyPresentation(a);
const bRecency = getFindingRecencyPresentation(b);
- return new Date(bRecency.timestamp).getTime() - new Date(aRecency.timestamp).getTime();
+ const recencyOrder =
+ new Date(bRecency.timestamp).getTime() - new Date(aRecency.timestamp).getTime();
+ if (recencyOrder) return recencyOrder;
+
+ // The API returns tied findings in no fixed order (a Patrol run stamps
+ // the same time on every finding it sees), so the id settles ties and
+ // rows hold their places from one refresh to the next.
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
});
// Limit items
@@ -457,22 +466,27 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
props.runSnapshot === undefined &&
props.resourceId === undefined,
);
- const patrolFindingDisplayGroups = createMemo(() => {
- const findings = patrolFindings();
- if (!shouldGroupActivePatrolFindings()) {
- return findings.map((finding) => ({
- id: `finding:${finding.id}`,
- affectedResourceCount: 1,
- kind: 'finding' as const,
- label: getFindingSubjectPresentation(finding).label,
- primaryFinding: finding,
- relatedFindings: [],
- findings: [finding],
- }));
- }
-
- return buildPatrolFindingDisplayGroups(findings);
- });
+ // Rows and the open review are keyed by group, so a group whose findings did
+ // not change is kept: a refresh that touches other findings leaves its row,
+ // and the review open beside it, in place.
+ const patrolFindingDisplayGroups = createMemo<PatrolFindingDisplayGroup<UnifiedFinding>[]>(
+ (previous) => {
+ const findings = patrolFindings();
+ const groups: PatrolFindingDisplayGroup<UnifiedFinding>[] = shouldGroupActivePatrolFindings()
+ ? buildPatrolFindingDisplayGroups(findings)
+ : findings.map((finding) => ({
+ id: `finding:${finding.id}`,
+ affectedResourceCount: 1,
+ kind: 'finding' as const,
+ label: getFindingSubjectPresentation(finding).label,
+ primaryFinding: finding,
+ relatedFindings: [],
+ findings: [finding],
+ }));
+ return reuseIdenticalPatrolFindingDisplayGroups(previous, groups);
+ },
+ [],
+ );
const selectedPatrolGroup = createMemo(() => {
if (!isPatrolFindingsSource() || !expandedId()) return undefined;
return patrolFindingDisplayGroups().find((group) =>
@@ -823,7 +837,10 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
}
};
- const formatTime = (isoString: string) => formatRelativeTime(isoString, { compact: true });
+ // Rows and the open review stay mounted across refreshes, so their ages read
+ // the shared clock to keep moving.
+ const formatTime = (isoString: string) =>
+ formatRelativeTime(isoString, { compact: true, now: now() });
// Mirror the backend's DefaultWillFixLaterRemindAfter (7 days) so the dismiss
// confirmation panel can preview the remind-at date before the operator
@@ -1363,7 +1380,9 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
) => {
const primaryAction = getFindingPrimaryActionPresentation(finding);
const manualControls = getFindingManualControlsPresentation(finding);
- const relatedFindings = options.relatedFindings ?? [];
+ // Read where it renders: the review passes a getter, so a change to a
+ // related finding updates this list without redrawing the review.
+ const relatedFindings = () => options.relatedFindings ?? [];
const proHandoff = !primaryAction ? props.patrolProHandoff?.(finding) : undefined;
const modeNudge = !primaryAction ? props.patrolModeNudge?.(finding) : undefined;
const shouldShowExpandedManageMenu =
@@ -1439,16 +1458,16 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
Regressions: {finding.regressionCount}
<Show when={finding.lastRegressionAt}>
{' '}
- (last {formatRelativeTime(finding.lastRegressionAt)})
+ (last {formatRelativeTime(finding.lastRegressionAt, { now: now() })})
</Show>
</p>
</Show>
- <Show when={relatedFindings.length > 0}>
+ <Show when={relatedFindings().length > 0}>
<div class="mt-3 rounded-sm border border-border bg-surface-alt p-2">
<div class="text-xs font-medium text-base-content">Related issues</div>
<div class="mt-2 space-y-1">
- <For each={relatedFindings}>
+ <For each={relatedFindings()}>
{(relatedFinding) => {
const relatedSeverity = getFindingSeverityPresentation(relatedFinding);
const relatedTitle = getFindingTitlePresentation(relatedFinding);
@@ -1509,7 +1528,7 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
</span>
</Show>
</span>
- <span class="shrink-0">{formatRelativeTime(event.at)}</span>
+ <span class="shrink-0">{formatRelativeTime(event.at, { now: now() })}</span>
</div>
);
}}
@@ -2156,7 +2175,11 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
</div>
<div class="max-h-[calc(100vh-12rem)] overflow-y-auto px-4 pb-4">
{renderExpandedContent(finding(), {
- relatedFindings: group()?.relatedFindings ?? [],
+ // A getter, so the review is redrawn only when its own
+ // finding changes, not when a related one does.
+ get relatedFindings() {
+ return group()?.relatedFindings ?? [];
+ },
})}
</div>
</aside>
diff --git a/frontend-modern/src/components/AI/__tests__/FindingsPanel.refresh.test.tsx b/frontend-modern/src/components/AI/__tests__/FindingsPanel.refresh.test.tsx
new file mode 100644
index 0000000000..64ee77284a
--- /dev/null
+++ b/frontend-modern/src/components/AI/__tests__/FindingsPanel.refresh.test.tsx
@@ -0,0 +1,334 @@
+import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
+import { Route, Router } from '@solidjs/router';
+import { Suspense } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { resetCreateNonSuspendingQueryCacheForTest } from '@/hooks/createNonSuspendingQuery';
+import { aiIntelligenceStore } from '@/stores/aiIntelligence';
+import { eventBus } from '@/stores/events';
+import { RELATIVE_TIME_TICK_MS } from '@/utils/relativeTimeClock';
+import { FindingsPanel } from '../FindingsPanel';
+
+// The Patrol findings list is re-read every 30s by the app shell and every
+// 60s by the Patrol page. These tests drive those reads through the real
+// store, FindingsPanel and review sections, under a Suspense boundary like the
+// app's route boundary, whose fallback replaces the whole page.
+
+const getPatrolFindingsMock = vi.hoisted(() => vi.fn());
+const getInvestigationMock = vi.hoisted(() => vi.fn());
+const getInvestigationMessagesMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@/api/patrol', async (importOriginal) => ({
+ ...((await importOriginal()) as object),
+ getPatrolFindings: getPatrolFindingsMock,
+ getInvestigation: getInvestigationMock,
+ getInvestigationMessages: getInvestigationMessagesMock,
+}));
+
+vi.mock('@/stores/notifications', () => ({
+ notificationStore: {
+ success: vi.fn(),
+ error: vi.fn(),
+ warning: vi.fn(),
+ },
+}));
+
+const SEEN_AT = '2026-10-23T09:40:00Z';
+
+type FindingRecord = Record<string, unknown> & { id: string };
+
+// Patrol stamps the same time on every finding a run sees, so these tie on
+// severity and recency, as real findings do.
+const findingRecords = (): FindingRecord[] => [
+ {
+ id: 'finding-nginx',
+ key: 'finding-nginx',
+ severity: 'warning',
+ category: 'reliability',
+ resource_id: 'instance:node:102',
+ resource_name: 'web-02',
+ resource_type: 'vm',
+ title: 'nginx on web-02 restarts every few hours',
+ description: 'systemd restarted nginx 7 times in the last 24 hours.',
+ recommendation: 'Check the nginx error log for the crash cause.',
+ detected_at: '2026-10-22T07:00:00Z',
+ last_seen_at: SEEN_AT,
+ investigation_session_id: 'session-nginx',
+ investigation_status: 'completed',
+ investigation_outcome: 'needs_attention',
+ investigation_attempts: 1,
+ },
+ {
+ id: 'finding-disk',
+ key: 'finding-disk',
+ severity: 'warning',
+ category: 'capacity',
+ resource_id: 'instance:node:105',
+ resource_name: 'db-01',
+ resource_type: 'vm',
+ title: 'db-01 data disk is 91% full',
+ description: 'The PostgreSQL volume grew 4% in two days.',
+ detected_at: '2026-10-22T07:00:00Z',
+ last_seen_at: SEEN_AT,
+ },
+ {
+ id: 'finding-backup',
+ key: 'finding-backup',
+ severity: 'warning',
+ category: 'backup',
+ resource_id: 'instance:node:201',
+ resource_name: 'pbs-01',
+ resource_type: 'host',
+ title: 'Nightly backup on pbs-01 takes three times longer than usual',
+ description: 'The last three backup jobs each ran for about 3 hours.',
+ detected_at: '2026-10-22T07:00:00Z',
+ last_seen_at: SEEN_AT,
+ },
+];
+
+// Each read parses new objects, and the API returns tied findings in no
+// fixed order.
+const respondWith = (records: FindingRecord[]) => {
+ getPatrolFindingsMock.mockImplementation(async () =>
+ records.map((record) => JSON.parse(JSON.stringify(record))),
+ );
+};
+
+const renderPanel = () => {
+ const fallbackShown = { count: 0 };
+ const observer = new MutationObserver((records) => {
+ for (const record of records) {
+ for (const node of record.addedNodes) {
+ if (node.textContent?.includes('Loading view...')) fallbackShown.count += 1;
+ }
+ }
+ });
+ observer.observe(document.body, { childList: true, subtree: true });
+ render(() => (
+ <Router>
+ <Route
+ path="/"
+ component={() => (
+ <Suspense fallback={<div>Loading view...</div>}>
+ <FindingsPanel findingsSource="patrol" />
+ </Suspense>
+ )}
+ />
+ </Router>
+ ));
+ return { fallbackShown, stop: () => observer.disconnect() };
+};
+
+const rowIds = () =>
+ [...document.querySelectorAll('div[id^="finding-"]:not([id$="-details"])')].map((row) => row.id);
+const reviewContent = () =>
+ document.querySelector('aside#finding-finding-nginx-details .overflow-y-auto > div');
+
+// Open the nginx finding's review and its investigation thread, as someone
+// reading the finding would.
+const openReview = async () => {
+ await aiIntelligenceStore.loadPatrolFindings();
+ fireEvent.click(
+ await screen.findByRole('button', {
+ name: 'Review issue for nginx on web-02 restarts every few hours',
+ }),
+ );
+ fireEvent.click(await screen.findByRole('button', { name: 'Show investigation thread' }));
+ await screen.findByText('Checked memory history on web-02.');
+};
+
+describe('FindingsPanel across periodic refreshes', () => {
+ beforeEach(() => {
+ eventBus.emit('org_switched', 'default');
+ resetCreateNonSuspendingQueryCacheForTest();
+ getPatrolFindingsMock.mockReset();
+ getInvestigationMock.mockReset();
+ getInvestigationMessagesMock.mockReset();
+ respondWith(findingRecords());
+ // Every read parses a new object, as the API client does.
+ getInvestigationMock.mockImplementation(async () => ({
+ id: 'inv-nginx',
+ finding_id: 'finding-nginx',
+ session_id: 'session-nginx',
+ status: 'completed',
+ outcome: 'needs_attention',
+ started_at: '2026-10-23T09:00:00Z',
+ turn_count: 3,
+ summary: 'Patrol traced the restarts to memory pressure on web-02.',
+ tools_used: ['metrics.history'],
+ }));
+ getInvestigationMessagesMock.mockResolvedValue({
+ investigation_id: 'inv-nginx',
+ session_id: 'session-nginx',
+ messages: [
+ {
+ id: 'message-1',
+ role: 'assistant',
+ content: 'Checked memory history on web-02.',
+ timestamp: '2026-10-23T09:01:00Z',
+ },
+ ],
+ });
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it('keeps the open review, its rows and the page when a refresh returns the same findings', async () => {
+ const { fallbackShown, stop } = renderPanel();
+ await openReview();
+
+ const row = document.getElementById('finding-finding-nginx');
+ const content = reviewContent();
+ const order = rowIds();
+ expect(row).not.toBeNull();
+ expect(content).not.toBeNull();
+ expect(order).toHaveLength(3);
+
+ // Same findings, new objects, in the opposite order.
+ respondWith(findingRecords().reverse());
+ await aiIntelligenceStore.loadPatrolFindings();
+ await aiIntelligenceStore.loadPatrolFindings({ includeResolved: true });
+
+ expect(document.getElementById('finding-finding-nginx')).toBe(row);
+ expect(reviewContent()).toBe(content);
+ expect(rowIds()).toEqual(order);
+ expect(screen.getByRole('button', { name: 'Hide investigation thread' })).toBeInTheDocument();
+ expect(getInvestigationMock).toHaveBeenCalledTimes(1);
+ expect(getInvestigationMessagesMock).toHaveBeenCalledTimes(1);
+ // Neither opening the review nor the refreshes suspended the route.
+ expect(fallbackShown.count).toBe(0);
+ stop();
+ });
+
+ it('keeps the open review when a refresh changes another finding', async () => {
+ const { fallbackShown, stop } = renderPanel();
+ await openReview();
+ const row = document.getElementById('finding-finding-nginx');
+ const content = reviewContent();
+
+ respondWith(
+ findingRecords().map((record) =>
+ record.id === 'finding-disk' ? { ...record, title: 'db-01 data disk is 93% full' } : record,
+ ),
+ );
+ await aiIntelligenceStore.loadPatrolFindings();
+
+ expect(await screen.findByText('db-01 data disk is 93% full')).toBeInTheDocument();
+ expect(document.getElementById('finding-finding-nginx')).toBe(row);
+ expect(reviewContent()).toBe(content);
+ expect(screen.getByRole('button', { name: 'Hide investigation thread' })).toBeInTheDocument();
+ expect(getInvestigationMock).toHaveBeenCalledTimes(1);
+ expect(fallbackShown.count).toBe(0);
+ stop();
+ });
+
+ it('keeps the open review when a related finding in its group changes', async () => {
+ const memory: FindingRecord = {
+ id: 'finding-memory',
+ key: 'finding-memory',
+ severity: 'warning',
+ category: 'performance',
+ resource_id: 'instance:node:102',
+ resource_name: 'web-02',
+ resource_type: 'vm',
+ title: 'Memory on web-02 peaks at 97%',
+ description: 'Memory peaked at 97% before each restart.',
+ detected_at: '2026-10-22T07:00:00Z',
+ last_seen_at: SEEN_AT,
+ };
+ respondWith([...findingRecords(), memory]);
+ const { fallbackShown, stop } = renderPanel();
+ await openReview();
+ const content = reviewContent();
+ expect(screen.getByText('Memory on web-02 peaks at 97%')).toBeInTheDocument();
+
+ respondWith([...findingRecords(), { ...memory, title: 'Memory on web-02 peaks at 99%' }]);
+ await aiIntelligenceStore.loadPatrolFindings();
+
+ // The related issues list updates inside the review, which stays as it was.
+ expect(
+ await screen.findByText('Memory on web-02 peaks at 99%', {
+ selector: 'aside#finding-finding-nginx-details span',
+ }),
+ ).toBeInTheDocument();
+ expect(reviewContent()).toBe(content);
+ expect(screen.getByRole('button', { name: 'Hide investigation thread' })).toBeInTheDocument();
+ expect(getInvestigationMock).toHaveBeenCalledTimes(1);
+ expect(fallbackShown.count).toBe(0);
+ stop();
+ });
+
+ it('keeps ages moving in the rows and review that stay mounted', async () => {
+ // Rows used to be rebuilt by every refresh, which also refreshed their
+ // ages. Mounted rows read the shared clock instead.
+ vi.useFakeTimers({
+ toFake: ['Date', 'setInterval', 'clearInterval'],
+ now: Date.parse('2026-10-23T10:00:00Z'),
+ });
+ try {
+ const { fallbackShown, stop } = renderPanel();
+ await openReview();
+ const row = document.getElementById('finding-finding-nginx');
+ const review = document.querySelector('aside#finding-finding-nginx-details');
+ const content = reviewContent();
+ expect(row).toHaveTextContent('last seen 20m ago');
+ expect(review).toHaveTextContent('last seen 20m ago');
+ expect(review).toHaveTextContent('started 1h ago');
+ expect(review).toHaveTextContent('59m ago');
+
+ // No findings re-read: only the shared clock moves.
+ const reads = getPatrolFindingsMock.mock.calls.length;
+ vi.setSystemTime(Date.parse('2026-10-23T11:05:00Z'));
+ vi.advanceTimersByTime(RELATIVE_TIME_TICK_MS);
+
+ expect(document.getElementById('finding-finding-nginx')).toBe(row);
+ expect(row).toHaveTextContent('last seen 1h ago');
+ expect(review).toHaveTextContent('last seen 1h ago');
+ expect(review).toHaveTextContent('started 2h ago');
+ expect(review).not.toHaveTextContent('59m ago');
+ expect(getPatrolFindingsMock.mock.calls.length).toBe(reads);
+
+ // The same 30s also re-read the finished investigation, as a new
+ // object. The thread belongs to the same run, so it is not read again,
+ // and the review is not redrawn.
+ await waitFor(() => expect(getInvestigationMock).toHaveBeenCalledTimes(2));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(getInvestigationMessagesMock).toHaveBeenCalledTimes(1);
+ expect(reviewContent()).toBe(content);
+ expect(screen.getByRole('button', { name: 'Hide investigation thread' })).toBeInTheDocument();
+ expect(fallbackShown.count).toBe(0);
+ stop();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('shows a change to the open finding without suspending the route or reloading its investigation', async () => {
+ const { fallbackShown, stop } = renderPanel();
+ await openReview();
+
+ respondWith(
+ findingRecords().map((record) =>
+ record.id === 'finding-nginx'
+ ? { ...record, description: 'systemd restarted nginx 9 times in the last 24 hours.' }
+ : record,
+ ),
+ );
+ await aiIntelligenceStore.loadPatrolFindings();
+
+ // The review shows the new description at once, and the investigation
+ // it already read stays on screen while it is read again.
+ expect(
+ screen.getAllByText('systemd restarted nginx 9 times in the last 24 hours.').length,
+ ).toBeGreaterThan(0);
+ expect(
+ screen.getByText('Patrol traced the restarts to memory pressure on web-02.'),
+ ).toBeInTheDocument();
+ expect(screen.queryByText('Loading investigation...')).not.toBeInTheDocument();
+ await waitFor(() => expect(getInvestigationMock).toHaveBeenCalledTimes(2));
+ expect(fallbackShown.count).toBe(0);
+ stop();
+ });
+});
diff --git a/frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts b/frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts
index cee1b06d51..c051677a80 100644
--- a/frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts
+++ b/frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts
@@ -48,6 +48,7 @@ import {
getInvestigationStatusBadgeTone,
getInvestigationConfidenceBadgeTone,
doesFindingNeedAttention,
+ reuseIdenticalPatrolFindingDisplayGroups,
} from '@/utils/aiFindingPresentation';
import { PATROL_PROVIDER_SETTINGS_ACTION } from '@/utils/patrolRuntimeActions';
@@ -1479,6 +1480,45 @@ describe('aiFindingPresentation', () => {
});
describe('Patrol finding display groups', () => {
+ it('keeps a group across rebuilds while its findings are the same objects', () => {
+ const usage = {
+ id: 'usage',
+ resourceId: 'storage:tower-array',
+ resourceName: 'Tower Array',
+ resourceType: 'storage',
+ title: 'High usage',
+ };
+ const parity = { ...usage, id: 'parity', title: 'No parity protection' };
+ const provider = {
+ id: 'provider',
+ resourceId: 'ai-service',
+ resourceName: 'Pulse Patrol service',
+ resourceType: 'service',
+ title: 'Provider connection issue',
+ };
+ const first = buildPatrolFindingDisplayGroups([usage, parity, provider]);
+
+ // Rows are keyed by group, so a refresh that changed only the provider
+ // finding leaves the storage group, and its rows, as they were.
+ const changedProvider = { ...provider, title: 'Provider rejected the API key' };
+ const second = reuseIdenticalPatrolFindingDisplayGroups(
+ first,
+ buildPatrolFindingDisplayGroups([usage, parity, changedProvider]),
+ );
+ expect(second[0]).toBe(first[0]);
+ expect(second[1]).not.toBe(first[1]);
+ expect(second[1].primaryFinding).toBe(changedProvider);
+
+ // A group whose members changed is rebuilt.
+ const third = reuseIdenticalPatrolFindingDisplayGroups(
+ second,
+ buildPatrolFindingDisplayGroups([usage, changedProvider]),
+ );
+ expect(third[0]).not.toBe(second[0]);
+ expect(third[0].findings).toEqual([usage]);
+ expect(third[1]).toBe(second[1]);
+ });
+
it('groups findings with the same resource identity while preserving sorted order', () => {
const groups = buildPatrolFindingDisplayGroups([
{
diff --git a/frontend-modern/src/components/patrol/ApprovalSection.tsx b/frontend-modern/src/components/patrol/ApprovalSection.tsx
index feecb424da..e146b461ef 100644
--- a/frontend-modern/src/components/patrol/ApprovalSection.tsx
+++ b/frontend-modern/src/components/patrol/ApprovalSection.tsx
@@ -7,9 +7,10 @@
*/
import ArrowRightIcon from 'lucide-solid/icons/arrow-right';
-import { Component, For, Show, createMemo, createResource } from 'solid-js';
-import { AIAPI } from '@/api/ai';
+import { Component, For, Show, createMemo } from 'solid-js';
+import { AIAPI, type InvestigationSession } from '@/api/ai';
import { ButtonLink } from '@/components/shared/Button';
+import { createNonSuspendingQuery } from '@/hooks/createNonSuspendingQuery';
import { LoadingSpinner } from '@/components/shared/LoadingSpinner';
import { MetadataBadge } from '@/components/shared/MetadataBadge';
import { buildActionReviewPath } from '@/features/actions/actionRouting';
@@ -34,6 +35,8 @@ const FIX_RELATED_OUTCOMES = new Set([
const BADGE_PROPS = { size: 'xs', shape: 'rounded' } as const;
+const ACTION_REVALIDATE_MS = 30_000;
+
function statePresentation(state: ActionAuditState): {
label: string;
tone: 'neutral' | 'info' | 'warning' | 'success' | 'danger';
@@ -79,21 +82,27 @@ function capabilityLabel(value: string): string {
}
export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
- const [investigation] = createResource(
- () => ({
- findingId: props.findingId,
- outcome: props.investigationOutcome,
- hasAction: props.hasAction,
- }),
- async ({ findingId, outcome, hasAction }) => {
- if (!hasAction && (!outcome || !FIX_RELATED_OUTCOMES.has(outcome))) return null;
- try {
- return await AIAPI.getInvestigation(findingId);
- } catch {
- return null;
- }
- },
+ const shouldShow = createMemo(() =>
+ Boolean(
+ props.hasAction ||
+ (props.investigationOutcome && FIX_RELATED_OUTCOMES.has(props.investigationOutcome)),
+ ),
);
+ // As in InvestigationSection, reads stay out of the app's route Suspense
+ // boundary, whose fallback replaces the page and loses the reader's place,
+ // and the mounted review re-reads its action on the cadence at which
+ // findings refreshes used to remount it. A finding without an investigation
+ // reads null; any other failure keeps the last answer for the next read to
+ // replace.
+ const investigationQuery = createNonSuspendingQuery<InvestigationSession | null, string>({
+ source: () => (shouldShow() ? props.findingId : null),
+ cacheKey: (findingId) => `patrol-action-investigation:${findingId}`,
+ retainPreviousValueOnSourceChange: false,
+ fetcher: (findingId) => AIAPI.getInvestigation(findingId),
+ initialValue: null,
+ pollMs: ACTION_REVALIDATE_MS,
+ });
+ const investigation = investigationQuery.value;
const action = createMemo<PatrolActionReference | null>(() => investigation()?.action ?? null);
const verificationStatus = createMemo(() => {
@@ -108,18 +117,11 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
return 'unknown';
}
});
- const shouldShow = createMemo(() =>
- Boolean(
- props.hasAction ||
- (props.investigationOutcome && FIX_RELATED_OUTCOMES.has(props.investigationOutcome)),
- ),
- );
-
return (
<Show when={shouldShow()}>
<div class="mt-3 border-t border-border-subtle pt-3">
<Show
- when={!investigation.loading}
+ when={investigationQuery.resolvedOnce()}
fallback={
<div class="flex items-center gap-2 text-sm text-muted">
<LoadingSpinner size="sm" />
diff --git a/frontend-modern/src/components/patrol/InvestigationMessages.tsx b/frontend-modern/src/components/patrol/InvestigationMessages.tsx
index c322ac588e..310f2527ee 100644
--- a/frontend-modern/src/components/patrol/InvestigationMessages.tsx
+++ b/frontend-modern/src/components/patrol/InvestigationMessages.tsx
@@ -5,9 +5,12 @@
* Lazy-loads messages when rendered.
*/
-import { Component, createResource, Show, For } from 'solid-js';
+import { Component, createEffect, createMemo, on, Show, For } from 'solid-js';
import { getInvestigationMessages, formatTimestamp, type ChatMessage } from '@/api/patrol';
+import { withAPIErrorStatusNull } from '@/api/responseUtils';
import { LoadingSpinner } from '@/components/shared/LoadingSpinner';
+import { createNonSuspendingQuery } from '@/hooks/createNonSuspendingQuery';
+import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
import { getInvestigationMessagesState } from '@/utils/patrolEmptyStatePresentation';
import { renderMarkdown } from '@/components/AI/aiChatUtils';
import { ToolExecutionBlock } from './ToolExecutionBlock';
@@ -19,47 +22,97 @@ const investigationMarkdownClass =
interface InvestigationMessagesProps {
findingId: string;
+ // The run whose thread this is: a new run reads its own thread instead of
+ // showing the last one's.
+ sessionId?: string;
+ // While the run is active, the thread is read again as it grows.
+ live?: boolean;
}
+const LIVE_THREAD_POLL_MS = 5_000;
+const FAILED_THREAD_RETRY_MS = 30_000;
+
/** Returns true if a message has no displayable content */
function isEmptyMessage(msg: ChatMessage): boolean {
return !msg.content && !msg.reasoning_content && !msg.tool_calls?.length && !msg.tool_result;
}
+// Each read parses new objects. A message that comes back unchanged keeps its
+// object, so its row, and any tool output expanded in it, stays as it was.
+function reuseIdenticalMessages(previous: ChatMessage[], next: ChatMessage[]): ChatMessage[] {
+ const previousById = new Map(previous.map((message) => [message.id, message]));
+ return next.map((message) => {
+ const prior = previousById.get(message.id);
+ return prior && JSON.stringify(prior) === JSON.stringify(message) ? prior : message;
+ });
+}
+
export const InvestigationMessages: Component<InvestigationMessagesProps> = (props) => {
- const [messages] = createResource(
- () => props.findingId,
- async (findingId) => {
- try {
- const result = await getInvestigationMessages(findingId);
- return result.messages || [];
- } catch {
- return [];
- }
+ // The thread is read again only when its run changes, so a finished thread
+ // keeps its rows, and any expanded tool output, across re-reads of the run.
+ const thread = createMemo(
+ () => ({ findingId: props.findingId, sessionId: props.sessionId ?? '' }),
+ undefined,
+ { equals: (a, b) => a.findingId === b.findingId && a.sessionId === b.sessionId },
+ );
+ // As in InvestigationSection, reads stay out of the app's route Suspense
+ // boundary, whose fallback replaces the page and loses the reader's place.
+ // The open thread is no longer remounted by findings refreshes, so it reads
+ // itself again every 5s while its run is live, and 30s after a failed read.
+ const messagesQuery = createNonSuspendingQuery<
+ ChatMessage[],
+ { findingId: string; sessionId: string }
+ >({
+ source: thread,
+ cacheKey: ({ findingId, sessionId }) =>
+ `patrol-investigation-messages:${findingId}:${sessionId}`,
+ retainPreviousValueOnSourceChange: false,
+ fetcher: async ({ findingId }): Promise<ChatMessage[]> => {
+ const read = await withAPIErrorStatusNull(getInvestigationMessages(findingId), 404);
+ // Read after the await: outside the query's source effect, so the
+ // thread on screen is not tracked as a reason to read again.
+ return reuseIdenticalMessages(messagesQuery.value(), read?.messages || []);
},
+ initialValue: [],
+ pollMs: (): number | undefined =>
+ props.live ? LIVE_THREAD_POLL_MS : messagesQuery.error() ? FAILED_THREAD_RETRY_MS : undefined,
+ });
+ // A run that finishes between two live reads gets one more, so the thread
+ // ends with the run's last messages.
+ createEffect(
+ on(
+ () => Boolean(props.live),
+ (live, wasLive) => {
+ if (wasLive && !live) void messagesQuery.refetch({ background: true });
+ },
+ ),
+ );
+ const messages = messagesQuery.value;
+ const messagesState = createMemo(() =>
+ getInvestigationMessagesState(!messagesQuery.resolvedOnce(), messages().length > 0),
);
+ // The thread stays mounted across refreshes, so its ages re-read on each
+ // tick of the shared clock to keep moving.
+ const now = useRelativeTimeNow();
+ const formatAge = (timestamp: string) => {
+ now();
+ return formatTimestamp(timestamp);
+ };
return (
<div class="mt-2">
- <Show
- when={
- !getInvestigationMessagesState(messages.loading, !!messages()?.length).empty &&
- getInvestigationMessagesState(messages.loading, !!messages()?.length).text
- }
- >
+ <Show when={!messagesState().empty && messagesState().text}>
<div class="flex items-center gap-2 text-xs text-muted py-2">
<LoadingSpinner size="sm" />
- {getInvestigationMessagesState(messages.loading, !!messages()?.length).text}
+ {messagesState().text}
</div>
</Show>
- <Show when={getInvestigationMessagesState(messages.loading, !!messages()?.length).empty}>
- <p class="text-xs text-muted py-1">
- {getInvestigationMessagesState(messages.loading, !!messages()?.length).text}
- </p>
+ <Show when={messagesState().empty}>
+ <p class="text-xs text-muted py-1">{messagesState().text}</p>
</Show>
- <Show when={!messages.loading && messages() && messages()!.length > 0}>
+ <Show when={messages().length > 0}>
<div class="space-y-2 max-h-80 overflow-y-auto rounded-sm border border-border p-2 bg-surface-alt">
<For each={messages()}>
{(msg: ChatMessage) => {
@@ -171,7 +224,7 @@ export const InvestigationMessages: Component<InvestigationMessagesProps> = (pro
</div>
</Show>
- <div class="text-[10px] text-muted mt-1">{formatTimestamp(msg.timestamp)}</div>
+ <div class="text-[10px] text-muted mt-1">{formatAge(msg.timestamp)}</div>
</div>
</div>
);
diff --git a/frontend-modern/src/components/patrol/InvestigationSection.tsx b/frontend-modern/src/components/patrol/InvestigationSection.tsx
index c132a4e2c7..e2ec7e6bed 100644
--- a/frontend-modern/src/components/patrol/InvestigationSection.tsx
+++ b/frontend-modern/src/components/patrol/InvestigationSection.tsx
@@ -6,17 +6,16 @@
* a collapsible investigation thread.
*/
+import { Component, createSignal, createMemo, Show, For } from 'solid-js';
import {
- Component,
- createSignal,
- createResource,
- createEffect,
- createMemo,
- onCleanup,
- Show,
- For,
-} from 'solid-js';
-import { getInvestigation, reinvestigateFinding, formatTimestamp } from '@/api/patrol';
+ getInvestigation,
+ reinvestigateFinding,
+ formatTimestamp,
+ type Investigation,
+} from '@/api/patrol';
+import { withAPIErrorStatusNull } from '@/api/responseUtils';
+import { createNonSuspendingQuery } from '@/hooks/createNonSuspendingQuery';
+import { useRelativeTimeNow } from '@/utils/relativeTimeClock';
import {
getInvestigationConfidenceBadgeTone,
getInvestigationOutcomeBadgeTone,
@@ -41,6 +40,9 @@ const INVESTIGATION_BADGE_PROPS = {
shape: 'rounded',
} as const;
+const ACTIVE_INVESTIGATION_POLL_MS = 5_000;
+const INVESTIGATION_REVALIDATE_MS = 30_000;
+
const summaryClass =
'text-sm prose prose-slate prose-sm dark:prose-invert max-w-none wrap-break-word prose-headings:my-2 prose-p:my-2 prose-pre:overflow-x-auto prose-code:break-all prose-code:before:content-none prose-code:after:content-none';
@@ -68,37 +70,54 @@ export const InvestigationSection: Component<InvestigationSectionProps> = (props
buildPatrolInvestigationRecordPresentation(props.investigationRecord),
);
- const [investigation, { refetch }] = createResource(
- () => props.findingId,
- async (findingId) => {
- try {
- return await getInvestigation(findingId);
- } catch {
- return null;
- }
- },
- );
+ // Reads stay out of the app's route Suspense boundary, whose fallback
+ // replaces the whole page: a read while someone reads this review (opening
+ // it, polling, Re-investigate) dropped them back to the top. The last answer
+ // stays on screen while the next loads, and a remounted review shows the
+ // retained answer at once. The review also stays mounted across findings
+ // refreshes, which used to remount it and so re-read it every 30s, so it
+ // re-reads on that cadence itself, and every 5s while the run is active.
+ const investigationQuery = createNonSuspendingQuery<Investigation | null, string>({
+ source: () => props.findingId,
+ cacheKey: (findingId) => `patrol-investigation:${findingId}`,
+ retainPreviousValueOnSourceChange: false,
+ // A finding Patrol has not investigated answers 404. Any other failure
+ // keeps the last answer on screen for the next read to replace.
+ fetcher: (findingId) => withAPIErrorStatusNull(getInvestigation(findingId), 404),
+ initialValue: null,
+ pollMs: (): number =>
+ investigationActive() ? ACTIVE_INVESTIGATION_POLL_MS : INVESTIGATION_REVALIDATE_MS,
+ });
+ const investigation = investigationQuery.value;
+ const refreshInvestigation = () => investigationQuery.refetch({ background: true });
+ // The review stays mounted across refreshes, so its ages re-read on each
+ // tick of the shared clock to keep moving.
+ const now = useRelativeTimeNow();
+ const formatAge = (timestamp: string) => {
+ now();
+ return formatTimestamp(timestamp);
+ };
const hasInvestigationContext = createMemo(
() => Boolean(investigation()) || investigationRecord().hasRecord,
);
const investigationSectionState = createMemo(() =>
- getInvestigationSectionState(investigation.loading, hasInvestigationContext()),
+ getInvestigationSectionState(!investigationQuery.resolvedOnce(), hasInvestigationContext()),
);
-
- // Auto-poll while investigation is active
- createEffect(() => {
+ const investigationActive = createMemo<boolean>(() => {
const inv = investigation();
- const isActive =
+ return (
inv?.status === 'running' ||
inv?.status === 'pending' ||
- props.investigationStatus === 'running';
- if (!isActive) return;
-
- const interval = setInterval(() => refetch(), 5000);
- onCleanup(() => clearInterval(interval));
+ props.investigationStatus === 'running'
+ );
});
+ // The thread follows the run's session id, not each re-read of the run.
+ const sessionId = createMemo(() => investigation()?.session_id ?? '');
const canReinvestigate = () => {
+ // Until the first read answers, a running investigation or a queued fix
+ // looks like no investigation at all, which would offer another run.
+ if (!investigationQuery.resolvedOnce()) return false;
if (Date.now() < cooldownUntil()) return false;
const inv = investigation();
if (!inv) return true; // No investigation yet
@@ -127,7 +146,7 @@ export const InvestigationSection: Component<InvestigationSectionProps> = (props
await reinvestigateFinding(props.findingId);
notificationStore.success('Re-investigation started');
setCooldownUntil(Date.now() + 60000);
- refetch();
+ void refreshInvestigation();
aiIntelligenceStore.loadFindings();
} catch (err) {
notificationStore.error((err as Error).message || 'Failed to start re-investigation');
@@ -347,7 +366,7 @@ export const InvestigationSection: Component<InvestigationSectionProps> = (props
</Show>
{/* Investigation details */}
- <Show when={!investigation.loading && investigation()}>
+ <Show when={investigation()}>
{(inv) => (
<div class="space-y-2">
{/* Error message for failed investigations */}
@@ -402,9 +421,7 @@ export const InvestigationSection: Component<InvestigationSectionProps> = (props
{inv().turn_count} turn{inv().turn_count === 1 ? '' : 's'}
</span>
<Show when={inv().started_at}>
- <span class="text-[10px] text-muted">
- started {formatTimestamp(inv().started_at)}
- </span>
+ <span class="text-[10px] text-muted">started {formatAge(inv().started_at)}</span>
</Show>
</div>
@@ -435,7 +452,11 @@ export const InvestigationSection: Component<InvestigationSectionProps> = (props
{/* Investigation messages (lazy loaded) */}
<Show when={showThread()}>
- <InvestigationMessages findingId={props.findingId} />
+ <InvestigationMessages
+ findingId={props.findingId}
+ sessionId={sessionId()}
+ live={investigationActive()}
+ />
</Show>
</div>
)}
diff --git a/frontend-modern/src/components/patrol/RunToolCallTrace.tsx b/frontend-modern/src/components/patrol/RunToolCallTrace.tsx
index 0ecf3ac165..48424f0e88 100644
--- a/frontend-modern/src/components/patrol/RunToolCallTrace.tsx
+++ b/frontend-modern/src/components/patrol/RunToolCallTrace.tsx
@@ -5,7 +5,7 @@
* Lazy-loads tool call details when expanded.
*/
-import { Component, createSignal, createResource, Show, For } from 'solid-js';
+import { Component, createSignal, Show, For } from 'solid-js';
import {
getPatrolRunWithToolCalls,
type ToolCallRecord,
@@ -13,6 +13,7 @@ import {
type ToolCallVerificationStatus,
} from '@/api/patrol';
import { LoadingSpinner } from '@/components/shared/LoadingSpinner';
+import { createNonSuspendingQuery } from '@/hooks/createNonSuspendingQuery';
import { MetadataBadge } from '@/components/shared/MetadataBadge';
import {
getToolCallResultBadgeTone,
@@ -106,11 +107,15 @@ export const RunToolCallTrace: Component<RunToolCallTraceProps> = (props) => {
const [expanded, setExpanded] = createSignal(false);
const [expandedCall, setExpandedCall] = createSignal<string | null>(null);
- // Lazy-load tool calls when expanded — fetch small batch since the run is likely recent
- const [toolCalls] = createResource(
- () => (expanded() ? props.runId : null),
- async (runId) => {
- if (!runId) return [];
+ // Lazy-load tool calls when expanded — fetch small batch since the run is likely recent.
+ // Like the finding review's reads, this one never suspends: the nearest
+ // Suspense boundary is the app's route boundary, whose fallback replaces
+ // the page and loses the reader's place.
+ const toolCallsQuery = createNonSuspendingQuery<ToolCallRecord[], string>({
+ source: () => (expanded() ? props.runId : null),
+ cacheKey: (runId) => `patrol-run-tool-calls:${runId}`,
+ retainPreviousValueOnSourceChange: false,
+ fetcher: async (runId) => {
try {
const run = await getPatrolRunWithToolCalls(runId);
return run?.tool_calls ?? [];
@@ -118,7 +123,10 @@ export const RunToolCallTrace: Component<RunToolCallTraceProps> = (props) => {
return [];
}
},
- );
+ initialValue: [],
+ });
+ const toolCalls = toolCallsQuery.value;
+ const toolCallsLoading = () => !toolCallsQuery.resolvedOnce();
const truncate = (text: string, max: number = 200) =>
text.length <= max ? text : text.slice(0, max - 1) + '...';
@@ -148,14 +156,14 @@ export const RunToolCallTrace: Component<RunToolCallTraceProps> = (props) => {
</button>
<Show when={expanded()}>
- <Show when={toolCalls.loading}>
+ <Show when={toolCallsLoading()}>
<div class="flex items-center gap-2 text-xs text-muted py-2 mt-2">
<LoadingSpinner size="sm" />
{getToolCallsLoadingState()}
</div>
</Show>
- <Show when={!toolCalls.loading && toolCalls() && toolCalls()!.length > 0}>
+ <Show when={toolCalls().length > 0}>
<div class="mt-2 space-y-1">
<For each={toolCalls()}>
{(call: ToolCallRecord, index) => {
@@ -232,7 +240,7 @@ export const RunToolCallTrace: Component<RunToolCallTraceProps> = (props) => {
</div>
</Show>
- <Show when={!toolCalls.loading && (!toolCalls() || toolCalls()!.length === 0)}>
+ <Show when={!toolCallsLoading() && toolCalls().length === 0}>
<p class="text-xs text-muted mt-2">{getToolCallsUnavailableState()}</p>
</Show>
</Show>
diff --git a/frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx b/frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx
index b382be0755..20921ff5f2 100644
--- a/frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx
+++ b/frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx
@@ -1,7 +1,9 @@
import { cleanup, render, screen } from '@solidjs/testing-library';
import { Route, Router } from '@solidjs/router';
+import { Suspense } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { InvestigationSession } from '@/api/ai';
+import { resetCreateNonSuspendingQueryCacheForTest } from '@/hooks/createNonSuspendingQuery';
import type { PatrolActionReference } from '@/types/actionAudit';
import approvalSectionSource from '../ApprovalSection.tsx?raw';
import ApprovalSection from '../ApprovalSection';
@@ -54,6 +56,7 @@ function investigation(action?: PatrolActionReference): InvestigationSession {
describe('ApprovalSection typed action handoff', () => {
beforeEach(() => {
+ resetCreateNonSuspendingQueryCacheForTest();
getInvestigationMock.mockReset();
});
@@ -88,6 +91,61 @@ describe('ApprovalSection typed action handoff', () => {
expect(approvalSectionSource).not.toContain('proposed_fix.commands');
});
+ it('reads the governed action through the non-suspending query', () => {
+ // The nearest Suspense boundary above a review is the app's route
+ // boundary, whose fallback replaces the page and loses the reader's place.
+ expect(approvalSectionSource).not.toContain('createResource');
+ expect(approvalSectionSource).toContain('createNonSuspendingQuery');
+ });
+
+ it('keeps the page around a finding review while the governed action loads', async () => {
+ let finishRead: (value: InvestigationSession) => void = () => {};
+ getInvestigationMock.mockReturnValue(
+ new Promise<InvestigationSession>((resolve) => {
+ finishRead = resolve;
+ }),
+ );
+
+ render(() => (
+ <Router>
+ <Route
+ path="/"
+ component={() => (
+ <Suspense fallback={<div>Loading view...</div>}>
+ <ApprovalSection findingId="finding-1" investigationOutcome="fix_queued" />
+ </Suspense>
+ )}
+ />
+ </Router>
+ ));
+
+ expect(await screen.findByText('Loading governed action…')).toBeInTheDocument();
+ expect(screen.queryByText('Loading view...')).not.toBeInTheDocument();
+
+ finishRead(investigation(actionReference('pending_approval')));
+ expect(await screen.findByRole('link', { name: /review in actions/i })).toBeInTheDocument();
+ expect(screen.queryByText('Loading view...')).not.toBeInTheDocument();
+ });
+
+ it('reads the action again on its own after a failed read', async () => {
+ // Findings refreshes no longer remount the review, so it retries itself.
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
+ try {
+ getInvestigationMock.mockRejectedValueOnce(new Error('Pulse is restarting'));
+ getInvestigationMock.mockResolvedValueOnce(
+ investigation(actionReference('pending_approval')),
+ );
+
+ renderSection('fix_queued');
+ expect(await screen.findByText('Action details unavailable')).toBeInTheDocument();
+
+ vi.advanceTimersByTime(30_000);
+ expect(await screen.findByRole('link', { name: /review in actions/i })).toBeInTheDocument();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('deep-links a pending action to its exact governed review', async () => {
getInvestigationMock.mockResolvedValue(investigation(actionReference('pending_approval')));
diff --git a/frontend-modern/src/components/patrol/__tests__/InvestigationMessages.test.tsx b/frontend-modern/src/components/patrol/__tests__/InvestigationMessages.test.tsx
index b1b8c6d3a6..bd11ee1dd0 100644
--- a/frontend-modern/src/components/patrol/__tests__/InvestigationMessages.test.tsx
+++ b/frontend-modern/src/components/patrol/__tests__/InvestigationMessages.test.tsx
@@ -1,5 +1,8 @@
import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createSignal, Suspense } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { resetCreateNonSuspendingQueryCacheForTest } from '@/hooks/createNonSuspendingQuery';
+import investigationMessagesSource from '../InvestigationMessages.tsx?raw';
import InvestigationMessages from '../InvestigationMessages';
const getMessages = vi.hoisted(() => vi.fn());
@@ -8,9 +11,163 @@ vi.mock('@/api/patrol', () => ({
formatTimestamp: (value: string) => value,
}));
+beforeEach(() => {
+ resetCreateNonSuspendingQueryCacheForTest();
+ getMessages.mockReset();
+});
afterEach(cleanup);
describe('InvestigationMessages', () => {
+ it('reads the thread through the non-suspending query', () => {
+ // The nearest Suspense boundary above a review is the app's route
+ // boundary, whose fallback replaces the page and loses the reader's place.
+ expect(investigationMessagesSource).not.toContain('createResource');
+ expect(investigationMessagesSource).toContain('createNonSuspendingQuery');
+ });
+
+ it('keeps the page around a finding review while the thread loads', async () => {
+ let finishRead: (value: unknown) => void = () => {};
+ getMessages.mockReturnValue(
+ new Promise((resolve) => {
+ finishRead = resolve;
+ }),
+ );
+
+ render(() => (
+ <Suspense fallback={<div>Loading view...</div>}>
+ <InvestigationMessages findingId="finding-3" />
+ </Suspense>
+ ));
+
+ expect(await screen.findByText('Loading messages...')).toBeInTheDocument();
+ expect(screen.queryByText('Loading view...')).not.toBeInTheDocument();
+
+ finishRead({
+ messages: [
+ { id: 'turn-1', role: 'assistant', content: 'Checked the service log.', timestamp: '1' },
+ ],
+ });
+ expect(await screen.findByText('Checked the service log.')).toBeInTheDocument();
+ expect(screen.queryByText('Loading view...')).not.toBeInTheDocument();
+ });
+
+ it("reads a new run's thread instead of keeping the last run's", async () => {
+ getMessages.mockResolvedValueOnce({
+ messages: [
+ { id: 'a-1', role: 'assistant', content: 'First run read the log.', timestamp: '1' },
+ ],
+ });
+ let finishSecondRead: (value: unknown) => void = () => {};
+ getMessages.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishSecondRead = resolve;
+ }),
+ );
+ const [sessionId, setSessionId] = createSignal('session-a');
+
+ render(() => <InvestigationMessages findingId="finding-4" sessionId={sessionId()} />);
+ expect(await screen.findByText('First run read the log.')).toBeInTheDocument();
+
+ // While the new run's thread loads, the last run's is not shown as its.
+ setSessionId('session-b');
+ expect(await screen.findByText('Loading messages...')).toBeInTheDocument();
+ expect(screen.queryByText('First run read the log.')).not.toBeInTheDocument();
+
+ finishSecondRead({
+ messages: [
+ { id: 'b-1', role: 'assistant', content: 'Second run read memory.', timestamp: '1' },
+ ],
+ });
+ expect(await screen.findByText('Second run read memory.')).toBeInTheDocument();
+ expect(screen.queryByText('First run read the log.')).not.toBeInTheDocument();
+ });
+
+ it('reads the thread again 30s after a failed read', async () => {
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
+ try {
+ getMessages.mockRejectedValueOnce(new Error('Pulse is restarting'));
+ getMessages.mockResolvedValueOnce({
+ messages: [{ id: 'r-1', role: 'assistant', content: 'Read on retry.', timestamp: '1' }],
+ });
+ render(() => <InvestigationMessages findingId="finding-7" sessionId="session-retry" />);
+ expect(await screen.findByText('No investigation messages available.')).toBeInTheDocument();
+
+ vi.advanceTimersByTime(30_000);
+ expect(await screen.findByText('Read on retry.')).toBeInTheDocument();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not read a finished thread again while it stays open', async () => {
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
+ try {
+ getMessages.mockResolvedValue({
+ messages: [{ id: 'f-1', role: 'assistant', content: 'Done.', timestamp: '1' }],
+ });
+ render(() => <InvestigationMessages findingId="finding-6" sessionId="session-done" />);
+ expect(await screen.findByText('Done.')).toBeInTheDocument();
+
+ vi.advanceTimersByTime(120_000);
+ expect(getMessages).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('reads the thread again while its run is live', async () => {
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
+ try {
+ const first = {
+ id: 'm-1',
+ role: 'assistant',
+ content: 'Started on the service.',
+ timestamp: '1',
+ };
+ // Each read parses new objects, as the API client does.
+ getMessages.mockResolvedValueOnce({ messages: [{ ...first }] });
+ getMessages.mockResolvedValueOnce({
+ messages: [
+ { ...first },
+ { id: 'm-2', role: 'assistant', content: 'Found the crash in the log.', timestamp: '2' },
+ ],
+ });
+
+ render(() => <InvestigationMessages findingId="finding-5" sessionId="session-live" live />);
+ const firstRow = await screen.findByText('Started on the service.');
+
+ vi.advanceTimersByTime(5_000);
+ expect(await screen.findByText('Found the crash in the log.')).toBeInTheDocument();
+ // The unchanged first message keeps its row.
+ expect(screen.getByText('Started on the service.')).toBe(firstRow);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('reads the thread once more when its run finishes', async () => {
+ getMessages.mockResolvedValueOnce({
+ messages: [{ id: 'e-1', role: 'assistant', content: 'Checking the log.', timestamp: '1' }],
+ });
+ getMessages.mockResolvedValueOnce({
+ messages: [
+ { id: 'e-1', role: 'assistant', content: 'Checking the log.', timestamp: '1' },
+ { id: 'e-2', role: 'assistant', content: 'The disk filled up.', timestamp: '2' },
+ ],
+ });
+ const [live, setLive] = createSignal(true);
+
+ render(() => (
+ <InvestigationMessages findingId="finding-8" sessionId="session-ending" live={live()} />
+ ));
+ expect(await screen.findByText('Checking the log.')).toBeInTheDocument();
+
+ // The run finished between two live reads.
+ setLive(false);
+ expect(await screen.findByText('The disk filled up.')).toBeInTheDocument();
+ expect(getMessages).toHaveBeenCalledTimes(2);
+ });
+
it('retains merged failed tool evidence and exposes it through the shared disclosure', async () => {
getMessages.mockResolvedValue({
messages: [
diff --git a/frontend-modern/src/components/patrol/__tests__/InvestigationSection.test.tsx b/frontend-modern/src/components/patrol/__tests__/InvestigationSection.test.tsx
index 1284332cf5..8e58ce620a 100644
--- a/frontend-modern/src/components/patrol/__tests__/InvestigationSection.test.tsx
+++ b/frontend-modern/src/components/patrol/__tests__/InvestigationSection.test.tsx
@@ -1,7 +1,9 @@
-import { cleanup, render, screen } from '@solidjs/testing-library';
+import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
+import { Suspense } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { InvestigationRecord } from '@/api/ai';
import type { Investigation } from '@/api/patrol';
+import { resetCreateNonSuspendingQueryCacheForTest } from '@/hooks/createNonSuspendingQuery';
import {
getInvestigationOutcomeBadgeTone,
getInvestigationOutcomeLabel,
@@ -39,6 +41,7 @@ vi.mock('../InvestigationMessages', () => ({
describe('InvestigationSection', () => {
beforeEach(() => {
+ resetCreateNonSuspendingQueryCacheForTest();
getInvestigationMock.mockReset();
reinvestigateFindingMock.mockReset();
loadFindingsMock.mockReset();
@@ -52,6 +55,140 @@ describe('InvestigationSection', () => {
expect(investigationSectionSource).toContain('LoadingSpinner');
});
+ it('reads the investigation without suspending the page around a finding review', () => {
+ // The nearest Suspense boundary above a review is the app's route
+ // boundary, whose fallback replaces the page and loses the reader's place.
+ expect(investigationSectionSource).not.toContain('createResource');
+ expect(investigationSectionSource).toContain('createNonSuspendingQuery');
+ });
+
+ it('does not offer another run before the first read says what the run is doing', async () => {
+ let finishRead: (value: Investigation) => void = () => {};
+ getInvestigationMock.mockReturnValueOnce(
+ new Promise<Investigation>((resolve) => {
+ finishRead = resolve;
+ }),
+ );
+
+ render(() => <InvestigationSection findingId="finding-pending" investigationStatus="failed" />);
+
+ expect(await screen.findByText('Loading investigation...')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Re-investigate' })).not.toBeInTheDocument();
+
+ finishRead({
+ id: 'inv-pending',
+ finding_id: 'finding-pending',
+ session_id: 'session-pending',
+ status: 'failed',
+ outcome: 'fix_queued',
+ started_at: '2026-10-23T10:00:00.000Z',
+ turn_count: 6,
+ });
+ expect(await screen.findByText(getInvestigationOutcomeLabel('fix_queued'))).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Re-investigate' })).not.toBeInTheDocument();
+ });
+
+ it('keeps the last answer when a later read fails', async () => {
+ getInvestigationMock.mockResolvedValueOnce({
+ id: 'inv-kept',
+ finding_id: 'finding-kept',
+ session_id: 'session-kept',
+ status: 'completed',
+ outcome: 'unclassified',
+ started_at: '2026-10-23T10:00:00.000Z',
+ turn_count: 3,
+ summary: 'The service restarted twice.',
+ } satisfies Investigation);
+ getInvestigationMock.mockRejectedValueOnce(new Error('Pulse is restarting'));
+ reinvestigateFindingMock.mockResolvedValue({ success: true });
+
+ render(() => <InvestigationSection findingId="finding-kept" investigationStatus="completed" />);
+ fireEvent.click(await screen.findByRole('button', { name: 'Re-investigate' }));
+ await waitFor(() => expect(getInvestigationMock).toHaveBeenCalledTimes(2));
+ // Let the failed read settle.
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(screen.getByText('The service restarted twice.')).toBeInTheDocument();
+ expect(screen.queryByText(/No investigation yet/)).not.toBeInTheDocument();
+ });
+
+ it('reads again on its own after a failed first read', async () => {
+ // Findings refreshes no longer remount the review, so it retries itself.
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
+ try {
+ getInvestigationMock.mockRejectedValueOnce(new Error('Pulse is restarting'));
+ getInvestigationMock.mockResolvedValueOnce({
+ id: 'inv-retry',
+ finding_id: 'finding-retry',
+ session_id: 'session-retry',
+ status: 'completed',
+ outcome: 'unclassified',
+ started_at: '2026-10-23T10:00:00.000Z',
+ turn_count: 3,
+ summary: 'Read on the second try.',
+ } satisfies Investigation);
+
+ render(() => (
+ <InvestigationSection findingId="finding-retry" investigationStatus="completed" />
+ ));
+ await waitFor(() => expect(getInvestigationMock).toHaveBeenCalledTimes(1));
+ expect(screen.queryByText('Read on the second try.')).not.toBeInTheDocument();
+
+ vi.advanceTimersByTime(30_000);
+ expect(await screen.findByText('Read on the second try.')).toBeInTheDocument();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps the investigation on screen, and the route in place, while it is read again', async () => {
+ getInvestigationMock.mockResolvedValueOnce({
+ id: 'inv-reread',
+ finding_id: 'finding-reread',
+ session_id: 'session-reread',
+ status: 'completed',
+ outcome: 'unclassified',
+ started_at: '2026-10-23T10:00:00.000Z',
+ turn_count: 3,
+ summary: 'Memory pressure explains the restarts.',
+ } satisfies Investigation);
+ let finishRead: (value: Investigation) => void = () => {};
+ getInvestigationMock.mockReturnValueOnce(
+ new Promise<Investigation>((resolve) => {
+ finishRead = resolve;
+ }),
+ );
+ reinvestigateFindingMock.mockResolvedValue({ success: true });
+
+ render(() => (
+ <Suspense fallback={<div>Loading view...</div>}>
+ <InvestigationSection findingId="finding-reread" investigationStatus="completed" />
+ </Suspense>
+ ));
+
+ expect(screen.queryByText('Loading view...')).not.toBeInTheDocument();
+ expect(await screen.findByText('Memory pressure explains the restarts.')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Re-investigate' }));
+ await waitFor(() => expect(getInvestigationMock).toHaveBeenCalledTimes(2));
+
+ // The second read is still in flight.
+ expect(screen.queryByText('Loading view...')).not.toBeInTheDocument();
+ expect(screen.queryByText('Loading investigation...')).not.toBeInTheDocument();
+ expect(screen.getByText('Memory pressure explains the restarts.')).toBeInTheDocument();
+
+ finishRead({
+ id: 'inv-reread-2',
+ finding_id: 'finding-reread',
+ session_id: 'session-reread-2',
+ status: 'running',
+ started_at: '2026-10-23T10:05:00.000Z',
+ turn_count: 0,
+ });
+ expect(await screen.findByText('Running')).toBeInTheDocument();
+ expect(screen.queryByText('Loading view...')).not.toBeInTheDocument();
+ });
+
it('renders investigation status badges from the shared finding presentation contract', async () => {
getInvestigationMock.mockResolvedValue({
id: 'inv-1',
diff --git a/frontend-modern/src/components/patrol/__tests__/RunToolCallTrace.test.tsx b/frontend-modern/src/components/patrol/__tests__/RunToolCallTrace.test.tsx
index acb505923b..b3e4cd5ef0 100644
--- a/frontend-modern/src/components/patrol/__tests__/RunToolCallTrace.test.tsx
+++ b/frontend-modern/src/components/patrol/__tests__/RunToolCallTrace.test.tsx
@@ -1,5 +1,8 @@
import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { Suspense } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { resetCreateNonSuspendingQueryCacheForTest } from '@/hooks/createNonSuspendingQuery';
+import { getToolCallsLoadingState } from '@/utils/patrolRunPresentation';
import runToolCallTraceSource from '../RunToolCallTrace.tsx?raw';
import { RunToolCallTrace } from '../RunToolCallTrace';
@@ -11,9 +14,52 @@ vi.mock('@/api/patrol', () => ({
describe('RunToolCallTrace', () => {
beforeEach(() => {
+ resetCreateNonSuspendingQueryCacheForTest();
getPatrolRunWithToolCallsMock.mockReset();
});
+ it('reads tool calls through the non-suspending query', () => {
+ // The nearest Suspense boundary above Patrol history is the app's route
+ // boundary, whose fallback replaces the page and loses the reader's place.
+ expect(runToolCallTraceSource).not.toContain('createResource');
+ expect(runToolCallTraceSource).toContain('createNonSuspendingQuery');
+ });
+
+ it('keeps the page around the run history while tool calls load', async () => {
+ let finishRead: (value: unknown) => void = () => {};
+ getPatrolRunWithToolCallsMock.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishRead = resolve;
+ }),
+ );
+
+ render(() => (
+ <Suspense fallback={<div>Loading view...</div>}>
+ <RunToolCallTrace runId="run-pending" toolCallCount={1} />
+ </Suspense>
+ ));
+ fireEvent.click(screen.getByRole('button', { name: /Tool calls \(1\)/ }));
+
+ expect(screen.getByText(getToolCallsLoadingState())).toBeInTheDocument();
+ expect(screen.queryByText('Loading view...')).not.toBeInTheDocument();
+
+ finishRead({
+ id: 'run-pending',
+ tool_calls: [
+ {
+ id: 'call-1',
+ tool_name: 'ssh_execute',
+ input: '{"command":"uptime"}',
+ output: 'ok',
+ success: true,
+ duration_ms: 42,
+ },
+ ],
+ });
+ expect(await screen.findByText('ssh_execute')).toBeInTheDocument();
+ expect(screen.queryByText('Loading view...')).not.toBeInTheDocument();
+ });
+
afterEach(() => {
cleanup();
});
diff --git a/frontend-modern/src/hooks/__tests__/createNonSuspendingQuery.test.tsx b/frontend-modern/src/hooks/__tests__/createNonSuspendingQuery.test.tsx
index 95d0cc4c82..464222f056 100644
--- a/frontend-modern/src/hooks/__tests__/createNonSuspendingQuery.test.tsx
+++ b/frontend-modern/src/hooks/__tests__/createNonSuspendingQuery.test.tsx
@@ -351,6 +351,37 @@ it('lets a background read slower than the poll interval settle', async () => {
expect(screen.getByTestId('query')).toHaveTextContent('third');
});
+it('polls on a cadence that follows state, and stops when it has none', async () => {
+ vi.useFakeTimers();
+ const fetcher = vi.fn().mockResolvedValue('read');
+ const [cadence, setCadence] = createSignal<number | undefined>(30_000);
+ const Probe = () => {
+ const query = createNonSuspendingQuery({
+ source: () => 'investigation',
+ fetcher,
+ initialValue: '',
+ pollMs: cadence,
+ });
+ return <output data-testid="query">{query.value()}</output>;
+ };
+ render(() => <Probe />);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(fetcher).toHaveBeenCalledTimes(1);
+
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(fetcher).toHaveBeenCalledTimes(2);
+
+ // A run starts: poll faster.
+ setCadence(5_000);
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(fetcher).toHaveBeenCalledTimes(4);
+
+ // Nothing left to follow: stop.
+ setCadence(undefined);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(fetcher).toHaveBeenCalledTimes(4);
+});
+
it('drops a stalled read loading state even when its replacement also hangs', async () => {
vi.useFakeTimers();
const hang = () => new Promise<string>(() => undefined);
diff --git a/frontend-modern/src/hooks/createNonSuspendingQuery.ts b/frontend-modern/src/hooks/createNonSuspendingQuery.ts
index 0ef3a1a43c..1ef8338768 100644
--- a/frontend-modern/src/hooks/createNonSuspendingQuery.ts
+++ b/frontend-modern/src/hooks/createNonSuspendingQuery.ts
@@ -7,7 +7,9 @@ interface CreateNonSuspendingQueryOptions<T, K> {
fetcher: (key: K, signal: AbortSignal) => Promise<T>;
initialValue: T;
cacheKey?: (key: K) => string | null;
- pollMs?: number;
+ // A fixed interval, or an accessor when the cadence follows state (polling
+ // faster while a job runs); an accessor that returns undefined stops polling.
+ pollMs?: number | Accessor<number | undefined>;
retainPreviousValueOnSourceChange?: boolean;
}
@@ -307,26 +309,38 @@ export function createNonSuspendingQuery<T, K>(options: CreateNonSuspendingQuery
return run(key, runOptions);
};
- if (typeof options.pollMs === 'number' && options.pollMs > 0) {
- const interval = setInterval(() => {
- if (activeAbortController !== null && activeRequestIsPoll) {
- if (Date.now() - activeRequestStartedAt < STALLED_QUERY_READ_MS) return;
- // The stalled read is abandoned and settles as a failure: its
- // replacement runs in the background and may hang too, so nothing
- // else would clear a spinner or a never-loaded state.
- batch(() => {
- setLoading(false);
- setError(new Error('The request timed out.'));
- setResolvedOnce(true);
- });
- }
- const key = options.source();
- if (key === null) {
- reset();
- return;
- }
- void run(key, { background: true }, true);
- }, options.pollMs);
+ const poll = () => {
+ if (activeAbortController !== null && activeRequestIsPoll) {
+ if (Date.now() - activeRequestStartedAt < STALLED_QUERY_READ_MS) return;
+ // The stalled read is abandoned and settles as a failure: its
+ // replacement runs in the background and may hang too, so nothing
+ // else would clear a spinner or a never-loaded state.
+ batch(() => {
+ setLoading(false);
+ setError(new Error('The request timed out.'));
+ setResolvedOnce(true);
+ });
+ }
+ const key = options.source();
+ if (key === null) {
+ reset();
+ return;
+ }
+ void run(key, { background: true }, true);
+ };
+
+ const pollMs = options.pollMs;
+ if (typeof pollMs === 'function') {
+ // A new cadence restarts the interval. A read already in flight keeps its
+ // protection, which belongs to the request rather than the timer.
+ createEffect(() => {
+ const ms = pollMs();
+ if (typeof ms !== 'number' || ms <= 0) return;
+ const interval = setInterval(poll, ms);
+ onCleanup(() => clearInterval(interval));
+ });
+ } else if (typeof pollMs === 'number' && pollMs > 0) {
+ const interval = setInterval(poll, pollMs);
onCleanup(() => clearInterval(interval));
}
diff --git a/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts b/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts
index 1912076b04..9af6b53115 100644
--- a/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts
+++ b/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts
@@ -174,6 +174,74 @@ describe('aiIntelligenceStore', () => {
});
});
+ it('keeps unchanged findings, and the list, when a refresh reads them again', async () => {
+ // Rows render findings with <For>, keyed by object: a refresh that
+ // replaced unchanged findings rebuilt every row and remounted an open
+ // review on each 30s/60s poll.
+ const records = () => [
+ {
+ id: 'patrol-disk',
+ key: 'patrol-disk',
+ severity: 'warning' as const,
+ category: 'capacity' as const,
+ resource_id: 'instance:node:105',
+ resource_name: 'db-01',
+ resource_type: 'vm',
+ title: 'db-01 data disk is 91% full',
+ description: 'The PostgreSQL volume grew 4% in two days.',
+ detected_at: '2026-10-22T07:00:00Z',
+ last_seen_at: '2026-10-23T09:40:00Z',
+ auto_resolved: false,
+ times_raised: 1,
+ suppressed: false,
+ investigation_attempts: 1,
+ lifecycle: [{ at: '2026-10-22T07:00:00Z', type: 'detected', message: 'Detected' }],
+ },
+ {
+ id: 'patrol-backup',
+ key: 'patrol-backup',
+ severity: 'warning' as const,
+ category: 'backup' as const,
+ resource_id: 'instance:node:201',
+ resource_name: 'pbs-01',
+ resource_type: 'host',
+ title: 'Nightly backup on pbs-01 takes three times longer than usual',
+ description: 'The last three backup jobs each ran for about 3 hours.',
+ detected_at: '2026-10-22T07:00:00Z',
+ last_seen_at: '2026-10-23T09:40:00Z',
+ auto_resolved: false,
+ times_raised: 1,
+ suppressed: false,
+ investigation_attempts: 0,
+ },
+ ];
+ vi.mocked(getPatrolFindings).mockImplementation(async () => records());
+ await aiIntelligenceStore.loadPatrolFindings();
+ const first = aiIntelligenceStore.patrolFindings;
+
+ await aiIntelligenceStore.loadPatrolFindings();
+ expect(aiIntelligenceStore.patrolFindings).toBe(first);
+
+ // The API returns tied findings in no fixed order.
+ vi.mocked(getPatrolFindings).mockImplementation(async () => records().reverse());
+ await aiIntelligenceStore.loadPatrolFindings();
+ const reordered = aiIntelligenceStore.patrolFindings;
+ expect(reordered.map((finding) => finding.id)).toEqual(['patrol-backup', 'patrol-disk']);
+ expect(reordered[0]).toBe(first[1]);
+ expect(reordered[1]).toBe(first[0]);
+
+ vi.mocked(getPatrolFindings).mockImplementation(async () =>
+ records().map((record) =>
+ record.id === 'patrol-disk' ? { ...record, title: 'db-01 data disk is 93% full' } : record,
+ ),
+ );
+ await aiIntelligenceStore.loadPatrolFindings();
+ const changed = aiIntelligenceStore.patrolFindings;
+ expect(changed[1]).toBe(first[1]);
+ expect(changed[0]).not.toBe(first[0]);
+ expect(changed[0].title).toBe('db-01 data disk is 93% full');
+ });
+
it('keeps the unclassified and interrupted outcomes on both finding feeds', async () => {
const outcomes = { 'run-unclassified': 'unclassified', 'run-interrupted': 'interrupted' };
const finding = (id: string, outcome: string) => ({
diff --git a/frontend-modern/src/stores/aiIntelligence.ts b/frontend-modern/src/stores/aiIntelligence.ts
index fa297f210d..145afa82ab 100644
--- a/frontend-modern/src/stores/aiIntelligence.ts
+++ b/frontend-modern/src/stores/aiIntelligence.ts
@@ -337,6 +337,48 @@ function normalizePatrolFindingRecord(item: PatrolFinding, now: number): Unified
};
}
+// Findings are plain JSON from the API, so two reads of an unchanged finding
+// are equal key by key.
+function isSameFindingValue(left: unknown, right: unknown): boolean {
+ if (left === right) return true;
+ if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null) {
+ return false;
+ }
+ if (Array.isArray(left) !== Array.isArray(right)) return false;
+ const leftRecord = left as Record<string, unknown>;
+ const rightRecord = right as Record<string, unknown>;
+ const leftKeys = Object.keys(leftRecord);
+ if (leftKeys.length !== Object.keys(rightRecord).length) return false;
+ return leftKeys.every(
+ (key) =>
+ Object.prototype.hasOwnProperty.call(rightRecord, key) &&
+ isSameFindingValue(leftRecord[key], rightRecord[key]),
+ );
+}
+
+// Findings are re-read every few seconds (the open-work badges every 30s,
+// the Patrol page every 60s), and every read parses new objects. Lists render
+// findings with <For>, which keys rows by object, so each poll rebuilt every
+// row and remounted an open review. A finding that comes back unchanged keeps
+// its object, and a read that changes nothing keeps the list.
+function reuseIdenticalFindings(
+ previous: UnifiedFinding[],
+ next: UnifiedFinding[],
+): UnifiedFinding[] {
+ const previousById = new Map(previous.map((finding) => [finding.id, finding]));
+ let changed = next.length !== previous.length;
+ const merged = next.map((finding, index) => {
+ const prior = previousById.get(finding.id);
+ if (prior && isSameFindingValue(prior, finding)) {
+ if (prior !== previous[index]) changed = true;
+ return prior;
+ }
+ changed = true;
+ return finding;
+ });
+ return changed ? merged : previous;
+}
+
// ============================================
// Pending Approvals
// ============================================
@@ -493,8 +535,11 @@ export const aiIntelligenceStore = {
if (!resp) return;
const now = Date.now();
- setUnifiedFindings(
- (resp.findings || []).map((item) => normalizeUnifiedFindingRecord(item, now)),
+ setUnifiedFindings((previous) =>
+ reuseIdenticalFindings(
+ previous,
+ (resp.findings || []).map((item) => normalizeUnifiedFindingRecord(item, now)),
+ ),
);
} catch (e) {
logger.error('Failed to load unified findings:', e);
@@ -524,7 +569,12 @@ export const aiIntelligenceStore = {
: undefined,
);
const now = Date.now();
- setPatrolFindings(findings.map((item) => normalizePatrolFindingRecord(item, now)));
+ setPatrolFindings((previous) =>
+ reuseIdenticalFindings(
+ previous,
+ findings.map((item) => normalizePatrolFindingRecord(item, now)),
+ ),
+ );
} catch (e) {
logger.error('Failed to load Patrol findings:', e);
setPatrolFindingsError(e instanceof Error ? e.message : 'Failed to load Patrol findings');
diff --git a/frontend-modern/src/utils/aiFindingPresentation.ts b/frontend-modern/src/utils/aiFindingPresentation.ts
index 4c4889a0bf..156257d5a0 100644
--- a/frontend-modern/src/utils/aiFindingPresentation.ts
+++ b/frontend-modern/src/utils/aiFindingPresentation.ts
@@ -648,6 +648,27 @@ export function buildPatrolFindingDisplayGroups<
});
}
+/**
+ * Keeps each group from the previous build whose findings are the same
+ * objects in the same order. A group's fields derive only from its findings,
+ * so the kept group is current, and rows keyed by group stay mounted when a
+ * refresh changes other findings.
+ */
+export function reuseIdenticalPatrolFindingDisplayGroups<TFinding>(
+ previous: readonly PatrolFindingDisplayGroup<TFinding>[],
+ next: PatrolFindingDisplayGroup<TFinding>[],
+): PatrolFindingDisplayGroup<TFinding>[] {
+ const previousById = new Map(previous.map((group) => [group.id, group]));
+ return next.map((group) => {
+ const prior = previousById.get(group.id);
+ return prior &&
+ prior.findings.length === group.findings.length &&
+ prior.findings.every((finding, index) => finding === group.findings[index])
+ ? prior
+ : group;
+ });
+}
+
export type PatrolFindingWorkType = 'approval' | 'failed' | 'in_progress' | 'recurring' | 'new';
const isFailedFixOutcome = (outcome: string | undefined): boolean =>