Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(dashboards): SSE query progress streaming frontend (#12445)

Valery Meleshkinf674b389341d
diff --git a/web/src/__tests__/server/execute-query-stream.servertest.ts b/web/src/__tests__/server/execute-query-stream.servertest.ts
index 24b699389f..0f4a8a047d 100644
--- a/web/src/__tests__/server/execute-query-stream.servertest.ts
+++ b/web/src/__tests__/server/execute-query-stream.servertest.ts
@@ -94,12 +94,14 @@ describe("execute-query-stream handler", () => {
function makeSession(overrides?: {
admin?: boolean;
projects?: Array<{ id: string }>;
+ v4BetaEnabled?: boolean;
}) {
return {
user: {
id: "user-1",
admin: overrides?.admin ?? false,
+ v4BetaEnabled: overrides?.v4BetaEnabled ?? true,
organizations: [
{
id: orgId,
@@ -127,6 +129,20 @@ describe("execute-query-stream handler", () => {
};
}
+ it("should return 400 when v4 beta is disabled", async () => {
+ mockGetServerAuthSession.mockResolvedValue(
+ makeSession({ v4BetaEnabled: false }),
+ );
+ const { req, res } = createPostMocks(makeBody());
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(400);
+ expect(JSON.parse(res._getData())).toMatchObject({
+ message: "Streaming is only supported for v4-enabled dashboard queries",
+ });
+ });
+
// --- Auth tests (mocks are appropriate here) ---
it("should return 405 for non-POST requests", async () => {
diff --git a/web/src/__tests__/sse-dashboard-query.clienttest.ts b/web/src/__tests__/sse-dashboard-query.clienttest.ts
new file mode 100644
index 0000000000..dbdeb6e2e6
--- /dev/null
+++ b/web/src/__tests__/sse-dashboard-query.clienttest.ts
@@ -0,0 +1,327 @@
+/**
+ * Tests for the SSE dashboard query hook's parsing and progress logic.
+ */
+import { renderHook, waitFor } from "@testing-library/react";
+import { TextDecoder, TextEncoder } from "util";
+import {
+ parseSSEBuffer,
+ computeMonotonicPercent,
+ useSSEDashboardQuery,
+} from "@/src/hooks/useSSEDashboardQuery";
+
+describe("parseSSEBuffer", () => {
+ it("should parse a single complete progress event", () => {
+ const buffer =
+ 'event: progress\ndata: {"read_rows":"100","total_rows_to_read":"1000"}\n\n';
+ const { events, remaining } = parseSSEBuffer(buffer);
+
+ expect(events).toHaveLength(1);
+ expect(events[0].type).toBe("progress");
+ expect(remaining).toBe("");
+
+ const data = JSON.parse(events[0].data);
+ expect(data.read_rows).toBe("100");
+ expect(data.total_rows_to_read).toBe("1000");
+ });
+
+ it("should parse multiple events in one buffer", () => {
+ const buffer =
+ 'event: progress\ndata: {"read_rows":"50"}\n\n' +
+ 'event: row\ndata: {"count":42}\n\n' +
+ "event: done\ndata: {}\n\n";
+
+ const { events, remaining } = parseSSEBuffer(buffer);
+
+ expect(events).toHaveLength(3);
+ expect(events[0].type).toBe("progress");
+ expect(events[1].type).toBe("row");
+ expect(events[2].type).toBe("done");
+ expect(remaining).toBe("");
+ });
+
+ it("should handle incomplete buffer (no trailing double newline)", () => {
+ const buffer = 'event: progress\ndata: {"read_rows":"50"}';
+ const { events, remaining } = parseSSEBuffer(buffer);
+
+ expect(events).toHaveLength(0);
+ expect(remaining).toBe('event: progress\ndata: {"read_rows":"50"}');
+ });
+
+ it("should handle buffer with complete event + incomplete trailing event", () => {
+ const buffer =
+ 'event: progress\ndata: {"read_rows":"50"}\n\n' +
+ 'event: progress\ndata: {"read_ro';
+
+ const { events, remaining } = parseSSEBuffer(buffer);
+
+ expect(events).toHaveLength(1);
+ expect(events[0].type).toBe("progress");
+ expect(remaining).toBe('event: progress\ndata: {"read_ro');
+ });
+
+ it("should parse error events", () => {
+ const buffer = 'event: error\ndata: {"message":"Query timed out"}\n\n';
+ const { events } = parseSSEBuffer(buffer);
+
+ expect(events).toHaveLength(1);
+ expect(events[0].type).toBe("error");
+
+ const data = JSON.parse(events[0].data);
+ expect(data.message).toBe("Query timed out");
+ });
+
+ it("should handle empty blocks between events", () => {
+ const buffer =
+ 'event: progress\ndata: {"x":1}\n\n' +
+ "\n\n" +
+ "event: result\ndata: []\n\n";
+
+ const { events } = parseSSEBuffer(buffer);
+
+ expect(events).toHaveLength(2);
+ expect(events[0].type).toBe("progress");
+ expect(events[1].type).toBe("result");
+ });
+
+ it("should default event type to 'message' when no event line", () => {
+ const buffer = 'data: {"foo":"bar"}\n\n';
+ const { events } = parseSSEBuffer(buffer);
+
+ expect(events).toHaveLength(1);
+ expect(events[0].type).toBe("message");
+ });
+
+ it("should skip blocks with no data line", () => {
+ const buffer = "event: progress\n\n";
+ const { events } = parseSSEBuffer(buffer);
+
+ expect(events).toHaveLength(0);
+ });
+});
+
+describe("computeMonotonicPercent", () => {
+ it("should compute percent from read_rows / total_rows_to_read", () => {
+ const percent = computeMonotonicPercent(3_000_000, 10_000_000, 0);
+ expect(percent).toBeCloseTo(0.3);
+ });
+
+ it("should handle zero total_rows_to_read", () => {
+ const percent = computeMonotonicPercent(0, 0, 0);
+ expect(percent).toBe(0);
+ });
+
+ it("should never decrease (monotonic progress)", () => {
+ const updates = [
+ { read: 100, total: 1000 }, // 0.1
+ { read: 300, total: 1000 }, // 0.3
+ { read: 250, total: 1000 }, // 0.25 (regression)
+ { read: 500, total: 1000 }, // 0.5
+ { read: 450, total: 1000 }, // 0.45 (regression)
+ { read: 800, total: 1000 }, // 0.8
+ { read: 1000, total: 1000 }, // 1.0
+ ];
+
+ let prevMax = 0;
+ const smoothed: number[] = [];
+
+ for (const { read, total } of updates) {
+ prevMax = computeMonotonicPercent(read, total, prevMax);
+ smoothed.push(prevMax);
+ }
+
+ for (let i = 1; i < smoothed.length; i++) {
+ expect(smoothed[i]).toBeGreaterThanOrEqual(smoothed[i - 1]);
+ }
+
+ expect(smoothed).toEqual([0.1, 0.3, 0.3, 0.5, 0.5, 0.8, 1.0]);
+ });
+
+ it("should preserve previous max when current percent is lower", () => {
+ expect(computeMonotonicPercent(10, 100, 0.5)).toBe(0.5);
+ });
+});
+
+describe("useSSEDashboardQuery", () => {
+ const originalFetch = global.fetch;
+ const originalTextDecoder = global.TextDecoder;
+
+ const createStreamReader = (chunks: Uint8Array[]) => {
+ let index = 0;
+
+ return {
+ read: jest.fn().mockImplementation(async () => {
+ if (index < chunks.length) {
+ return {
+ done: false,
+ value: chunks[index++],
+ };
+ }
+
+ return {
+ done: true,
+ value: undefined,
+ };
+ }),
+ };
+ };
+
+ const createInput = (fromTimestamp: string, toTimestamp: string) => ({
+ projectId: "project-1",
+ version: "v1" as const,
+ query: {
+ view: "traces" as const,
+ dimensions: [],
+ metrics: [{ measure: "count", aggregation: "count" as const }],
+ filters: [],
+ timeDimension: null,
+ fromTimestamp,
+ toTimestamp,
+ orderBy: null,
+ chartConfig: { type: "BAR_TIME_SERIES" },
+ },
+ });
+
+ afterEach(() => {
+ global.fetch = originalFetch;
+ global.TextDecoder = originalTextDecoder;
+ jest.restoreAllMocks();
+ });
+
+ it("preserves successful state when disabled after the stream completes", async () => {
+ const encoder = new TextEncoder();
+
+ global.fetch = jest.fn().mockImplementation(async () => ({
+ ok: true,
+ body: {
+ getReader: () =>
+ createStreamReader([
+ encoder.encode(
+ 'event: row\ndata: {"count_count":42}\n\n' +
+ "event: done\ndata: {}\n\n",
+ ),
+ ]),
+ },
+ })) as typeof fetch;
+ global.TextDecoder = TextDecoder as typeof global.TextDecoder;
+
+ const { result, rerender } = renderHook(
+ ({ enabled }) =>
+ useSSEDashboardQuery(
+ createInput("2026-03-22T00:00:00.000Z", "2026-03-23T00:00:00.000Z"),
+ {
+ enabled,
+ queryId: "widget-1",
+ },
+ ),
+ {
+ initialProps: { enabled: true },
+ },
+ );
+
+ await waitFor(() => {
+ expect(result.current.isSuccess).toBe(true);
+ });
+
+ rerender({ enabled: false });
+
+ await waitFor(() => {
+ expect(result.current.isSuccess).toBe(true);
+ });
+
+ expect(result.current.isPending).toBe(false);
+ expect(result.current.data).toEqual([{ count_count: 42 }]);
+ });
+
+ it("treats a changed input as pending immediately and hides stale results", async () => {
+ const encoder = new TextEncoder();
+ let releaseSecondResponse: (() => void) | null = null;
+
+ global.fetch = jest
+ .fn()
+ .mockImplementationOnce(async () => ({
+ ok: true,
+ body: {
+ getReader: () =>
+ createStreamReader([
+ encoder.encode(
+ 'event: row\ndata: {"count_count":42}\n\n' +
+ "event: done\ndata: {}\n\n",
+ ),
+ ]),
+ },
+ }))
+ .mockImplementationOnce(async () => ({
+ ok: true,
+ body: {
+ getReader: () => {
+ let released = false;
+ const waitForRelease = new Promise<void>((resolve) => {
+ releaseSecondResponse = () => {
+ released = true;
+ resolve();
+ };
+ });
+
+ return {
+ read: jest.fn().mockImplementation(async () => {
+ if (!released) {
+ await waitForRelease;
+ }
+
+ return {
+ done: true,
+ value: undefined,
+ };
+ }),
+ };
+ },
+ },
+ })) as typeof fetch;
+ global.TextDecoder = TextDecoder as typeof global.TextDecoder;
+
+ const firstInput = createInput(
+ "2026-03-22T00:00:00.000Z",
+ "2026-03-23T00:00:00.000Z",
+ );
+ const secondInput = createInput(
+ "2026-03-16T00:00:00.000Z",
+ "2026-03-23T00:00:00.000Z",
+ );
+
+ const { result, rerender } = renderHook(
+ ({ input }) =>
+ useSSEDashboardQuery(input, {
+ enabled: true,
+ queryId: "widget-1",
+ }),
+ {
+ initialProps: { input: firstInput },
+ },
+ );
+
+ await waitFor(() => {
+ expect(result.current.isSuccess).toBe(true);
+ });
+
+ rerender({ input: secondInput });
+
+ expect(result.current.isPending).toBe(true);
+ expect(result.current.isLoading).toBe(true);
+ expect(result.current.isSuccess).toBe(false);
+ expect(result.current.fetchStatus).toBe("fetching");
+ expect(result.current.data).toBeUndefined();
+ expect(result.current.progress).toBeNull();
+ expect(result.current.error).toBeNull();
+
+ await waitFor(() => {
+ expect(global.fetch).toHaveBeenCalledTimes(2);
+ expect(releaseSecondResponse).not.toBeNull();
+ });
+
+ releaseSecondResponse?.();
+
+ await waitFor(() => {
+ expect(result.current.isError).toBe(true);
+ });
+ });
+});
diff --git a/web/src/__tests__/widget-default-view.clienttest.ts b/web/src/__tests__/widget-default-view.clienttest.ts
index 73f1b8e921..ceac9b8420 100644
--- a/web/src/__tests__/widget-default-view.clienttest.ts
+++ b/web/src/__tests__/widget-default-view.clienttest.ts
@@ -1,4 +1,7 @@
-import { getDefaultView } from "@/src/features/widgets/utils";
+import {
+ getDefaultView,
+ shouldUseWidgetSSE,
+} from "@/src/features/widgets/utils";
describe("getDefaultView", () => {
it("should return 'observations' when v4 beta is enabled", () => {
@@ -9,3 +12,32 @@ describe("getDefaultView", () => {
expect(getDefaultView(false)).toBe("traces");
});
});
+
+describe("shouldUseWidgetSSE", () => {
+ it("should enable SSE on the v4 beta v2 path", () => {
+ expect(
+ shouldUseWidgetSSE({
+ isV4BetaEnabled: true,
+ version: "v2",
+ }),
+ ).toBe(true);
+ });
+
+ it("should disable SSE when v4 beta is off", () => {
+ expect(
+ shouldUseWidgetSSE({
+ isV4BetaEnabled: false,
+ version: "v2",
+ }),
+ ).toBe(false);
+ });
+
+ it("should disable SSE for non-v4 query versions", () => {
+ expect(
+ shouldUseWidgetSSE({
+ isV4BetaEnabled: true,
+ version: "v1",
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/web/src/features/widgets/chart-library/QueryProgressBar.tsx b/web/src/features/widgets/chart-library/QueryProgressBar.tsx
new file mode 100644
index 0000000000..34a8c3df5b
--- /dev/null
+++ b/web/src/features/widgets/chart-library/QueryProgressBar.tsx
@@ -0,0 +1,33 @@
+import { type QueryProgress } from "@/src/hooks/useSSEDashboardQuery";
+import { cn } from "@/src/utils/tailwind";
+
+function formatRows(n: number): string {
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
+ if (n >= 1_000) return `${(n / 1_000).toFixed(0)}K`;
+ return String(n);
+}
+
+export function QueryProgressBar({
+ progress,
+ className,
+}: {
+ progress: QueryProgress;
+ className?: string;
+}) {
+ const percent = Math.min(progress.percent * 100, 100);
+
+ return (
+ <div className={cn("flex flex-col items-center gap-1.5", className)}>
+ <div className="bg-muted h-1.5 w-32 overflow-hidden rounded-full">
+ <div
+ className="bg-primary/60 h-full rounded-full transition-all duration-500 ease-out"
+ style={{ width: `${percent}%` }}
+ />
+ </div>
+ <p className="text-muted-foreground text-xs">
+ Reading {formatRows(progress.read_rows)} / ~
+ {formatRows(progress.total_rows_to_read)} rows
+ </p>
+ </div>
+ );
+}
diff --git a/web/src/features/widgets/chart-library/chartLoadingStateUtils.ts b/web/src/features/widgets/chart-library/chartLoadingStateUtils.ts
index 53dc4042b7..a825026657 100644
--- a/web/src/features/widgets/chart-library/chartLoadingStateUtils.ts
+++ b/web/src/features/widgets/chart-library/chartLoadingStateUtils.ts
@@ -3,6 +3,7 @@ import { RESOURCE_LIMIT_ERROR_MESSAGE } from "@langfuse/shared";
type ChartQueryState = {
isPending: boolean;
isError: boolean;
+ errorMessage?: string | null;
};
type ChartLoadingProps = {
@@ -15,11 +16,14 @@ type ChartLoadingProps = {
export function getChartLoadingStateProps({
isPending,
isError,
+ errorMessage,
}: ChartQueryState): ChartLoadingProps {
return {
isLoading: isPending || isError,
showSpinner: isPending,
showHintImmediately: isError,
- hintText: isError ? RESOURCE_LIMIT_ERROR_MESSAGE : undefined,
+ hintText: isError
+ ? (errorMessage ?? RESOURCE_LIMIT_ERROR_MESSAGE)
+ : undefined,
};
}
diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsx
index 642ffba4ae..dfc25cc0f8 100644
--- a/web/src/features/widgets/components/DashboardWidget.tsx
+++ b/web/src/features/widgets/components/DashboardWidget.tsx
@@ -20,12 +20,16 @@ import { useRouter } from "next/router";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { showErrorToast } from "@/src/features/notifications/showErrorToast";
import { DownloadButton } from "@/src/features/widgets/chart-library/DownloadButton";
-import { formatMetricName } from "@/src/features/widgets/utils";
+import {
+ formatMetricName,
+ shouldUseWidgetSSE,
+} from "@/src/features/widgets/utils";
import { ChartLoadingState } from "@/src/features/widgets/chart-library/ChartLoadingState";
import { getChartLoadingStateProps } from "@/src/features/widgets/chart-library/chartLoadingStateUtils";
import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
import { type ViewVersion } from "@/src/features/query";
import { useScheduledDashboardExecuteQuery } from "@/src/hooks/useDashboardQueryScheduler";
+import { QueryProgressBar } from "@/src/features/widgets/chart-library/QueryProgressBar";
import {
validateQuery,
toQueryChartConfig,
@@ -187,6 +191,10 @@ export function DashboardWidget({
meta: {
silentHttpCodes: [422],
},
+ useSSE: shouldUseWidgetSSE({
+ isV4BetaEnabled: isBetaEnabled,
+ version: metricsVersion,
+ }),
enabled:
!widget.isPending && Boolean(widget.data) && queryValidation.valid,
},
@@ -195,6 +203,7 @@ export function DashboardWidget({
const chartLoadingState = getChartLoadingStateProps({
isPending: queryResult.isPending,
isError: queryResult.isError,
+ errorMessage: queryResult.error,
});
const transformedData = useMemo(() => {
@@ -410,6 +419,12 @@ export function DashboardWidget({
className="bg-background/80 absolute inset-0 z-20 backdrop-blur-xs"
hintClassName="max-w-sm px-4"
/>
+ {queryResult.progress && queryResult.isPending ? (
+ <QueryProgressBar
+ progress={queryResult.progress}
+ className="absolute inset-x-0 bottom-4 z-30"
+ />
+ ) : null}
</>
)}
</div>
diff --git a/web/src/features/widgets/utils.ts b/web/src/features/widgets/utils.ts
index 8b893df56b..99fccc76b7 100644
--- a/web/src/features/widgets/utils.ts
+++ b/web/src/features/widgets/utils.ts
@@ -144,3 +144,16 @@ export function getDefaultView(
): "traces" | "observations" {
return isBetaEnabled ? "observations" : "traces";
}
+
+/**
+ * SSE progress is only enabled on the v4 beta dashboard query path.
+ */
+export function shouldUseWidgetSSE({
+ isV4BetaEnabled,
+ version,
+}: {
+ isV4BetaEnabled: boolean;
+ version: "v1" | "v2";
+}): boolean {
+ return isV4BetaEnabled && version === "v2";
+}
diff --git a/web/src/hooks/useDashboardQueryScheduler.tsx b/web/src/hooks/useDashboardQueryScheduler.tsx
index d9641e93d1..4335271ca7 100644
--- a/web/src/hooks/useDashboardQueryScheduler.tsx
+++ b/web/src/hooks/useDashboardQueryScheduler.tsx
@@ -14,6 +14,10 @@ import {
useRef,
useState,
} from "react";
+import {
+ useSSEDashboardQuery,
+ type QueryProgress,
+} from "@/src/hooks/useSSEDashboardQuery";
type SchedulerItemStatus = "queued" | "running" | "done";
@@ -265,6 +269,7 @@ type ScheduledDashboardExecuteQueryOptions = Omit<
priority?: number;
queryId: string;
runKey?: string;
+ useSSE?: boolean;
};
const getDefaultRunKey = (input: DashboardExecuteQueryInput) =>
@@ -278,9 +283,19 @@ export const useScheduledDashboardExecuteQuery = (
priority = 1000,
queryId,
runKey,
+ useSSE = false,
...queryOptions
}: ScheduledDashboardExecuteQueryOptions,
-) => {
+): {
+ data: Record<string, unknown>[] | undefined;
+ isLoading: boolean;
+ isError: boolean;
+ isSuccess: boolean;
+ fetchStatus: string;
+ isPending: boolean;
+ progress: QueryProgress | null;
+ error: string | null;
+} => {
const context = useDashboardQuerySchedulerContext();
const scheduler = context?.scheduler;
const register = scheduler?.register;
@@ -305,19 +320,28 @@ export const useScheduledDashboardExecuteQuery = (
const canFetch = scheduler ? scheduler.canFetch(queryId) : true;
- const queryResult = api.dashboard.executeQuery.useQuery<
+ // tRPC path (default)
+ const trpcResult = api.dashboard.executeQuery.useQuery<
Record<string, unknown>[]
>(input, {
...queryOptions,
- enabled: enabled && canFetch,
+ enabled: enabled && canFetch && !useSSE,
meta,
});
+ // SSE path (opt-in)
+ const sseResult = useSSEDashboardQuery(input, {
+ enabled: enabled && canFetch && useSSE,
+ queryId,
+ });
+
+ const activeResult = useSSE ? sseResult : trpcResult;
+
useEffect(() => {
if (!markDone) return;
if (!enabled || !canFetch) return;
- if (queryResult.fetchStatus !== "idle") return;
- if (queryResult.isPending) return;
+ if (activeResult.fetchStatus !== "idle") return;
+ if (activeResult.isPending) return;
markDone(queryId);
}, [
@@ -325,9 +349,18 @@ export const useScheduledDashboardExecuteQuery = (
enabled,
markDone,
queryId,
- queryResult.fetchStatus,
- queryResult.isPending,
+ activeResult.fetchStatus,
+ activeResult.isPending,
]);
- return queryResult;
+ return {
+ data: activeResult.data,
+ isLoading: activeResult.isLoading,
+ isError: activeResult.isError,
+ isSuccess: activeResult.isSuccess,
+ fetchStatus: activeResult.fetchStatus,
+ isPending: activeResult.isPending,
+ progress: useSSE ? sseResult.progress : null,
+ error: useSSE ? sseResult.error : null,
+ };
};
diff --git a/web/src/hooks/useSSEDashboardQuery.ts b/web/src/hooks/useSSEDashboardQuery.ts
new file mode 100644
index 0000000000..2b826eea78
--- /dev/null
+++ b/web/src/hooks/useSSEDashboardQuery.ts
@@ -0,0 +1,263 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { type RouterInputs } from "@/src/utils/api";
+import { env } from "@/src/env.mjs";
+
+type DashboardExecuteQueryInput = RouterInputs["dashboard"]["executeQuery"];
+
+export type QueryProgress = {
+ read_rows: number;
+ total_rows_to_read: number;
+ elapsed_ns: number;
+ read_bytes: number;
+ percent: number;
+};
+
+type SSEQueryStatus = "idle" | "loading" | "success" | "error";
+
+type SSEQueryResult = {
+ data: Record<string, unknown>[] | undefined;
+ progress: QueryProgress | null;
+ status: SSEQueryStatus;
+ isLoading: boolean;
+ isSuccess: boolean;
+ isError: boolean;
+ error: string | null;
+ fetchStatus: "fetching" | "idle";
+ isPending: boolean;
+};
+
+export type SSEEvent = {
+ type: string;
+ data: string;
+};
+
+export function parseSSEBuffer(buffer: string): {
+ events: SSEEvent[];
+ remaining: string;
+} {
+ const events: SSEEvent[] = [];
+ const blocks = buffer.split("\n\n");
+
+ // Last block may be incomplete
+ const remaining = blocks.pop() ?? "";
+
+ for (const block of blocks) {
+ if (!block.trim()) continue;
+
+ let type = "message";
+ let data = "";
+
+ for (const line of block.split("\n")) {
+ if (line.startsWith("event: ")) {
+ type = line.slice(7);
+ } else if (line.startsWith("data: ")) {
+ data = line.slice(6);
+ }
+ }
+
+ if (data) {
+ events.push({ type, data });
+ }
+ }
+
+ return { events, remaining };
+}
+
+export function computeMonotonicPercent(
+ readRows: number,
+ totalRows: number,
+ prevMax: number,
+): number {
+ const rawPercent = totalRows > 0 ? readRows / totalRows : 0;
+ return Math.max(prevMax, rawPercent);
+}
+
+export function useSSEDashboardQuery(
+ input: DashboardExecuteQueryInput,
+ options: {
+ enabled?: boolean;
+ queryId: string;
+ },
+): SSEQueryResult {
+ const { enabled = true } = options;
+ const [data, setData] = useState<Record<string, unknown>[] | undefined>(
+ undefined,
+ );
+ const [progress, setProgress] = useState<QueryProgress | null>(null);
+ const [status, setStatus] = useState<SSEQueryStatus>("idle");
+ const [error, setError] = useState<string | null>(null);
+ const [stateInputKey, setStateInputKey] = useState<string | null>(null);
+ const maxPercentRef = useRef(0);
+ const basePath = env.NEXT_PUBLIC_BASE_PATH ?? "";
+
+ // Stable reference for the input to avoid re-triggering on every render
+ const inputRef = useRef(input);
+ inputRef.current = input;
+
+ const runQuery = useCallback(
+ async (runInputKey: string, signal: AbortSignal) => {
+ setStateInputKey(runInputKey);
+ setStatus("loading");
+ setProgress(null);
+ setError(null);
+ setData(undefined);
+ maxPercentRef.current = 0;
+
+ try {
+ const resp = await fetch(
+ `${basePath}/api/dashboard/execute-query-stream`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(inputRef.current),
+ signal,
+ },
+ );
+
+ if (!resp.ok) {
+ const body = await resp.text();
+ let message = `HTTP ${resp.status}`;
+ try {
+ const parsed = JSON.parse(body);
+ if (parsed.message) message = parsed.message;
+ } catch {
+ if (body) message = body;
+ }
+ throw new Error(message);
+ }
+
+ if (!resp.body) {
+ throw new Error("No response body");
+ }
+
+ const reader = resp.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ const rows: Record<string, unknown>[] = [];
+ let terminated = false;
+
+ const handleEvent = (event: SSEEvent) => {
+ if (terminated) return;
+ if (event.type === "progress") {
+ try {
+ const p = JSON.parse(event.data);
+ const readRows = Number(p.read_rows);
+ const totalRows = Number(p.total_rows_to_read);
+ const percent = computeMonotonicPercent(
+ readRows,
+ totalRows,
+ maxPercentRef.current,
+ );
+ maxPercentRef.current = percent;
+
+ setProgress({
+ read_rows: readRows,
+ total_rows_to_read: totalRows,
+ elapsed_ns: Number(p.elapsed_ns),
+ read_bytes: Number(p.read_bytes),
+ percent,
+ });
+ } catch {
+ // Ignore malformed progress events
+ }
+ } else if (event.type === "row") {
+ try {
+ rows.push(JSON.parse(event.data));
+ } catch {
+ // Ignore malformed row events
+ }
+ } else if (event.type === "done") {
+ setData(rows);
+ setStatus("success");
+ terminated = true;
+ } else if (event.type === "error") {
+ try {
+ const err = JSON.parse(event.data);
+ setError(err.message ?? "Unknown error");
+ } catch {
+ setError(event.data);
+ }
+ setStatus("error");
+ terminated = true;
+ }
+ };
+
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+
+ buffer += decoder.decode(value, { stream: true });
+ const { events, remaining } = parseSSEBuffer(buffer);
+ buffer = remaining;
+
+ for (const event of events) {
+ handleEvent(event);
+ }
+ }
+
+ // Flush any remaining buffer (e.g. "done" event without trailing newline)
+ if (!terminated && buffer.trim()) {
+ const { events } = parseSSEBuffer(buffer + "\n\n");
+ for (const event of events) {
+ handleEvent(event);
+ }
+ }
+
+ // Fallback if stream ended without a terminal event
+ if (!terminated) {
+ if (rows.length > 0) {
+ setData(rows);
+ setStatus("success");
+ } else {
+ setError("Stream ended unexpectedly");
+ setStatus("error");
+ }
+ }
+ } catch (err) {
+ if (signal.aborted) return;
+ setError(err instanceof Error ? err.message : "Unknown error");
+ setStatus("error");
+ }
+ },
+ [basePath],
+ );
+
+ // Derive a stable key from the input to detect changes
+ const inputKey = JSON.stringify(input);
+
+ useEffect(() => {
+ if (!enabled) {
+ setStatus((current) =>
+ current === "success" || current === "error" ? current : "idle",
+ );
+ return;
+ }
+
+ const abortController = new AbortController();
+ void runQuery(inputKey, abortController.signal);
+
+ return () => {
+ abortController.abort();
+ };
+ }, [enabled, inputKey, runQuery]);
+
+ const hasCurrentState = stateInputKey === inputKey;
+ const shouldHidePreviousRunState = enabled && !hasCurrentState;
+ const isPendingForCurrentRun =
+ enabled &&
+ (status === "idle" || status === "loading" || shouldHidePreviousRunState);
+ const effectiveStatus = isPendingForCurrentRun ? "loading" : status;
+
+ return {
+ data: shouldHidePreviousRunState ? undefined : data,
+ progress: shouldHidePreviousRunState ? null : progress,
+ status: effectiveStatus,
+ isLoading: effectiveStatus === "loading",
+ isSuccess: effectiveStatus === "success",
+ isError: effectiveStatus === "error",
+ error: shouldHidePreviousRunState ? null : error,
+ // Compatibility with existing scheduler expectations
+ fetchStatus: isPendingForCurrentRun ? "fetching" : "idle",
+ isPending: isPendingForCurrentRun,
+ };
+}
diff --git a/web/src/pages/api/dashboard/execute-query-stream.ts b/web/src/pages/api/dashboard/execute-query-stream.ts
index ec98b3ce5a..5dc4930f22 100644
--- a/web/src/pages/api/dashboard/execute-query-stream.ts
+++ b/web/src/pages/api/dashboard/execute-query-stream.ts
@@ -103,6 +103,13 @@ export default async function handler(
});
}
+ if (session.user.v4BetaEnabled !== true) {
+ res.status(400).json({
+ message: "Streaming is only supported for v4-enabled dashboard queries",
+ });
+ return;
+ }
+
const validation = validateQuery(query, version);
if (!validation.valid) {
res.status(400).json({ message: "Invalid query", errors: validation });