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.

Add Assistant stream paint checkpoints

rcourtman94d26c61e91b
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index f2c2b68b99..c418358d3c 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -278,11 +278,15 @@ runtime cost control, and shared AI transport surfaces.
`session.next.tool.progress`, line 317; `session.next.tool.success`, line
328; `session.next.tool.failed`, line 350), so Pulse's shared browser SSE
consumer must treat opted-in non-text Assistant progress events as paint
- checkpoints. `frontend-modern/src/api/streaming.ts` must not drain queued
- workflow/tool/model events from separate stream reads without yielding to the
- browser, or the drawer will show those steps only after a batch has already
- finished. Token content and hidden reasoning may continue to opt out of those
- checkpoints through the caller predicate so answer streaming remains fast.
+ checkpoints. `frontend-modern/src/api/streaming.ts` must yield through an
+ animation-frame-backed browser paint checkpoint, with a bounded timer
+ fallback for inactive tabs, before draining the next opted-in event; a plain
+ synchronous loop or microtask-only pause is insufficient because it can still
+ render workflow/tool steps only after a batch has already finished.
+ `frontend-modern/src/api/aiChat.ts` owns the Assistant predicate: token
+ content and hidden reasoning may continue to opt out of those checkpoints so
+ answer streaming remains fast, while session/workflow/tool/approval/question
+ events remain user-visible progress checkpoints.
Completed Assistant tool rows follow the same source-anchored display policy:
the referenced OpenCode commit
`9ed17da55ab1f7360cc0e01075f763e27fa899e9` keeps ordinary tool activity terse
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 606e66715b..54b7ba4cc7 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -464,12 +464,13 @@ payload shape change when the portal presents compact client rows.
visible tool row from pending to running/waiting to completed/error, or
cancel a runtime-policy-hidden pending row, without inventing a
browser-only event shape. The shared frontend SSE consumer in
- `frontend-modern/src/api/streaming.ts` may insert a bounded task break after
+ `frontend-modern/src/api/streaming.ts` may insert an
+ animation-frame-backed paint checkpoint with a bounded timer fallback after
opted-in Assistant progress/tool/status events, including events that arrive
- through separate queued stream reads rather than the same decoded HTTP chunk.
- That pacing is an API-client consumption rule only: it must not change event
- payload shape, event order, timeout handling, reader cleanup, parse-error
- handling, or ordinary content-token throughput.
+ through separate queued stream reads rather than the same decoded HTTP
+ chunk. That pacing is an API-client consumption rule only: it must not
+ change event payload shape, event order, timeout handling, reader cleanup,
+ parse-error handling, or ordinary content-token throughput.
Cold Assistant streams must include a typed `session` event backed by
`internal/ai/chat.SessionData` as soon as the HTTP SSE writer is ready and
an immediate neutral `workflow_state` preparation event before backend
diff --git a/frontend-modern/src/api/__tests__/aiChat.test.ts b/frontend-modern/src/api/__tests__/aiChat.test.ts
index 344eda0190..8c0e175838 100644
--- a/frontend-modern/src/api/__tests__/aiChat.test.ts
+++ b/frontend-modern/src/api/__tests__/aiChat.test.ts
@@ -14,7 +14,7 @@ vi.mock('@/utils/logger', () => ({
},
}));
-import { AIChatAPI } from '@/api/aiChat';
+import { AIChatAPI, shouldYieldAfterAIChatStreamEvent } from '@/api/aiChat';
import { apiFetch, apiFetchJSON } from '@/utils/apiClient';
import { logger } from '@/utils/logger';
@@ -27,6 +27,24 @@ describe('AIChatAPI', () => {
apiFetchJSONMock.mockReset();
});
+ it('uses paint checkpoints for visible Assistant progress events but not text tokens', () => {
+ expect(shouldYieldAfterAIChatStreamEvent({ type: 'content' })).toBe(false);
+ expect(shouldYieldAfterAIChatStreamEvent({ type: 'thinking' })).toBe(false);
+
+ for (const type of [
+ 'session',
+ 'workflow_state',
+ 'tool_start',
+ 'tool_progress',
+ 'tool_cancel',
+ 'tool_end',
+ 'approval_needed',
+ 'question',
+ ] as const) {
+ expect(shouldYieldAfterAIChatStreamEvent({ type })).toBe(true);
+ }
+ });
+
it('preserves safe handoff summaries on listed chat sessions', async () => {
const session = {
id: 'session-operator-briefing',
diff --git a/frontend-modern/src/api/__tests__/streaming.test.ts b/frontend-modern/src/api/__tests__/streaming.test.ts
index db61fd8b91..0039441a9e 100644
--- a/frontend-modern/src/api/__tests__/streaming.test.ts
+++ b/frontend-modern/src/api/__tests__/streaming.test.ts
@@ -37,14 +37,51 @@ const flushMicrotasks = async () => {
}
};
+const originalRequestAnimationFrame = window.requestAnimationFrame;
+const originalCancelAnimationFrame = window.cancelAnimationFrame;
+
describe('consumeJSONEventStream', () => {
afterEach(() => {
vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ Object.defineProperty(window, 'requestAnimationFrame', {
+ configurable: true,
+ value: originalRequestAnimationFrame,
+ });
+ Object.defineProperty(window, 'cancelAnimationFrame', {
+ configurable: true,
+ value: originalCancelAnimationFrame,
+ });
vi.useRealTimers();
});
+ const installAnimationFrame = () => {
+ const requestAnimationFrame = vi.fn((callback: FrameRequestCallback) => {
+ return window.setTimeout(() => callback(performance.now()), 16);
+ });
+ const cancelAnimationFrame = vi.fn((id: number) => window.clearTimeout(id));
+ vi.stubGlobal('requestAnimationFrame', requestAnimationFrame);
+ vi.stubGlobal('cancelAnimationFrame', cancelAnimationFrame);
+ Object.defineProperty(window, 'requestAnimationFrame', {
+ configurable: true,
+ value: requestAnimationFrame,
+ });
+ Object.defineProperty(window, 'cancelAnimationFrame', {
+ configurable: true,
+ value: cancelAnimationFrame,
+ });
+ return requestAnimationFrame;
+ };
+
+ const advancePaintCheckpoint = async () => {
+ await vi.advanceTimersToNextTimerAsync();
+ await vi.advanceTimersToNextTimerAsync();
+ await flushMicrotasks();
+ };
+
it('yields to the browser between coalesced stream events when requested', async () => {
vi.useFakeTimers();
+ const requestAnimationFrame = installAnimationFrame();
const events: string[] = [];
const streamPromise = consumeJSONEventStream<{ type: string }>(
@@ -70,14 +107,15 @@ describe('consumeJSONEventStream', () => {
await flushMicrotasks();
expect(events).toEqual(['tool_start']);
+ expect(requestAnimationFrame).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBeGreaterThan(0);
- await vi.advanceTimersByTimeAsync(1);
- await flushMicrotasks();
+ await advancePaintCheckpoint();
expect(events).toEqual(['tool_start', 'tool_progress']);
+ expect(requestAnimationFrame).toHaveBeenCalledTimes(2);
expect(vi.getTimerCount()).toBeGreaterThan(0);
- await vi.advanceTimersByTimeAsync(1);
+ await advancePaintCheckpoint();
await streamPromise;
expect(events).toEqual(['tool_start', 'tool_progress', 'done']);
expect(vi.getTimerCount()).toBe(0);
@@ -85,6 +123,7 @@ describe('consumeJSONEventStream', () => {
it('does not yield for coalesced events rejected by the event predicate', async () => {
vi.useFakeTimers();
+ const requestAnimationFrame = installAnimationFrame();
const events: string[] = [];
const streamPromise = consumeJSONEventStream<{ type: string }>(
@@ -110,9 +149,10 @@ describe('consumeJSONEventStream', () => {
await flushMicrotasks();
expect(events).toEqual(['content', 'tool_progress']);
+ expect(requestAnimationFrame).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBeGreaterThan(0);
- await vi.advanceTimersByTimeAsync(1);
+ await advancePaintCheckpoint();
await streamPromise;
expect(events).toEqual(['content', 'tool_progress', 'done']);
expect(vi.getTimerCount()).toBe(0);
@@ -120,6 +160,7 @@ describe('consumeJSONEventStream', () => {
it('yields to the browser between matching events that arrive in separate queued reads', async () => {
vi.useFakeTimers();
+ const requestAnimationFrame = installAnimationFrame();
const events: string[] = [];
const streamPromise = consumeJSONEventStream<{ type: string }>(
@@ -139,16 +180,59 @@ describe('consumeJSONEventStream', () => {
await flushMicrotasks();
expect(events).toEqual(['tool_start']);
+ expect(requestAnimationFrame).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBeGreaterThan(0);
+ await advancePaintCheckpoint();
+ expect(events).toEqual(['tool_start', 'tool_progress']);
+ expect(requestAnimationFrame).toHaveBeenCalledTimes(2);
+ expect(vi.getTimerCount()).toBeGreaterThan(0);
+
+ await advancePaintCheckpoint();
+ await streamPromise;
+ expect(events).toEqual(['tool_start', 'tool_progress', 'done']);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('falls back to a short timer when animation frames are unavailable', async () => {
+ vi.useFakeTimers();
+ vi.stubGlobal('requestAnimationFrame', undefined);
+ Object.defineProperty(window, 'requestAnimationFrame', {
+ configurable: true,
+ value: undefined,
+ });
+
+ const events: string[] = [];
+ const streamPromise = consumeJSONEventStream<{ type: string }>(
+ makeEventStreamResponse(
+ [
+ 'data: {"type":"tool_start"}',
+ '',
+ 'data: {"type":"tool_progress"}',
+ '',
+ 'data: {"type":"done"}',
+ '',
+ '',
+ ].join('\n'),
+ ),
+ {
+ onEvent: (event) => {
+ events.push(event.type);
+ return event.type === 'done';
+ },
+ yieldBetweenEvents: true,
+ },
+ );
+
+ await flushMicrotasks();
+ expect(events).toEqual(['tool_start']);
+
await vi.advanceTimersByTimeAsync(1);
await flushMicrotasks();
expect(events).toEqual(['tool_start', 'tool_progress']);
- expect(vi.getTimerCount()).toBeGreaterThan(0);
await vi.advanceTimersByTimeAsync(1);
await streamPromise;
expect(events).toEqual(['tool_start', 'tool_progress', 'done']);
- expect(vi.getTimerCount()).toBe(0);
});
});
diff --git a/frontend-modern/src/api/aiChat.ts b/frontend-modern/src/api/aiChat.ts
index 2e6ff69afb..54c5677809 100644
--- a/frontend-modern/src/api/aiChat.ts
+++ b/frontend-modern/src/api/aiChat.ts
@@ -119,6 +119,11 @@ export interface ToolCall {
export type StreamEvent = AIChatStreamEvent;
+const AI_CHAT_STREAM_PAINT_CHECKPOINT_EXCLUDED_TYPES = new Set(['content', 'thinking']);
+
+export const shouldYieldAfterAIChatStreamEvent = (event: Pick<StreamEvent, 'type'>): boolean =>
+ !AI_CHAT_STREAM_PAINT_CHECKPOINT_EXCLUDED_TYPES.has(event.type);
+
export interface AIStatus {
running: boolean;
engine: string;
@@ -358,7 +363,7 @@ export class AIChatAPI {
onComplete: () => {
onEvent({ type: 'done' });
},
- yieldBetweenEvents: (event) => event.type !== 'content' && event.type !== 'thinking',
+ yieldBetweenEvents: shouldYieldAfterAIChatStreamEvent,
});
}
}
diff --git a/frontend-modern/src/api/streaming.ts b/frontend-modern/src/api/streaming.ts
index 53a3e8a545..2effd8214c 100644
--- a/frontend-modern/src/api/streaming.ts
+++ b/frontend-modern/src/api/streaming.ts
@@ -10,9 +10,35 @@ export interface JSONEventStreamOptions<T> {
yieldBetweenEvents?: boolean | ((event: T) => boolean);
}
-const yieldToBrowser = () =>
+const PAINT_CHECKPOINT_FALLBACK_MS = 50;
+
+const yieldToBrowserPaint = () =>
new Promise<void>((resolve) => {
- setTimeout(resolve, 1);
+ const raf =
+ typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function'
+ ? window.requestAnimationFrame.bind(window)
+ : undefined;
+
+ if (!raf) {
+ setTimeout(resolve, 1);
+ return;
+ }
+
+ let settled = false;
+ let fallbackId: ReturnType<typeof setTimeout> | undefined;
+ const finish = () => {
+ if (settled) return;
+ settled = true;
+ if (fallbackId !== undefined) {
+ clearTimeout(fallbackId);
+ }
+ resolve();
+ };
+
+ fallbackId = setTimeout(finish, PAINT_CHECKPOINT_FALLBACK_MS);
+ raf(() => {
+ setTimeout(finish, 0);
+ });
});
const shouldYieldAfterEvent = <T,>(
@@ -85,7 +111,7 @@ export async function consumeJSONEventStream<T>(
return true;
}
if (shouldYieldAfterEvent(event, options)) {
- await yieldToBrowser();
+ await yieldToBrowserPaint();
}
}
}