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.

Pace Assistant chat stream paints

rcourtman5e9828c8ed96
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 0764f555bb..8dcf205fe3 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -304,12 +304,15 @@ runtime cost control, and shared AI transport surfaces.
(`apply(event)`, line 120; `session.next.tool.input.started`, line 276;
`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 yield through an
+ consumer must treat opted-in Assistant progress events as paint 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.
+ render workflow/tool steps only after a batch has already finished. Chat text
+ and reasoning deltas must paint immediately for the first delta in a run and
+ then periodically so coalesced provider chunks do not arrive as one burst,
+ while avoiding a frame wait for every token.
Pulse's reducer must also keep the same keyed-part behavior: repeated
`tool_start` or `tool_progress` events for one backend tool ID, or the same
normalized tool name when an older server omits IDs, upsert one pending tool
@@ -505,8 +508,10 @@ runtime cost control, and shared AI transport surfaces.
stream consumer must let the browser paint between buffered Assistant
progress/tool/status events for chat streams instead of synchronously
draining a coalesced `tool_start`/`tool_progress`/`tool_end` batch in one
- JavaScript task. Ordinary content-token streaming must not be frame-throttled
- by that progress-batch safeguard.
+ JavaScript task. Ordinary content-token streaming must also get an immediate
+ first-delta paint checkpoint and periodic checkpoints for long coalesced
+ chunks, but must not be frame-throttled on every token by that progress-batch
+ safeguard.
The referenced OpenCode source at fetched `origin/dev` commit
`09d9cf01f93798939c1284fbe974b6e1f4d2759d` renders tool-specific inline
labels such as `Read <path>`, `Grep "<pattern>"`, `WebFetch <url>`, and bash
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 54b7ba4cc7..35315ec09d 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -468,9 +468,17 @@ payload shape change when the portal presents compact client rows.
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.
+ chunk. OpenCode parity is source-backed by fetched `origin/dev` commit
+ `9ed17da55ab1f7360cc0e01075f763e27fa899e9`,
+ `packages/opencode/src/cli/cmd/tui/context/sync-v2.tsx`, where
+ `apply(event)` mutates typed message parts event-by-event (`apply(event)`,
+ line 120; `session.next.tool.progress`, line 317). Pulse chat text and
+ reasoning deltas must therefore get an immediate first-delta paint checkpoint
+ and bounded periodic checkpoints for long coalesced `content` / `thinking`
+ runs, without yielding after every token. 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 8c0e175838..54f928898e 100644
--- a/frontend-modern/src/api/__tests__/aiChat.test.ts
+++ b/frontend-modern/src/api/__tests__/aiChat.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('@/utils/apiClient', () => ({
apiFetchJSON: vi.fn(),
@@ -14,22 +14,72 @@ vi.mock('@/utils/logger', () => ({
},
}));
-import { AIChatAPI, shouldYieldAfterAIChatStreamEvent } from '@/api/aiChat';
+import { AIChatAPI, createAIChatStreamPaintCheckpointPredicate } from '@/api/aiChat';
import { apiFetch, apiFetchJSON } from '@/utils/apiClient';
import { logger } from '@/utils/logger';
+const flushMicrotasks = async () => {
+ for (let attempt = 0; attempt < 20; attempt += 1) {
+ await Promise.resolve();
+ }
+};
+
describe('AIChatAPI', () => {
const apiFetchMock = vi.mocked(apiFetch);
const apiFetchJSONMock = vi.mocked(apiFetchJSON);
+ const originalRequestAnimationFrame = window.requestAnimationFrame;
+ const originalCancelAnimationFrame = window.cancelAnimationFrame;
beforeEach(() => {
apiFetchMock.mockReset();
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);
+ afterEach(() => {
+ 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('uses immediate and periodic paint checkpoints for text while yielding every progress event', () => {
+ const shouldYield = createAIChatStreamPaintCheckpointPredicate();
+
+ expect(shouldYield({ type: 'content' })).toBe(true);
+ for (let index = 0; index < 14; index += 1) {
+ expect(shouldYield({ type: 'content' })).toBe(false);
+ }
+ expect(shouldYield({ type: 'content' })).toBe(true);
for (const type of [
'session',
@@ -41,8 +91,59 @@ describe('AIChatAPI', () => {
'approval_needed',
'question',
] as const) {
- expect(shouldYieldAfterAIChatStreamEvent({ type })).toBe(true);
+ expect(shouldYield({ type })).toBe(true);
}
+
+ expect(shouldYield({ type: 'thinking' })).toBe(true);
+ expect(shouldYield({ type: 'thinking' })).toBe(false);
+ });
+
+ it('lets the browser paint the first visible text delta before draining a coalesced chat chunk', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ const requestAnimationFrame = installAnimationFrame();
+ const encoder = new TextEncoder();
+ const read = vi
+ .fn()
+ .mockResolvedValueOnce({
+ done: false,
+ value: encoder.encode(
+ [
+ 'data: {"type":"content","data":{"text":"First"}}',
+ '',
+ 'data: {"type":"content","data":{"text":" second"}}',
+ '',
+ 'data: {"type":"done"}',
+ '',
+ '',
+ ].join('\n'),
+ ),
+ })
+ .mockResolvedValueOnce({ done: true, value: undefined });
+ const releaseLock = vi.fn();
+ const onEvent = vi.fn();
+
+ apiFetchMock.mockResolvedValueOnce({
+ ok: true,
+ body: {
+ getReader: () => ({ read, releaseLock }),
+ },
+ } as unknown as Response);
+
+ const streamPromise = AIChatAPI.chat('hello', undefined, undefined, onEvent);
+
+ await flushMicrotasks();
+ expect(onEvent.mock.calls.map(([event]) => event.type)).toEqual(['content']);
+ expect(requestAnimationFrame).toHaveBeenCalledTimes(1);
+
+ await advancePaintCheckpoint();
+ await streamPromise;
+
+ expect(onEvent.mock.calls.map(([event]) => event.type)).toEqual([
+ 'content',
+ 'content',
+ 'done',
+ ]);
+ expect(releaseLock).toHaveBeenCalledTimes(1);
});
it('preserves safe handoff summaries on listed chat sessions', async () => {
diff --git a/frontend-modern/src/api/aiChat.ts b/frontend-modern/src/api/aiChat.ts
index 54c5677809..42c4e9cc69 100644
--- a/frontend-modern/src/api/aiChat.ts
+++ b/frontend-modern/src/api/aiChat.ts
@@ -119,10 +119,35 @@ export interface ToolCall {
export type StreamEvent = AIChatStreamEvent;
-const AI_CHAT_STREAM_PAINT_CHECKPOINT_EXCLUDED_TYPES = new Set(['content', 'thinking']);
+const AI_CHAT_STREAM_TEXT_PAINT_CHECKPOINT_INTERVAL = 16;
+const AI_CHAT_STREAM_TEXT_EVENT_TYPES = new Set(['content', 'thinking']);
-export const shouldYieldAfterAIChatStreamEvent = (event: Pick<StreamEvent, 'type'>): boolean =>
- !AI_CHAT_STREAM_PAINT_CHECKPOINT_EXCLUDED_TYPES.has(event.type);
+const isAIChatStreamTextEvent = (event: Pick<StreamEvent, 'type'>): boolean =>
+ AI_CHAT_STREAM_TEXT_EVENT_TYPES.has(event.type);
+
+export const createAIChatStreamPaintCheckpointPredicate = () => {
+ let textEventsSinceCheckpoint = 0;
+
+ return (event: Pick<StreamEvent, 'type'>): boolean => {
+ if (!isAIChatStreamTextEvent(event)) {
+ textEventsSinceCheckpoint = 0;
+ return true;
+ }
+
+ textEventsSinceCheckpoint += 1;
+ if (
+ textEventsSinceCheckpoint === 1 ||
+ textEventsSinceCheckpoint >= AI_CHAT_STREAM_TEXT_PAINT_CHECKPOINT_INTERVAL
+ ) {
+ if (textEventsSinceCheckpoint >= AI_CHAT_STREAM_TEXT_PAINT_CHECKPOINT_INTERVAL) {
+ textEventsSinceCheckpoint = 0;
+ }
+ return true;
+ }
+
+ return false;
+ };
+};
export interface AIStatus {
running: boolean;
@@ -363,7 +388,7 @@ export class AIChatAPI {
onComplete: () => {
onEvent({ type: 'done' });
},
- yieldBetweenEvents: shouldYieldAfterAIChatStreamEvent,
+ yieldBetweenEvents: createAIChatStreamPaintCheckpointPredicate(),
});
}
}