Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ import { RepeatDetector, callKey } from "./repeat-detector.ts";
import { RoutineManager, type RoutineRunOn, type RoutineRunTrigger } from "./routines.ts";
import { fetchGithubTeam, fetchLibraryTeam, fetchTeamCatalog } from "./team-library.ts";
import { createTeamManifest, parseTeamManifest } from "./team-manifest.ts";
import { readThreadEvents } from "./thread-events.ts";
import { listenWebhookIngress, webhookCredential, type WebhookIngress } from "./webhook-ingress.ts";
import { memberTurnSelection } from "./member-turn.ts";
import { WebhookManager } from "./webhooks.ts";
Expand Down Expand Up @@ -2850,6 +2851,20 @@ const server = createServer(async (req, res) => {
return json(res, 200, { app: "openmausbot", pid: process.pid, static: Boolean(STATIC_DIR) });
}

// ── inspector: a thread's runtime events + native protocol tee ──
// Both logs already exist on disk; this only reads them back. Threads
// belong to bots or rooms — anything else is not a thread we know.
m = path.match(/^\/api\/threads\/([\w-]+)\/events$/);
if (m && method === "GET") {
const threadId = m[1];
const known =
store.bots.some((b) => store.tasks(b.id).some((t) => t.threadId === threadId)) ||
Boolean(store.groupByThread(threadId));
if (!known) return json(res, 404, { error: "no such thread" });
const limit = Number(url.searchParams.get("limit")) || undefined;
return json(res, 200, readThreadEvents({ eventsDir: EVENTS_DIR, nativeDir: NATIVE_DIR, threadId, limit }));
}

// ── provider instances (model picker) ──
if (method === "GET" && path === "/api/instances") {
// Rescan PATH first: this endpoint is how the app answers "what can I
Expand Down
86 changes: 86 additions & 0 deletions server/thread-events.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";

import { readThreadEvents } from "./thread-events.ts";

const dirs: string[] = [];
function tmp() {
const d = mkdtempSync(join(tmpdir(), "omb-thread-events-"));
dirs.push(d);
return d;
}
afterEach(() => {
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});

const line = (o: unknown) => JSON.stringify(o) + "\n";

describe("readThreadEvents", () => {
it("returns an empty page when neither log exists", () => {
const eventsDir = tmp();
const nativeDir = tmp();
expect(readThreadEvents({ eventsDir, nativeDir, threadId: "t1" })).toEqual({
entries: [],
total: { runtime: 0, native: 0 },
});
});

it("merges runtime and native lines by time, tagging their source", () => {
const eventsDir = tmp();
const nativeDir = tmp();
writeFileSync(
join(eventsDir, "t1.ndjson"),
line({ eventId: "e1", type: "turn.started", threadId: "t1", createdAt: "2026-08-17T10:00:00.000Z" }) +
line({ eventId: "e2", type: "turn.completed", threadId: "t1", createdAt: "2026-08-17T10:00:02.000Z", ok: true }),
);
writeFileSync(
join(nativeDir, "t1.ndjson"),
line({ at: "2026-08-17T10:00:01.000Z", dir: "out", source: "claude.sdk.message", msg: { type: "user" } }),
);
const page = readThreadEvents({ eventsDir, nativeDir, threadId: "t1" });
expect(page.total).toEqual({ runtime: 2, native: 1 });
expect(page.entries.map((e) => [e.kind, e.at])).toEqual([
["runtime", "2026-08-17T10:00:00.000Z"],
["native", "2026-08-17T10:00:01.000Z"],
["runtime", "2026-08-17T10:00:02.000Z"],
]);
// each entry keeps its original record whole under `data`
expect(page.entries[1]).toMatchObject({ kind: "native", data: { dir: "out", msg: { type: "user" } } });
expect(page.entries[0]).toMatchObject({ kind: "runtime", data: { eventId: "e1" } });
});

it("caps each log to its most recent `limit` lines and reports what it skipped", () => {
const eventsDir = tmp();
const nativeDir = tmp();
let body = "";
for (let i = 0; i < 10; i++) {
body += line({ eventId: `e${i}`, type: "content.delta", threadId: "t1", createdAt: `2026-08-17T10:00:${String(i).padStart(2, "0")}.000Z` });
}
writeFileSync(join(eventsDir, "t1.ndjson"), body);
const page = readThreadEvents({ eventsDir, nativeDir, threadId: "t1", limit: 3 });
expect(page.entries.map((e) => (e.data as { eventId: string }).eventId)).toEqual(["e7", "e8", "e9"]);
expect(page.total.runtime).toBe(10);
});

it("skips a corrupt line rather than failing the whole read", () => {
const eventsDir = tmp();
const nativeDir = tmp();
writeFileSync(
join(eventsDir, "t1.ndjson"),
line({ eventId: "e1", type: "turn.started", threadId: "t1", createdAt: "2026-08-17T10:00:00.000Z" }) +
"{not json\n" +
line({ eventId: "e2", type: "turn.completed", threadId: "t1", createdAt: "2026-08-17T10:00:02.000Z", ok: true }),
);
const page = readThreadEvents({ eventsDir, nativeDir, threadId: "t1" });
expect(page.entries).toHaveLength(2);
expect(page.total.runtime).toBe(2);
});

it("refuses a thread id that could escape the log directory", () => {
const eventsDir = tmp();
const nativeDir = tmp();
expect(() => readThreadEvents({ eventsDir, nativeDir, threadId: "../bots" })).toThrow(/thread id/);
});
});
89 changes: 89 additions & 0 deletions server/thread-events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// The inspector's data: what a thread's turn actually looked like on the
// wire. Nothing new is captured here — the harness already tees two logs
// per thread, and this just reads them back:
//
// events/<threadId>.ndjson — the normalized RuntimeEvent stream the bus
// publishes (server/harness/bus.ts)
// native/<threadId>.ndjson — the provider's own protocol messages,
// verbatim and secret-redacted
// (server/drivers/native.ts)
//
// Merged by timestamp so a tool call and the raw message behind it sit
// next to each other. Newest-`limit` only: a long-lived thread has
// thousands of native lines and the panel wants the recent ones first.
import { readFileSync } from "node:fs";
import { join } from "node:path";

export type InspectorEntry =
| { kind: "runtime"; at: string; data: unknown }
| { kind: "native"; at: string; data: unknown };

export interface InspectorPage {
entries: InspectorEntry[];
/** line counts before the cap, so the UI can say "showing 200 of 1,687" */
total: { runtime: number; native: number };
}

const DEFAULT_LIMIT = 300;
const MAX_LIMIT = 2000;

/** Thread ids are uuids the harness minted; anything else is not a file we
* should be reading. */
function assertThreadId(threadId: string) {
if (!/^[\w-]+$/.test(threadId)) throw new Error("invalid thread id");
}

function readLines(file: string): unknown[] {
let text: string;
try {
text = readFileSync(file, "utf8");
} catch {
return [];
}
const out: unknown[] = [];
for (const raw of text.split("\n")) {
if (!raw) continue;
try {
out.push(JSON.parse(raw));
} catch {
// a torn last line during a write, or a hand-edited file — the rest
// of the log is still worth showing
}
}
return out;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated

const timeOf = (value: unknown, key: "createdAt" | "at"): string => {
const record = value as Record<string, unknown> | null;
const at = record?.[key];
return typeof at === "string" ? at : "";
};

export function readThreadEvents(input: {
eventsDir: string;
nativeDir: string;
threadId: string;
limit?: number;
}): InspectorPage {
const { eventsDir, nativeDir, threadId } = input;
assertThreadId(threadId);
const limit = Math.max(1, Math.min(input.limit ?? DEFAULT_LIMIT, MAX_LIMIT));

const runtime = readLines(join(eventsDir, `${threadId}.ndjson`));
const native = readLines(join(nativeDir, `${threadId}.ndjson`));

// cap each log on its own, then merge: the native tee is several times
// chattier than the runtime stream, and one shared cap would leave the
// Events lens with a handful of rows behind hundreds of raw ones
const merged: InspectorEntry[] = [
...runtime.slice(-limit).map((data): InspectorEntry => ({ kind: "runtime", at: timeOf(data, "createdAt"), data })),
...native.slice(-limit).map((data): InspectorEntry => ({ kind: "native", at: timeOf(data, "at"), data })),
];
// stable sort: ties keep file order, which is emit order
merged.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));

return {
entries: merged,
total: { runtime: runtime.length, native: native.length },
};
}
2 changes: 2 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { GroupView } from "@/components/GroupView";
import { SettingsPanel } from "@/components/SettingsPanel";
import { PluginsPanel } from "@/components/PluginsPanel";
import { ComputerPanel } from "@/components/ComputerPanel";
import { InspectorPanel } from "@/components/InspectorPanel";
import { SettingsModal } from "@/components/SettingsModal";
import { UpdateBanner } from "@/components/UpdateBanner";
import { DesktopCapabilitiesProvider } from "@/components/DesktopCapabilities";
Expand Down Expand Up @@ -128,6 +129,7 @@ function Shell() {
)}
{state.settingsOpen && bot && <SettingsPanel bot={bot} />}
{state.computerOpen && bot && <ComputerPanel bot={bot} />}
{state.inspectorOpen && bot && <InspectorPanel bot={bot} />}
{state.appSettingsOpen && <SettingsModal />}
{state.pluginsOpen && <PluginsPanel />}
{/* mounted after the modals: same z-50 tier, so DOM order keeps the
Expand Down
11 changes: 11 additions & 0 deletions src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
ChevronDown,
ChevronLeft,
ChevronRight,
Bug,
Copy,
Crown,
Folder,
Expand Down Expand Up @@ -849,6 +850,16 @@ export function ChatView({ bot }: { bot: Bot }) {
>
<Monitor size={18} />
</button>
<button
onClick={() => dispatch({ type: "toggleInspector" })}
className={cn(
"rounded-md p-1.5 hover:bg-raised",
state.inspectorOpen ? "text-accent" : "text-ink-secondary hover:text-ink",
)}
title="Inspector — runtime events and raw protocol for this thread"
>
<Bug size={18} />
</button>
</div>
</div>

Expand Down
Loading
Loading