An open-source, faster Devin alternative
TypeScript
Smooth managed-agent streaming: WebSocket live events + paced chat deltas
Devin AI0341384f7db8
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex e750b9bb..8191e432 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -4882,6 +4882,155 @@ describe("managed agents proxy", () => {expect(JSON.stringify(body)).not.toContain("Workerd");});+ it("relays the session WebSocket with the same public event redaction", async () => {+ class FakeSocket extends EventTarget {+ peer!: FakeSocket;+ sent: string[] = [];+ closed: { code?: number; reason?: string } | null = null;+ accept() {}+ send(data: string) {+ this.sent.push(data);+ }+ close(code?: number, reason?: string) {+ if (this.closed) return;+ this.closed = { code, reason };+ this.peer.dispatchEvent(+ Object.assign(new Event("close"), { code, reason }),+ );+ }+ receive(data: string) {+ this.dispatchEvent(Object.assign(new Event("message"), { data }));+ }+ }+ const pairs: FakeSocket[][] = [];+ vi.stubGlobal(+ "WebSocketPair",+ class {+ 0: FakeSocket;+ 1: FakeSocket;+ constructor() {+ const a = new FakeSocket();+ const b = new FakeSocket();+ a.peer = b;+ b.peer = a;+ this[0] = a;+ this[1] = b;+ pairs.push([a, b]);+ }+ },+ );++ const upstream = new FakeSocket();+ upstream.peer = new FakeSocket();+ upstream.peer.peer = upstream;+ const fetchMock = vi.fn(+ async (_input: URL | RequestInfo, _init?: RequestInit) =>+ ({ status: 101, webSocket: upstream }) as unknown as Response,+ );+ vi.stubGlobal("fetch", fetchMock);+ // Node's Response rejects status 101; workerd accepts it for upgrades.+ const NativeResponse = Response;+ vi.stubGlobal(+ "Response",+ class extends NativeResponse {+ constructor(body: BodyInit | null, init?: ResponseInit) {+ if (init?.status === 101) {+ super(null, { ...init, status: 200 });+ Object.defineProperty(this, "status", { value: 101 });+ } else {+ super(body, init);+ }+ }+ },+ );++ const response = await proxyManagedAgents(+ new Request(+ "https://app.opencomputer.dev/api/managed-agents/sessions/session-1/connect?cursor=4",+ { headers: { upgrade: "websocket" } },+ ),+ memoryEnv,+ memoryCaller,+ "/api/managed-agents",+ );++ expect(response.status).toBe(101);+ const target = new URL(String(fetchMock.mock.calls[0]?.[0]));+ expect(target.pathname).toBe("/v1/sessions/session-1/connect");+ expect(target.searchParams.get("role")).toBe("client");+ expect(target.searchParams.get("cursor")).toBe("4");+ const [, server] = pairs[0];++ upstream.receive(+ JSON.stringify({ type: "ready", sessionId: "session-1", cursor: 4 }),+ );+ upstream.receive("not json");+ upstream.receive(+ JSON.stringify({+ type: "event",+ event: {+ id: "event_1",+ seq: 5,+ type: "turn.failed",+ data: {+ message: "The agent runtime stopped reporting on this turn and its lease expired",+ reason: "runtime_lost",+ runtimeToken: "never-return-this",+ },+ },+ }),+ );+ upstream.receive(+ JSON.stringify({ type: "error", code: "boom", message: "stack trace" }),+ );++ expect(server.sent.map((frame) => JSON.parse(frame))).toEqual([+ { type: "ready", sessionId: "session-1", cursor: 4 },+ {+ type: "event",+ event: {+ id: "event_1",+ seq: 5,+ type: "turn.failed",+ data: {+ code: "runtime_lost",+ message:+ "The agent runtime stopped responding and the turn was abandoned.",+ },+ },+ },+ {+ type: "error",+ code: "boom",+ message: "The session stream reported an error.",+ },+ ]);+ expect(server.sent.join("")).not.toContain("never-return-this");+ expect(server.sent.join("")).not.toContain("stack trace");++ server.receive(JSON.stringify({ type: "ping" }));+ expect(upstream.sent).toEqual([JSON.stringify({ type: "ping" })]);++ upstream.peer.close(1006, "");+ expect(server.closed).toEqual({ code: 1000, reason: "" });+ expect(upstream.closed).toEqual({ code: 1000, reason: "" });+ });++ it("rejects non-upgrade requests to the session connect route", async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const response = await proxyManagedAgents(+ new Request(+ "https://app.opencomputer.dev/api/managed-agents/sessions/session-1/connect",+ ),+ memoryEnv,+ memoryCaller,+ "/api/managed-agents",+ );+ expect(response.status).toBe(426);+ expect(fetchMock).not.toHaveBeenCalled();+ });+it("classifies known runtime failures into typed public failures", () => {expect(publicFailure({ reason: "interrupted" })).toEqual({code: "interrupted",diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex ca5b0783..ac8d4a6a 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -1392,6 +1392,101 @@ function publicEventData();}+export function publicEvent(value: unknown): Record<string, unknown> {+ const event = record(value) ?? {};+ const type = typeof event.type === "string" ? event.type : "";+ return {+ id: event.id,+ seq: event.seq,+ timestamp: event.timestamp,+ sessionId: event.sessionId,+ turnId: event.turnId,+ type,+ data: publicEventData(type, event.data),+ };+}++const SESSION_CONNECT_ROUTE = /^\/sessions\/[^/]+\/connect$/;++// Live session stream. The browser opens a WebSocket against the edge; the+// edge opens the backend's client socket and relays frames, applying the same+// redaction as GET /events to every event. Only keepalive pings travel+// upstream: turns are admitted over REST, where the credit gate lives.+function relaySessionSocket(upstream: WebSocket): Response {+ const pair = new WebSocketPair();+ const [client, server] = Object.values(pair) as [WebSocket, WebSocket];+ server.accept();+ upstream.accept();++ const closeBoth = (code: number, reason: string) => {+ for (const socket of [server, upstream]) {+ try {+ socket.close(code, reason);+ } catch {+ // Already closed.+ }+ }+ };++ upstream.addEventListener("message", (message) => {+ let frame: Record<string, unknown> | null = null;+ try {+ frame = record(+ JSON.parse(+ typeof message.data === "string"+ ? message.data+ : new TextDecoder().decode(message.data as ArrayBuffer),+ ),+ );+ } catch {+ return;+ }+ if (!frame) return;+ if (frame.type === "event") {+ server.send(+ JSON.stringify({ type: "event", event: publicEvent(frame.event) }),+ );+ } else if (frame.type === "ready" || frame.type === "pong") {+ server.send(JSON.stringify(frame));+ } else if (frame.type === "error") {+ server.send(+ JSON.stringify({+ type: "error",+ code: typeof frame.code === "string" ? frame.code : "stream_error",+ message: "The session stream reported an error.",+ }),+ );+ }+ });+ upstream.addEventListener("close", (event) =>+ closeBoth(+ event.code === 1005 || event.code === 1006 ? 1000 : event.code,+ event.reason,+ ),+ );+ upstream.addEventListener("error", () => closeBoth(1011, "upstream error"));++ server.addEventListener("message", (message) => {+ if (typeof message.data !== "string") return;+ let frame: Record<string, unknown> | null = null;+ try {+ frame = record(JSON.parse(message.data));+ } catch {+ return;+ }+ if (frame?.type === "ping") upstream.send(JSON.stringify({ type: "ping" }));+ });+ server.addEventListener("close", (event) =>+ closeBoth(+ event.code === 1005 || event.code === 1006 ? 1000 : event.code,+ event.reason,+ ),+ );+ server.addEventListener("error", () => closeBoth(1011, "client error"));++ return new Response(null, { status: 101, webSocket: client });+}+function publicTemplateInspection(value: unknown): Record<string, unknown> {const inspection = record(value) ?? {};if (inspection.status === "preparing") {@@ -1850,21 +1945,7 @@ function publicSuccessBody(}if (method === "GET" && /^\/sessions\/[^/]+\/events$/.test(suffix)) {return {- events: Array.isArray(body.events)- ? body.events.map((value) => {- const event = record(value) ?? {};- const type = typeof event.type === "string" ? event.type : "";- return {- id: event.id,- seq: event.seq,- timestamp: event.timestamp,- sessionId: event.sessionId,- turnId: event.turnId,- type,- data: publicEventData(type, event.data),- };- })- : [],+ events: Array.isArray(body.events) ? body.events.map(publicEvent) : [],};}if (method === "POST" && /\/turns$/.test(suffix)) {@@ -2402,6 +2483,7 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {if (method === "GET" && /^\/sessions\/[^/]+\/events$/.test(suffix)) {return true;}+ if (method === "GET" && SESSION_CONNECT_ROUTE.test(suffix)) return true;if (method === "GET" &&/^\/sessions\/[^/]+\/workspace\/files$/.test(suffix)@@ -2962,6 +3044,39 @@ export async function proxyManagedAgents();}const headers = copyRequestHeaders(request);+ if (method === "GET" && SESSION_CONNECT_ROUTE.test(suffix)) {+ if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") {+ return Response.json(+ { error: "expected a WebSocket upgrade" },+ { status: 426 },+ );+ }+ target.searchParams.set("role", "client");+ headers.set("upgrade", "websocket");+ headers.set(+ "x-opencomputer-agent-token",+ await mintManagedAgentsAssertion(env.OC_MANAGED_AGENTS_SECRET, caller),+ );+ try {+ const upstream = await fetch(target, { method: "GET", headers });+ if (upstream.status !== 101 || !upstream.webSocket) {+ return publicErrorResponse(upstream);+ }+ return relaySessionSocket(upstream.webSocket);+ } catch (error) {+ console.error(+ JSON.stringify({+ level: "error",+ event: "managed_agents.upstream_failed",+ message: error instanceof Error ? error.message : String(error),+ }),+ );+ return Response.json(+ { error: "managed agents service is unavailable" },+ { status: 502 },+ );+ }+ }const memoryRoute = isMemoryRoute(method, suffix);if (memoryRoute) {for (const name of MEMORY_CONDITIONAL_REQUEST_HEADERS) {diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsxindex 73f3388b..a6a67d64 100644--- a/web/src/managed-agents/Detail.tsx+++ b/web/src/managed-agents/Detail.tsx@@ -63,6 +63,7 @@ import {type ManagedProjectOverview,} from './api'import { ManagedAgentChatTransport } from './chat-transport'+import { useLiveSessionEvents } from './use-live-session-events'import { PostSessionUpsell } from '@/components/post-session-upsell'import { useCreditState } from '@/hooks/useCreditState'import {@@ -292,7 +293,6 @@ function PlaygroundChat({queryKey: ['managed-agent-session-events', liveSessionId],queryFn: () => getManagedAgentSessionEvents(liveSessionId!),enabled: Boolean(liveSessionId),- refetchInterval: 1_000,})useEffect(() => {liveSessionIdRef.current = liveSessionId@@ -325,6 +325,11 @@ function PlaygroundChat({const halted = credits.isHaltedconst turnFinished =!agentWorking && status === 'ready' && messages.length > 0+ const inspectorEvents = useLiveSessionEvents(+ liveSessionId,+ debugEvents.data ?? events,+ agentWorking,+ )useEffect(() => {if (!initialPrompt || session || initialPromptSentRef.current) return@@ -572,7 +577,7 @@ function PlaygroundChat({</div></div><DebugInspector- events={debugEvents.data ?? events}+ events={inspectorEvents}deploymentId={session?.deploymentId}sessionId={liveSessionId}sessionLive={agentWorking}@@ -733,7 +738,7 @@ export default function ManagedAgentDetail({queryKey: ['managed-agent-session-events', selectedPlaygroundId],queryFn: () => getManagedAgentSessionEvents(selectedPlaygroundId!),enabled: Boolean(selectedPlaygroundId),- refetchInterval: 1_000,+ refetchInterval: 5_000,})// The list carries rows; the open session's turns come from its own route.const selectedPlaygroundSession = useQuery({diff --git a/web/src/managed-agents/api.test.ts b/web/src/managed-agents/api.test.tsindex 63cb3527..c8882466 100644--- a/web/src/managed-agents/api.test.ts+++ b/web/src/managed-agents/api.test.ts@@ -4,7 +4,6 @@ import {displayManagedAgentName,managedAgentModelRoute,managedAgentRenderDebug,- nextAgentEventDeadline,} from './api'describe('collectManagedAgentEventPages', () => {@@ -32,13 +31,6 @@ describe('collectManagedAgentEventPages', () => {})})-describe('nextAgentEventDeadline', () => {- it('refreshes the inactivity deadline only when progress arrives', () => {- expect(nextAgentEventDeadline(10_000, 3_000, 0, 9_000)).toBe(10_000)- expect(nextAgentEventDeadline(10_000, 3_000, 1, 9_000)).toBe(12_000)- })-})-describe('displayManagedAgentName', () => {it('hides UUID-shaped legacy names without hiding readable stable names', () => {expect(diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.tsindex 378793ad..c6a0b7fd 100644--- a/web/src/managed-agents/api.ts+++ b/web/src/managed-agents/api.ts@@ -1,5 +1,10 @@import { z } from 'zod'import { apiFetch, apiFetchResponse, validate } from '@/api/client'+import { managedAgentEventSchema, type ManagedAgentEvent } from './events'+import {+ ManagedAgentEventStream,+ ManagedAgentEventStreamTimeout,+} from './live-events'import {Sha256,ZipWriter,@@ -553,15 +558,7 @@ const sessionCreateSchema = z.object({deployment: deploymentSchema.optional(),})-const eventSchema = z.object({- id: z.string().optional(),- seq: z.number(),- timestamp: z.string().optional(),- sessionId: z.string().optional(),- turnId: z.string().optional(),- type: z.string(),- data: z.record(z.string(), z.unknown()),-})+const eventSchema = managedAgentEventSchemaconst renderDebugSchema = z.object({renderId: z.string(),@@ -773,7 +770,7 @@ export type ManagedRuntimeProfile = z.infer<typeof managedRuntimeProfileSchema>export type ManagedProject = z.infer<typeof projectSchema>export type ManagedProjectOverview = z.infer<typeof projectOverviewSchema>export type ManagedAgentDeployment = z.infer<typeof deploymentSchema>-export type ManagedAgentEvent = z.infer<typeof eventSchema>+export type { ManagedAgentEvent } from './events'export type ManagedAgentRenderDebug = z.infer<typeof renderDebugSchema>export type ManagedAgentModelRoute = z.infer<typeof modelRouteSchema>export type ManagedAgentSession = z.infer<typeof sessionSchema>@@ -2037,38 +2034,32 @@ export async function deleteManagedMemoryDocument(})}-async function sleep(milliseconds: number) {- await new Promise((resolve) => setTimeout(resolve, milliseconds))-}--export function nextAgentEventDeadline(- deadline: number,- timeoutMs: number,- receivedEvents: number,- now = Date.now(),+export function openManagedAgentEventStream(+ sessionId: string,+ after: number,+ signal?: AbortSignal,) {- return receivedEvents > 0 ? now + timeoutMs : deadline+ return new ManagedAgentEventStream(sessionId, after, {+ fetchEvents: getManagedAgentSessionEvents,+ signal,+ })}+// `timeoutMs` is an inactivity deadline: multi-step agents can run for longer+// than one fixed window while continuing to stream useful progress.async function waitForAgentEvent(sessionId: string,after: number,- terminal: (event: z.infer<typeof eventSchema>) => boolean,- onEvent: (event: z.infer<typeof eventSchema>) => void,+ terminal: (event: ManagedAgentEvent) => boolean,+ onEvent: (event: ManagedAgentEvent) => void,timeoutMs: number,signal?: AbortSignal,) {- let deadline = Date.now() + timeoutMs- let cursor = after- while (Date.now() < deadline) {- if (signal?.aborted) throw new DOMException('Aborted', 'AbortError')- const { events } = await apiFetch(- `/managed-agents/sessions/${encodeURIComponent(sessionId)}/events?after=${cursor}`,- { signal },- eventsResponseSchema,- )- for (const event of events) {- cursor = Math.max(cursor, event.seq)+ if (signal?.aborted) throw new DOMException('Aborted', 'AbortError')+ const stream = openManagedAgentEventStream(sessionId, after, signal)+ try {+ for (;;) {+ const event = await stream.next(timeoutMs)onEvent(event)if (event.type === 'runtime.disconnected' ||@@ -2082,14 +2073,16 @@ async function waitForAgentEvent(: 'The agent runtime disconnected.',)}- if (terminal(event)) return { event, cursor }+ if (terminal(event)) return { event, cursor: stream.position }}- // Treat timeoutMs as an inactivity deadline. Multi-step agents can run for- // longer than one fixed window while continuing to stream useful progress.- deadline = nextAgentEventDeadline(deadline, timeoutMs, events.length)- await sleep(600)+ } catch (error) {+ if (error instanceof ManagedAgentEventStreamTimeout) {+ throw new Error('Timed out waiting for the agent.')+ }+ throw error+ } finally {+ stream.close()}- throw new Error('Timed out waiting for the agent.')}export async function runManagedAgent(diff --git a/web/src/managed-agents/chat-transport.test.ts b/web/src/managed-agents/chat-transport.test.tsindex da98cff8..ec84d390 100644--- a/web/src/managed-agents/chat-transport.test.ts+++ b/web/src/managed-agents/chat-transport.test.ts@@ -76,6 +76,7 @@ describe('ManagedAgentChatTransport', () => {'agent-1',undefined,(sessionId) => assigned.push(sessionId),+ false,)const first = await readChunks(@@ -121,4 +122,84 @@ describe('ManagedAgentChatTransport', () => {)expect(runManagedAgent).toHaveBeenCalledTimes(1)})++ it('paces bursty deltas into a steady trickle without changing the transcript', async () => {+ const reasoning = 'Thinking about the request carefully.'+ const answer = 'Here is the full answer, delivered in two big bursts.'+ runManagedAgent.mockImplementation(+ (+ _agentId: string,+ _input: string,+ onEvent: (event: unknown) => void,+ options: { onSession: (sessionId: string) => void },+ ) => {+ options.onSession('session-2')+ onEvent({ seq: 1, type: 'reasoning.delta', data: { text: reasoning } })+ onEvent({+ seq: 2,+ type: 'tool.started',+ data: { callId: 'call-1', tool: 'search', input: {} },+ })+ onEvent({+ seq: 3,+ type: 'message.delta',+ data: { text: answer.slice(0, 20) },+ })+ onEvent({+ seq: 4,+ type: 'tool.completed',+ data: { callId: 'call-1', tool: 'search', output: 'ok' },+ })+ onEvent({+ seq: 5,+ type: 'message.delta',+ data: { text: answer.slice(20) },+ })+ onEvent({ seq: 6, type: 'message.completed', data: { text: answer } })+ return Promise.resolve()+ },+ )+ const transport = new ManagedAgentChatTransport(+ 'agent-1',+ undefined,+ () => undefined,+ { intervalMs: 1, catchUpMs: 8 },+ )++ const chunks = await readChunks(+ await transport.sendMessages({+ trigger: 'submit-message',+ chatId: 'chat-2',+ messageId: undefined,+ messages: messages('Go'),+ abortSignal: undefined,+ }),+ )++ const text = (type: 'text-delta' | 'reasoning-delta') =>+ chunks+ .filter((chunk) => chunk.type === type)+ .map((chunk) => (chunk as { delta: string }).delta)+ expect(text('reasoning-delta').join('')).toBe(reasoning)+ expect(text('text-delta').join('')).toBe(answer)+ expect(text('reasoning-delta').length).toBeGreaterThan(1)+ expect(text('text-delta').length).toBeGreaterThan(2)++ const types = chunks.map((chunk) => chunk.type)+ expect(types[0]).toBe('start')+ expect(types.slice(-3)).toEqual(['reasoning-end', 'text-end', 'finish'])+ // The tool call stays where it happened: after all reasoning, and the+ // tool result lands after exactly the first 20 characters of text.+ const toolInput = types.indexOf('tool-input-available')+ const toolOutput = types.indexOf('tool-output-available')+ expect(types.lastIndexOf('reasoning-delta')).toBeLessThan(toolInput)+ expect(toolInput).toBeLessThan(types.indexOf('text-start'))+ expect(+ chunks+ .slice(0, toolOutput)+ .filter((chunk) => chunk.type === 'text-delta')+ .map((chunk) => (chunk as { delta: string }).delta)+ .join(''),+ ).toBe(answer.slice(0, 20))+ })})diff --git a/web/src/managed-agents/chat-transport.ts b/web/src/managed-agents/chat-transport.tsindex f0110be4..cfff94d7 100644--- a/web/src/managed-agents/chat-transport.ts+++ b/web/src/managed-agents/chat-transport.ts@@ -4,6 +4,7 @@ import {runManagedAgent,type ManagedAgentEvent,} from './api'+import { UIMessageChunkPacer, type ChunkPacerOptions } from './chunk-pacer'function eventText(event: ManagedAgentEvent) {return typeof event.data.text === 'string' ? event.data.text : ''@@ -36,6 +37,7 @@ export class ManagedAgentChatTransport implements ChatTransport<UIMessage> {private readonly agentId: string,sessionId: string | undefined,private readonly onSession: (sessionId: string) => void,+ private readonly pacing: ChunkPacerOptions | false = {},) {this.sessionId = sessionId}@@ -59,9 +61,18 @@ export class ManagedAgentChatTransport implements ChatTransport<UIMessage> {let reasoningStarted = falseconst startedTools = new Set<string>()- const enqueue = (chunk: UIMessageChunk) => {+ const emit = (chunk: UIMessageChunk) => {if (!closed && !abortSignal?.aborted) controller.enqueue(chunk)}+ const pacer =+ this.pacing === false+ ? null+ : new UIMessageChunkPacer(emit, this.pacing)+ const enqueue = (chunk: UIMessageChunk) =>+ pacer ? pacer.push(chunk) : emit(chunk)+ abortSignal?.addEventListener('abort', () => pacer?.dispose(), {+ once: true,+ })const finishParts = () => {if (reasoningStarted)enqueue({ type: 'reasoning-end', id: reasoningId })@@ -158,11 +169,15 @@ export class ManagedAgentChatTransport implements ChatTransport<UIMessage> {},}))- .then(() => {+ .then(async () => {+ // Let the tail of the reply trickle out at the same pace instead+ // of dumping the remaining backlog on completion.+ await pacer?.drain()finishParts()enqueue({ type: 'finish', finishReason: 'stop' })}).catch((error: unknown) => {+ pacer?.flush()if (abortSignal?.aborted) enqueue({ type: 'abort' })elseenqueue({@@ -172,6 +187,7 @@ export class ManagedAgentChatTransport implements ChatTransport<UIMessage> {})}).finally(() => {+ pacer?.dispose()closed = truecontroller.close()})diff --git a/web/src/managed-agents/chunk-pacer.test.ts b/web/src/managed-agents/chunk-pacer.test.tsnew file mode 100644index 00000000..78a711f9--- /dev/null+++ b/web/src/managed-agents/chunk-pacer.test.ts@@ -0,0 +1,109 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { UIMessageChunk } from 'ai'+import { UIMessageChunkPacer } from './chunk-pacer'++function collect() {+ const out: UIMessageChunk[] = []+ return { out, sink: (chunk: UIMessageChunk) => out.push(chunk) }+}++const text = (out: UIMessageChunk[]) =>+ out+ .filter((chunk) => chunk.type === 'text-delta')+ .map((chunk) => (chunk as { delta: string }).delta)++beforeEach(() => vi.useFakeTimers())+afterEach(() => vi.useRealTimers())++describe('UIMessageChunkPacer', () => {+ it('trickles a burst out over several ticks and scales with backlog', () => {+ const { out, sink } = collect()+ const pacer = new UIMessageChunkPacer(sink, { intervalMs: 10, catchUpMs: 40 })+ pacer.push({ type: 'text-start', id: 't' })+ pacer.push({ type: 'text-delta', id: 't', delta: 'abcd' })+ pacer.push({ type: 'text-delta', id: 't', delta: 'efgh' })+ expect(out.map((c) => c.type)).toEqual(['text-start'])++ vi.advanceTimersByTime(10)+ // 8 chars / 4 ticks = 2 per tick, easing down to the 2-char floor+ expect(text(out)).toEqual(['ab'])+ vi.advanceTimersByTime(30)+ expect(text(out)).toEqual(['ab', 'cd', 'ef', 'gh'])+ expect(pacer.pending).toBe(false)+ })++ it('keeps non-text chunks in order relative to the text around them', () => {+ const { out, sink } = collect()+ const pacer = new UIMessageChunkPacer(sink, { intervalMs: 10, catchUpMs: 10 })+ pacer.push({ type: 'text-delta', id: 't', delta: 'one' })+ pacer.push({+ type: 'tool-input-available',+ toolCallId: 'c',+ toolName: 'x',+ input: {},+ })+ pacer.push({ type: 'text-delta', id: 't', delta: 'two' })+ expect(out).toEqual([])++ vi.advanceTimersByTime(10)+ expect(out.map((c) => c.type)).toEqual(['text-delta', 'tool-input-available'])+ expect(text(out)).toEqual(['one'])+ vi.advanceTimersByTime(10)+ expect(text(out)).toEqual(['one', 'two'])+ })++ it('emits non-text chunks immediately when nothing is queued', () => {+ const { out, sink } = collect()+ const pacer = new UIMessageChunkPacer(sink)+ pacer.push({ type: 'start', messageId: 'm' })+ expect(out.map((c) => c.type)).toEqual(['start'])+ })++ it('never splits a surrogate pair', () => {+ const { out, sink } = collect()+ const pacer = new UIMessageChunkPacer(sink, {+ intervalMs: 10,+ catchUpMs: 10,+ minCharsPerTick: 1,+ })+ pacer.push({ type: 'text-delta', id: 't', delta: 'πx' })+ vi.advanceTimersByTime(10)+ expect(text(out).join('')).toBe('πx')++ const slow = new UIMessageChunkPacer(sink, { intervalMs: 10, catchUpMs: 1_000 })+ out.length = 0+ slow.push({ type: 'text-delta', id: 't', delta: 'πx' })+ vi.advanceTimersByTime(10)+ expect(text(out)).toEqual(['π'])+ })++ it('drain resolves once paced out, flush dumps everything at once', async () => {+ const { out, sink } = collect()+ const pacer = new UIMessageChunkPacer(sink, { intervalMs: 10, catchUpMs: 1_000 })+ pacer.push({ type: 'text-delta', id: 't', delta: 'hello world' })+ let drained = false+ void pacer.drain().then(() => {+ drained = true+ })+ vi.advanceTimersByTime(30)+ await Promise.resolve()+ expect(drained).toBe(false)+ expect(text(out).join('')).toBe('hello ')++ pacer.flush()+ await Promise.resolve()+ expect(drained).toBe(true)+ expect(text(out).join('')).toBe('hello world')+ expect(pacer.pending).toBe(false)+ })++ it('drops queued output after dispose', () => {+ const { out, sink } = collect()+ const pacer = new UIMessageChunkPacer(sink, { intervalMs: 10 })+ pacer.push({ type: 'text-delta', id: 't', delta: 'late' })+ pacer.dispose()+ vi.advanceTimersByTime(100)+ pacer.push({ type: 'finish' })+ expect(out).toEqual([])+ })+})diff --git a/web/src/managed-agents/chunk-pacer.ts b/web/src/managed-agents/chunk-pacer.tsnew file mode 100644index 00000000..e8ebfd2e--- /dev/null+++ b/web/src/managed-agents/chunk-pacer.ts@@ -0,0 +1,148 @@+import type { UIMessageChunk } from 'ai'++type TextChunk = Extract<+ UIMessageChunk,+ { type: 'text-delta' } | { type: 'reasoning-delta' }+>++function isTextChunk(chunk: UIMessageChunk): chunk is TextChunk {+ return chunk.type === 'text-delta' || chunk.type === 'reasoning-delta'+}++export type ChunkPacerOptions = {+ /** Tick cadence; one visual update per tick. */+ intervalMs?: number+ /** How quickly a backlog should be drained. Bigger = smoother but laggier. */+ catchUpMs?: number+ /** Never emit fewer than this many characters per tick while text is pending. */+ minCharsPerTick?: number+}++/**+ * Re-times `UIMessageChunk`s so text and reasoning arrive as a steady trickle+ * rather than in the bursts the network delivers them in.+ *+ * Text deltas are merged into one pending run per part and released a few+ * characters per tick; the per-tick amount scales with the backlog so the+ * display never falls more than ~`catchUpMs` behind the source. Every other+ * chunk keeps its position relative to the text around it, so tool calls still+ * show up exactly where they happened in the transcript.+ */+export class UIMessageChunkPacer {+ private readonly queue: UIMessageChunk[] = []+ private timer: ReturnType<typeof setTimeout> | null = null+ private disposed = false+ private drainWaiters: Array<() => void> = []+ private readonly intervalMs: number+ private readonly catchUpMs: number+ private readonly minCharsPerTick: number++ constructor(+ private readonly sink: (chunk: UIMessageChunk) => void,+ options: ChunkPacerOptions = {},+ ) {+ this.intervalMs = options.intervalMs ?? 16+ this.catchUpMs = options.catchUpMs ?? 320+ this.minCharsPerTick = options.minCharsPerTick ?? 2+ }++ get pending() {+ return this.queue.length > 0+ }++ push(chunk: UIMessageChunk) {+ if (this.disposed) return+ if (isTextChunk(chunk)) {+ if (chunk.delta.length === 0) return+ const tail = this.queue[this.queue.length - 1]+ if (tail && isTextChunk(tail) && tail.type === chunk.type && tail.id === chunk.id) {+ this.queue[this.queue.length - 1] = {+ ...tail,+ delta: tail.delta + chunk.delta,+ }+ } else {+ this.queue.push({ ...chunk })+ }+ this.schedule()+ return+ }+ if (this.queue.length === 0) {+ this.sink(chunk)+ return+ }+ this.queue.push(chunk)+ }++ /** Resolves once the queue has been paced out (or the pacer is disposed). */+ drain(): Promise<void> {+ if (this.queue.length === 0 || this.disposed) return Promise.resolve()+ return new Promise((resolve) => this.drainWaiters.push(resolve))+ }++ /** Emit everything still queued, immediately and in order. */+ flush() {+ if (this.timer) {+ clearTimeout(this.timer)+ this.timer = null+ }+ while (this.queue.length > 0) {+ const chunk = this.queue.shift()!+ this.sink(chunk)+ }+ this.settleDrain()+ }++ dispose() {+ this.disposed = true+ if (this.timer) clearTimeout(this.timer)+ this.timer = null+ this.queue.length = 0+ this.settleDrain()+ }++ private settleDrain() {+ const waiters = this.drainWaiters+ this.drainWaiters = []+ for (const resolve of waiters) resolve()+ }++ private schedule() {+ if (this.timer || this.disposed) return+ this.timer = setTimeout(() => {+ this.timer = null+ this.tick()+ }, this.intervalMs)+ }++ private tick() {+ if (this.disposed) return+ const head = this.queue[0]+ if (head && isTextChunk(head)) {+ const ticksToCatchUp = Math.max(1, this.catchUpMs / this.intervalMs)+ const take = Math.max(+ this.minCharsPerTick,+ Math.ceil(head.delta.length / ticksToCatchUp),+ )+ const piece = sliceGraphemes(head.delta, take)+ const rest = head.delta.slice(piece.length)+ if (rest.length === 0) this.queue.shift()+ else this.queue[0] = { ...head, delta: rest }+ this.sink({ ...head, delta: piece })+ }+ while (this.queue.length > 0 && !isTextChunk(this.queue[0])) {+ this.sink(this.queue.shift()!)+ }+ if (this.queue.length > 0) this.schedule()+ else this.settleDrain()+ }+}++// Avoid splitting surrogate pairs (emoji etc.) across ticks.+function sliceGraphemes(text: string, count: number) {+ let end = Math.min(count, text.length)+ if (end < text.length) {+ const code = text.charCodeAt(end - 1)+ if (code >= 0xd800 && code <= 0xdbff) end += 1+ }+ return text.slice(0, end)+}diff --git a/web/src/managed-agents/events.ts b/web/src/managed-agents/events.tsnew file mode 100644index 00000000..fb9e38dc--- /dev/null+++ b/web/src/managed-agents/events.ts@@ -0,0 +1,13 @@+import { z } from 'zod'++export const managedAgentEventSchema = z.object({+ id: z.string().optional(),+ seq: z.number(),+ timestamp: z.string().optional(),+ sessionId: z.string().optional(),+ turnId: z.string().optional(),+ type: z.string(),+ data: z.record(z.string(), z.unknown()),+})++export type ManagedAgentEvent = z.infer<typeof managedAgentEventSchema>diff --git a/web/src/managed-agents/live-events.test.ts b/web/src/managed-agents/live-events.test.tsnew file mode 100644index 00000000..b2e59688--- /dev/null+++ b/web/src/managed-agents/live-events.test.ts@@ -0,0 +1,175 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { ManagedAgentEvent } from './events'+import {+ ManagedAgentEventStream,+ ManagedAgentEventStreamTimeout,+ managedAgentSocketUrl,+} from './live-events'++class FakeSocket extends EventTarget {+ static instances: FakeSocket[] = []+ closed: { code?: number; reason?: string } | null = null+ constructor(readonly url: string) {+ super()+ FakeSocket.instances.push(this)+ }+ close(code?: number, reason?: string) {+ this.closed = { code, reason }+ }+ frame(frame: unknown) {+ this.dispatchEvent(+ Object.assign(new Event('message'), { data: JSON.stringify(frame) }),+ )+ }+ raw(data: string) {+ this.dispatchEvent(Object.assign(new Event('message'), { data }))+ }+ drop() {+ this.dispatchEvent(new Event('close'))+ }+}++const Socket = FakeSocket as unknown as new (url: string) => WebSocket++function event(seq: number, type = 'message.delta'): ManagedAgentEvent {+ return { seq, type, data: { text: String(seq) } }+}++const tick = () => new Promise<void>((resolve) => setTimeout(resolve, 0))+const noSleep = tick++beforeEach(() => {+ vi.stubGlobal('location', { protocol: 'https:', host: 'app.test' })+})++afterEach(() => {+ vi.unstubAllGlobals()+ FakeSocket.instances = []+})++describe('ManagedAgentEventStream', () => {+ it('yields socket events in order and drops replays at or below the cursor', async () => {+ const fetchEvents = vi.fn()+ const stream = new ManagedAgentEventStream('s1', 2, {+ fetchEvents,+ webSocket: Socket,+ sleep: noSleep,+ })+ const socket = FakeSocket.instances[0]+ expect(socket.url).toBe(+ 'wss://app.test/api/dashboard/managed-agents/sessions/s1/connect?role=client&cursor=2',+ )+ socket.frame({ type: 'ready', sessionId: 's1', cursor: 2 })+ socket.raw('not json')+ socket.frame({ type: 'event', event: event(2) })+ socket.frame({ type: 'event', event: event(3) })+ socket.frame({ type: 'pong' })+ const next = stream.next(1_000)+ socket.frame({ type: 'event', event: event(4) })++ expect((await next).seq).toBe(3)+ expect((await stream.next(1_000)).seq).toBe(4)+ expect(stream.position).toBe(4)+ expect(fetchEvents).not.toHaveBeenCalled()++ stream.close()+ expect(socket.closed).toEqual({ code: 1000, reason: 'done' })+ })++ it('reconnects from the last cursor when a live socket drops', async () => {+ const stream = new ManagedAgentEventStream('s1', 0, {+ fetchEvents: vi.fn(),+ webSocket: Socket,+ sleep: noSleep,+ })+ const first = FakeSocket.instances[0]+ first.frame({ type: 'ready', sessionId: 's1', cursor: 0 })+ first.frame({ type: 'event', event: event(1) })+ first.drop()+ await tick()+ await tick()++ const second = FakeSocket.instances[1]+ expect(second.url).toBe(managedAgentSocketUrl('s1', 1))+ second.frame({ type: 'ready', sessionId: 's1', cursor: 1 })+ second.frame({ type: 'event', event: event(1) })+ second.frame({ type: 'event', event: event(2) })++ expect((await stream.next(1_000)).seq).toBe(1)+ expect((await stream.next(1_000)).seq).toBe(2)+ stream.close()+ })++ it('falls back to polling when the socket never becomes ready', async () => {+ const pages = new Map([+ [0, [event(1), event(2)]],+ [2, []],+ [3, [event(3)]],+ ])+ const fetchEvents = vi.fn((_sessionId: string, after: number) => {+ const page = pages.get(after) ?? []+ pages.set(after, [])+ if (after === 2) pages.set(3, pages.get(3) ?? [])+ return Promise.resolve(page)+ })+ const stream = new ManagedAgentEventStream('s1', 0, {+ fetchEvents,+ webSocket: Socket,+ sleep: noSleep,+ })+ FakeSocket.instances[0].dispatchEvent(new Event('error'))++ expect((await stream.next(1_000)).seq).toBe(1)+ expect((await stream.next(1_000)).seq).toBe(2)+ expect(FakeSocket.instances).toHaveLength(1)+ expect(fetchEvents.mock.calls[0]).toEqual(['s1', 0])+ stream.close()+ })++ it('polls directly when WebSockets are unavailable', async () => {+ const fetchEvents = vi+ .fn<(sessionId: string, after: number) => Promise<ManagedAgentEvent[]>>()+ .mockResolvedValueOnce([event(1)])+ .mockResolvedValue([])+ const stream = new ManagedAgentEventStream('s1', 0, {+ fetchEvents,+ webSocket: null,+ sleep: noSleep,+ })+ expect((await stream.next(1_000)).seq).toBe(1)+ stream.close()+ })++ it('times out when nothing arrives within the inactivity window', async () => {+ vi.useFakeTimers()+ try {+ const stream = new ManagedAgentEventStream('s1', 0, {+ fetchEvents: vi.fn(),+ webSocket: Socket,+ sleep: noSleep,+ })+ const pending = stream.next(500)+ vi.advanceTimersByTime(500)+ await expect(pending).rejects.toBeInstanceOf(+ ManagedAgentEventStreamTimeout,+ )+ stream.close()+ } finally {+ vi.useRealTimers()+ }+ })++ it('rejects pending reads and closes the socket when aborted', async () => {+ const controller = new AbortController()+ const stream = new ManagedAgentEventStream('s1', 0, {+ fetchEvents: vi.fn(),+ webSocket: Socket,+ sleep: noSleep,+ signal: controller.signal,+ })+ const pending = stream.next(1_000)+ controller.abort()+ await expect(pending).rejects.toMatchObject({ name: 'AbortError' })+ expect(FakeSocket.instances[0].closed?.code).toBe(1000)+ })+})diff --git a/web/src/managed-agents/live-events.ts b/web/src/managed-agents/live-events.tsnew file mode 100644index 00000000..ecc01d3e--- /dev/null+++ b/web/src/managed-agents/live-events.ts@@ -0,0 +1,216 @@+import { z } from 'zod'+import { managedAgentEventSchema, type ManagedAgentEvent } from './events'++const frameSchema = z.discriminatedUnion('type', [+ z.object({ type: z.literal('ready'), sessionId: z.string(), cursor: z.number() }),+ z.object({ type: z.literal('event'), event: managedAgentEventSchema }),+ z.object({ type: z.literal('pong') }),+ z.object({ type: z.literal('error'), code: z.string(), message: z.string() }),+])++export type ManagedAgentEventStreamOptions = {+ /** REST fallback used when the WebSocket relay is unavailable. */+ fetchEvents: (sessionId: string, after: number) => Promise<ManagedAgentEvent[]>+ signal?: AbortSignal+ /** Delay between REST polls when the WebSocket path is unavailable. */+ pollIntervalMs?: number+ /** WebSocket reconnect attempts before falling back to polling for good. */+ maxSocketReconnects?: number+ /** Override the WebSocket constructor (tests). `null` disables sockets. */+ webSocket?: (new (url: string) => WebSocket) | null+ sleep?: (ms: number) => Promise<void>+}++export function managedAgentSocketUrl(+ sessionId: string,+ cursor: number,+ location: { protocol: string; host: string } = globalThis.location,+) {+ const proto = location.protocol === 'https:' ? 'wss:' : 'ws:'+ return `${proto}//${location.host}/api/dashboard/managed-agents/sessions/${encodeURIComponent(sessionId)}/connect?role=client&cursor=${cursor}`+}++export class ManagedAgentEventStreamTimeout extends Error {+ constructor() {+ super('Timed out waiting for the agent.')+ this.name = 'ManagedAgentEventStreamTimeout'+ }+}++/**+ * Ordered, de-duplicated feed of a session's events starting after `after`.+ *+ * Prefers the edge WebSocket relay (events arrive the moment the runtime+ * emits them); falls back to REST polling when sockets can't be established.+ * Either way `next()` yields one event at a time in `seq` order.+ */+export class ManagedAgentEventStream {+ private cursor: number+ private readonly queue: ManagedAgentEvent[] = []+ private waiter: {+ resolve: (event: ManagedAgentEvent) => void+ reject: (error: Error) => void+ } | null = null+ private failure: Error | null = null+ private closed = false+ private socket: WebSocket | null = null+ private readonly onAbort = () =>+ this.fail(new DOMException('Aborted', 'AbortError'))++ constructor(+ private readonly sessionId: string,+ after: number,+ private readonly options: ManagedAgentEventStreamOptions,+ ) {+ this.cursor = after+ options.signal?.addEventListener('abort', this.onAbort, { once: true })+ if (options.signal?.aborted) this.onAbort()+ else void this.run()+ }++ /** Highest `seq` delivered so far. */+ get position() {+ return this.cursor+ }++ next(timeoutMs: number): Promise<ManagedAgentEvent> {+ const queued = this.queue.shift()+ if (queued) return Promise.resolve(queued)+ if (this.failure) return Promise.reject(this.failure)+ if (this.closed) return Promise.reject(new Error('Event stream closed.'))+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ this.waiter = null+ reject(new ManagedAgentEventStreamTimeout())+ }, timeoutMs)+ this.waiter = {+ resolve: (event) => {+ clearTimeout(timer)+ resolve(event)+ },+ reject: (error) => {+ clearTimeout(timer)+ reject(error)+ },+ }+ })+ }++ close() {+ if (this.closed) return+ this.closed = true+ this.options.signal?.removeEventListener('abort', this.onAbort)+ this.socket?.close(1000, 'done')+ this.socket = null+ this.waiter?.reject(new Error('Event stream closed.'))+ this.waiter = null+ }++ private fail(reason: unknown) {+ if (this.closed) return+ const error =+ reason instanceof Error ? reason : new Error(String(reason))+ this.failure = error+ const waiter = this.waiter+ this.waiter = null+ this.close()+ waiter?.reject(error)+ }++ private deliver(event: ManagedAgentEvent) {+ if (this.closed || event.seq <= this.cursor) return+ this.cursor = event.seq+ if (this.waiter) {+ const waiter = this.waiter+ this.waiter = null+ waiter.resolve(event)+ } else {+ this.queue.push(event)+ }+ }++ private async run() {+ const Socket =+ this.options.webSocket === undefined+ ? typeof WebSocket === 'undefined'+ ? null+ : WebSocket+ : this.options.webSocket+ const maxReconnects = this.options.maxSocketReconnects ?? 3+ let attempts = 0+ while (Socket && !this.closed && attempts <= maxReconnects) {+ const outcome = await this.runSocket(Socket)+ if (this.closed) return+ if (outcome === 'unavailable') break+ attempts += 1+ await this.pause(Math.min(250 * 2 ** attempts, 2_000))+ }+ if (!this.closed) await this.runPolling()+ }++ private runSocket(+ Socket: new (url: string) => WebSocket,+ ): Promise<'unavailable' | 'dropped'> {+ return new Promise((resolve) => {+ let ready = false+ let settled = false+ const settle = (outcome: 'unavailable' | 'dropped') => {+ if (settled) return+ settled = true+ if (this.socket === socket) this.socket = null+ resolve(outcome)+ }+ let socket: WebSocket+ try {+ socket = new Socket(managedAgentSocketUrl(this.sessionId, this.cursor))+ } catch {+ resolve('unavailable')+ return+ }+ this.socket = socket+ socket.addEventListener('message', (message) => {+ if (typeof message.data !== 'string') return+ let parsed: unknown+ try {+ parsed = JSON.parse(message.data)+ } catch {+ return+ }+ const frame = frameSchema.safeParse(parsed)+ if (!frame.success) return+ if (frame.data.type === 'ready') ready = true+ else if (frame.data.type === 'event') this.deliver(frame.data.event)+ })+ socket.addEventListener('close', () =>+ settle(ready ? 'dropped' : 'unavailable'),+ )+ socket.addEventListener('error', () =>+ settle(ready ? 'dropped' : 'unavailable'),+ )+ })+ }++ private async runPolling() {+ const { fetchEvents } = this.options+ const interval = this.options.pollIntervalMs ?? 300+ while (!this.closed) {+ try {+ const events = await fetchEvents(this.sessionId, this.cursor)+ for (const event of events) this.deliver(event)+ } catch (error) {+ if (this.options.signal?.aborted) return+ this.fail(error)+ return+ }+ await this.pause(interval)+ }+ }++ private pause(ms: number) {+ return (this.options.sleep ?? defaultSleep)(ms)+ }+}++function defaultSleep(ms: number) {+ return new Promise<void>((resolve) => setTimeout(resolve, ms))+}diff --git a/web/src/managed-agents/use-live-session-events.test.ts b/web/src/managed-agents/use-live-session-events.test.tsnew file mode 100644index 00000000..3fd48259--- /dev/null+++ b/web/src/managed-agents/use-live-session-events.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest'+import { mergeManagedAgentEvents } from './use-live-session-events'+import type { ManagedAgentEvent } from './events'++const ev = (seq: number): ManagedAgentEvent => ({+ seq,+ type: 'message.delta',+ data: { text: String(seq) },+})++describe('mergeManagedAgentEvents', () => {+ it('appends new events in seq order and drops duplicates', () => {+ const base = [ev(1), ev(2), ev(3)]+ expect(+ mergeManagedAgentEvents(base, [ev(2), ev(5), ev(4)]).map((e) => e.seq),+ ).toEqual([1, 2, 3, 4, 5])+ })++ it('returns the base array untouched when nothing is new', () => {+ const base = [ev(1), ev(2)]+ expect(mergeManagedAgentEvents(base, [ev(1)])).toBe(base)+ expect(mergeManagedAgentEvents(base, [])).toBe(base)+ })++ it('returns the live list when there is no history yet', () => {+ const live = [ev(7)]+ expect(mergeManagedAgentEvents([], live)).toBe(live)+ })+})diff --git a/web/src/managed-agents/use-live-session-events.ts b/web/src/managed-agents/use-live-session-events.tsnew file mode 100644index 00000000..261da455--- /dev/null+++ b/web/src/managed-agents/use-live-session-events.ts@@ -0,0 +1,90 @@+import { useEffect, useMemo, useRef, useState } from 'react'+import { openManagedAgentEventStream } from './api'+import type { ManagedAgentEvent } from './events'++const NEXT_TIMEOUT_MS = 60 * 60 * 1_000+const FLUSH_MS = 40++/** Union of two seq-ordered event lists, de-duplicated by `seq`. */+export function mergeManagedAgentEvents(+ base: ManagedAgentEvent[],+ extra: ManagedAgentEvent[],+): ManagedAgentEvent[] {+ if (extra.length === 0) return base+ if (base.length === 0) return extra+ const seen = new Set(base.map((event) => event.seq))+ const added = extra.filter((event) => !seen.has(event.seq))+ if (added.length === 0) return base+ return [...base, ...added].sort((a, b) => a.seq - b.seq)+}++/**+ * Overlays live session events on top of a fetched history while `active`.+ * Events are pushed the moment they arrive (WebSocket, polling fallback) and+ * coalesced into ~25fps state updates so the inspector re-renders smoothly.+ */+export function useLiveSessionEvents(+ sessionId: string | undefined,+ history: ManagedAgentEvent[] | undefined,+ active: boolean,+) {+ const [live, setLive] = useState<{+ sessionId: string | undefined+ events: ManagedAgentEvent[]+ }>({ sessionId, events: [] })++ const historyRef = useRef(history)+ useEffect(() => {+ historyRef.current = history+ }, [history])++ useEffect(() => {+ if (!sessionId || !active) return+ const known = historyRef.current+ const stream = openManagedAgentEventStream(+ sessionId,+ known?.[known.length - 1]?.seq ?? 0,+ )+ let buffer: ManagedAgentEvent[] = []+ let flushTimer: ReturnType<typeof setTimeout> | null = null+ let stopped = false++ const flush = () => {+ flushTimer = null+ if (buffer.length === 0) return+ const batch = buffer+ buffer = []+ setLive((prev) =>+ prev.sessionId === sessionId+ ? { sessionId, events: mergeManagedAgentEvents(prev.events, batch) }+ : { sessionId, events: batch },+ )+ }+ const pump = async () => {+ try {+ while (!stopped) {+ buffer.push(await stream.next(NEXT_TIMEOUT_MS))+ flushTimer ??= setTimeout(flush, FLUSH_MS)+ }+ } catch {+ // Stream closed (unmount, session change) or failed; the fetched+ // history remains the source of truth.+ }+ }+ void pump()+ return () => {+ stopped = true+ if (flushTimer) clearTimeout(flushTimer)+ stream.close()+ }+ }, [sessionId, active])++ return useMemo(+ () =>+ mergeManagedAgentEvents(+ history ?? [],+ live.sessionId === sessionId ? live.events : [],+ ),+ [history, live, sessionId],+ )+}diff --git a/web/vite.config.ts b/web/vite.config.tsindex 0cb85b25..70556942 100644--- a/web/vite.config.ts+++ b/web/vite.config.ts@@ -39,14 +39,13 @@ const managedAgentsProxy: Record<string, ProxyOptions> = managedAgentsToken'/api/dashboard/managed-agents': {target: managedAgentsTarget,changeOrigin: true,+ ws: true,rewrite: (p) => p.replace(/^\/api\/dashboard\/managed-agents/, '/v1'),configure: (proxy) => {- proxy.on('proxyReq', (proxyReq) => {- proxyReq.setHeader(- 'x-opencomputer-agent-token',- managedAgentsToken,- )- })+ const inject = (proxyReq: { setHeader(k: string, v: string): void }) =>+ proxyReq.setHeader('x-opencomputer-agent-token', managedAgentsToken)+ proxy.on('proxyReq', inject)+ proxy.on('proxyReqWs', inject)},},}