The Open Standard for Generative UI
fix(devtools): settle stream rows when the Renderer unmounts mid-stream (#1500)
devin-ai-integration[bot]d4711b2b5c53
diff --git a/.changeset/devtools-renderer-unmounted.md b/.changeset/devtools-renderer-unmounted.mdnew file mode 100644index 000000000..5fc9fb35d--- /dev/null+++ b/.changeset/devtools-renderer-unmounted.md@@ -0,0 +1,6 @@+---+"@openuidev/react-lang": patch+"@openuidev/devtools": patch+---++Settle the devtools stream row when a Renderer unmounts mid-stream. It used to stay on "Streaming" forever; react-lang now publishes an `unmounted` stream event and devtools shows an "Interrupted" badge with the final duration.diff --git a/packages/devtools/src/OpenUIDevtools.test.ts b/packages/devtools/src/OpenUIDevtools.test.tsindex b6afcc42c..801aa5952 100644--- a/packages/devtools/src/OpenUIDevtools.test.ts+++ b/packages/devtools/src/OpenUIDevtools.test.ts@@ -347,6 +347,40 @@ describe("OpenUIDevtools", () => {expect(container.textContent).toContain("Orphaned: unused");});+ it("marks a stream whose Renderer unmounted before it settled", () => {+ render({ enabled: true, errorsOnly: false });++ act(() =>+ observability.info({+ kind: "react-lang:stream",+ id: "stream-1",+ phase: "streaming",+ updateIndex: 1,+ response: "root = Car",+ startedAt: Date.now() - 1500,+ }),+ );+ expect(container.textContent).toContain("Streaming");++ act(() =>+ observability.warn({+ kind: "react-lang:stream",+ id: "stream-1",+ phase: "unmounted",+ updateIndex: 2,+ response: "root = Car",+ startedAt: Date.now() - 1500,+ durationMs: 1500,+ message: "Stream interrupted",+ }),+ );++ expect(container.textContent?.match(/OpenUI Lang stream/g)).toHaveLength(1);+ expect(container.textContent).not.toContain("Streaming");+ expect(container.textContent).toContain("Interrupted");+ expect(container.textContent).toContain("1.5s");+ });+it("replaces a stream update with its settled diagnostics", () => {render({ enabled: true, errorsOnly: false });diff --git a/packages/devtools/src/inspect/ReactLangStreamEventRow.tsx b/packages/devtools/src/inspect/ReactLangStreamEventRow.tsxindex fa0ad9aef..b27a06b88 100644--- a/packages/devtools/src/inspect/ReactLangStreamEventRow.tsx+++ b/packages/devtools/src/inspect/ReactLangStreamEventRow.tsx@@ -6,7 +6,7 @@ import { FONT, MONO, useStyles, type ThemeTokens } from "../theme";import { LevelIcon } from "./LevelIcon";export interface ReactLangStreamDetail {- phase: "streaming" | "settled";+ phase: "streaming" | "settled" | "unmounted";response?: string;errors: Record<string, unknown>[];parser?: {@@ -25,7 +25,9 @@ export function getReactLangStreamDetail(event: ObservabilityEvent): ReactLangStconst detail = asRecord(event.detail);if (detail["kind"] !== "react-lang:stream" ||- (detail["phase"] !== "streaming" && detail["phase"] !== "settled")+ (detail["phase"] !== "streaming" &&+ detail["phase"] !== "settled" &&+ detail["phase"] !== "unmounted")) {return null;}@@ -80,6 +82,7 @@ export function ReactLangStreamEventRow({[expanded, stream.response],);const isStreaming = stream.phase === "streaming";+ const isUnmounted = stream.phase === "unmounted";const elapsedMs = useStreamElapsedMs(stream, isStreaming);const visibleErrors = isStreaming ? [] : stream.errors;const statementCount = stream.parser?.statementCount;@@ -127,6 +130,14 @@ export function ReactLangStreamEventRow({{isStreaming ? (<span style={{ ...styles.badge, ...styles.badgeStreaming }}>Streaming</span>) : null}+ {isUnmounted ? (+ <span+ style={{ ...styles.badge, ...styles.badgeUnmounted }}+ title="The Renderer unmounted before the stream settled"+ >+ Interrupted+ </span>+ ) : null}</div><div style={styles.rowHeaderRight}><span style={styles.time}>@@ -423,6 +434,11 @@ function streamRowStyles(t: ThemeTokens) {color: t.success,borderColor: t.successBorder,},+ badgeUnmounted: {+ background: t.warningBg,+ color: t.warning,+ borderColor: t.warningBorder,+ },time: {color: t.fgFaint,fontSize: 11,diff --git a/packages/react-lang/src/hooks/streamEvent.ts b/packages/react-lang/src/hooks/streamEvent.tsindex 547bd0c54..b3b01d554 100644--- a/packages/react-lang/src/hooks/streamEvent.ts+++ b/packages/react-lang/src/hooks/streamEvent.ts@@ -10,7 +10,10 @@ export type StreamEventKind = typeof STREAM_EVENT_KIND;export const STREAM_PHASE_STREAMING = "streaming" as const;export const STREAM_PHASE_SETTLED = "settled" as const;-export type StreamPhase = typeof STREAM_PHASE_STREAMING | typeof STREAM_PHASE_SETTLED;+/** The Renderer unmounted while streaming, so the stream will never settle. */+export const STREAM_PHASE_UNMOUNTED = "unmounted" as const;+export type StreamPhase =+ typeof STREAM_PHASE_STREAMING | typeof STREAM_PHASE_SETTLED | typeof STREAM_PHASE_UNMOUNTED;export interface StreamParserMetadata {incomplete: boolean;diff --git a/packages/react-lang/src/hooks/useStreamingObservability.integration.test.ts b/packages/react-lang/src/hooks/useStreamingObservability.integration.test.tsindex 34fb897d9..3c28dc060 100644--- a/packages/react-lang/src/hooks/useStreamingObservability.integration.test.ts+++ b/packages/react-lang/src/hooks/useStreamingObservability.integration.test.ts@@ -1,7 +1,7 @@// @vitest-environment jsdomimport type { OpenUIError, ParseResult, QuerySnapshot } from "@openuidev/lang-core";import { observability, type ObservabilityEvent } from "@openuidev/observability";-import { act, createElement, useRef } from "react";+import { act, createElement, StrictMode, useRef } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it } from "vitest";import type { Library } from "../library";@@ -193,4 +193,60 @@ describe("streaming observability integration", () => {expect(settled[1]?.detail["errors"]).toEqual([queryError]);expect(settled[1]?.detail["response"]).toBe(response);});++ it("publishes unmounted when the Renderer unmounts mid-stream", () => {+ const events: ObservabilityEvent[] = [];+ const removeListener = observability.listenAll((event) => {+ if (event.detail.kind === "react-lang:stream") events.push(event);+ });++ act(() =>+ root.render(+ createElement(Harness, { isStreaming: true, queryErrors: [], currentResponse: "root = " }),+ ),+ );+ act(() => root.render(null));+ removeListener();++ expect(events.map((event) => event.detail["phase"])).toEqual(["streaming", "unmounted"]);+ expect(events[1]?.level).toBe("warning");+ expect(events[1]?.detail.id).toBe(events[0]?.detail.id);+ expect(events[1]?.detail["response"]).toBe("root = ");+ expect(events[1]?.detail["message"]).toBe("Stream interrupted");+ });++ it("does not publish unmounted after the stream settled", () => {+ const events: ObservabilityEvent[] = [];+ const removeListener = observability.listenAll((event) => {+ if (event.detail.kind === "react-lang:stream") events.push(event);+ });++ act(() => root.render(createElement(Harness, { isStreaming: true, queryErrors: [] })));+ act(() => root.render(createElement(Harness, { isStreaming: false, queryErrors: [] })));+ act(() => root.render(null));+ removeListener();++ expect(events.map((event) => event.detail["phase"])).toEqual(["streaming", "settled"]);+ });++ it("resumes streaming after a StrictMode effect replay", () => {+ const events: ObservabilityEvent[] = [];+ const removeListener = observability.listenAll((event) => {+ if (event.detail.kind === "react-lang:stream") events.push(event);+ });++ act(() =>+ root.render(+ createElement(+ StrictMode,+ null,+ createElement(Harness, { isStreaming: true, queryErrors: [] }),+ ),+ ),+ );+ removeListener();++ expect(events.at(-1)?.detail["phase"]).toBe("streaming");+ expect(new Set(events.map((event) => event.detail.id)).size).toBe(1);+ });});diff --git a/packages/react-lang/src/hooks/useStreamingObservability.test.ts b/packages/react-lang/src/hooks/useStreamingObservability.test.tsindex 10a982358..01c369bdb 100644--- a/packages/react-lang/src/hooks/useStreamingObservability.test.ts+++ b/packages/react-lang/src/hooks/useStreamingObservability.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";import {advanceStreamingObservability,createStreamingObservabilityState,+ unmountStreamingObservability,} from "./useStreamingObservability";describe("streaming observability lifecycle", () => {@@ -124,4 +125,20 @@ describe("streaming observability lifecycle", () => {),).toEqual({ id: "stream-1", phase: "settled", updateIndex: 4 });});++ it("ends an unsettled stream when its Renderer unmounts", () => {+ const state = createStreamingObservabilityState();+ const idFactory = () => "stream-1";++ expect(unmountStreamingObservability(state)).toBeNull();+ advanceStreamingObservability(state, true, "root = Car", null, idFactory);+ expect(unmountStreamingObservability(state)).toEqual({+ id: "stream-1",+ phase: "unmounted",+ updateIndex: 2,+ });++ advanceStreamingObservability(state, false, "root = Car", "[]", idFactory);+ expect(unmountStreamingObservability(state)).toBeNull();+ });});diff --git a/packages/react-lang/src/hooks/useStreamingObservability.ts b/packages/react-lang/src/hooks/useStreamingObservability.tsindex b06c2e109..dca1858de 100644--- a/packages/react-lang/src/hooks/useStreamingObservability.ts+++ b/packages/react-lang/src/hooks/useStreamingObservability.ts@@ -5,6 +5,7 @@ import {STREAM_EVENT_KIND,STREAM_PHASE_SETTLED,STREAM_PHASE_STREAMING,+ STREAM_PHASE_UNMOUNTED,type SettledStreamEventDetail,type StreamPhase,} from "./streamEvent";@@ -114,6 +115,17 @@ export function advanceStreamingObservability(return { id: state.id, phase: STREAM_PHASE_SETTLED, updateIndex: state.updateIndex };}+/** Ends a stream whose Renderer unmounted before it settled. */+export function unmountStreamingObservability(+ state: StreamingObservabilityState,+): StreamingObservabilityUpdate | null {+ if (!state.id || state.settled) return null;+ state.updateIndex += 1;+ // A StrictMode remount reuses this state; let it republish the stream it resumes.+ state.hasPublishedStreamingSnapshot = false;+ return { id: state.id, phase: STREAM_PHASE_UNMOUNTED, updateIndex: state.updateIndex };+}+function parserMetadata(result: ParseResult | null) {if (!result) return undefined;return {@@ -138,6 +150,34 @@ export function useStreamingObservability({__libraryId,}: UseStreamingObservabilityOptions): void {const streamRef = useRef<StreamingObservabilityState>(createStreamingObservabilityState());+ const lastStreamingRef = useRef<{ result: ParseResult | null; __libraryId?: string }>({+ result: null,+ });++ useEffect(() => {+ const stream = streamRef.current;+ return () => {+ const update = unmountStreamingObservability(stream);+ if (!update) return;+ const { result: lastResult, __libraryId: lastLibraryId } = lastStreamingRef.current;+ const startedAt = stream.startedAt ?? Date.now();+ const durationMs = Math.max(0, Date.now() - startedAt);+ observability.warn({+ id: update.id,+ kind: STREAM_EVENT_KIND,+ phase: update.phase,+ updateIndex: update.updateIndex,+ response: stream.lastResponse,+ responseLength: stream.lastResponse?.length ?? 0,+ parser: parserMetadata(lastResult),+ startedAt,+ elapsedMs: durationMs,+ durationMs,+ ...(lastLibraryId !== undefined ? { __libraryId: lastLibraryId } : {}),+ message: "Stream interrupted",+ });+ };+ }, []);useEffect(() => {if (!publish) return;@@ -153,6 +193,7 @@ export function useStreamingObservability({if (isStreaming) {if (update) {+ lastStreamingRef.current = { result, __libraryId };observability.info({id: update.id,kind: STREAM_EVENT_KIND,