Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(inspector): bound live runtime history during long turns
agooll316473cc2e1f
diff --git a/docs/verification/evidence/inspector-window/after.png b/docs/verification/evidence/inspector-window/after.pngnew file mode 100644index 0000000000..be904da75fBinary files /dev/null and b/docs/verification/evidence/inspector-window/after.png differdiff --git a/docs/verification/evidence/inspector-window/before.png b/docs/verification/evidence/inspector-window/before.pngnew file mode 100644index 0000000000..6d8f3841a9Binary files /dev/null and b/docs/verification/evidence/inspector-window/before.png differdiff --git a/src/components/InspectorPanel.tsx b/src/components/InspectorPanel.tsxindex 731b1aaacc..7f1fc6bf96 100644--- a/src/components/InspectorPanel.tsx+++ b/src/components/InspectorPanel.tsx@@ -3,7 +3,7 @@ import { Bug, ChevronDown, ChevronRight, RefreshCw, X } from "lucide-react";import { useStore, visibleMessages, type Bot } from "@/state/store";import { cn } from "@/lib/cn";import { useCaptionChrome } from "@/components/DesktopCapabilities";-import { formatTime, toRows, type InspectorEntry, type InspectorPage, type InspectorRow } from "@/lib/inspector";+import { formatTime, toRows, type InspectorPage, type InspectorRow } from "@/lib/inspector";import { listenLiveFrames } from "@/lib/live-events";import type { RuntimeEvent } from "../../shared/runtime-events";import { RunLog } from "./RunLog";@@ -11,6 +11,7 @@ import { timelineEvents } from "@/lib/taskTimeline";import { activeLocale, t } from "@/lib/i18n";import { capital } from "@/lib/automations";import type { LocaleKey } from "@/locales";+import { appendInspectorRuntime, boundInspectorEntries, INSPECTOR_WINDOW_LIMIT } from "@/lib/inspector-window";const tabLabel = (key: LocaleKey) => (activeLocale() === "en" ? t(key) : capital(t(key)));@@ -35,12 +36,12 @@ export function InspectorPanel({ bot }: { bot: Bot }) {const controller = new AbortController();loadAbort.current = controller;try {- const res = await fetch(`/api/threads/${threadId}/events?limit=400`, { signal: controller.signal });+ const res = await fetch(`/api/threads/${threadId}/events?limit=${INSPECTOR_WINDOW_LIMIT}`, { signal: controller.signal });if (!res.ok) throw new Error(`${res.status}`);// SAFETY: the same-version harness's typed inspector endpoint; malformed transport data is handled by catch.const next = (await res.json()) as InspectorPage;if (controller.signal.aborted) return;- setPage(next);+ setPage({ ...next, entries: boundInspectorEntries(next.entries) });setError(null);} catch (e) {if (controller.signal.aborted) return;@@ -64,21 +65,20 @@ export function InspectorPanel({ bot }: { bot: Bot }) {let refreshGeneration = 0;let refreshing = false;const pendingRuntime: RuntimeEvent[] = [];+ let batch: RuntimeEvent[] = [];+ let batchTimer: ReturnType<typeof setTimeout> | null = null;+ const flushBatch = () => {+ if (batchTimer) clearTimeout(batchTimer);+ batchTimer = null;+ const events = batch;+ batch = [];+ if (events.length) setPage((prev) => appendInspectorRuntime(prev, events));+ };const appendRuntime = (runtime: RuntimeEvent) => {- setPage((prev) => {- // eventId is canonical, so a replayed entry already in the snapshot is a no-op.- if (- prev?.entries.some(- (entry) => entry.kind === "runtime" && entry.data.eventId === runtime.eventId,- )- ) {- return prev;- }- const entry: InspectorEntry = { kind: "runtime", at: runtime.createdAt, data: runtime };- if (!prev) return { entries: [entry], total: { runtime: 1, native: 0 } };- return { entries: [...prev.entries, entry], total: { ...prev.total, runtime: prev.total.runtime + 1 } };- });+ batch.push(runtime);+ if (batch.length >= INSPECTOR_WINDOW_LIMIT) flushBatch();+ else batchTimer ??= setTimeout(flushBatch, 16);};const flushPendingRuntime = () => {@@ -86,6 +86,7 @@ export function InspectorPanel({ bot }: { bot: Bot }) {};const refresh = async () => {+ flushBatch();const generation = ++refreshGeneration;refreshing = true;await load();@@ -116,6 +117,8 @@ export function InspectorPanel({ bot }: { bot: Bot }) {if (managedRefresh.current === requestRefresh) managedRefresh.current = () => {};stopLive();if (settle) clearTimeout(settle);+ if (batchTimer) clearTimeout(batchTimer);+ batch = [];};}, [threadId, load]);@@ -125,10 +128,19 @@ export function InspectorPanel({ bot }: { bot: Bot }) {);const rows = useMemo(() => toRows(entries), [entries]);+ useEffect(() => {+ const retained = new Set(["runtime", "native"].flatMap((kind) =>+ toRows(page?.entries.filter((entry) => entry.kind === kind) ?? []).map((row) => row.key)));+ setExpanded((previous) => {+ const next = new Set([...previous].filter((key) => retained.has(key)));+ return next.size === previous.size ? previous : next;+ });+ }, [page]);+useEffect(() => {const el = listRef.current;if (el && stickToBottom.current) el.scrollTop = el.scrollHeight;- }, [page?.entries.length, rows.length, lens]);+ }, [page, rows.length, lens]);const onScroll = () => {const el = listRef.current;if (!el) return;diff --git a/src/components/live-panels.test.ts b/src/components/live-panels.test.tsindex d86618cdd4..6624b63c52 100644--- a/src/components/live-panels.test.ts+++ b/src/components/live-panels.test.ts@@ -70,6 +70,34 @@ afterEach(() => {});describe("Inspector on the app's live stream", () => {+ it("keeps only the newest 400 runtime entries during a long turn, with its total and raw snapshot", async () => {+ vi.stubGlobal("fetch", () => Promise.resolve(new Response(JSON.stringify({+ entries: [{ kind: "native", at: "2026-10-04T09:00:00.000Z", data: { at: "2026-10-04T09:00:00.000Z", dir: "out", source: "fixture", msg: { type: "raw retained" } } }],+ total: { runtime: 700, native: 12 },+ }))));+ await mount(InspectorPanel);+ const events = [...document.querySelectorAll<HTMLButtonElement>('[role="tab"]')].find((tab) => tab.textContent === "events")!;+ flushSync(() => events.click());+ flushSync(() => {+ for (let i = 0; i < 1_000; i++) frame(runtime(`bounded-${i}`, { type: "item.started", itemType: "tool", title: `long step ${i}` }));+ });+ await vi.waitFor(() => expect(document.body.textContent).toContain("long step 999"));+ expect(document.body.textContent).not.toContain("long step 599");+ expect(document.body.textContent).toContain("long step 600");+ expect(document.body.textContent).toContain("1700");+ expect(document.querySelectorAll('button .tabular-nums')).toHaveLength(400);+ flushSync(() => {+ frame(runtime("bounded-999", { type: "item.started", itemType: "tool", title: "duplicated tail" }));+ frame(runtime("bounded-1000", { type: "item.started", itemType: "tool", title: "next batch" }));+ });+ await vi.waitFor(() => expect(document.body.textContent).toContain("next batch"));+ expect(document.body.textContent).not.toContain("duplicated tail");+ expect(document.body.textContent).toContain("1701");+ const raw = [...document.querySelectorAll<HTMLButtonElement>('[role="tab"]')].find((tab) => tab.textContent === "raw")!;+ flushSync(() => raw.click());+ expect(document.body.textContent).toContain("raw retained");+ });+it("shows this thread's runtime events and opens no stream of its own", async () => {await mount(InspectorPanel);const events = [...document.querySelectorAll<HTMLButtonElement>('[role="tab"]')].find((tab) => tab.textContent === "events")!;@@ -78,12 +106,40 @@ describe("Inspector on the app's live stream", () => {frame(runtime("e1", { type: "item.started", itemType: "tool", title: "List the files" }));frame(runtime("e2", { type: "item.started", itemType: "tool", title: "Somebody else's step" }, "other-thread"));});- await settle();- expect(document.body.textContent).toContain("tool: List the files");+ await vi.waitFor(() => expect(document.body.textContent).toContain("tool: List the files"));expect(document.body.textContent).not.toContain("Somebody else's step");expect(opened).not.toHaveBeenCalled();});+ it("merges events received during a reload once and keeps the new live tail", async () => {+ await mount(InspectorPanel);+ const events = [...document.querySelectorAll<HTMLButtonElement>('[role="tab"]')].find((tab) => tab.textContent === "events")!;+ flushSync(() => events.click());+ let finish!: (response: Response) => void;+ vi.stubGlobal("fetch", () => new Promise<Response>((resolve) => { finish = resolve; }));+ missed();+ frame(runtime("overlap", { type: "item.started", itemType: "tool", title: "in both sources" }));+ frame(runtime("tail", { type: "item.started", itemType: "tool", title: "after snapshot" }));+ finish(new Response(JSON.stringify({+ entries: [{ kind: "runtime", at: "2026-10-04T09:00:00.000Z", data: runtime("overlap", { type: "item.started", itemType: "tool", title: "in both sources" }) }],+ total: { runtime: 70, native: 0 },+ })));+ await vi.waitFor(() => expect(document.body.textContent).toContain("after snapshot"));+ expect(document.querySelectorAll('button .tabular-nums')).toHaveLength(2);+ expect(document.body.textContent).toContain("71");+ });++ it("cancels the old thread's queued batch when switching conversations", async () => {+ const render = await mount(InspectorPanel);+ frame(runtime("old", { type: "item.started", itemType: "tool", title: "old queued work" }));+ render({ ...bot, threadId: "next-thread" });+ const events = [...document.querySelectorAll<HTMLButtonElement>('[role="tab"]')].find((tab) => tab.textContent === "events")!;+ flushSync(() => events.click());+ frame(runtime("next", { type: "item.started", itemType: "tool", title: "next thread work" }, "next-thread"));+ await vi.waitFor(() => expect(document.body.textContent).toContain("next thread work"));+ expect(document.body.textContent).not.toContain("old queued work");+ });+it("reloads from disk when the stream missed frames it could not replay", async () => {await mount(InspectorPanel);expect(fetched).toEqual(["/api/threads/thread/events?limit=400"]);diff --git a/src/lib/inspector-window.test.ts b/src/lib/inspector-window.test.tsnew file mode 100644index 0000000000..33257721f9--- /dev/null+++ b/src/lib/inspector-window.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from "vitest";+import type { RuntimeEvent } from "../../shared/runtime-events";+import type { InspectorEntry, InspectorPage } from "../../shared/inspector";+import { appendInspectorRuntime, boundInspectorEntries } from "./inspector-window";++const event = (i: number): RuntimeEvent => ({+ eventId: `e${i}`, provider: "fixture", threadId: "t", createdAt: String(i), type: "turn.started",+});+const entry = (i: number): InspectorEntry => ({ kind: "runtime", at: String(i), data: event(i) });++describe("Inspector's recent event window", () => {+ it("bounds each log separately while keeping the original interleaving and totals", () => {+ const entries: InspectorEntry[] = [];+ for (let i = 0; i < 500; i++) {+ entries.push(entry(i), { kind: "native", at: String(i), data: { at: String(i), dir: "out", source: "fixture", msg: i } });+ }+ const kept = boundInspectorEntries(entries);+ expect(kept).toEqual(entries.slice(200));+ expect(entries).toHaveLength(1_000);+ expect(boundInspectorEntries(kept)).toBe(kept);+ });++ it("keeps its last 400 events over 10,000 arrivals without resetting the total", () => {+ let page: InspectorPage | null = null;+ for (let start = 0; start < 10_000; start += 200) {+ page = appendInspectorRuntime(page, Array.from({ length: 200 }, (_, i) => event(start + i)));+ expect(page!.entries.length).toBeLessThanOrEqual(400);+ }+ expect(page!.total).toEqual({ runtime: 10_000, native: 0 });+ expect(page!.entries).toEqual(Array.from({ length: 400 }, (_, i) => entry(9_600 + i)));+ });++ it("deduplicates the snapshot and the current batch without mutating published pages", () => {+ const page: InspectorPage = { entries: [entry(1)], total: { runtime: 40, native: 12 } };+ expect(appendInspectorRuntime(page, [event(1)])).toBe(page);+ const next = appendInspectorRuntime(page, [event(1), event(2), event(2)])!;+ expect(next.entries).toEqual([entry(1), entry(2)]);+ expect(next.total).toEqual({ runtime: 41, native: 12 });+ expect(page).toEqual({ entries: [entry(1)], total: { runtime: 40, native: 12 } });+ expect(appendInspectorRuntime(null, [])).toBeNull();+ });+});diff --git a/src/lib/inspector-window.ts b/src/lib/inspector-window.tsnew file mode 100644index 0000000000..e3fe54b49b--- /dev/null+++ b/src/lib/inspector-window.ts@@ -0,0 +1,31 @@+import type { RuntimeEvent } from "../../shared/runtime-events";+import type { InspectorEntry, InspectorPage } from "../../shared/inspector";++export const INSPECTOR_WINDOW_LIMIT = 400;++export function boundInspectorEntries(entries: InspectorEntry[]): InspectorEntry[] {+ const counts = { runtime: 0, native: 0 };+ const kept: InspectorEntry[] = [];+ for (let i = entries.length - 1; i >= 0; i--) {+ const entry = entries[i];+ if (++counts[entry.kind] <= INSPECTOR_WINDOW_LIMIT) kept.push(entry);+ }+ return kept.length === entries.length ? entries : kept.reverse();+}++export function appendInspectorRuntime(page: InspectorPage | null, events: RuntimeEvent[]): InspectorPage | null {+ if (!events.length) return page;+ const previous = page ?? { entries: [], total: { runtime: 0, native: 0 } };+ const seen = new Set(previous.entries.flatMap((entry) => entry.kind === "runtime" ? [entry.data.eventId] : []));+ const added: InspectorEntry[] = [];+ for (const event of events) {+ if (seen.has(event.eventId)) continue;+ seen.add(event.eventId);+ added.push({ kind: "runtime", at: event.createdAt, data: event });+ }+ if (!added.length) return page;+ return {+ entries: boundInspectorEntries([...previous.entries, ...added]),+ total: { ...previous.total, runtime: previous.total.runtime + added.length },+ };+}