Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(dev): realtime events, cache and agent panels in the dev toolbar (MUL-9139) (#10470)
Jiayuan Zhang80df530b62ba
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex bb3f4d4631..8cc139364e 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -604,6 +604,12 @@ To keep it on, add the line to the env file `make` loads (`.env` / `.env.worktreEach reading opens the last five minutes behind it, kept in memory in that tab only: the heap curve and Query cache size (Mem), route changes and their timings (Nav), long tasks and the route they hit (Jank), every API request with its status, `X-Request-ID`, body and a copyable curl (Net), WebSocket state changes (Sync), and console errors, uncaught exceptions and unhandled rejections (Errors).+For realtime and agent bugs:++- **Events** lists WebSocket events, filterable by type and searchable by issue key, ID or payload text. Each event shows which query keys its handling wrote, invalidated, removed or refetched, including the refreshes realtime sync debounces onto a timer (work after an `await` is not followed). A reconnect shows how long the socket was down and how many queries it refetched; **Drop connection** closes the socket to try it. **Replay locally** runs a recorded event through realtime sync's handlers again, without other subscribers, and any write request made while handling it is refused.+- **Cache** lists the TanStack Query cache, stale and fetching entries, searchable by key, with a button to invalidate one query.+- **Runtimes** shows each runtime's status and CLI version; **Tasks** lists the workspace's queued and running agent tasks, and clicking one opens its issue.+## How Database Creation WorksDatabase creation is automatic.diff --git a/apps/desktop/src/renderer/src/components/desktop-dev-toolbar.tsx b/apps/desktop/src/renderer/src/components/desktop-dev-toolbar.tsxindex 6016e69082..ec57163313 100644--- a/apps/desktop/src/renderer/src/components/desktop-dev-toolbar.tsx+++ b/apps/desktop/src/renderer/src/components/desktop-dev-toolbar.tsx@@ -1,10 +1,11 @@import { DevToolbar } from "@multica/views/dev-toolbar";import { useActiveTabUrl } from "@/stores/tab-store";+import { routeContentLinkPath } from "@/platform/navigation";const BUILD =import.meta.env.MODE === "development" ? "desktop" : `desktop · ${import.meta.env.MODE}`;export function DesktopDevToolbar({ apiUrl }: { apiUrl: string }) {const route = useActiveTabUrl() ?? "/";- return <DevToolbar build={BUILD} apiUrl={apiUrl} route={route} />;+ return <DevToolbar build={BUILD} apiUrl={apiUrl} route={route} onNavigate={routeContentLinkPath} />;}diff --git a/apps/web/components/web-dev-toolbar.tsx b/apps/web/components/web-dev-toolbar.tsxindex afe80bad58..787eee2765 100644--- a/apps/web/components/web-dev-toolbar.tsx+++ b/apps/web/components/web-dev-toolbar.tsx@@ -2,8 +2,12 @@import { usePathname } from "next/navigation";import { DevToolbar } from "@multica/views/dev-toolbar";+import { useNavigation } from "@multica/views/navigation";export function WebDevToolbar({ apiUrl }: { apiUrl: string }) {const pathname = usePathname();- return <DevToolbar build="web" apiUrl={apiUrl} route={pathname} />;+ const navigation = useNavigation();+ return (+ <DevToolbar build="web" apiUrl={apiUrl} route={pathname} onNavigate={(path) => navigation.push(path)} />+ );}diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex a86c46d2a5..a7e750e6a8 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -811,6 +811,9 @@ function subscriberTarget(*/type WorkspaceScope = string | { workspaceId: string };+/** `readOnly` marks a POST that changes nothing on the server. */+type ApiRequestInit = RequestInit & { readOnly?: boolean };+function workspaceHeader(scope?: WorkspaceScope,): Record<string, string> | undefined {@@ -999,11 +1002,14 @@ export class ApiClient {// path, plain text for the attachment-preview proxy, etc.private async fetchRaw(path: string,- init?: RequestInit & { extraHeaders?: Record<string, string> },+ init?: ApiRequestInit & { extraHeaders?: Record<string, string> },): Promise<Response> {const rid = createRequestId();const start = Date.now();const method = init?.method ?? "GET";+ const observer = getApiRequestObserver();+ const refusal = observer?.refuse?.({ method, path, readOnly: init?.readOnly === true });+ if (refusal) throw new Error(refusal);// Rebuilt per attempt rather than captured once: authHeaders() reads the// CSRF cookie at call time, and the retry below exists precisely because@@ -1021,7 +1027,6 @@ export class ApiClient {this.logger.info(`→ ${method} ${path}`, { rid });- const observer = getApiRequestObserver();observer?.onStart({requestId: rid,method,@@ -1029,10 +1034,11 @@ export class ApiClient {body: typeof init?.body === "string" ? init.body : null,});+ const { readOnly: _readOnly, ...requestInit } = init ?? {};const send = async () => {try {return await fetch(`${this.baseUrl}${path}`, {- ...init,+ ...requestInit,headers: buildHeaders(),credentials: "include",});@@ -1084,7 +1090,7 @@ export class ApiClient {return res;}- private async fetch<T>(path: string, init?: RequestInit): Promise<T> {+ private async fetch<T>(path: string, init?: ApiRequestInit): Promise<T> {const res = await this.fetchRaw(path, {...init,extraHeaders: { "Content-Type": "application/json" },@@ -1355,6 +1361,7 @@ export class ApiClient {async listIssueTableGroups(params: IssueTableGroupsRequest): Promise<IssueTableGroupsResponse> {const raw = await this.fetch<unknown>("/api/issues/table/groups", {method: "POST",+ readOnly: true,body: JSON.stringify(params),});return parseWithFallback(@@ -1368,6 +1375,7 @@ export class ApiClient {async listIssueTableRows(params: IssueTableRowsRequest): Promise<IssueTableRowsResponse> {const raw = await this.fetch<unknown>("/api/issues/table/rows", {method: "POST",+ readOnly: true,body: JSON.stringify(params),});return parseWithFallback(@@ -1381,6 +1389,7 @@ export class ApiClient {async listIssueTableFacets(params: IssueTableFacetsRequest): Promise<IssueTableFacetsResponse> {const raw = await this.fetch<unknown>("/api/issues/table/facets", {method: "POST",+ readOnly: true,body: JSON.stringify(params),});return parseWithFallback(@@ -1836,6 +1845,7 @@ export class ApiClient {async previewCommentTriggers(issueId: string, content: string, parentId?: string, editingCommentId?: string): Promise<CommentTriggerPreview> {const raw = await this.fetch<unknown>(`/api/issues/${issueId}/comments/trigger-preview`, {method: "POST",+ readOnly: true,body: JSON.stringify({content,...(parentId ? { parent_id: parentId } : {}),@@ -1854,6 +1864,7 @@ export class ApiClient {async previewIssueTrigger(params: IssueTriggerPreviewParams): Promise<IssueTriggerPreview> {const raw = await this.fetch<unknown>("/api/issues/preview-trigger", {method: "POST",+ readOnly: true,body: JSON.stringify({...(params.issueIds?.length ? { issue_ids: params.issueIds } : {}),...(params.isCreate ? { is_create: true } : {}),@@ -2172,7 +2183,7 @@ export class ApiClient {}async listQoderEnvironments(wsId: string, token: string, baseUrl: string, signal?: AbortSignal) {- return parseQoderCatalog(await this.fetch(`/api/workspaces/${wsId}/qoder/environments`, { method: "POST", body: JSON.stringify({ qoder_token: token, base_url: baseUrl }), signal }));+ return parseQoderCatalog(await this.fetch(`/api/workspaces/${wsId}/qoder/environments`, { method: "POST", readOnly: true, body: JSON.stringify({ qoder_token: token, base_url: baseUrl }), signal }));}async listQoderAgents(wsId: string) {return parseQoderCatalog(await this.fetch(`/api/workspaces/${wsId}/qoder/agents`));@@ -3533,6 +3544,7 @@ export class ApiClient {async previewPlugin(workspaceId: string, request: PluginPreviewRequest): Promise<PluginPreview> {const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/preview`, {method: "POST",+ readOnly: true,body: JSON.stringify(request),});return parseWithFallback(raw, PluginPreviewSchema, EMPTY_PLUGIN_PREVIEW, {@@ -4663,6 +4675,7 @@ export class ApiClient {async dryRunProjectWorkflow(projectId: string, workflowId: string | null): Promise<IssueWorkflowDryRunResponse> {const raw = await this.fetch<unknown>(`/api/projects/${projectId}/workflow`, {method: "POST",+ readOnly: true,body: JSON.stringify({ workflow_id: workflowId, dry_run: true }),});return parseWithFallback(raw, IssueWorkflowDryRunResponseSchema, EMPTY_ISSUE_WORKFLOW_DRY_RUN, {diff --git a/packages/core/api/realtime-observer.ts b/packages/core/api/realtime-observer.tsnew file mode 100644index 0000000000..dfcfa5fcb2--- /dev/null+++ b/packages/core/api/realtime-observer.ts@@ -0,0 +1,94 @@+import type { WSMessage } from "../types/events";++/**+ * Development hook into realtime sync: which WebSocket frame caused which+ * query cache change, plus a way to run a frame through the sync handlers+ * again. Nothing registers an observer in production; the dev toolbar's+ * recorder is the only one. Without it the helpers below pass straight+ * through and no frame is ever tagged.+ */+export interface RealtimeObserver {+ /** A frame arrived, or is being replayed. Returns the id its cache changes are credited to. */+ onEvent(msg: WSMessage, replayed: boolean): number;+ /** The socket came back after a drop. Returns the id the catch-up refetch is credited to. */+ onReconnect(): number;+}++/** What realtime sync offers for local debugging. */+export interface RealtimeSyncTarget {+ /** Run a frame through realtime sync's own handlers, not every subscriber. */+ replay(msg: WSMessage): void;+ /** Close the socket the way a network drop would, so the client reconnects. */+ drop(): void;+}++/** Ids of the frames (or reconnects) whose handling is running right now. */+export type SyncCauses = readonly number[];++const NONE: SyncCauses = [];+// A debounced refresh coalesces every frame that asked for it; a burst of+// hundreds should not grow the list without bound.+const MAX_HELD_CAUSES = 20;++let observer: RealtimeObserver | null = null;+let target: RealtimeSyncTarget | null = null;+let active: SyncCauses = NONE;++export function setRealtimeObserver(next: RealtimeObserver | null): void {+ observer = next;+}++export function getRealtimeObserver(): RealtimeObserver | null {+ return observer;+}++export function activeSyncCauses(): SyncCauses {+ return active;+}++/** Run `fn` with the cache changes it makes credited to `causes`. */+export function runWithSyncCauses<T>(causes: SyncCauses, fn: () => T): T {+ if (causes.length === 0) return fn();+ const previous = active;+ active = causes;+ try {+ return fn();+ } finally {+ active = previous;+ }+}++/**+ * The causes running now, added to `held`. Work deferred to a timer holds+ * these and later runs under them, so a debounced refetch is still credited+ * to the frames that asked for it. Work after an `await` is not followed.+ */+export function holdSyncCauses(held: SyncCauses = NONE): SyncCauses {+ if (active.length === 0) return held;+ if (held.length === 0) return active;+ return [...new Set([...held, ...active])].slice(-MAX_HELD_CAUSES);+}++/** Realtime sync registers itself while subscribed; returns the unregister. */+export function registerRealtimeSyncTarget(next: RealtimeSyncTarget): () => void {+ target = next;+ return () => {+ if (target === next) target = null;+ };+}++/** Run a recorded frame through realtime sync again. False when nothing is subscribed. */+export function replayRealtimeEvent(msg: WSMessage): boolean {+ const current = target;+ if (!current) return false;+ const id = observer?.onEvent(msg, true);+ runWithSyncCauses(id === undefined ? NONE : [id], () => current.replay(msg));+ return true;+}++/** Drop the live socket so it reconnects. False when there is none. */+export function dropRealtimeConnection(): boolean {+ if (!target) return false;+ target.drop();+ return true;+}diff --git a/packages/core/api/request-observer.ts b/packages/core/api/request-observer.tsindex 04d28bed82..f2d51d725e 100644--- a/packages/core/api/request-observer.ts+++ b/packages/core/api/request-observer.ts@@ -4,6 +4,11 @@* only observer.*/export interface ApiRequestObserver {+ /**+ * A reason not to send the request at all; the call then rejects with it.+ * `readOnly` marks a POST that only reads, such as an issue table query.+ */+ refuse?(request: { method: string; path: string; readOnly: boolean }): string | null;onStart(request: {requestId: string;method: string;diff --git a/packages/core/api/ws-client.ts b/packages/core/api/ws-client.tsindex 7e513dc1e6..c3bdcc86d7 100644--- a/packages/core/api/ws-client.ts+++ b/packages/core/api/ws-client.ts@@ -1,5 +1,6 @@import type { WSMessage, WSEventType } from "../types/events";import { type Logger, noopLogger } from "../logger";+import { getRealtimeObserver, runWithSyncCauses } from "./realtime-observer";type EventHandler = (payload: unknown, actorId?: string, actorType?: string) => void;@@ -151,14 +152,11 @@ export class WSClient {return;}this.logger.debug("received", msg.type);- const eventHandlers = this.handlers.get(msg.type);- if (eventHandlers) {- for (const handler of eventHandlers) {- handler(msg.payload, msg.actor_id, msg.actor_type);- }- }- for (const handler of this.anyHandlers) {- handler(msg);+ const observer = getRealtimeObserver();+ if (observer) {+ runWithSyncCauses([observer.onEvent(msg, false)], () => this.dispatch(msg));+ } else {+ this.dispatch(msg);}};@@ -172,6 +170,18 @@ export class WSClient {};}+ private dispatch(msg: WSMessage) {+ const eventHandlers = this.handlers.get(msg.type);+ if (eventHandlers) {+ for (const handler of eventHandlers) {+ handler(msg.payload, msg.actor_id, msg.actor_type);+ }+ }+ for (const handler of this.anyHandlers) {+ handler(msg);+ }+ }+/*** Schedule a reconnection attempt with exponential backoff and jitter.* Retries indefinitely with a capped delay because the web/desktop UI@@ -203,17 +213,27 @@ export class WSClient {this.reconnectAttempt = 0;this.setStatus("connected");if (recoveredConnection) {- for (const cb of this.onReconnectCallbacks) {- try {- cb();- } catch {- // ignore reconnect callback errors+ const runCallbacks = () => {+ for (const cb of this.onReconnectCallbacks) {+ try {+ cb();+ } catch {+ // ignore reconnect callback errors+ }}- }+ };+ const observer = getRealtimeObserver();+ if (observer) runWithSyncCauses([observer.onReconnect()], runCallbacks);+ else runCallbacks();}this.hasConnectedBefore = true;}+ /** Close the socket the way a network drop would; the usual reconnect follows. */+ drop() {+ this.ws?.close();+ }+disconnect() {if (this.reconnectTimer) {clearTimeout(this.reconnectTimer);diff --git a/packages/core/diagnostics/dev-recorder-realtime.test.tsx b/packages/core/diagnostics/dev-recorder-realtime.test.tsxnew file mode 100644index 0000000000..52427942e6--- /dev/null+++ b/packages/core/diagnostics/dev-recorder-realtime.test.tsx@@ -0,0 +1,274 @@+// @vitest-environment jsdom+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ReactNode } from "react";+import { renderHook } from "@testing-library/react";+import { QueryClient, QueryClientProvider, QueryObserver } from "@tanstack/react-query";+import { ApiClient } from "../api/client";+import { activeSyncCauses, getRealtimeObserver, holdSyncCauses, runWithSyncCauses } from "../api/realtime-observer";+import { WSClient } from "../api/ws-client";+import { chatKeys } from "../chat/queries";+import { issueKeys } from "../issues/queries";+import { useRealtimeSync, type RealtimeSyncStores } from "../realtime/use-realtime-sync";+import type { WSMessage } from "../types/events";+import { workspaceKeys } from "../workspace/queries";+import {+ dropDevConnection,+ getDevRecording,+ installDevRecorder,+ recordDevSyncStatus,+ replayDevEvent,+ resetDevRecorder,+} from "./dev-recorder";++const workspace = vi.hoisted(() => ({ id: "ws-1" }));++vi.mock("../platform/workspace-storage", () => ({+ getCurrentWsId: () => workspace.id,+ getCurrentSlug: () => "acme",+ subscribeToCurrentSlug: () => () => {},+ createWorkspaceAwareStorage: (adapter: unknown) => adapter,+ registerForWorkspaceRehydration: () => {},+}));++vi.mock("../paths", () => ({+ useHasOnboarded: () => true,+ resolvePostAuthDestination: () => "/",+}));++class FakeSocket {+ static last: FakeSocket | null = null;+ onopen: (() => void) | null = null;+ onmessage: ((ev: { data: string }) => void) | null = null;+ onclose: (() => void) | null = null;+ onerror: (() => void) | null = null;+ readyState = 1;+ constructor() {+ FakeSocket.last = this;+ }+ send() {}+ close() {+ this.onclose?.();+ }+}++const stores = {+ authStore: Object.assign(() => ({}), {+ getState: () => ({ user: { id: "u1" } }),+ subscribe: () => () => {},+ }),+} as unknown as RealtimeSyncStores;++function emit(msg: WSMessage) {+ FakeSocket.last!.onmessage!({ data: JSON.stringify(msg) });+}++function setup() {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ installDevRecorder(qc);+ const client = new WSClient("ws://example.test/ws", { cookieAuth: true });+ client.setAuth(null, "acme");+ client.connect();+ FakeSocket.last!.onopen!();+ renderHook(() => useRealtimeSync(client, stores), {+ wrapper: ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>+ ),+ });+ return { qc, client };+}++function hash(key: readonly unknown[]) {+ return JSON.stringify(key);+}++describe("dev recorder: realtime events", () => {+ beforeEach(() => {+ workspace.id = "ws-1";+ vi.useFakeTimers();+ vi.stubGlobal("WebSocket", FakeSocket as unknown as typeof WebSocket);+ });++ afterEach(() => {+ resetDevRecorder();+ vi.unstubAllGlobals();+ vi.useRealTimers();+ });++ it("tags each frame with the cache keys its handling wrote or invalidated, debounced refreshes included", () => {+ const { qc } = setup();+ qc.setQueryData(chatKeys.sessions("ws-1"), [{ id: "s1", title: "old" }]);+ qc.setQueryData(issueKeys.timeline("issue-1"), []);+ qc.setQueryData(workspaceKeys.members("ws-1"), []);++ emit({ type: "chat:session_updated", payload: { chat_session_id: "s1", title: "new" } });+ emit({ type: "comment:created", payload: { comment: { id: "c1", issue_id: "issue-1" } } });+ emit({ type: "member:updated", payload: { member: { user_id: "u2" } } });+ vi.advanceTimersByTime(100);++ const [renamed, commented, member] = getDevRecording().events;+ expect(renamed).toMatchObject({ kind: "frame", type: "chat:session_updated" });+ expect(renamed!.cache.written).toEqual([hash(chatKeys.sessions("ws-1"))]);+ expect(commented).toMatchObject({ type: "comment:created", issueId: "issue-1" });+ expect(commented!.cache.invalidated).toContain(hash(issueKeys.timeline("issue-1")));+ expect(commented!.cache.written).toEqual([]);+ // The member prefix refresh runs 100ms later, on a timer.+ expect(member!.cache.invalidated).toEqual([hash(workspaceKeys.members("ws-1"))]);+ });++ it("credits an issue edit with the issue detail it wrote", () => {+ const { qc } = setup();+ const before = { id: "issue-1", identifier: "MUL-1", title: "Old", revision: 1, status: "todo" };+ qc.setQueryData(issueKeys.detail("ws-1", "issue-1"), before);+ emit({+ type: "issue:updated",+ payload: { issue: { ...before, title: "New", revision: 2 }, title_changed: true },+ });+ const [edit] = getDevRecording().events;+ expect(edit!.cache.written).toContain(hash(issueKeys.detail("ws-1", "issue-1")));+ });++ it("keeps the issue key and redacts credentials in the payload", () => {+ setup();+ emit({+ type: "issue:updated",+ payload: { issue: { id: "issue-1", identifier: "MUL-1", title: "Fix" } },+ actor_type: "member",+ actor_id: "u2",+ });+ emit({ type: "agent:created", payload: { agent: { id: "a1", custom_env: { OPENAI_API_KEY: "fake-key-for-test" } } } });++ const [issue, agent] = getDevRecording().events;+ expect(issue).toMatchObject({ issueId: "issue-1", issueKey: "MUL-1", actor: "member u2" });+ expect(agent!.payload).not.toContain("fake-key-for-test");+ expect(JSON.parse(agent!.payload!)).toEqual({ agent: { id: "a1", custom_env: "[redacted]" } });+ });++ it("marks a dropped connection's reconnect with its downtime and the queries it refetched", async () => {+ const { qc } = setup();+ const unsubscribe = new QueryObserver(qc, {+ queryKey: workspaceKeys.list(),+ queryFn: () => Promise.resolve([]),+ }).subscribe(() => {});+ await vi.runOnlyPendingTimersAsync();+ recordDevSyncStatus("connected");++ expect(dropDevConnection()).toBe(true);+ recordDevSyncStatus("reconnecting");+ vi.advanceTimersByTime(1_500);+ FakeSocket.last!.onopen!();++ const reconnect = getDevRecording().events.at(-1)!;+ expect(reconnect.kind).toBe("reconnect");+ expect(reconnect.downMs).toBe(1_500);+ expect(reconnect.cache.invalidated).toContain(hash(workspaceKeys.list()));+ expect(reconnect.cache.refetched).toEqual([hash(workspaceKeys.list())]);+ unsubscribe();+ });++ it("replays a frame through realtime sync alone, as a new replay event", () => {+ const { qc, client } = setup();+ const otherSubscriber = vi.fn();+ client.on("comment:created", otherSubscriber);+ qc.setQueryData(issueKeys.timeline("issue-1"), []);+ emit({ type: "comment:created", payload: { comment: { id: "c1", issue_id: "issue-1" } } });+ const original = getDevRecording().events[0]!;+ qc.setQueryData(issueKeys.timeline("issue-1"), []);++ expect(replayDevEvent(original.id)).toBeNull();+ const replay = getDevRecording().events[1]!;+ expect(replay).toMatchObject({ kind: "replay", type: "comment:created", issueId: "issue-1" });+ expect(replay.cache.invalidated).toContain(hash(issueKeys.timeline("issue-1")));+ expect(otherSubscriber).toHaveBeenCalledOnce();+ });++ it("refuses write requests made while a replayed event is handled, and only then", async () => {+ setup();+ const fetchMock = vi.fn((_url: string, _init?: RequestInit) => Promise.resolve(new Response("{}", { status: 200 })));+ vi.stubGlobal("fetch", fetchMock);+ const api = new ApiClient("http://localhost:18080");+ emit({ type: "comment:created", payload: { comment: { id: "c1", issue_id: "issue-1" } } });+ replayDevEvent(getDevRecording().events[0]!.id);+ const replayId = getDevRecording().events[1]!.id;++ await expect(runWithSyncCauses([replayId], () => api.createComment("issue-1", "hi"))).rejects.toThrow(+ "POST not sent: a replayed realtime event runs locally only",+ );+ await runWithSyncCauses([replayId], () => api.listMembers("ws-1"));+ await api.createComment("issue-1", "hi");+ expect(fetchMock.mock.calls.map(([, init]) => init?.method ?? "GET")).toEqual(["GET", "POST"]);+ });++ it("lets a read-only POST query refetch while a replayed event is handled", async () => {+ const { qc } = setup();+ const fetchMock = vi.fn((_url: string, _init?: RequestInit) =>+ Promise.resolve(new Response(JSON.stringify({ rows: [], next_cursor: null }), { status: 200 })),+ );+ vi.stubGlobal("fetch", fetchMock);+ const api = new ApiClient("http://localhost:18080");+ const key = [...issueKeys.tableAll("ws-1"), "rows", "replay"];+ const unsubscribe = new QueryObserver(qc, {+ queryKey: key,+ queryFn: () => api.listIssueTableRows({} as Parameters<ApiClient["listIssueTableRows"]>[0]),+ }).subscribe(() => {});+ await vi.advanceTimersByTimeAsync(0);+ const created = { issue: { id: "i1", workspace_id: "ws-1", status: "todo", status_category: "unstarted" } };+ emit({ type: "issue:created", payload: created });+ await vi.advanceTimersByTimeAsync(0);++ expect(replayDevEvent(getDevRecording().events[0]!.id)).toBeNull();+ await vi.advanceTimersByTimeAsync(0);+ const state = qc.getQueryState(key);+ unsubscribe();+ expect(state).toMatchObject({ status: "success", error: null });+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual(+ Array(3).fill("http://localhost:18080/api/issues/table/rows"),+ );+ });++ it("does not replay an event into a workspace other than the one it arrived in", () => {+ const { qc } = setup();+ const created = { issue: { id: "issue-A", workspace_id: "ws-1", status: "todo", status_category: "unstarted" } };+ emit({ type: "issue:created", payload: created });+ const original = getDevRecording().events[0]!;+ workspace.id = "ws-2";+ const empty = { byStatus: { unstarted: { issues: [], total: 0 } } };+ qc.setQueryData(issueKeys.list("ws-2"), empty);++ expect(replayDevEvent(original.id)).toBe("it was recorded in another workspace");+ expect(qc.getQueryData(issueKeys.list("ws-2"))).toEqual(empty);+ expect(getDevRecording().events).toHaveLength(1);+ });++ it("counts every frame of a busy minute, apart from the capped event list and replays", () => {+ setup();+ for (let i = 0; i < 501; i++) emit({ type: "daemon:heartbeat", payload: {} });+ replayDevEvent(getDevRecording().events.at(-1)!.id);+ const { events, frameCounts } = getDevRecording();+ expect(events).toHaveLength(500);+ expect(frameCounts.reduce((sum, bucket) => sum + bucket.count, 0)).toBe(501);+ });++ it("forgets events that aged out of the window, and can no longer replay them", () => {+ setup();+ emit({ type: "comment:created", payload: { comment: { id: "c1", issue_id: "issue-1" } } });+ const id = getDevRecording().events[0]!.id;++ vi.advanceTimersByTime(6 * 60_000);+ expect(getDevRecording().events).toEqual([]);+ expect(replayDevEvent(id)).toBe("the event aged out of the recording");+ });++ it("tags nothing and holds no causes when the recorder is not installed", () => {+ const client = new WSClient("ws://example.test/ws", { cookieAuth: true });+ client.connect();+ FakeSocket.last!.onopen!();+ let seen: unknown[] = ["unset"];+ client.on("comment:created", () => {+ seen = [...activeSyncCauses(), ...holdSyncCauses()];+ });+ emit({ type: "comment:created", payload: {} });++ expect(getRealtimeObserver()).toBeNull();+ expect(seen).toEqual([]);+ });+});diff --git a/packages/core/diagnostics/dev-recorder.ts b/packages/core/diagnostics/dev-recorder.tsindex c1e879d078..6b5721cbd6 100644--- a/packages/core/diagnostics/dev-recorder.ts+++ b/packages/core/diagnostics/dev-recorder.ts@@ -1,9 +1,18 @@// In-memory recording of what this client did recently: API requests, route-// changes, long tasks, errors, WebSocket state and heap size. It backs the-// development toolbar's panels and is only installed by that toolbar, so-// production builds never record anything.+// changes, long tasks, errors, WebSocket state and events, and heap size. It+// backs the development toolbar's panels and is only installed by that+// toolbar, so production builds never record anything.+import type { QueryCacheNotifyEvent, QueryClient } from "@tanstack/react-query";import { setApiRequestObserver } from "../api/request-observer";+import {+ activeSyncCauses,+ dropRealtimeConnection,+ replayRealtimeEvent,+ setRealtimeObserver,+} from "../api/realtime-observer";+import { getCurrentWsId } from "../platform/workspace-storage";+import type { WSMessage } from "../types/events";export interface DevRequest {requestId: string;@@ -57,12 +66,53 @@ export interface DevMemorySample {bytes: number;}+export type DevCacheChange = "written" | "invalidated" | "removed" | "refetched";++/** Query hashes an event changed, by how. */+export type DevCacheEffects = Readonly<Record<DevCacheChange, readonly string[]>>;++export interface DevRealtimeEvent {+ id: number;+ at: number;+ /** A frame from the server, a recorded frame run again locally, or the socket coming back. */+ kind: "frame" | "replay" | "reconnect";+ /** Event type such as `issue:updated`; `reconnect` for a reconnect. */+ type: string;+ issueId: string | null;+ /** Issue key such as `MUL-12`, when the payload carries one. */+ issueKey: string | null;+ /** JSON payload with sensitive fields redacted; null for a reconnect. */+ payload: string | null;+ /** Why `payload` is not the whole payload. */+ payloadNote: string | null;+ /** `member <id>` or `agent <id>` when the frame names who caused it. */+ actor: string | null;+ /** Workspace that was current when the event arrived; replay runs only there. */+ workspaceId: string | null;+ /**+ * What handling the event did to the query cache, including refreshes it+ * deferred to a timer. Work a handler does after an `await` is not seen.+ */+ cache: DevCacheEffects;+ /** Reconnects: how long the socket was down, when the sync history shows it. */+ downMs: number | null;+}++/** Frames received during one second, starting at `at`. */+export interface DevFrameCount {+ at: number;+ count: number;+}+export interface DevRecording {requests: readonly DevRequest[];navigations: readonly DevNavigation[];longTasks: readonly DevLongTask[];errors: readonly DevError[];sync: readonly DevSyncChange[];+ events: readonly DevRealtimeEvent[];+ /** Server frames per second, kept apart from `events` so its cap never lowers the rate. */+ frameCounts: readonly DevFrameCount[];memory: readonly DevMemorySample[];/** JS heap ceiling on engines that report one. */heapLimit: number | null;@@ -76,10 +126,15 @@ const CAPS: Record<Exclude<keyof DevRecording, "heapLimit">, number> = {longTasks: 200,errors: 100,sync: 50,+ events: 500,+ frameCounts: DEV_RECORDING_WINDOW_MS / 1000,memory: 150,};const BODY_MAX_CHARS = 2_000;+const PAYLOAD_MAX_CHARS = 4_000;+// A reconnect invalidates a few hundred queries; listing more says nothing new.+const CACHE_KEYS_MAX = 500;const MESSAGE_MAX_CHARS = 1_000;const MEMORY_SAMPLE_MS = 2_000;const PRUNE_INTERVAL_MS = 5_000;@@ -93,24 +148,67 @@ const EMPTY: DevRecording = {longTasks: [],errors: [],sync: [],+ events: [],+ frameCounts: [],memory: [],heapLimit: null,};+const NO_CACHE_EFFECTS: DevCacheEffects = { written: [], invalidated: [], removed: [], refetched: [] };+let recording: DevRecording = EMPTY;let currentRoute: string | null = null;const listeners = new Set<() => void>();let notifyTimer: ReturnType<typeof setTimeout> | null = null;let teardown: (() => void) | null = null;+// Per recorded event, keyed by id and dropped with the event.+let nextEventId = 1;+const eventMessages = new Map<number, WSMessage>();+const replayIds = new Set<number>();+// Cache changes arrive one query at a time, often hundreds per event. They+// collect here and reach `recording` when it is next read or published.+const cacheEffects = new Map<number, Record<DevCacheChange, Set<string>>>();+const dirtyEffects = new Set<number>();+function scheduleNotify() {if (notifyTimer) return;notifyTimer = setTimeout(() => {notifyTimer = null;+ applyCacheEffects();for (const listener of listeners) listener();}, NOTIFY_DELAY_MS);}+function applyCacheEffects() {+ if (dirtyEffects.size === 0) return;+ recording = {+ ...recording,+ events: recording.events.map((event) => {+ const effects = dirtyEffects.has(event.id) ? cacheEffects.get(event.id) : undefined;+ if (!effects) return event;+ return {+ ...event,+ cache: {+ written: [...effects.written],+ invalidated: [...effects.invalidated],+ removed: [...effects.removed],+ refetched: [...effects.refetched],+ },+ };+ }),+ };+ dirtyEffects.clear();+}++/** Forget per-event state for events no longer in the recording. */+function forgetDroppedEvents() {+ const oldest = recording.events[0]?.id ?? nextEventId;+ for (const ids of [eventMessages, cacheEffects, replayIds, dirtyEffects]) {+ for (const id of ids.keys()) if (id < oldest) ids.delete(id);+ }+}+function prune<T extends { at: number }>(items: readonly T[], cap: number, now: number): T[] {const fresh = items.filter((item) => now - item.at <= DEV_RECORDING_WINDOW_MS);return fresh.length > cap ? fresh.slice(fresh.length - cap) : fresh;@@ -131,12 +229,16 @@ function pruneExpired(now: number) {longTasks: prune(recording.longTasks, CAPS.longTasks, now),errors: prune(recording.errors, CAPS.errors, now),sync: prune(recording.sync, CAPS.sync, now),+ events: prune(recording.events, CAPS.events, now),+ frameCounts: prune(recording.frameCounts, CAPS.frameCounts, now),memory: prune(recording.memory, CAPS.memory, now),};const changed = (Object.keys(CAPS) as (keyof typeof CAPS)[]).some((key) => next[key].length !== recording[key].length,);- if (changed) update(next);+ if (!changed) return;+ update(next);+ forgetDroppedEvents();}// Names of fields and query parameters that carry credentials: VCS and bot@@ -194,6 +296,136 @@ export function recordableBody(body: string | null): Pick<DevRequest, "body" | "};}+/** A WebSocket payload as kept for display: redacted like request bodies, cut to a bounded size. */+export function recordablePayload(payload: unknown): Pick<DevRealtimeEvent, "payload" | "payloadNote"> {+ let text: string;+ try {+ text = JSON.stringify(redactValue(payload)) ?? "null";+ } catch {+ return { payload: null, payloadNote: "not serializable, so not recorded" };+ }+ if (text.length <= PAYLOAD_MAX_CHARS) return { payload: text, payloadNote: null };+ return {+ payload: truncate(text, PAYLOAD_MAX_CHARS),+ payloadNote: `truncated to ${PAYLOAD_MAX_CHARS} of ${text.length} characters`,+ };+}++function nonEmptyString(value: unknown): string | null {+ return typeof value === "string" && value ? value : null;+}++/** The issue an event is about, from the payload shapes that name one. */+export function eventIssue(payload: unknown): Pick<DevRealtimeEvent, "issueId" | "issueKey"> {+ if (!payload || typeof payload !== "object") return { issueId: null, issueKey: null };+ const fields = payload as Record<string, unknown>;+ const nested = (key: string) =>+ fields[key] && typeof fields[key] === "object" ? (fields[key] as Record<string, unknown>) : null;+ const issue = nested("issue");+ return {+ issueId:+ nonEmptyString(issue?.id) ??+ nonEmptyString(fields.issue_id) ??+ nonEmptyString(nested("comment")?.issue_id) ??+ nonEmptyString(nested("item")?.issue_id),+ issueKey: nonEmptyString(issue?.identifier),+ };+}++function recordEvent(event: Omit<DevRealtimeEvent, "id" | "cache">): number {+ const id = nextEventId++;+ append("events", { ...event, id, cache: NO_CACHE_EFFECTS });+ forgetDroppedEvents();+ return id;+}++function countFrame(now: number) {+ const second = now - (now % 1000);+ const counts = recording.frameCounts;+ const last = counts[counts.length - 1];+ const next =+ last?.at === second+ ? [...counts.slice(0, -1), { at: second, count: last.count + 1 }]+ : prune([...counts, { at: second, count: 1 }], CAPS.frameCounts, now);+ update({ frameCounts: next });+}++function recordFrame(msg: WSMessage, replayed: boolean): number {+ const now = Date.now();+ if (!replayed) countFrame(now);+ const id = recordEvent({+ at: now,+ kind: replayed ? "replay" : "frame",+ type: msg.type,+ ...eventIssue(msg.payload),+ ...recordablePayload(msg.payload),+ actor: msg.actor_type && msg.actor_id ? `${msg.actor_type} ${msg.actor_id}` : null,+ workspaceId: getCurrentWsId(),+ downMs: null,+ });+ eventMessages.set(id, msg);+ if (replayed) replayIds.add(id);+ return id;+}++/** How long the socket has been down, from the last unbroken run of non-connected states. */+function downtime(now: number): number | null {+ const { sync } = recording;+ let end = sync.length - 1;+ let upAt = now;+ // The status hook may already have recorded the connection coming back.+ while (end >= 0 && sync[end]!.status === "connected") upAt = sync[end--]!.at;+ if (end < 0) return null;+ let start = end;+ while (start > 0 && sync[start - 1]!.status !== "connected") start -= 1;+ return upAt - sync[start]!.at;+}++function recordReconnect(): number {+ const now = Date.now();+ return recordEvent({+ at: now,+ kind: "reconnect",+ type: "reconnect",+ issueId: null,+ issueKey: null,+ payload: null,+ payloadNote: null,+ actor: null,+ workspaceId: getCurrentWsId(),+ downMs: downtime(now),+ });+}++function cacheChange(event: QueryCacheNotifyEvent): DevCacheChange | null {+ if (event.type === "removed") return "removed";+ if (event.type !== "updated") return null;+ const { action } = event;+ if (action.type === "success" && action.manual) return "written";+ if (action.type === "invalidate") return "invalidated";+ if (action.type === "fetch") return "refetched";+ return null;+}++/** Credit a cache change to the realtime events whose handling is running. */+function onCacheEvent(event: QueryCacheNotifyEvent) {+ const causes = activeSyncCauses();+ if (causes.length === 0) return;+ const change = cacheChange(event);+ if (!change) return;+ for (const id of causes) {+ let effects = cacheEffects.get(id);+ if (!effects) {+ effects = { written: new Set(), invalidated: new Set(), removed: new Set(), refetched: new Set() };+ cacheEffects.set(id, effects);+ }+ if (effects[change].size >= CACHE_KEYS_MAX) continue;+ effects[change].add(event.query.queryHash);+ dirtyEffects.add(id);+ }+ scheduleNotify();+}+function update(patch: Partial<DevRecording>) {recording = { ...recording, ...patch };scheduleNotify();@@ -263,12 +495,27 @@ function readHeap(): { used: number; limit: number } | null {return memory ? { used: memory.usedJSHeapSize, limit: memory.jsHeapSizeLimit } : null;}-/** Start recording. Idempotent, and a no-op outside the browser. */-export function installDevRecorder(): void {+/** A write sent while a replayed event is being handled; replays stay local. */+function refuseReplayWrite({ method, readOnly }: { method: string; readOnly: boolean }): string | null {+ if (readOnly || method === "GET" || method === "HEAD") return null;+ const replaying = activeSyncCauses().some((id) => replayIds.has(id));+ return replaying ? `${method} not sent: a replayed realtime event runs locally only` : null;+}++/**+ * Start recording. Idempotent, and a no-op outside the browser. With a query+ * client, realtime events are tagged with the cache changes they caused.+ */+export function installDevRecorder(queryClient?: QueryClient): void {if (teardown || typeof window === "undefined") return;const cleanups: (() => void)[] = [];+ setRealtimeObserver({ onEvent: recordFrame, onReconnect: recordReconnect });+ cleanups.push(() => setRealtimeObserver(null));+ if (queryClient) cleanups.push(queryClient.getQueryCache().subscribe(onCacheEvent));+setApiRequestObserver({+ refuse: refuseReplayWrite,onStart: ({ requestId, method, path, body }) => {const request: DevRequest = {requestId,@@ -385,6 +632,31 @@ export function clearDevErrors(): void {update({ errors: [] });}+export function clearDevEvents(): void {+ update({ events: [], frameCounts: [] });+ forgetDroppedEvents();+}++/**+ * Run a recorded event through realtime sync's handlers again, recorded as a+ * new `replay` event. Only cache handling runs: no other subscriber sees it,+ * and a write request made while handling it is refused. Handlers write into+ * the current workspace's caches, so an event recorded in another workspace+ * does not run. Returns why it did not run, or null when it did.+ */+export function replayDevEvent(id: number): string | null {+ const msg = eventMessages.get(id);+ const event = recording.events.find((e) => e.id === id);+ if (!msg || !event) return "the event aged out of the recording";+ if (event.workspaceId !== getCurrentWsId()) return "it was recorded in another workspace";+ return replayRealtimeEvent(msg) ? null : "realtime sync is not running";+}++/** Close the live socket as a network drop would, to watch the reconnect. */+export function dropDevConnection(): boolean {+ return dropRealtimeConnection();+}+export function subscribeDevRecording(listener: () => void): () => void {listeners.add(listener);return () => {@@ -393,6 +665,7 @@ export function subscribeDevRecording(listener: () => void): () => void {}export function getDevRecording(): DevRecording {+ applyCacheEffects();return recording;}@@ -405,4 +678,9 @@ export function resetDevRecorder(): void {recording = EMPTY;currentRoute = null;listeners.clear();+ nextEventId = 1;+ eventMessages.clear();+ replayIds.clear();+ cacheEffects.clear();+ dirtyEffects.clear();}diff --git a/packages/core/diagnostics/index.ts b/packages/core/diagnostics/index.tsindex 2070ef62c6..6b55ef0506 100644--- a/packages/core/diagnostics/index.ts+++ b/packages/core/diagnostics/index.ts@@ -2,22 +2,29 @@ export { installFreezeWatchdog } from "./freeze-watchdog";export { installUserTimingCap } from "./user-timing-cap";export {clearDevErrors,+ clearDevEvents,clearDevRequests,DEV_RECORDING_WINDOW_MS,+ dropDevConnection,getDevRecording,installDevRecorder,recordDevNavigationDuration,recordDevRoute,recordDevSyncStatus,+ replayDevEvent,resetDevRecorder,subscribeDevRecording,} from "./dev-recorder";export type {+ DevCacheChange,+ DevCacheEffects,DevError,DevErrorSource,+ DevFrameCount,DevLongTask,DevMemorySample,DevNavigation,+ DevRealtimeEvent,DevRecording,DevRequest,DevSyncChange,diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 88142301f3..a83a5c1a99 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -4,6 +4,13 @@ import { useEffect, useRef } from "react";import { forgetLocalSearchIndex } from "../search-index/instance";import { useQueryClient, type InfiniteData, type QueryClient, type QueryFilters } from "@tanstack/react-query";import type { WSClient } from "../api/ws-client";+import {+ holdSyncCauses,+ registerRealtimeSyncTarget,+ runWithSyncCauses,+ type SyncCauses,+} from "../api/realtime-observer";+import type { WSMessage } from "../types/events";import type { StoreApi, UseBoundStore } from "zustand";import type { AuthState } from "../auth/store";import { createLogger } from "../logger";@@ -738,7 +745,11 @@ function invalidateWorkspaceScopedQueries(qc: QueryClient): void {qc.invalidateQueries({ queryKey: workspaceKeys.list() });}-async function refreshWorkingAgentQueries(qc: QueryClient, wsId: string): Promise<void> {+async function refreshWorkingAgentQueries(+ qc: QueryClient,+ wsId: string,+ causes: SyncCauses,+): Promise<void> {const filters: QueryFilters[] = [{ queryKey: workspaceWorkingAgentsKeys.all(wsId) },{ queryKey: agentTaskSnapshotKeys.all(wsId) },@@ -774,7 +785,48 @@ async function refreshWorkingAgentQueries(qc: QueryClient, wsId: string): Promis// captured before that event. With staleTime=Infinity it could otherwise// leave a completed run visible until another event happens to arrive.await Promise.all(filters.map((filter) => qc.cancelQueries(filter)));- await Promise.all(filters.map((filter) => qc.invalidateQueries(filter)));+ await runWithSyncCauses(causes, () =>+ Promise.all(filters.map((filter) => qc.invalidateQueries(filter))),+ );+}++type SyncEventHandler = Parameters<WSClient["on"]>[1];++/**+ * `ws.on` / `ws.onAny` that remember realtime sync's own handlers, so the dev+ * toolbar can replay a frame through them alone. Other subscribers stay out+ * of a replay: some answer an event with a server write, such as reading the+ * inbox notification of the issue on screen.+ */+function replayableSubscriptions(ws: WSClient) {+ const handlers = new Map<string, Set<SyncEventHandler>>();+ const anyHandlers = new Set<(msg: WSMessage) => void>();+ return {+ on(event: Parameters<WSClient["on"]>[0], handler: SyncEventHandler) {+ const set = handlers.get(event) ?? new Set();+ handlers.set(event, set);+ set.add(handler);+ const unsubscribe = ws.on(event, handler);+ return () => {+ set.delete(handler);+ unsubscribe();+ };+ },+ onAny(handler: (msg: WSMessage) => void) {+ anyHandlers.add(handler);+ const unsubscribe = ws.onAny(handler);+ return () => {+ anyHandlers.delete(handler);+ unsubscribe();+ };+ },+ replay(msg: WSMessage) {+ for (const handler of handlers.get(msg.type) ?? []) {+ handler(msg.payload, msg.actor_id, msg.actor_type);+ }+ for (const handler of anyHandlers) handler(msg);+ },+ };}function invalidateSquadMemberStatusQueries(qc: QueryClient, wsId: string): void {@@ -808,12 +860,12 @@ export interface RealtimeSyncStores {* updates). Daemon register events invalidate runtimes globally; heartbeats* are skipped to avoid excessive refetches.*- * @param ws - WebSocket client instance (null when not yet connected)+ * @param client - WebSocket client instance (null when not yet connected)* @param stores - Platform-created Zustand store instances for auth and workspace* @param onToast - Optional callback for showing toast messages (platform-specific)*/export function useRealtimeSync(- ws: WSClient | null,+ client: WSClient | null,stores: RealtimeSyncStores,onToast?: (message: string, type?: "info" | "error") => void,) {@@ -829,7 +881,12 @@ export function useRealtimeSync(// Main sync: onAny -> refreshMap with debounceuseEffect(() => {- if (!ws) return;+ if (!client) return;+ const ws = replayableSubscriptions(client);+ const releaseSyncTarget = registerRealtimeSyncTarget({+ replay: ws.replay,+ drop: () => client.drop(),+ });const refreshMap: Record<string, () => void> = {inbox: () => {@@ -1073,6 +1130,7 @@ export function useRealtimeSync(const workingAgentTimers = new Map<string, ReturnType<typeof setTimeout>>();const workingAgentInFlight = new Set<string>();const workingAgentDirty = new Set<string>();+ const workingAgentCauses = new Map<string, SyncCauses>();let disposed = false;const scheduleWorkingAgentRefresh = (wsId: string) => {// Flush one second after the FIRST event in a batch. Later events do@@ -1080,13 +1138,16 @@ export function useRealtimeSync(// Capture the workspace now: navigation must not redirect a queued// refresh into a different workspace's cache.workingAgentDirty.add(wsId);+ workingAgentCauses.set(wsId, holdSyncCauses(workingAgentCauses.get(wsId)));if (workingAgentTimers.has(wsId) || workingAgentInFlight.has(wsId)) return;workingAgentTimers.set(wsId, setTimeout(async () => {workingAgentTimers.delete(wsId);workingAgentDirty.delete(wsId);workingAgentInFlight.add(wsId);+ const causes = workingAgentCauses.get(wsId) ?? [];+ workingAgentCauses.delete(wsId);try {- await refreshWorkingAgentQueries(qc, wsId);+ await refreshWorkingAgentQueries(qc, wsId, causes);} finally {workingAgentInFlight.delete(wsId);// Serialize slow requests: cancelling our own refresh every second@@ -1098,14 +1159,18 @@ export function useRealtimeSync(};const timers = new Map<string, ReturnType<typeof setTimeout>>();+ const timerCauses = new Map<string, SyncCauses>();const debouncedRefresh = (prefix: string, fn: () => void) => {const existing = timers.get(prefix);if (existing) clearTimeout(existing);+ const causes = holdSyncCauses(timerCauses.get(prefix));+ if (causes.length > 0) timerCauses.set(prefix, causes);timers.set(prefix,setTimeout(() => {timers.delete(prefix);- fn();+ timerCauses.delete(prefix);+ runWithSyncCauses(causes, fn);}, 100),);};@@ -1592,6 +1657,7 @@ export function useRealtimeSync(// re-checks rather than trusting the gate — see flushTaskMessages.const taskMessageBatches = new Map<string, TaskMessagePayload[]>();let taskMessageFlushTimer: ReturnType<typeof setTimeout> | null = null;+ let taskMessageCauses: SyncCauses = [];const writeTaskMessageBatch = (taskId: string, batch: TaskMessagePayload[]) => {// Re-check, because a queued batch may be up to one window old and@@ -1613,10 +1679,14 @@ export function useRealtimeSync(const flushTaskMessages = () => {taskMessageFlushTimer = null;+ const causes = taskMessageCauses;+ taskMessageCauses = [];- for (const [taskId, batch] of taskMessageBatches) {- writeTaskMessageBatch(taskId, batch);- }+ runWithSyncCauses(causes, () => {+ for (const [taskId, batch] of taskMessageBatches) {+ writeTaskMessageBatch(taskId, batch);+ }+ });taskMessageBatches.clear();};@@ -1637,6 +1707,7 @@ export function useRealtimeSync(const batch = taskMessageBatches.get(payload.task_id);if (batch) batch.push(payload);else taskMessageBatches.set(payload.task_id, [payload]);+ taskMessageCauses = holdSyncCauses(taskMessageCauses);}chatWsLogger.debug("task:message (global)", {@@ -1670,11 +1741,15 @@ export function useRealtimeSync(// aggregate is refreshed only on task lifecycle transitions, which are// per-task and low-frequency, then coalesced by the debounce below.let aggregateRefreshTimer: ReturnType<typeof setTimeout> | null = null;+ let aggregateCauses: SyncCauses = [];const invalidatePendingAggregate = () => {if (aggregateRefreshTimer) clearTimeout(aggregateRefreshTimer);+ aggregateCauses = holdSyncCauses(aggregateCauses);aggregateRefreshTimer = setTimeout(() => {aggregateRefreshTimer = null;- refetchPendingChatAggregate(qc, getCurrentWsId());+ const causes = aggregateCauses;+ aggregateCauses = [];+ runWithSyncCauses(causes, () => refetchPendingChatAggregate(qc, getCurrentWsId()));}, 750);};const invalidateSessionLists = () => {@@ -1948,6 +2023,7 @@ export function useRealtimeSync(});return () => {+ releaseSyncTarget();unsubAny();unsubGitHubInstallationCreated();unsubIssueUpdated();@@ -2005,14 +2081,15 @@ export function useRealtimeSync(workingAgentTimers.forEach(clearTimeout);workingAgentTimers.clear();workingAgentDirty.clear();+ workingAgentCauses.clear();};- }, [ws, qc, authStore, onToast]);+ }, [client, qc, authStore, onToast]);// Reconnect -> refetch all data to recover missed eventsuseEffect(() => {- if (!ws) return;+ if (!client) return;- const unsub = ws.onReconnect(async () => {+ const unsub = client.onReconnect(async () => {logger.info("reconnected, refetching all data");try {invalidateWorkspaceScopedQueries(qc);@@ -2022,23 +2099,23 @@ export function useRealtimeSync(});return unsub;- }, [ws, qc]);+ }, [client, qc]);// New WSClient instance (workspace switch) -> invalidate workspace-scoped// queries to recover events missed while the previous instance was torn down.// Skips the initial assignment to avoid a redundant refetch on first mount.const wsInstanceRef = useRef<WSClient | null>(null);useEffect(() => {- if (!ws) return;+ if (!client) return;if (wsInstanceRef.current === null) {// First non-null instance — store and skip invalidation.- wsInstanceRef.current = ws;+ wsInstanceRef.current = client;return;}- if (wsInstanceRef.current === ws) return;- wsInstanceRef.current = ws;+ if (wsInstanceRef.current === client) return;+ wsInstanceRef.current = client;logger.info("new WSClient instance detected, invalidating workspace queries");invalidateWorkspaceScopedQueries(qc);- }, [ws, qc]);+ }, [client, qc]);}diff --git a/packages/views/dev-toolbar/dev-toolbar.test.tsx b/packages/views/dev-toolbar/dev-toolbar.test.tsxindex 4332d8c008..779995c655 100644--- a/packages/views/dev-toolbar/dev-toolbar.test.tsx+++ b/packages/views/dev-toolbar/dev-toolbar.test.tsx@@ -1,16 +1,46 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { render, screen, fireEvent, waitFor } from "@testing-library/react";+import { render, screen, fireEvent, waitFor, within } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { ApiClient } from "@multica/core/api/client";+import { WSClient } from "@multica/core/api/ws-client";import { resetDevRecorder } from "@multica/core/diagnostics";import { setCurrentWorkspace } from "@multica/core/platform";+import type { WSMessage } from "@multica/core/types";import { DevToolbar, type DevToolbarProps } from "./dev-toolbar";const mocks = vi.hoisted(() => ({wsStatus: "connected" as string,listMembers: vi.fn(),+ listRuntimes: vi.fn(),+ getAgentTaskSnapshot: vi.fn(),+ listAgents: vi.fn(),}));+class FakeSocket {+ static last: FakeSocket | null = null;+ onopen: (() => void) | null = null;+ onmessage: ((ev: { data: string }) => void) | null = null;+ onclose: (() => void) | null = null;+ onerror: (() => void) | null = null;+ constructor() {+ FakeSocket.last = this;+ }+ send() {}+ close() {}+}++/** A connected client whose frames go through the real dispatch path. */+function connectSocket() {+ vi.stubGlobal("WebSocket", FakeSocket as unknown as typeof WebSocket);+ const client = new WSClient("ws://localhost:18080/ws", { cookieAuth: true });+ client.connect();+ FakeSocket.last!.onopen!();+ return {+ client,+ emit: (msg: WSMessage) => FakeSocket.last!.onmessage!({ data: JSON.stringify(msg) }),+ };+}+vi.mock("@multica/core/realtime", () => ({useWSStatus: () => mocks.wsStatus,}));@@ -26,23 +56,31 @@ vi.mock("@multica/core/auth", () => {});vi.mock("@multica/core/api", () => ({- api: { listMembers: mocks.listMembers },+ api: {+ listMembers: mocks.listMembers,+ listRuntimes: mocks.listRuntimes,+ getAgentTaskSnapshot: mocks.getAgentTaskSnapshot,+ listAgents: mocks.listAgents,+ },}));function renderToolbar(props: Partial<DevToolbarProps> = {}) {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },});- return render(+ const onNavigate = vi.fn();+ const view = render(<QueryClientProvider client={queryClient}><DevToolbarbuild="web"apiUrl="http://localhost:18080"route="/acme/issues"+ onNavigate={onNavigate}{...props}/></QueryClientProvider>,);+ return { ...view, queryClient, onNavigate };}describe("DevToolbar", () => {@@ -52,6 +90,9 @@ describe("DevToolbar", () => {{ user_id: "user-1", role: "admin" },{ user_id: "user-2", role: "owner" },]);+ mocks.listRuntimes.mockReset().mockResolvedValue([]);+ mocks.getAgentTaskSnapshot.mockReset().mockResolvedValue([]);+ mocks.listAgents.mockReset().mockResolvedValue([]);});afterEach(() => {@@ -138,4 +179,75 @@ describe("DevToolbar", () => {fireEvent.click(screen.getByTestId("dev-toolbar-errors"));expect(await screen.findByText("Error: Cannot read properties of undefined")).toBeInTheDocument();});++ it("lists a realtime event with the query keys its handling wrote", async () => {+ const { queryClient } = renderToolbar();+ const { client, emit } = connectSocket();+ client.on("issue:updated", () => queryClient.setQueryData(["issues", "ws-1", "detail", "issue-1"], { id: "issue-1" }));+ emit({ type: "issue:updated", payload: { issue: { id: "issue-1", identifier: "MUL-1" } } });++ await waitFor(() => expect(screen.getByTestId("dev-toolbar-events")).toHaveTextContent("Events1/m"));+ fireEvent.click(screen.getByTestId("dev-toolbar-events"));+ fireEvent.click(await screen.findByText("issue:updated"));+ expect(screen.getByText("1 written")).toBeInTheDocument();+ expect(screen.getByText("written (1)")).toBeInTheDocument();+ expect(screen.getByText('["issues","ws-1","detail","issue-1"]')).toBeInTheDocument();+ });++ it("finds events that carry only an issue ID when searching by its key", async () => {+ renderToolbar();+ const { emit } = connectSocket();+ emit({ type: "issue:updated", payload: { issue: { id: "issue-1", identifier: "MUL-1" } } });+ emit({ type: "comment:created", payload: { comment: { id: "c1", issue_id: "issue-1" } } });+ emit({ type: "comment:created", payload: { comment: { id: "c2", issue_id: "issue-2" } } });++ await waitFor(() => expect(screen.getByTestId("dev-toolbar-events")).toHaveTextContent("Events3/m"));+ fireEvent.click(screen.getByTestId("dev-toolbar-events"));+ fireEvent.change(await screen.findByLabelText("Search events"), { target: { value: "mul-1" } });+ expect(screen.getAllByText(/^(issue:updated|comment:created)$/)).toHaveLength(2);++ fireEvent.change(screen.getByLabelText("Event type"), { target: { value: "comment:created" } });+ expect(screen.getAllByText("comment:created")).toHaveLength(1);+ expect(screen.queryByText("issue:updated")).not.toBeInTheDocument();+ });++ it("searches the query cache and invalidates one query by hand", async () => {+ const { queryClient } = renderToolbar();+ queryClient.setQueryData(["issues", "ws-1", "detail", "issue-1"], { id: "issue-1" });+ queryClient.setQueryData(["labels", "ws-1"], []);++ fireEvent.click(screen.getByTestId("dev-toolbar-cache"));+ fireEvent.change(await screen.findByLabelText("Search query keys"), { target: { value: "labels" } });+ expect(screen.queryByText('["issues","ws-1","detail","issue-1"]')).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: 'Invalidate ["labels","ws-1"]' }));+ expect(queryClient.getQueryState(["labels", "ws-1"])?.isInvalidated).toBe(true);+ expect(queryClient.getQueryState(["issues", "ws-1", "detail", "issue-1"])?.isInvalidated).toBe(false);+ });++ it("shows runtime health and opens the issue a running agent task works on", async () => {+ setCurrentWorkspace("acme", "ws-1");+ mocks.listRuntimes.mockResolvedValue([+ { id: "rt-1", name: "Claude (mac)", provider: "claude", runtime_mode: "local", status: "online", metadata: { cli_version: "0.9.1" }, last_seen_at: null, device_info: "" },+ { id: "rt-2", name: "Codex (mac)", provider: "codex", runtime_mode: "local", status: "offline", metadata: {}, last_seen_at: null, device_info: "" },+ ]);+ mocks.getAgentTaskSnapshot.mockResolvedValue([+ { id: "t-1", agent_id: "agent-1", issue_id: "issue-1", status: "running", created_at: "2026-11-12T04:00:00Z", started_at: null, dispatched_at: null },+ { id: "t-2", agent_id: "agent-1", issue_id: "issue-2", status: "completed", created_at: "2026-11-12T03:00:00Z", started_at: null, dispatched_at: null },+ ]);+ mocks.listAgents.mockResolvedValue([{ id: "agent-1", name: "Lambda" }]);+ const { onNavigate } = renderToolbar();++ await waitFor(() => expect(screen.getByTestId("dev-toolbar-runtimes")).toHaveTextContent("Runtimes1/2"));+ expect(screen.getByTestId("dev-toolbar-tasks")).toHaveTextContent("Tasks1");++ fireEvent.click(screen.getByTestId("dev-toolbar-runtimes"));+ expect(await screen.findByText("Claude (mac)")).toBeInTheDocument();+ expect(screen.getByText("v0.9.1")).toBeInTheDocument();++ fireEvent.click(screen.getByTestId("dev-toolbar-tasks"));+ const row = (await screen.findByText("Lambda")).closest("button")!;+ expect(within(row).getByText("running")).toBeInTheDocument();+ fireEvent.click(row);+ expect(onNavigate).toHaveBeenCalledWith("/acme/issues/issue-1");+ });});diff --git a/packages/views/dev-toolbar/dev-toolbar.tsx b/packages/views/dev-toolbar/dev-toolbar.tsxindex 072d7df740..c04bbbe3c1 100644--- a/packages/views/dev-toolbar/dev-toolbar.tsx+++ b/packages/views/dev-toolbar/dev-toolbar.tsx@@ -1,20 +1,25 @@"use client";import { useState, useSyncExternalStore, type ReactNode } from "react";-import { useQuery } from "@tanstack/react-query";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { agentTaskSnapshotOptions } from "@multica/core/agents/queries";import { useAuthStore } from "@multica/core/auth";+import { paths } from "@multica/core/paths";import {getCurrentSlug,getCurrentWsId,subscribeToCurrentSlug,} from "@multica/core/platform";import { useWSStatus, type WSStatus } from "@multica/core/realtime";+import { runtimeListOptions } from "@multica/core/runtimes/queries";import { memberListOptions } from "@multica/core/workspace/queries";import { Popover, PopoverContent, PopoverTrigger } from "@multica/ui/components/ui/popover";import { ChevronUp, Minus } from "@multica/ui/icons";import { cn } from "@multica/ui/lib/utils";import {+ activeTasks,apiHost,+ eventsInLastMinute,formatBytes,jankTone,memoryTone,@@ -31,6 +36,7 @@ import {SyncPanel,TONE_CLASS,} from "./panels";+import { CachePanel, EventsPanel, RuntimesPanel, TasksPanel } from "./realtime-panels";import { useDevRecorder, useMainThreadBlocked, useNavDuration, useNow } from "./use-dev-metrics";export interface DevToolbarProps {@@ -40,6 +46,8 @@ export interface DevToolbarProps {apiUrl: string;/** Current route as the platform's router sees it. */route: string;+ /** Open an in-app path, such as the issue an agent task runs for. */+ onNavigate: (path: string) => void;}// App shells size themselves to the viewport (`h-svh`, `h-screen`), so a fixed@@ -71,7 +79,14 @@ function useCurrentWorkspace() {enabled: Boolean(wsId),});const role = members?.find((m) => m.user_id === userId)?.role ?? null;- return { slug, role };+ return { slug, wsId, role };+}++/** Runtimes and agent tasks of the current workspace, from the app's own queries. */+function useWorkspaceAgents(wsId: string | null) {+ const { data: runtimes } = useQuery({ ...runtimeListOptions(wsId ?? ""), enabled: Boolean(wsId) });+ const { data: tasks } = useQuery({ ...agentTaskSnapshotOptions(wsId ?? ""), enabled: Boolean(wsId) });+ return { runtimes, tasks };}/** A bar reading that opens its detail panel. */@@ -113,18 +128,25 @@ function Metric({* client health. Each reading opens the recent history behind it. Platforms* mount it only in dev builds, behind an opt-in flag.*/-export function DevToolbar({ build, apiUrl, route }: DevToolbarProps) {+export function DevToolbar({ build, apiUrl, route, onNavigate }: DevToolbarProps) {const [minimized, setMinimized] = useState(false);const sync = useWSStatus();const recording = useDevRecorder(route, sync);const now = useNow(1_000);- const { slug, role } = useCurrentWorkspace();+ const queryClient = useQueryClient();+ const { slug, wsId, role } = useCurrentWorkspace();+ const { runtimes, tasks } = useWorkspaceAgents(wsId);const blocked = useMainThreadBlocked(recording, now);const nav = useNavDuration(route);const heap = recording.memory.at(-1)?.bytes ?? null;const inFlight = recording.requests.filter((r) => r.durationMs === null).length;const failed = recording.requests.filter(requestFailed).length;const errors = recording.errors.length;+ const queries = queryClient.getQueryCache().getAll();+ const fetching = queries.filter((q) => q.state.fetchStatus === "fetching").length;+ const online = runtimes?.filter((r) => r.status === "online").length ?? 0;+ const running = activeTasks(tasks ?? []).filter((t) => t.status === "running").length;+ const openIssue = slug ? (issueId: string) => onNavigate(paths.workspace(slug).issueDetail(issueId)) : null;const syncDot = (<span className={cn("size-1.5 shrink-0 rounded-full", SYNC_DOT_CLASS[sync])} />@@ -194,6 +216,14 @@ export function DevToolbar({ build, apiUrl, route }: DevToolbarProps) {><NetworkPanel recording={recording} apiUrl={apiUrl} workspaceSlug={slug} /></Metric>+ <Metric+ label="Cache"+ value={String(queries.length)}+ wide+ extra={fetching > 0 && <span className="text-brand">{`· ${fetching}↻`}</span>}+ >+ <CachePanel now={now} />+ </Metric><Metriclabel="Sync"value={sync}@@ -201,6 +231,24 @@ export function DevToolbar({ build, apiUrl, route }: DevToolbarProps) {><SyncPanel recording={recording} status={sync} /></Metric>+ <Metric label="Events" value={`${eventsInLastMinute(recording.frameCounts, now)}/m`} wide>+ <EventsPanel recording={recording} now={now} onOpenIssue={openIssue} />+ </Metric>+ {wsId && (+ <>+ <Metric+ label="Runtimes"+ value={runtimes ? `${online}/${runtimes.length}` : "—"}+ tone={runtimes && runtimes.length > 0 && online === 0 ? "bad" : "normal"}+ wide+ >+ <RuntimesPanel runtimes={runtimes} now={now} />+ </Metric>+ <Metric label="Tasks" value={tasks ? String(running) : "—"}>+ <TasksPanel tasks={tasks} wsId={wsId} now={now} onOpenIssue={openIssue} />+ </Metric>+ </>+ )}<Metric label="Errors" value={String(errors)} tone={errors > 0 ? "bad" : "normal"}><ErrorsPanel recording={recording} /></Metric>diff --git a/packages/views/dev-toolbar/metrics.test.ts b/packages/views/dev-toolbar/metrics.test.tsindex 783d70a6b4..9cf5506105 100644--- a/packages/views/dev-toolbar/metrics.test.ts+++ b/packages/views/dev-toolbar/metrics.test.ts@@ -1,12 +1,19 @@// @vitest-environment nodeimport { describe, expect, it } from "vitest";-import type { DevRequest } from "@multica/core/diagnostics";+import type { DevRealtimeEvent, DevRequest } from "@multica/core/diagnostics";+import type { AgentTask } from "@multica/core/types";import {+ activeTasks,apiHost,blockedRatio,+ cacheEffectSummary,curlCommand,+ eventMatches,+ eventsInLastMinute,firstStackFrame,+ formatAge,formatBytes,+ issueIdsForKey,jankTone,memoryTone,navDuration,@@ -15,6 +22,24 @@ import {requestFailed,} from "./metrics";+function event(overrides: Partial<DevRealtimeEvent>): DevRealtimeEvent {+ return {+ id: 1,+ at: 0,+ kind: "frame",+ type: "issue:updated",+ issueId: null,+ issueKey: null,+ payload: null,+ payloadNote: null,+ actor: null,+ workspaceId: "ws-1",+ cache: { written: [], invalidated: [], removed: [], refetched: [] },+ downMs: null,+ ...overrides,+ };+}+const MB = 1024 * 1024;describe("formatBytes", () => {@@ -153,3 +178,75 @@ describe("firstStackFrame", () => {expect(firstStackFrame(null)).toBeNull();});});++describe("eventsInLastMinute", () => {+ it("sums the per-second frame counts from the last minute only", () => {+ const counts = [+ { at: 0, count: 7 },+ { at: 50_000, count: 400 },+ { at: 60_000, count: 101 },+ ];+ expect(eventsInLastMinute(counts, 61_000)).toBe(501);+ });+});++describe("cacheEffectSummary", () => {+ it("lists each kind of change with its count", () => {+ expect(cacheEffectSummary({ written: ["a"], invalidated: ["b", "c"], removed: [], refetched: ["b"] })).toBe(+ "1 written · 2 invalidated · 1 refetched",+ );+ expect(cacheEffectSummary(event({}).cache)).toBe("");+ });+});++describe("issueIdsForKey", () => {+ it("resolves an issue key through events and cached issues that carry both", () => {+ const events = [event({ issueId: "issue-1", issueKey: "MUL-1" })];+ const cached = [{ id: "issue-9", identifier: "mul-1" }, { id: "issue-2", identifier: "MUL-2" }, null, []];+ expect(issueIdsForKey(" mul-1 ", events, cached)).toEqual(["issue-1", "issue-9"]);+ });++ it("does nothing for a search that is not an issue key", () => {+ expect(issueIdsForKey("issue:updated", [event({ issueId: "issue-1", issueKey: "MUL-1" })], [])).toEqual([]);+ });+});++describe("eventMatches", () => {+ const comment = event({ type: "comment:created", issueId: "issue-1", payload: '{"comment":{"body":"Looks good"}}' });++ it("matches type, issue ID and payload text, case-insensitively", () => {+ expect(eventMatches(comment, "COMMENT:", [])).toBe(true);+ expect(eventMatches(comment, "issue-1", [])).toBe(true);+ expect(eventMatches(comment, "looks good", [])).toBe(true);+ expect(eventMatches(comment, "MUL-1", [])).toBe(false);+ });++ it("matches an issue key through the IDs it resolved to", () => {+ expect(eventMatches(comment, "MUL-1", ["issue-1"])).toBe(true);+ });+});++describe("activeTasks", () => {+ it("keeps tasks that have not finished, oldest first", () => {+ const task = (id: string, status: AgentTask["status"], created_at: string) =>+ ({ id, status, created_at }) as AgentTask;+ const tasks = [+ task("done", "completed", "2026-01-01T00:00:00Z"),+ task("later", "running", "2026-01-01T00:02:00Z"),+ task("first", "queued", "2026-01-01T00:01:00Z"),+ task("parked", "waiting_local_directory", "2026-01-01T00:03:00Z"),+ ];+ expect(activeTasks(tasks).map((t) => t.id)).toEqual(["first", "later", "parked"]);+ });+});++describe("formatAge", () => {+ it("rounds down to the largest whole unit", () => {+ expect([formatAge(400), formatAge(12_900), formatAge(4 * 60_000 + 5), formatAge(2 * 3_600_000)]).toEqual([+ "now",+ "12s",+ "4m",+ "2h",+ ]);+ });+});diff --git a/packages/views/dev-toolbar/metrics.ts b/packages/views/dev-toolbar/metrics.tsindex 83460708a5..86417827d8 100644--- a/packages/views/dev-toolbar/metrics.ts+++ b/packages/views/dev-toolbar/metrics.ts@@ -1,4 +1,11 @@-import type { DevRequest } from "@multica/core/diagnostics";+import type {+ DevCacheChange,+ DevCacheEffects,+ DevFrameCount,+ DevRealtimeEvent,+ DevRequest,+} from "@multica/core/diagnostics";+import type { AgentTask } from "@multica/core/types";export type MetricTone = "normal" | "warn" | "bad";@@ -125,3 +132,87 @@ export function formatClock(at: number): string {export function formatDuration(ms: number): string {return ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`;}++/** Coarse age: `now`, `12s`, `4m`, `2h`. */+export function formatAge(ms: number): string {+ if (ms < 1000) return "now";+ if (ms < 60_000) return `${Math.floor(ms / 1000)}s`;+ if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m`;+ return `${Math.floor(ms / 3_600_000)}h`;+}++/** Frames received from the server in the last minute, from the per-second counts. */+export function eventsInLastMinute(frameCounts: readonly DevFrameCount[], now: number): number {+ let total = 0;+ for (const bucket of frameCounts) if (now - bucket.at < 60_000) total += bucket.count;+ return total;+}++export const CACHE_CHANGE_LABEL: Record<DevCacheChange, string> = {+ written: "written",+ invalidated: "invalidated",+ removed: "removed",+ refetched: "refetched",+};++/** `2 written · 5 invalidated`, or empty when the event left the cache alone. */+export function cacheEffectSummary(cache: DevCacheEffects): string {+ return (Object.keys(CACHE_CHANGE_LABEL) as DevCacheChange[])+ .filter((change) => cache[change].length > 0)+ .map((change) => `${cache[change].length} ${CACHE_CHANGE_LABEL[change]}`)+ .join(" · ");+}++const ISSUE_KEY = /^[a-z][a-z0-9]*-\d+$/i;++/**+ * IDs of the issue a search names by key, such as `MUL-12`. Most events carry+ * only an issue ID, so the key is resolved through events and cached issues+ * that carry both.+ */+export function issueIdsForKey(+ query: string,+ events: readonly DevRealtimeEvent[],+ cachedData: readonly unknown[],+): string[] {+ const key = query.trim();+ if (!ISSUE_KEY.test(key)) return [];+ const sameKey = (value: unknown) => typeof value === "string" && value.toLowerCase() === key.toLowerCase();+ const ids = new Set<string>();+ for (const event of events) if (event.issueId && sameKey(event.issueKey)) ids.add(event.issueId);+ for (const data of cachedData) {+ if (!data || typeof data !== "object") continue;+ const { id, identifier } = data as { id?: unknown; identifier?: unknown };+ if (typeof id === "string" && sameKey(identifier)) ids.add(id);+ }+ return [...ids];+}++/** Matches type, issue key or ID, or any payload text; `issueIds` widens a key search. */+export function eventMatches(event: DevRealtimeEvent, query: string, issueIds: readonly string[]): boolean {+ const needle = query.trim().toLowerCase();+ if (!needle) return true;+ if (event.issueId && issueIds.includes(event.issueId)) return true;+ return [event.type, event.issueKey, event.issueId, event.payload].some(+ (text) => text?.toLowerCase().includes(needle),+ );+}++/** The issue an event is about, as the event list labels it. */+export function eventSubject(event: DevRealtimeEvent): string {+ return event.issueKey ?? (event.issueId ? event.issueId.slice(0, 8) : "");+}++const TERMINAL_TASK_STATUSES: ReadonlySet<AgentTask["status"]> = new Set(["completed", "failed", "cancelled"]);++/** Tasks still queued, waiting or running, oldest first. */+export function activeTasks(tasks: readonly AgentTask[]): AgentTask[] {+ return tasks+ .filter((task) => !TERMINAL_TASK_STATUSES.has(task.status))+ .sort((a, b) => a.created_at.localeCompare(b.created_at));+}++/** When the task started doing anything: run start, else dispatch, else creation. */+export function taskStartedAt(task: AgentTask): number {+ return Date.parse(task.started_at ?? task.dispatched_at ?? task.created_at);+}diff --git a/packages/views/dev-toolbar/panels.tsx b/packages/views/dev-toolbar/panels.tsxindex 83509f8049..3d9408dcaa 100644--- a/packages/views/dev-toolbar/panels.tsx+++ b/packages/views/dev-toolbar/panels.tsx@@ -44,42 +44,53 @@ function longTaskTone(ms: number): MetricTone {return "normal";}-async function copy(text: string, what: string) {+export async function copy(text: string, what: string) {if (await copyText(text)) toast.success(`Copied ${what}`);else toast.error(`Could not copy ${what}`);}-function PanelHeader({ title, children }: { title: string; children?: ReactNode }) {+export function PanelHeader({+ title,+ note = `last ${DEV_RECORDING_WINDOW_MS / 60_000} min`,+ children,+}: {+ title: string;+ /** What the panel covers; recorded history by default. */+ note?: string;+ children?: ReactNode;+}) {return (<div className="flex items-center gap-2 border-b border-border px-3 py-2"><span className="font-medium text-foreground">{title}</span>- <span className="text-micro text-muted-foreground">last {DEV_RECORDING_WINDOW_MS / 60_000} min</span>+ <span className="text-micro text-muted-foreground">{note}</span><div className="ml-auto flex items-center gap-1">{children}</div></div>);}-function Stats({ items }: { items: { label: string; value: string; tone?: MetricTone }[] }) {+export function Stats({ items }: { items: { label: string; value: string; tone?: MetricTone }[] }) {return (<div className="grid grid-flow-col auto-cols-fr border-b border-border">{items.map((item) => (- <div key={item.label} className="flex flex-col gap-0.5 px-3 py-2">+ <div key={item.label} className="flex min-w-0 flex-col gap-0.5 px-3 py-2"><span className="text-micro text-muted-foreground">{item.label}</span>- <span className={cn("font-mono tabular-nums", TONE_CLASS[item.tone ?? "normal"])}>{item.value}</span>+ <span className={cn("truncate font-mono tabular-nums", TONE_CLASS[item.tone ?? "normal"])} title={item.value}>+ {item.value}+ </span></div>))}</div>);}-function Rows({ children, empty }: { children: ReactNode[]; empty: string }) {+export function Rows({ children, empty }: { children: ReactNode[]; empty: string }) {if (children.length === 0) {return <div className="px-3 py-6 text-center text-muted-foreground">{empty}</div>;}return <div className="max-h-80 overflow-y-auto py-1">{children}</div>;}-function SmallButton({+export function SmallButton({onClick,children,active,diff --git a/packages/views/dev-toolbar/realtime-panels.tsx b/packages/views/dev-toolbar/realtime-panels.tsxnew file mode 100644index 0000000000..1bdf2889b4--- /dev/null+++ b/packages/views/dev-toolbar/realtime-panels.tsx@@ -0,0 +1,432 @@+"use client";++import { useState } from "react";+import { useQuery, useQueryClient, type Query } from "@tanstack/react-query";+import { toast } from "sonner";+import {+ clearDevEvents,+ dropDevConnection,+ replayDevEvent,+ type DevCacheChange,+ type DevRealtimeEvent,+ type DevRecording,+} from "@multica/core/diagnostics";+import { agentListOptions } from "@multica/core/workspace/queries";+import { readRuntimeCliVersion, runtimeDisplayName } from "@multica/core/runtimes";+import type { AgentRuntime, AgentTask } from "@multica/core/types";+import { ChevronDown, ChevronRight, Copy, ExternalLink, RefreshCw, RotateCcw, Trash2, Unplug } from "@multica/ui/icons";+import { cn } from "@multica/ui/lib/utils";+import {+ activeTasks,+ CACHE_CHANGE_LABEL,+ cacheEffectSummary,+ eventMatches,+ eventsInLastMinute,+ eventSubject,+ formatAge,+ formatClock,+ formatDuration,+ issueIdsForKey,+ taskStartedAt,+} from "./metrics";+import { copy, PanelHeader, Rows, SmallButton, Stats } from "./panels";++const FIELD_CLASS =+ "h-6 min-w-0 rounded-md border border-border bg-background px-2 text-caption text-foreground outline-none placeholder:text-muted-foreground focus:border-ring";+const SHOWN_MAX = 200;+const LIVE = "live";++function KeyList({ change, keys }: { change: DevCacheChange; keys: readonly string[] }) {+ if (keys.length === 0) return null;+ return (+ <div className="flex flex-col gap-0.5">+ <span className="text-muted-foreground">{`${CACHE_CHANGE_LABEL[change]} (${keys.length})`}</span>+ <div className="max-h-24 overflow-auto rounded-md bg-muted px-2 py-1 font-mono text-micro">+ {keys.map((key) => (+ <div key={key} className="truncate" title={key}>+ {key}+ </div>+ ))}+ </div>+ </div>+ );+}++function ReconnectRow({ event }: { event: DevRealtimeEvent }) {+ const { invalidated, refetched } = event.cache;+ return (+ <div className="flex items-center gap-2 border-y border-warning/30 bg-warning/10 px-3 py-1 font-mono">+ <Unplug className="size-3 shrink-0 text-warning" />+ <span className="shrink-0 text-muted-foreground">{formatClock(event.at)}</span>+ <span className="min-w-0 flex-1 truncate text-foreground">+ {event.downMs === null ? "Reconnected" : `Reconnected after ${formatDuration(event.downMs)} down`}+ </span>+ <span className="shrink-0 text-muted-foreground">+ {`refetched ${refetched.length} · invalidated ${invalidated.length}`}+ </span>+ </div>+ );+}++function EventRow({+ event,+ expanded,+ onToggle,+ onOpenIssue,+}: {+ event: DevRealtimeEvent;+ expanded: boolean;+ onToggle: () => void;+ onOpenIssue: ((issueId: string) => void) | null;+}) {+ const summary = cacheEffectSummary(event.cache);+ const Chevron = expanded ? ChevronDown : ChevronRight;+ const replay = () => {+ const refusal = replayDevEvent(event.id);+ if (refusal) toast.error(`Cannot replay: ${refusal}`);+ else toast.success(`Replayed ${event.type} locally`);+ };+ return (+ <div className={cn(event.kind === "replay" && "bg-brand/5")}>+ <button+ type="button"+ onClick={onToggle}+ aria-expanded={expanded}+ className="flex w-full items-center gap-2 px-3 py-1 text-left font-mono hover:bg-accent"+ >+ <Chevron className="size-3 shrink-0 text-muted-foreground" />+ <span className="shrink-0 text-muted-foreground">{formatClock(event.at)}</span>+ <span className="shrink-0 text-foreground">{event.type}</span>+ {event.kind === "replay" && <span className="shrink-0 text-brand">replay</span>}+ <span className="min-w-0 flex-1 truncate text-muted-foreground">{eventSubject(event)}</span>+ <span className={cn("shrink-0", summary ? "text-foreground" : "text-muted-foreground")}>+ {summary || "no cache change"}+ </span>+ </button>+ {expanded && (+ <div className="flex flex-col gap-2 px-3 pt-1 pb-2 pl-8">+ {event.actor && <div className="font-mono text-muted-foreground">{`by ${event.actor}`}</div>}+ {summary ? (+ (Object.keys(CACHE_CHANGE_LABEL) as DevCacheChange[]).map((change) => (+ <KeyList key={change} change={change} keys={event.cache[change]} />+ ))+ ) : (+ <div className="text-muted-foreground">+ Handling this event did not touch the query cache, or did so only after an await.+ </div>+ )}+ {event.payload !== null && (+ <pre className="max-h-40 overflow-auto rounded-md bg-muted p-2 font-mono text-micro whitespace-pre-wrap break-all">+ {event.payload}+ </pre>+ )}+ {event.payloadNote && <div className="text-muted-foreground">{`Payload ${event.payloadNote}.`}</div>}+ <div className="flex gap-1">+ <SmallButton onClick={replay}>+ <RotateCcw className="size-3" />+ Replay locally+ </SmallButton>+ {event.payload !== null && (+ <SmallButton onClick={() => void copy(event.payload!, "payload")}>+ <Copy className="size-3" />+ Copy payload+ </SmallButton>+ )}+ {event.issueId && onOpenIssue && (+ <SmallButton onClick={() => onOpenIssue(event.issueId!)}>+ <ExternalLink className="size-3" />+ Open issue+ </SmallButton>+ )}+ </div>+ </div>+ )}+ </div>+ );+}++export function EventsPanel({+ recording,+ now,+ onOpenIssue,+}: {+ recording: DevRecording;+ now: number;+ onOpenIssue: ((issueId: string) => void) | null;+}) {+ const queryClient = useQueryClient();+ const [search, setSearch] = useState("");+ const [type, setType] = useState("");+ const [expandedId, setExpandedId] = useState<number | null>(null);+ const { events } = recording;++ const typeCounts = new Map<string, number>();+ for (const event of events) {+ if (event.kind !== "reconnect") typeCounts.set(event.type, (typeCounts.get(event.type) ?? 0) + 1);+ }+ const issueIds = issueIdsForKey(+ search,+ events,+ queryClient.getQueryCache().getAll().map((q) => q.state.data),+ );+ const shown = events+ .filter((e) => (type ? e.type === type : true) && eventMatches(e, search, issueIds))+ .slice(-SHOWN_MAX)+ .reverse();+ const reconnects = events.filter((e) => e.kind === "reconnect").length;+ const changed = events.filter((e) => e.kind !== "reconnect" && cacheEffectSummary(e.cache)).length;+ const drop = () => {+ if (!dropDevConnection()) toast.error("No live connection to drop");+ };++ return (+ <>+ <PanelHeader title="Realtime events">+ <SmallButton onClick={drop}>+ <Unplug className="size-3" />+ Drop connection+ </SmallButton>+ <SmallButton onClick={clearDevEvents}>+ <Trash2 className="size-3" />+ Clear+ </SmallButton>+ </PanelHeader>+ <Stats+ items={[+ { label: "Last minute", value: String(eventsInLastMinute(recording.frameCounts, now)) },+ { label: "Recorded", value: String(events.length - reconnects) },+ { label: "Changed cache", value: String(changed) },+ { label: "Reconnects", value: String(reconnects), tone: reconnects > 0 ? "warn" : "normal" },+ ]}+ />+ <div className="flex items-center gap-2 border-b border-border px-3 py-2">+ <input+ aria-label="Search events"+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Issue key, ID or payload text"+ className={cn(FIELD_CLASS, "flex-1")}+ />+ <select+ aria-label="Event type"+ value={type}+ onChange={(e) => setType(e.target.value)}+ className={cn(FIELD_CLASS, "w-48")}+ >+ <option value="">All types</option>+ {[...typeCounts].sort(([a], [b]) => a.localeCompare(b)).map(([name, count]) => (+ <option key={name} value={name}>{`${name} (${count})`}</option>+ ))}+ </select>+ </div>+ <Rows empty={events.length === 0 ? "No realtime events yet." : "No events match."}>+ {shown.map((event) =>+ event.kind === "reconnect" ? (+ <ReconnectRow key={event.id} event={event} />+ ) : (+ <EventRow+ key={event.id}+ event={event}+ expanded={expandedId === event.id}+ onToggle={() => setExpandedId((id) => (id === event.id ? null : event.id))}+ onOpenIssue={onOpenIssue}+ />+ ),+ )}+ </Rows>+ </>+ );+}++type CacheFilter = "all" | "stale" | "fetching";++function queryState(query: Query): { label: string; className: string } {+ if (query.state.fetchStatus === "fetching") return { label: "fetching", className: "text-brand" };+ if (query.state.status === "error") return { label: "error", className: "text-destructive" };+ if (query.state.status === "pending") return { label: "empty", className: "text-muted-foreground" };+ if (query.isStale()) return { label: "stale", className: "text-warning" };+ return { label: "fresh", className: "text-foreground" };+}++export function CachePanel({ now }: { now: number }) {+ const queryClient = useQueryClient();+ const [search, setSearch] = useState("");+ const [filter, setFilter] = useState<CacheFilter>("all");+ const queries = queryClient.getQueryCache().getAll();+ const stale = queries.filter((q) => q.isStale());+ const fetching = queries.filter((q) => q.state.fetchStatus === "fetching");+ const needle = search.trim().toLowerCase();+ const shown = (filter === "stale" ? stale : filter === "fetching" ? fetching : queries)+ .filter((q) => !needle || q.queryHash.toLowerCase().includes(needle))+ .sort((a, b) => b.state.dataUpdatedAt - a.state.dataUpdatedAt)+ .slice(0, SHOWN_MAX);+ const invalidate = (query: Query) => {+ void queryClient.invalidateQueries({ queryKey: query.queryKey, exact: true });+ };++ return (+ <>+ <PanelHeader title="Query cache" note={LIVE}>+ {(["all", "stale", "fetching"] as const).map((value) => (+ <SmallButton key={value} onClick={() => setFilter(value)} active={filter === value}>+ {value[0]!.toUpperCase() + value.slice(1)}+ </SmallButton>+ ))}+ </PanelHeader>+ <Stats+ items={[+ { label: "Queries", value: String(queries.length) },+ { label: "Stale", value: String(stale.length), tone: stale.length > 0 ? "warn" : "normal" },+ { label: "Fetching", value: String(fetching.length) },+ { label: "Unobserved", value: String(queries.filter((q) => q.getObserversCount() === 0).length) },+ ]}+ />+ <div className="flex items-center border-b border-border px-3 py-2">+ <input+ aria-label="Search query keys"+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Search query keys"+ className={cn(FIELD_CLASS, "flex-1")}+ />+ </div>+ <Rows empty={queries.length === 0 ? "The cache is empty." : "No queries match."}>+ {shown.map((query) => {+ const state = queryState(query);+ const observers = query.getObserversCount();+ return (+ <div key={query.queryHash} className="flex items-center gap-2 px-3 py-0.5 font-mono">+ <span className="min-w-0 flex-1 truncate" title={query.queryHash}>+ {query.queryHash}+ </span>+ <span className={cn("w-14 shrink-0 text-right", state.className)}>{state.label}</span>+ <span className="w-8 shrink-0 text-right text-muted-foreground" title="Observers">+ {observers === 0 ? "–" : `×${observers}`}+ </span>+ <span className="w-8 shrink-0 text-right text-muted-foreground" title="Last updated">+ {query.state.dataUpdatedAt ? formatAge(now - query.state.dataUpdatedAt) : "—"}+ </span>+ <button+ type="button"+ onClick={() => invalidate(query)}+ aria-label={`Invalidate ${query.queryHash}`}+ title="Invalidate"+ className="flex size-5 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"+ >+ <RefreshCw className="size-3" />+ </button>+ </div>+ );+ })}+ </Rows>+ </>+ );+}++export function RuntimesPanel({ runtimes, now }: { runtimes: readonly AgentRuntime[] | undefined; now: number }) {+ const list = runtimes ?? [];+ const online = list.filter((r) => r.status === "online");+ const versions = [...new Set(list.map((r) => readRuntimeCliVersion(r.metadata)).filter(Boolean))];+ return (+ <>+ <PanelHeader title="Runtimes" note={LIVE} />+ <Stats+ items={[+ { label: "Online", value: String(online.length), tone: list.length > 0 && online.length === 0 ? "bad" : "normal" },+ { label: "Offline", value: String(list.length - online.length) },+ { label: "CLI versions", value: versions.join(", ") || "—" },+ ]}+ />+ <Rows empty={runtimes === undefined ? "Loading runtimes…" : "No runtimes in this workspace."}>+ {list.map((runtime) => {+ const version = readRuntimeCliVersion(runtime.metadata);+ const seen = runtime.last_seen_at ? Date.parse(runtime.last_seen_at) : null;+ return (+ <div key={runtime.id} className="flex items-center gap-2 px-3 py-1 font-mono">+ <span+ className={cn(+ "size-1.5 shrink-0 rounded-full",+ runtime.status === "online" ? "bg-success" : "bg-muted-foreground/50",+ )}+ />+ <span className="min-w-0 flex-1 truncate text-foreground" title={runtime.device_info}>+ {runtimeDisplayName(runtime)}+ </span>+ <span className="shrink-0 text-muted-foreground">{`${runtime.provider} · ${runtime.runtime_mode}`}</span>+ <span className="max-w-44 shrink-0 truncate text-right" title={version ?? undefined}>+ {version ? `v${version.replace(/^v/, "")}` : "—"}+ </span>+ <span className="w-14 shrink-0 text-right text-muted-foreground" title="Last heartbeat">+ {seen === null ? "—" : formatAge(now - seen)}+ </span>+ </div>+ );+ })}+ </Rows>+ </>+ );+}++function taskSource(task: AgentTask): string {+ if (task.issue_id) return task.issue_identifier ?? task.issue_id.slice(0, 8);+ if (task.chat_session_id) return "chat";+ if (task.autopilot_run_id) return "autopilot";+ return "—";+}++export function TasksPanel({+ tasks,+ wsId,+ now,+ onOpenIssue,+}: {+ tasks: readonly AgentTask[] | undefined;+ wsId: string;+ now: number;+ onOpenIssue: ((issueId: string) => void) | null;+}) {+ const { data: agents } = useQuery(agentListOptions(wsId));+ const agentName = new Map(agents?.map((a) => [a.id, a.name]));+ const active = activeTasks(tasks ?? []);+ const running = active.filter((t) => t.status === "running").length;+ return (+ <>+ <PanelHeader title="Agent tasks" note={LIVE} />+ <Stats+ items={[+ { label: "Running", value: String(running) },+ { label: "Queued", value: String(active.filter((t) => t.status === "queued" || t.status === "dispatched").length) },+ { label: "Waiting", value: String(active.filter((t) => t.status === "waiting_local_directory" || t.status === "deferred").length) },+ ]}+ />+ <Rows empty={tasks === undefined ? "Loading tasks…" : "No agent task is queued or running."}>+ {active.map((task) => {+ const open = task.issue_id && onOpenIssue ? () => onOpenIssue(task.issue_id) : undefined;+ return (+ <button+ type="button"+ key={task.id}+ onClick={open}+ disabled={!open}+ title={open ? "Open the issue" : undefined}+ className="flex w-full items-center gap-2 px-3 py-1 text-left font-mono enabled:hover:bg-accent"+ >+ <span className={cn("w-20 shrink-0", task.status === "running" ? "text-success" : "text-warning")}>+ {task.status === "waiting_local_directory" ? "waiting" : task.status}+ </span>+ <span className="min-w-0 flex-1 truncate text-foreground">+ {agentName.get(task.agent_id) ?? task.agent_id.slice(0, 8)}+ </span>+ <span className="min-w-0 max-w-40 shrink-0 truncate text-muted-foreground" title={task.issue_title}>+ {taskSource(task)}+ </span>+ <span className="w-12 shrink-0 text-right tabular-nums text-muted-foreground">+ {formatAge(now - taskStartedAt(task))}+ </span>+ </button>+ );+ })}+ </Rows>+ </>+ );+}diff --git a/packages/views/dev-toolbar/use-dev-metrics.ts b/packages/views/dev-toolbar/use-dev-metrics.tsindex 3f0ea6d070..ab7512ba3e 100644--- a/packages/views/dev-toolbar/use-dev-metrics.ts+++ b/packages/views/dev-toolbar/use-dev-metrics.ts@@ -1,6 +1,7 @@"use client";import { useEffect, useRef, useState, useSyncExternalStore } from "react";+import { useQueryClient } from "@tanstack/react-query";import {getDevRecording,installDevRecorder,@@ -14,7 +15,8 @@ import { blockedRatio, JANK_WINDOW_MS, navDuration } from "./metrics";/** Start the recorder and feed it what only the platform knows: route and sync. */export function useDevRecorder(route: string, sync: string): DevRecording {- useEffect(() => installDevRecorder(), []);+ const queryClient = useQueryClient();+ useEffect(() => installDevRecorder(queryClient), [queryClient]);useEffect(() => recordDevRoute(route), [route]);useEffect(() => recordDevSyncStatus(sync), [sync]);return useSyncExternalStore(subscribeDevRecording, getDevRecording, getDevRecording);