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.

Separate Assistant buffered progress events

rcourtman98812fd88f72
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 024cbe8956..174508175c 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -341,7 +341,14 @@ runtime cost control, and shared AI transport surfaces.
(`ensureToolCall`, `updateToolCall`, `completeToolCall`) and renders the
typed part immediately in
`packages/opencode/src/cli/cmd/tui/feature-plugins/system/session-v2.tsx`
- (`AssistantTool`, `pendingInput`, `toolComplete`).
+ (`AssistantTool`, `pendingInput`, `toolComplete`). Pulse's Assistant chat
+ stream must also preserve that event-by-event feel when HTTP or browser
+ buffering delivers several SSE messages in one network chunk: the frontend
+ 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.
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 b5930d5167..d821f927c2 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -455,7 +455,13 @@ payload shape change when the portal presents compact client rows.
generated from `internal/ai/chat` structs so the frontend can mutate one
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.
+ browser-only event shape. The shared frontend SSE consumer in
+ `frontend-modern/src/api/streaming.ts` may insert a bounded task break
+ between already-buffered Assistant progress/tool/status events so coalesced
+ HTTP chunks preserve visible event order, but 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__/streaming.test.ts b/frontend-modern/src/api/__tests__/streaming.test.ts
new file mode 100644
index 0000000000..b8de19cdbc
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/streaming.test.ts
@@ -0,0 +1,103 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { consumeJSONEventStream } from '@/api/streaming';
+
+const makeEventStreamResponse = (body: string) =>
+ ({
+ body: {
+ getReader: () => ({
+ read: vi
+ .fn()
+ .mockResolvedValueOnce({ done: false, value: new TextEncoder().encode(body) })
+ .mockResolvedValueOnce({ done: true, value: undefined }),
+ releaseLock: vi.fn(),
+ }),
+ },
+ }) as unknown as Response;
+
+const flushMicrotasks = async () => {
+ for (let attempt = 0; attempt < 20; attempt += 1) {
+ await Promise.resolve();
+ }
+};
+
+describe('consumeJSONEventStream', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ });
+
+ it('yields to the browser between coalesced stream events when requested', async () => {
+ vi.useFakeTimers();
+
+ 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']);
+ expect(vi.getTimerCount()).toBeGreaterThan(0);
+
+ 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);
+ });
+
+ it('does not yield for coalesced events rejected by the event predicate', async () => {
+ vi.useFakeTimers();
+
+ const events: string[] = [];
+ const streamPromise = consumeJSONEventStream<{ type: string }>(
+ makeEventStreamResponse(
+ [
+ 'data: {"type":"content"}',
+ '',
+ 'data: {"type":"tool_progress"}',
+ '',
+ 'data: {"type":"done"}',
+ '',
+ '',
+ ].join('\n'),
+ ),
+ {
+ onEvent: (event) => {
+ events.push(event.type);
+ return event.type === 'done';
+ },
+ yieldBetweenEvents: (event) => event.type !== 'content',
+ },
+ );
+
+ await flushMicrotasks();
+ expect(events).toEqual(['content', 'tool_progress']);
+ expect(vi.getTimerCount()).toBeGreaterThan(0);
+
+ await vi.advanceTimersByTimeAsync(1);
+ await streamPromise;
+ expect(events).toEqual(['content', '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 f5cbb66165..6590a993e5 100644
--- a/frontend-modern/src/api/aiChat.ts
+++ b/frontend-modern/src/api/aiChat.ts
@@ -346,6 +346,7 @@ export class AIChatAPI {
onComplete: () => {
onEvent({ type: 'done' });
},
+ yieldBetweenEvents: (event) => event.type !== 'content' && event.type !== 'thinking',
});
}
}
diff --git a/frontend-modern/src/api/streaming.ts b/frontend-modern/src/api/streaming.ts
index c51f0614eb..575aea60f2 100644
--- a/frontend-modern/src/api/streaming.ts
+++ b/frontend-modern/src/api/streaming.ts
@@ -7,8 +7,26 @@ export interface JSONEventStreamOptions<T> {
onTimeout?: () => void;
onComplete?: () => void;
timeoutMs?: number;
+ yieldBetweenEvents?: boolean | ((event: T) => boolean);
}
+const yieldToBrowser = () =>
+ new Promise<void>((resolve) => {
+ setTimeout(resolve, 1);
+ });
+
+const shouldYieldAfterEvent = <T,>(
+ event: T,
+ options: JSONEventStreamOptions<T>,
+ hasBufferedEventAfterThisOne: boolean,
+) => {
+ if (!hasBufferedEventAfterThisOne || !options.yieldBetweenEvents) return false;
+ if (typeof options.yieldBetweenEvents === 'function') {
+ return options.yieldBetweenEvents(event);
+ }
+ return true;
+};
+
export async function consumeJSONEventStream<T>(
response: Response,
options: JSONEventStreamOptions<T>,
@@ -39,18 +57,25 @@ export async function consumeJSONEventStream<T>(
}
};
- const processMessages = (chunk: string): boolean => {
+ const processMessages = async (chunk: string): Promise<boolean> => {
const normalizedBuffer = chunk.replace(/\r\n/g, '\n');
const messages = normalizedBuffer.split('\n\n');
buffer = messages.pop() || '';
- for (const message of messages) {
+ const messageHasData = (message: string) =>
+ !!message
+ .split('\n')
+ .find((line) => line.startsWith('data: ') && !!line.slice(6).trim());
+
+ for (let messageIndex = 0; messageIndex < messages.length; messageIndex += 1) {
+ const message = messages[messageIndex];
if (!message.trim() || message.trim().startsWith(':')) {
continue;
}
const dataLines = message.split('\n').filter((line) => line.startsWith('data: '));
- for (const line of dataLines) {
+ for (let lineIndex = 0; lineIndex < dataLines.length; lineIndex += 1) {
+ const line = dataLines[lineIndex];
const jsonStr = line.slice(6);
if (!jsonStr.trim()) {
continue;
@@ -65,6 +90,12 @@ export async function consumeJSONEventStream<T>(
if (options.onEvent(event)) {
return true;
}
+ const hasBufferedEventAfterThisOne =
+ dataLines.slice(lineIndex + 1).some((nextLine) => !!nextLine.slice(6).trim()) ||
+ messages.slice(messageIndex + 1).some(messageHasData);
+ if (shouldYieldAfterEvent(event, options, hasBufferedEventAfterThisOne)) {
+ await yieldToBrowser();
+ }
}
}
@@ -95,7 +126,7 @@ export async function consumeJSONEventStream<T>(
lastEventTime = Date.now();
buffer += decoder.decode(value, { stream: true });
- if (processMessages(buffer)) {
+ if (await processMessages(buffer)) {
return;
}
}