Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9120 feat(dev): opt-in dev toolbar with detail panels (#10442)
Jiayuan Zhang52adf833da21
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex a1a7b8dd4b..bb3f4d4631 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -592,6 +592,18 @@ make migrate-downThese generic targets require a valid env file in the current directory.+### Dev Toolbar++Set `VITE_DEV_TOOLBAR=1` to pin a status bar to the bottom of the Web and Desktop dev builds. It shows the client, backend host, workspace, your role, and route, plus live JS heap, last navigation time, main-thread long-task share, in-flight requests, and WebSocket state. Production builds never render it.++```bash+VITE_DEV_TOOLBAR=1 make up # or: VITE_DEV_TOOLBAR=1 pnpm dev:web / pnpm dev:desktop+```++To keep it on, add the line to the env file `make` loads (`.env` / `.env.worktree`), or to `apps/web/.env.local` / `apps/desktop/.env.development.local` for a direct `pnpm dev:*`. The minimize button at its right end collapses it to a small handle.++Each 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).+## How Database Creation WorksDatabase creation is automatic.diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsxindex 9693cdfb7a..5b4d3dbbbd 100644--- a/apps/desktop/src/renderer/src/App.tsx+++ b/apps/desktop/src/renderer/src/App.tsx@@ -17,6 +17,7 @@ import { DesktopShell } from "./components/desktop-layout";import { UpdateNotification } from "./components/update-notification";import { NativeContextMenu } from "./components/native-context-menu";import { IssueWindow } from "./components/issue-window";+import { DesktopDevToolbar } from "./components/desktop-dev-toolbar";import { useTabStore } from "./stores/tab-store";import { useWindowOverlayStore } from "./stores/window-overlay-store";import { useOpenSettingsShortcut } from "./hooks/use-open-settings-shortcut";@@ -501,6 +502,12 @@ export default function App() {) : (<AppContent />)}+ {/* Opt-in dev status bar; see "Dev Toolbar" in CONTRIBUTING.md. */}+ {import.meta.env.DEV &&+ import.meta.env.VITE_DEV_TOOLBAR &&+ windowContext.kind === "main" && (+ <DesktopDevToolbar apiUrl={runtimeConfigResult.config.apiUrl} />+ )}</CoreProvider>) : (<BlockingRuntimeConfigError message={runtimeConfigResult.error.message} />diff --git a/apps/desktop/src/renderer/src/components/desktop-dev-toolbar.tsx b/apps/desktop/src/renderer/src/components/desktop-dev-toolbar.tsxnew file mode 100644index 0000000000..6016e69082--- /dev/null+++ b/apps/desktop/src/renderer/src/components/desktop-dev-toolbar.tsx@@ -0,0 +1,10 @@+import { DevToolbar } from "@multica/views/dev-toolbar";+import { useActiveTabUrl } from "@/stores/tab-store";++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} />;+}diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsxindex c828587032..bbdc314e2d 100644--- a/apps/web/app/layout.tsx+++ b/apps/web/app/layout.tsx@@ -12,6 +12,7 @@ import { SITE_TITLE, TITLE_TEMPLATE } from "@/platform/document-title";import {resolveBrowserApiBaseUrl,resolveBrowserWsUrl,+ resolveDevRemoteApiUrl,} from "@/config/runtime-urls";import { resolveGoogleAnalyticsId } from "@/config/google-analytics";import { GoogleAnalytics } from "@/components/google-analytics";@@ -140,6 +141,15 @@ export default async function RootLayout({const wsUrl = resolveBrowserWsUrl(process.env);// Opt-in Google Analytics: omitted entirely unless GOOGLE_ANALYTICS_ID is set.const googleAnalyticsId = resolveGoogleAnalyticsId(process.env);+ // Dev toolbar: a status bar pinned to the bottom of the window. Opt-in per+ // developer with VITE_DEV_TOOLBAR=1, the same convention and var prefix as+ // react-grab below, so one variable enables it on web and desktop. Without+ // an explicit API URL the browser goes through the dev proxy, so the+ // toolbar reports the proxy's upstream.+ const devToolbarApiUrl =+ process.env.NODE_ENV === "development" && process.env.VITE_DEV_TOOLBAR+ ? apiBaseUrl || resolveDevRemoteApiUrl(process.env)+ : undefined;return (<html@@ -172,6 +182,7 @@ export default async function RootLayout({resources={resources}apiBaseUrl={apiBaseUrl}wsUrl={wsUrl}+ devToolbarApiUrl={devToolbarApiUrl}>{children}</WebProviders>diff --git a/apps/web/components/web-dev-toolbar.tsx b/apps/web/components/web-dev-toolbar.tsxnew file mode 100644index 0000000000..afe80bad58--- /dev/null+++ b/apps/web/components/web-dev-toolbar.tsx@@ -0,0 +1,9 @@+"use client";++import { usePathname } from "next/navigation";+import { DevToolbar } from "@multica/views/dev-toolbar";++export function WebDevToolbar({ apiUrl }: { apiUrl: string }) {+ const pathname = usePathname();+ return <DevToolbar build="web" apiUrl={apiUrl} route={pathname} />;+}diff --git a/apps/web/components/web-providers.tsx b/apps/web/components/web-providers.tsxindex 4ff3f1b875..9acdd6f1ee 100644--- a/apps/web/components/web-providers.tsx+++ b/apps/web/components/web-providers.tsx@@ -1,6 +1,7 @@"use client";import { useEffect, useMemo } from "react";+import dynamic from "next/dynamic";import { CoreProvider } from "@multica/core/platform";import { installUserTimingCap } from "@multica/core/diagnostics";import { createBrowserCookieLocaleAdapter } from "@multica/core/i18n/browser";@@ -15,6 +16,13 @@ import {import { detectWebOS } from "@/platform/client-os";import { useUserLocaleSyncEnabled } from "@/platform/user-locale-sync";+// Client-only: every reading is a live client measurement the server cannot+// render, so server HTML would only ever mismatch on hydration.+const WebDevToolbar = dynamic(+ () => import("./web-dev-toolbar").then((m) => m.WebDevToolbar),+ { ssr: false },+);+// Legacy token in localStorage → keep this session in token mode so users who// logged in before the cookie-auth migration stay authed. They migrate to// cookie mode on their next logout/login cycle (logout clears multica_token).@@ -51,12 +59,15 @@ export function WebProviders({resources,apiBaseUrl,wsUrl,+ devToolbarApiUrl,}: {children: React.ReactNode;locale: SupportedLocale;resources: Record<string, LocaleResources>;apiBaseUrl?: string;wsUrl?: string;+ /** Set only when the dev toolbar is enabled; the backend it reports. */+ devToolbarApiUrl?: string;}) {const cookieAuth = !hasLegacyToken();const syncUserLocale = useUserLocaleSyncEnabled();@@ -87,6 +98,9 @@ export function WebProviders({><WebNavigationProvider><WebScrollRestorationProvider>{children}</WebScrollRestorationProvider>+ {process.env.NODE_ENV === "development" && devToolbarApiUrl && (+ <WebDevToolbar apiUrl={devToolbarApiUrl} />+ )}</WebNavigationProvider></CoreProvider>);diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex a8e92fa92d..f0f6bf1904 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -4,6 +4,7 @@ import { setCurrentWorkspace } from "../platform/workspace-storage";import { configStore } from "../config";import type { StorageAdapter, User } from "../types";import { ApiClient, ApiError, CHAT_DRAFT_RESTORE_CAPABILITY, clientErrorMessage } from "./client";+import { setApiRequestObserver } from "./request-observer";import { EMPTY_PLUGIN_PACKAGE_LIST, EMPTY_PLUGIN_PREVIEW, EMPTY_PLUGIN_SURFACE_LAUNCH } from "./schemas";afterEach(() => {@@ -3555,3 +3556,47 @@ describe("grouped created-by compatibility", () => {expect(new URL(fetchMock.mock.calls[1]![0]).searchParams.get("creator_id")).toBe("me");});});++describe("ApiClient request observer", () => {+ afterEach(() => setApiRequestObserver(null));++ function observe() {+ const events: unknown[] = [];+ setApiRequestObserver({+ onStart: (request) => events.push({ phase: "start", ...request }),+ onEnd: (result) => events.push({ phase: "end", ...result }),+ });+ return events;+ }++ it("reports each request's start and its status, sharing the X-Request-ID", async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response("[]", {+ status: 200, headers: { "Content-Type": "application/json" },+ }));+ vi.stubGlobal("fetch", fetchMock);+ const events = observe();+ await new ApiClient("https://api.example.test").listMembers("ws-1");++ const sentId = (fetchMock.mock.calls[0]?.[1]?.headers as Record<string, string>)["X-Request-ID"];+ expect(events).toEqual([+ { phase: "start", requestId: sentId, method: "GET", path: "/api/workspaces/ws-1/members", body: null },+ { phase: "end", requestId: sentId, status: 200, error: null },+ ]);+ });++ it("reports the server's error message for a failed request", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: "version conflict" }), {+ status: 500, headers: { "Content-Type": "application/json" },+ })));+ const events = observe();+ await expect(new ApiClient("https://api.example.test").listMembers("ws-1")).rejects.toThrow();+ expect(events[1]).toMatchObject({ phase: "end", status: 500, error: "version conflict" });+ });++ it("reports a request that never got a response", async () => {+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new TypeError("Failed to fetch")));+ const events = observe();+ await expect(new ApiClient("https://api.example.test").listMembers("ws-1")).rejects.toThrow();+ expect(events[1]).toMatchObject({ phase: "end", status: null, error: "TypeError: Failed to fetch" });+ });+});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 7f22c2943e..04b9c6812d 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -282,6 +282,7 @@ import { type Logger, noopLogger } from "../logger";import { createRequestId, createSafeId } from "../utils";import { getCurrentSlug } from "../platform/workspace-storage";import { parseWithFallback } from "./schema";+import { getApiRequestObserver } from "./request-observer";import {RuntimeProfileSchema,RuntimeProfileListSchema,@@ -1016,12 +1017,30 @@ export class ApiClient {this.logger.info(`→ ${method} ${path}`, { rid });- const send = () =>- fetch(`${this.baseUrl}${path}`, {- ...init,- headers: buildHeaders(),- credentials: "include",- });+ const observer = getApiRequestObserver();+ observer?.onStart({+ requestId: rid,+ method,+ path,+ body: typeof init?.body === "string" ? init.body : null,+ });++ const send = async () => {+ try {+ return await fetch(`${this.baseUrl}${path}`, {+ ...init,+ headers: buildHeaders(),+ credentials: "include",+ });+ } catch (err) {+ observer?.onEnd({+ requestId: rid,+ status: null,+ error: err instanceof Error && err.name === "AbortError" ? "aborted" : String(err),+ });+ throw err;+ }+ };let res = await send();@@ -1052,10 +1071,12 @@ export class ApiClient {const { message, body } = await this.parseErrorBody(res, `API error: ${res.status} ${res.statusText}`);const logLevel = res.status === 404 ? "warn" : "error";this.logger[logLevel](`← ${res.status} ${path}`, { rid, duration: `${Date.now() - start}ms`, error: message });+ observer?.onEnd({ requestId: rid, status: res.status, error: message });throw new ApiError(message, res.status, res.statusText, body);}this.logger.info(`← ${res.status} ${path}`, { rid, duration: `${Date.now() - start}ms` });+ observer?.onEnd({ requestId: rid, status: res.status, error: null });return res;}diff --git a/packages/core/api/index.ts b/packages/core/api/index.tsindex 10ad9a254e..68a2a5f1a2 100644--- a/packages/core/api/index.ts+++ b/packages/core/api/index.ts@@ -17,6 +17,8 @@ export type { ParseOptions } from "./schema";export { DuplicateIssueErrorBodySchema } from "./schemas";export type { DuplicateIssueErrorBody } from "./schemas";export { WSClient } from "./ws-client";+export { setApiRequestObserver } from "./request-observer";+export type { ApiRequestObserver } from "./request-observer";import type { ApiClient as ApiClientType } from "./client";diff --git a/packages/core/api/request-observer.ts b/packages/core/api/request-observer.tsnew file mode 100644index 0000000000..04d28bed82--- /dev/null+++ b/packages/core/api/request-observer.ts@@ -0,0 +1,25 @@+/**+ * Development hook into every request `ApiClient` sends through its common+ * path. Nothing registers one in production; the dev toolbar's recorder is the+ * only observer.+ */+export interface ApiRequestObserver {+ onStart(request: {+ requestId: string;+ method: string;+ path: string;+ body: string | null;+ }): void;+ /** `status` is null when the request never got a response. */+ onEnd(result: { requestId: string; status: number | null; error: string | null }): void;+}++let observer: ApiRequestObserver | null = null;++export function setApiRequestObserver(next: ApiRequestObserver | null): void {+ observer = next;+}++export function getApiRequestObserver(): ApiRequestObserver | null {+ return observer;+}diff --git a/packages/core/api/ws-client.test.ts b/packages/core/api/ws-client.test.tsindex 251e955c58..8a83f3219d 100644--- a/packages/core/api/ws-client.test.ts+++ b/packages/core/api/ws-client.test.ts@@ -243,6 +243,27 @@ describe("WSClient", () => {});}+ it("reports connecting, connected, then reconnecting until the next auth ack", () => {+ const ws = new WSClient("ws://example.test/ws");+ const listener = vi.fn();+ ws.onStatusChange(listener);+ ws.setAuth("tok", "acme");+ ws.connect();+ expect(ws.getStatus()).toBe("connecting");++ simulateAuthAck();+ expect(ws.getStatus()).toBe("connected");++ simulateDisconnect();+ expect(ws.getStatus()).toBe("reconnecting");+ vi.runOnlyPendingTimers();+ expect(ws.getStatus()).toBe("reconnecting");++ simulateAuthAck();+ expect(ws.getStatus()).toBe("connected");+ expect(listener).toHaveBeenCalledTimes(3);+ });+it("uses ~1000ms base delay for the first reconnect attempt", () => {// Pin Math.random so jitter is deterministic: random()=0.5 → jitter=0.vi.stubGlobal(diff --git a/packages/core/api/ws-client.ts b/packages/core/api/ws-client.tsindex 1e764ac526..7e513dc1e6 100644--- a/packages/core/api/ws-client.ts+++ b/packages/core/api/ws-client.ts@@ -32,6 +32,9 @@ export interface WSClientIdentity {os?: string;}+/** `connecting` covers the first attempt; any later attempt is `reconnecting`. */+export type WSConnectionStatus = "connecting" | "connected" | "reconnecting";+export class WSClient {private ws: WebSocket | null = null;private baseUrl: string;@@ -49,6 +52,8 @@ export class WSClient {private badFrameLogged = false;private onReconnectCallbacks = new Set<() => void>();private anyHandlers = new Set<(msg: WSMessage) => void>();+ private status: WSConnectionStatus = "connecting";+ private statusListeners = new Set<() => void>();private logger: Logger;/**@@ -82,6 +87,7 @@ export class WSClient {connect() {this.badFrameLogged = false;+ this.setStatus(this.reconnectAttempt > 0 ? "reconnecting" : "connecting");const url = new URL(this.baseUrl);// Token is never sent as a URL query parameter — it would be logged by// proxies, CDNs, and browser history. In cookie mode the HttpOnly cookie@@ -184,6 +190,7 @@ export class WSClient {);this.reconnectAttempt++;+ this.setStatus("reconnecting");this.logger.warn(`ws: disconnected, reconnecting in ${delay}ms (attempt ${this.reconnectAttempt})`,);@@ -194,6 +201,7 @@ export class WSClient {this.logger.info("connected");const recoveredConnection = this.hasConnectedBefore || this.reconnectAttempt > 0;this.reconnectAttempt = 0;+ this.setStatus("connected");if (recoveredConnection) {for (const cb of this.onReconnectCallbacks) {try {@@ -223,6 +231,24 @@ export class WSClient {this.handlers.clear();this.anyHandlers.clear();this.onReconnectCallbacks.clear();+ this.statusListeners.clear();+ }++ getStatus(): WSConnectionStatus {+ return this.status;+ }++ onStatusChange(listener: () => void) {+ this.statusListeners.add(listener);+ return () => {+ this.statusListeners.delete(listener);+ };+ }++ private setStatus(next: WSConnectionStatus) {+ if (this.status === next) return;+ this.status = next;+ for (const listener of this.statusListeners) listener();}on(event: WSEventType, handler: EventHandler) {diff --git a/packages/core/diagnostics/dev-recorder.test.ts b/packages/core/diagnostics/dev-recorder.test.tsnew file mode 100644index 0000000000..d119de6e93--- /dev/null+++ b/packages/core/diagnostics/dev-recorder.test.ts@@ -0,0 +1,192 @@+// @vitest-environment jsdom+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ApiClient } from "../api/client";+import { getApiRequestObserver } from "../api/request-observer";+import { createLogger } from "../logger";+import {+ formatConsoleArgs,+ getDevRecording,+ recordableBody,+ redactPath,+ installDevRecorder,+ recordDevNavigationDuration,+ recordDevRoute,+ recordDevSyncStatus,+ resetDevRecorder,+ subscribeDevRecording,+} from "./dev-recorder";++describe("dev recorder", () => {+ let consoleError: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ vi.useFakeTimers();+ consoleError = vi.spyOn(console, "error").mockImplementation(() => {});+ });++ afterEach(() => {+ resetDevRecorder();+ consoleError.mockRestore();+ vi.useRealTimers();+ });++ it("records a request from start to its response", () => {+ installDevRecorder();+ const observer = getApiRequestObserver()!;+ observer.onStart({ requestId: "r1", method: "POST", path: "/api/issues", body: '{"title":"x"}' });+ expect(getDevRecording().requests[0]).toMatchObject({ requestId: "r1", status: null, durationMs: null });++ vi.advanceTimersByTime(120);+ observer.onEnd({ requestId: "r1", status: 422, error: "title too long" });+ expect(getDevRecording().requests[0]).toMatchObject({ status: 422, error: "title too long", durationMs: 120 });+ });++ it("keeps credentials a request sent out of the recording", async () => {+ const fake = "fake-credential-for-test";+ const fetchMock = vi.fn().mockResolvedValue(new Response("{}", { status: 200 }));+ vi.stubGlobal("fetch", fetchMock);+ installDevRecorder();+ await new ApiClient("http://localhost:18080").connectVCS("ws-1", {+ provider: "gitlab",+ instance_url: "https://gitlab.example.test",+ access_token: fake,+ });++ expect(String(fetchMock.mock.calls[0]?.[1]?.body)).toContain(fake);+ const recorded = getDevRecording().requests[0]!;+ expect(recorded.body).not.toContain(fake);+ expect(JSON.parse(recorded.body!)).toMatchObject({ instance_url: "https://gitlab.example.test", access_token: "[redacted]" });+ vi.unstubAllGlobals();+ });++ it("expires history that has aged out of the window while idle, except requests still in flight", () => {+ installDevRecorder();+ const observer = getApiRequestObserver()!;+ recordDevRoute("/acme/issues");+ recordDevSyncStatus("connected");+ console.error("old error");+ observer.onStart({ requestId: "done", method: "GET", path: "/api/issues", body: null });+ observer.onEnd({ requestId: "done", status: 200, error: null });+ observer.onStart({ requestId: "hung", method: "GET", path: "/api/slow", body: null });++ vi.advanceTimersByTime(6 * 60_000);+ const recording = getDevRecording();+ expect(recording.requests.map((r) => r.requestId)).toEqual(["hung"]);+ expect([recording.errors.length, recording.navigations.length, recording.sync.length]).toEqual([0, 0, 0]);+ });++ it("tags errors with the route they happened on and keeps logging them", () => {+ installDevRecorder();+ recordDevRoute("/acme/issues");+ console.error("%s failed:", "Saving", new Error("boom"));++ expect(consoleError).toHaveBeenCalledOnce();+ expect(getDevRecording().errors[0]).toMatchObject({+ source: "console",+ message: "Saving failed: Error: boom",+ route: "/acme/issues",+ });+ expect(getDevRecording().errors[0]?.stack).toContain("boom");+ });++ it("leaves failed responses to the request log instead of counting them as errors too", () => {+ installDevRecorder();+ createLogger("api").error("← 500 /api/issues", { rid: "r1" });+ createLogger("auth").error("refresh failed");+ expect(getDevRecording().errors.map((e) => e.message)).toEqual([expect.stringContaining("refresh failed")]);+ });++ it("records uncaught errors but not Chromium's ResizeObserver notice", () => {+ installDevRecorder();+ window.dispatchEvent(new ErrorEvent("error", { message: "ResizeObserver loop completed with undelivered notifications." }));+ window.dispatchEvent(new ErrorEvent("error", { message: "boom", error: new TypeError("boom") }));+ expect(getDevRecording().errors.map((e) => [e.source, e.message])).toEqual([["uncaught", "TypeError: boom"]]);+ });++ it("records route changes and attaches the measured duration to the latest visit", () => {+ recordDevRoute("/acme/issues");+ recordDevRoute("/acme/inbox");+ recordDevRoute("/acme/inbox");+ recordDevNavigationDuration("/acme/inbox", 84);++ expect(getDevRecording().navigations.map((n) => [n.route, n.durationMs])).toEqual([+ ["/acme/issues", null],+ ["/acme/inbox", 84],+ ]);+ });++ it("records only actual sync status changes", () => {+ recordDevSyncStatus("connecting");+ recordDevSyncStatus("connected");+ recordDevSyncStatus("connected");+ expect(getDevRecording().sync.map((s) => s.status)).toEqual(["connecting", "connected"]);+ });++ it("notifies subscribers once per burst of changes", () => {+ const listener = vi.fn();+ subscribeDevRecording(listener);+ recordDevSyncStatus("connecting");+ recordDevSyncStatus("connected");+ expect(listener).not.toHaveBeenCalled();+ vi.advanceTimersByTime(100);+ expect(listener).toHaveBeenCalledOnce();+ });++ it("stops observing requests and restores console.error when reset", () => {+ const patched = console.error;+ installDevRecorder();+ expect(console.error).not.toBe(patched);+ resetDevRecorder();+ expect(console.error).toBe(patched);+ expect(getApiRequestObserver()).toBeNull();+ });+});++describe("formatConsoleArgs", () => {+ it("substitutes format tokens and drops %c styles", () => {+ expect(formatConsoleArgs(["%cWarn%c %d rows", "color:red", "", 3]).message).toBe("Warn 3 rows");+ });++ it("serializes objects that follow the message", () => {+ expect(formatConsoleArgs(["bad payload", { id: 1 }]).message).toBe('bad payload {"id":1}');+ });+});++describe("recordableBody", () => {+ it("redacts credential fields at any depth but keeps usage counts", () => {+ const { body, bodyNote } = recordableBody(+ JSON.stringify({+ name: "slack",+ config: { bot_token: "xoxb-1", app_token: "xapp-1", signing_secret: "s" },+ custom_env: { OPENAI_API_KEY: "sk-1" },+ github_tokens: ["ghp-1"],+ input_tokens: 120,+ }),+ );+ expect(bodyNote).toBeNull();+ expect(JSON.parse(body!)).toEqual({+ name: "slack",+ config: { bot_token: "[redacted]", app_token: "[redacted]", signing_secret: "[redacted]" },+ custom_env: "[redacted]",+ github_tokens: "[redacted]",+ input_tokens: 120,+ });+ });++ it("marks a long body as cut instead of passing it off as the whole request", () => {+ const { body, bodyNote } = recordableBody(JSON.stringify({ content: "a".repeat(2100) }));+ expect(body!.length).toBe(2001);+ expect(bodyNote).toBe("truncated to 2000 of 2114 characters");+ });++ it("keeps no body it cannot inspect for secrets", () => {+ expect(recordableBody("token=abc")).toEqual({ body: null, bodyNote: "not JSON (9 characters), so not recorded" });+ });+});++describe("redactPath", () => {+ it("redacts credential query parameters only", () => {+ expect(redactPath("/api/x?token=abc&limit=5")).toBe("/api/x?token=%5Bredacted%5D&limit=5");+ expect(redactPath("/api/issues?limit=5")).toBe("/api/issues?limit=5");+ });+});diff --git a/packages/core/diagnostics/dev-recorder.ts b/packages/core/diagnostics/dev-recorder.tsnew file mode 100644index 0000000000..c1e879d078--- /dev/null+++ b/packages/core/diagnostics/dev-recorder.ts@@ -0,0 +1,408 @@+// 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.++import { setApiRequestObserver } from "../api/request-observer";++export interface DevRequest {+ requestId: string;+ method: string;+ /** Sensitive query parameters are redacted. */+ path: string;+ /** JSON body with sensitive fields redacted; see `bodyNote` for what is missing. */+ body: string | null;+ /** Why `body` is not the whole request body, so it cannot be replayed as is. */+ bodyNote: string | null;+ /** Epoch ms. */+ startedAt: number;+ /** Null while in flight. */+ durationMs: number | null;+ /** Null while in flight, or when no response arrived. */+ status: number | null;+ /** Server error message, network error, or `aborted`. */+ error: string | null;+}++export interface DevNavigation {+ at: number;+ route: string;+ /** Input-to-paint time; null when no input explains the change. */+ durationMs: number | null;+}++export interface DevLongTask {+ at: number;+ durationMs: number;+ route: string | null;+}++export type DevErrorSource = "console" | "uncaught" | "rejection";++export interface DevError {+ at: number;+ source: DevErrorSource;+ message: string;+ stack: string | null;+ route: string | null;+}++export interface DevSyncChange {+ at: number;+ status: string;+}++export interface DevMemorySample {+ at: number;+ bytes: number;+}++export interface DevRecording {+ requests: readonly DevRequest[];+ navigations: readonly DevNavigation[];+ longTasks: readonly DevLongTask[];+ errors: readonly DevError[];+ sync: readonly DevSyncChange[];+ memory: readonly DevMemorySample[];+ /** JS heap ceiling on engines that report one. */+ heapLimit: number | null;+}++export const DEV_RECORDING_WINDOW_MS = 5 * 60_000;++const CAPS: Record<Exclude<keyof DevRecording, "heapLimit">, number> = {+ requests: 300,+ navigations: 50,+ longTasks: 200,+ errors: 100,+ sync: 50,+ memory: 150,+};++const BODY_MAX_CHARS = 2_000;+const MESSAGE_MAX_CHARS = 1_000;+const MEMORY_SAMPLE_MS = 2_000;+const PRUNE_INTERVAL_MS = 5_000;+// Panels re-render on every change; coalescing keeps a burst of requests, or+// an error logged while rendering, from turning into a render per entry.+const NOTIFY_DELAY_MS = 100;++const EMPTY: DevRecording = {+ requests: [],+ navigations: [],+ longTasks: [],+ errors: [],+ sync: [],+ memory: [],+ heapLimit: null,+};++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;++function scheduleNotify() {+ if (notifyTimer) return;+ notifyTimer = setTimeout(() => {+ notifyTimer = null;+ for (const listener of listeners) listener();+ }, NOTIFY_DELAY_MS);+}++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;+}++/** Requests still in flight stay however old they are: they have not ended yet. */+function pruneRequests(requests: readonly DevRequest[], now: number): DevRequest[] {+ const kept = requests.filter((r) => r.durationMs === null || now - r.startedAt <= DEV_RECORDING_WINDOW_MS);+ return kept.length > CAPS.requests ? kept.slice(kept.length - CAPS.requests) : kept;+}++/** Drop what has aged out of the window, so idle time empties the panels too. */+function pruneExpired(now: number) {+ const next: DevRecording = {+ ...recording,+ requests: pruneRequests(recording.requests, now),+ navigations: prune(recording.navigations, CAPS.navigations, now),+ longTasks: prune(recording.longTasks, CAPS.longTasks, now),+ errors: prune(recording.errors, CAPS.errors, now),+ sync: prune(recording.sync, CAPS.sync, 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);+}++// Names of fields and query parameters that carry credentials: VCS and bot+// tokens, webhook secrets and URLs, passwords, agent environment variables.+// Numbers are never redacted, so usage counts such as `input_tokens` survive.+const SENSITIVE_KEY =+ /(token|secret|password|passphrase|credential|api_?key|private_?key|webhook_url|env)s?$/i;+const REDACTED = "[redacted]";++function redactValue(value: unknown): unknown {+ if (Array.isArray(value)) return value.map(redactValue);+ if (value === null || typeof value !== "object") return value;+ return Object.fromEntries(+ Object.entries(value).map(([key, field]) => [+ key,+ SENSITIVE_KEY.test(key) && field !== null && typeof field !== "number" && typeof field !== "boolean"+ ? REDACTED+ : redactValue(field),+ ]),+ );+}++/** The path with sensitive query parameters redacted. */+export function redactPath(path: string): string {+ const query = path.indexOf("?");+ if (query < 0) return path;+ const params = new URLSearchParams(path.slice(query + 1));+ let redacted = false;+ for (const key of [...params.keys()]) {+ if (!SENSITIVE_KEY.test(key)) continue;+ params.set(key, REDACTED);+ redacted = true;+ }+ return redacted ? `${path.slice(0, query)}?${params.toString()}` : path;+}++/**+ * What of a request body can be kept for display and replay: JSON with+ * sensitive fields redacted, cut to a bounded size. Anything else is not kept,+ * since there is no telling what in it is a secret.+ */+export function recordableBody(body: string | null): Pick<DevRequest, "body" | "bodyNote"> {+ if (body === null) return { body: null, bodyNote: null };+ let parsed: unknown;+ try {+ parsed = JSON.parse(body);+ } catch {+ return { body: null, bodyNote: `not JSON (${body.length} characters), so not recorded` };+ }+ const redacted = JSON.stringify(redactValue(parsed));+ if (redacted.length <= BODY_MAX_CHARS) return { body: redacted, bodyNote: null };+ return {+ body: truncate(redacted, BODY_MAX_CHARS),+ bodyNote: `truncated to ${BODY_MAX_CHARS} of ${redacted.length} characters`,+ };+}++function update(patch: Partial<DevRecording>) {+ recording = { ...recording, ...patch };+ scheduleNotify();+}++function append<K extends Exclude<keyof DevRecording, "heapLimit" | "requests">>(+ key: K,+ item: DevRecording[K][number],+) {+ const list = [...(recording[key] as readonly { at: number }[]), item as { at: number }];+ update({ [key]: prune(list, CAPS[key], Date.now()) } as Partial<DevRecording>);+}++function truncate(text: string, max: number): string {+ return text.length > max ? `${text.slice(0, max)}…` : text;+}++/** `console.error("%s failed: %o", a, b)` as the console would print it. */+export function formatConsoleArgs(args: readonly unknown[]): { message: string; stack: string | null } {+ const rest = [...args];+ let stack: string | null = null;+ const show = (value: unknown): string => {+ if (value instanceof Error) {+ stack ??= value.stack ?? null;+ return `${value.name}: ${value.message}`;+ }+ if (typeof value === "string") return value;+ try {+ return JSON.stringify(value) ?? String(value);+ } catch {+ return String(value);+ }+ };+ let message = "";+ if (typeof rest[0] === "string") {+ message = (rest.shift() as string).replace(/%[sdifoOc]/g, (token) =>+ token === "%c" ? (rest.shift(), "") : rest.length ? show(rest.shift()) : token,+ );+ }+ const tail = rest.map(show).join(" ");+ message = [message, tail].filter(Boolean).join(" ");+ return { message: truncate(message, MESSAGE_MAX_CHARS), stack };+}++/**+ * The API client logs every failed response (`createLogger("api")`, message+ * `← 500 /path`). Requests already carry that failure, with more detail, so+ * counting the log line too would report each failure twice.+ */+function isApiResponseLog(args: readonly unknown[]): boolean {+ return (+ typeof args[0] === "string" &&+ args[0].endsWith("[api]") &&+ typeof args[2] === "string" &&+ args[2].startsWith("← ")+ );+}++function recordError(source: DevErrorSource, message: string, stack: string | null) {+ append("errors", { at: Date.now(), source, message, stack, route: currentRoute });+}++function readHeap(): { used: number; limit: number } | null {+ const memory = (+ performance as Performance & { memory?: { usedJSHeapSize: number; jsHeapSizeLimit: number } }+ ).memory;+ return memory ? { used: memory.usedJSHeapSize, limit: memory.jsHeapSizeLimit } : null;+}++/** Start recording. Idempotent, and a no-op outside the browser. */+export function installDevRecorder(): void {+ if (teardown || typeof window === "undefined") return;+ const cleanups: (() => void)[] = [];++ setApiRequestObserver({+ onStart: ({ requestId, method, path, body }) => {+ const request: DevRequest = {+ requestId,+ method,+ path: redactPath(path),+ ...recordableBody(body),+ startedAt: Date.now(),+ durationMs: null,+ status: null,+ error: null,+ };+ update({ requests: pruneRequests([...recording.requests, request], request.startedAt) });+ },+ onEnd: ({ requestId, status, error }) => {+ const now = Date.now();+ update({+ requests: recording.requests.map((r) =>+ r.requestId === requestId+ ? { ...r, status, error: error === null ? null : truncate(error, MESSAGE_MAX_CHARS), durationMs: now - r.startedAt }+ : r,+ ),+ });+ },+ });+ cleanups.push(() => setApiRequestObserver(null));++ if (PerformanceObserver.supportedEntryTypes?.includes("longtask")) {+ const observer = new PerformanceObserver((list) => {+ for (const entry of list.getEntries()) {+ append("longTasks", {+ at: performance.timeOrigin + entry.startTime,+ durationMs: entry.duration,+ route: currentRoute,+ });+ }+ });+ observer.observe({ type: "longtask" });+ cleanups.push(() => observer.disconnect());+ }++ const onError = (event: ErrorEvent) => {+ // Chromium reports a skipped resize callback as an error; it is not a bug.+ if (event.message.startsWith("ResizeObserver loop")) return;+ const error = event.error instanceof Error ? event.error : null;+ recordError("uncaught", error ? `${error.name}: ${error.message}` : event.message, error?.stack ?? null);+ };+ const onRejection = (event: PromiseRejectionEvent) => {+ const { message, stack } = formatConsoleArgs([event.reason]);+ recordError("rejection", message, stack);+ };+ window.addEventListener("error", onError);+ window.addEventListener("unhandledrejection", onRejection);+ cleanups.push(() => {+ window.removeEventListener("error", onError);+ window.removeEventListener("unhandledrejection", onRejection);+ });++ const originalConsoleError = console.error;+ console.error = (...args: unknown[]) => {+ originalConsoleError.apply(console, args);+ if (isApiResponseLog(args)) return;+ const { message, stack } = formatConsoleArgs(args);+ recordError("console", message, stack);+ };+ cleanups.push(() => {+ console.error = originalConsoleError;+ });++ const sampleHeap = () => {+ const heap = readHeap();+ if (!heap) return;+ recording = { ...recording, heapLimit: heap.limit };+ append("memory", { at: Date.now(), bytes: heap.used });+ };+ sampleHeap();+ const heapTimer = setInterval(sampleHeap, MEMORY_SAMPLE_MS);+ const pruneTimer = setInterval(() => pruneExpired(Date.now()), PRUNE_INTERVAL_MS);+ cleanups.push(() => {+ clearInterval(heapTimer);+ clearInterval(pruneTimer);+ });++ teardown = () => cleanups.forEach((cleanup) => cleanup());+}++/** The current route, so later entries say where they happened. */+export function recordDevRoute(route: string): void {+ if (route === currentRoute) return;+ currentRoute = route;+ append("navigations", { at: Date.now(), route, durationMs: null });+}++/** Attach the measured input-to-paint time to the latest visit of `route`. */+export function recordDevNavigationDuration(route: string, durationMs: number): void {+ const navigations = [...recording.navigations];+ for (let i = navigations.length - 1; i >= 0; i -= 1) {+ if (navigations[i]!.route !== route) continue;+ navigations[i] = { ...navigations[i]!, durationMs };+ update({ navigations });+ return;+ }+}++export function recordDevSyncStatus(status: string): void {+ if (recording.sync.at(-1)?.status === status) return;+ append("sync", { at: Date.now(), status });+}++export function clearDevRequests(): void {+ update({ requests: recording.requests.filter((r) => r.durationMs === null) });+}++export function clearDevErrors(): void {+ update({ errors: [] });+}++export function subscribeDevRecording(listener: () => void): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++export function getDevRecording(): DevRecording {+ return recording;+}++/** Test seam: stop recording and drop everything recorded. */+export function resetDevRecorder(): void {+ teardown?.();+ teardown = null;+ if (notifyTimer) clearTimeout(notifyTimer);+ notifyTimer = null;+ recording = EMPTY;+ currentRoute = null;+ listeners.clear();+}diff --git a/packages/core/diagnostics/index.ts b/packages/core/diagnostics/index.tsindex 87a30fac6e..2070ef62c6 100644--- a/packages/core/diagnostics/index.ts+++ b/packages/core/diagnostics/index.ts@@ -1,5 +1,27 @@export { installFreezeWatchdog } from "./freeze-watchdog";export { installUserTimingCap } from "./user-timing-cap";+export {+ clearDevErrors,+ clearDevRequests,+ DEV_RECORDING_WINDOW_MS,+ getDevRecording,+ installDevRecorder,+ recordDevNavigationDuration,+ recordDevRoute,+ recordDevSyncStatus,+ resetDevRecorder,+ subscribeDevRecording,+} from "./dev-recorder";+export type {+ DevError,+ DevErrorSource,+ DevLongTask,+ DevMemorySample,+ DevNavigation,+ DevRecording,+ DevRequest,+ DevSyncChange,+} from "./dev-recorder";export {bucketDiagnosticPath,getDiagnosticRoute,diff --git a/packages/core/realtime/hooks.ts b/packages/core/realtime/hooks.tsindex b909c55c8c..db47b22ed5 100644--- a/packages/core/realtime/hooks.ts+++ b/packages/core/realtime/hooks.ts@@ -1,8 +1,8 @@"use client";-import { useEffect } from "react";+import { useEffect, useSyncExternalStore } from "react";import type { WSEventType } from "../types";-import { useWS } from "./provider";+import { useWS, type WSStatus } from "./provider";type EventHandler = (payload: unknown, actorId?: string, actorType?: string) => void;@@ -31,3 +31,9 @@ export function useWSReconnect(callback: () => void) {return unsub;}, [callback, onReconnect]);}++/** Live connection state of the workspace WebSocket. */+export function useWSStatus(): WSStatus {+ const { subscribeStatus, getStatus } = useWS();+ return useSyncExternalStore(subscribeStatus, getStatus, () => "offline");+}diff --git a/packages/core/realtime/index.ts b/packages/core/realtime/index.tsindex 639c9ae683..d4b3334758 100644--- a/packages/core/realtime/index.ts+++ b/packages/core/realtime/index.ts@@ -1,5 +1,5 @@export { WSProvider, useWS } from "./provider";-export type { WSProviderProps } from "./provider";-export { useWSEvent, useWSReconnect } from "./hooks";+export type { WSProviderProps, WSStatus } from "./provider";+export { useWSEvent, useWSReconnect, useWSStatus } from "./hooks";export { useRealtimeSync, removeChatMessageFromCaches } from "./use-realtime-sync";export type { RealtimeSyncStores } from "./use-realtime-sync";diff --git a/packages/core/realtime/provider.tsx b/packages/core/realtime/provider.tsxindex b1ee65aa25..0b023fec67 100644--- a/packages/core/realtime/provider.tsx+++ b/packages/core/realtime/provider.tsx@@ -9,7 +9,7 @@ import {useSyncExternalStore,type ReactNode,} from "react";-import { WSClient } from "../api/ws-client";+import { WSClient, type WSConnectionStatus } from "../api/ws-client";import type { WSEventType, StorageAdapter } from "../types";import type { ClientIdentity } from "../platform/types";import type { StoreApi, UseBoundStore } from "zustand";@@ -26,9 +26,14 @@ import { useRealtimeSync, type RealtimeSyncStores } from "./use-realtime-sync";type EventHandler = (payload: unknown, actorId?: string, actorType?: string) => void;+/** `offline` means no connection is wanted: signed out or outside a workspace. */+export type WSStatus = WSConnectionStatus | "offline";+interface WSContextValue {subscribe: (event: WSEventType, handler: EventHandler) => () => void;onReconnect: (callback: () => void) => () => void;+ subscribeStatus: (listener: () => void) => () => void;+ getStatus: () => WSStatus;}const WSContext = createContext<WSContextValue | null>(null);@@ -149,8 +154,23 @@ export function WSProvider({[wsClient],);+ const subscribeStatus = useCallback(+ (listener: () => void) => {+ if (!wsClient) return () => {};+ return wsClient.onStatusChange(listener);+ },+ [wsClient],+ );++ const getStatus = useCallback(+ (): WSStatus => wsClient?.getStatus() ?? "offline",+ [wsClient],+ );+return (- <WSContext.Provider value={{ subscribe, onReconnect: onReconnectCb }}>+ <WSContext.Provider+ value={{ subscribe, onReconnect: onReconnectCb, subscribeStatus, getStatus }}+ >{children}</WSContext.Provider>);diff --git a/packages/views/dev-toolbar/dev-toolbar.test.tsx b/packages/views/dev-toolbar/dev-toolbar.test.tsxnew file mode 100644index 0000000000..4332d8c008--- /dev/null+++ b/packages/views/dev-toolbar/dev-toolbar.test.tsx@@ -0,0 +1,141 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { render, screen, fireEvent, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { ApiClient } from "@multica/core/api/client";+import { resetDevRecorder } from "@multica/core/diagnostics";+import { setCurrentWorkspace } from "@multica/core/platform";+import { DevToolbar, type DevToolbarProps } from "./dev-toolbar";++const mocks = vi.hoisted(() => ({+ wsStatus: "connected" as string,+ listMembers: vi.fn(),+}));++vi.mock("@multica/core/realtime", () => ({+ useWSStatus: () => mocks.wsStatus,+}));++vi.mock("@multica/core/auth", () => {+ const state = { user: { id: "user-1" } };+ return {+ useAuthStore: Object.assign(+ (selector: (s: typeof state) => unknown) => selector(state),+ { getState: () => state },+ ),+ };+});++vi.mock("@multica/core/api", () => ({+ api: { listMembers: mocks.listMembers },+}));++function renderToolbar(props: Partial<DevToolbarProps> = {}) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={queryClient}>+ <DevToolbar+ build="web"+ apiUrl="http://localhost:18080"+ route="/acme/issues"+ {...props}+ />+ </QueryClientProvider>,+ );+}++describe("DevToolbar", () => {+ beforeEach(() => {+ mocks.wsStatus = "connected";+ mocks.listMembers.mockReset().mockResolvedValue([+ { user_id: "user-1", role: "admin" },+ { user_id: "user-2", role: "owner" },+ ]);+ });++ afterEach(() => {+ resetDevRecorder();+ vi.unstubAllGlobals();+ setCurrentWorkspace(null, null);+ });++ it("shows the client, backend, workspace role and connection state", async () => {+ setCurrentWorkspace("acme", "ws-1");+ mocks.wsStatus = "reconnecting";+ renderToolbar();++ const bar = screen.getByTestId("dev-toolbar");+ expect(bar).toHaveTextContent("web");+ expect(bar).toHaveTextContent("localhost:18080");+ expect(bar).toHaveTextContent("acme");+ expect(bar).toHaveTextContent("/acme/issues");+ expect(bar).toHaveTextContent("Syncreconnecting");+ expect(await screen.findByText("admin")).toBeInTheDocument();+ expect(mocks.listMembers).toHaveBeenCalledWith("ws-1");+ });++ it("does not look up a role outside a workspace", () => {+ renderToolbar();+ expect(screen.getByTestId("dev-toolbar")).toBeInTheDocument();+ expect(mocks.listMembers).not.toHaveBeenCalled();+ });++ it("reserves its height from viewport-sized shells only while expanded", () => {+ const reservesSpace = () =>+ [...document.querySelectorAll("style")].some((s) =>+ s.textContent?.includes(".h-svh{height:calc(100svh - 24px)}"),+ );+ renderToolbar();+ expect(reservesSpace()).toBe(true);++ fireEvent.click(screen.getByRole("button", { name: "Hide dev toolbar" }));+ expect(screen.queryByTestId("dev-toolbar")).not.toBeInTheDocument();+ expect(reservesSpace()).toBe(false);++ fireEvent.click(screen.getByTestId("dev-toolbar-restore"));+ expect(screen.getByTestId("dev-toolbar")).toBeInTheDocument();+ expect(reservesSpace()).toBe(true);+ });++ it("counts a failed API request and shows it with its request ID", async () => {+ renderToolbar();+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ error: "version conflict" }), {+ status: 409,+ headers: { "Content-Type": "application/json" },+ }),+ ),+ );+ await expect(new ApiClient("http://localhost:18080").listMembers("ws-1")).rejects.toThrow();++ await waitFor(() => expect(screen.getByTestId("dev-toolbar-net")).toHaveTextContent("· 1 failed"));+ fireEvent.click(screen.getByTestId("dev-toolbar-net"));+ fireEvent.click(await screen.findByText("/api/workspaces/ws-1/members"));+ expect(screen.getByText("version conflict")).toBeInTheDocument();+ expect(screen.getByText(/^X-Request-ID /)).toBeInTheDocument();+ });++ it("will not copy a long request as curl, and says why", async () => {+ renderToolbar();+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("{}", { status: 201 })));+ await new ApiClient("http://localhost:18080").createComment("issue-1", "a".repeat(2100)).catch(() => {});++ fireEvent.click(screen.getByTestId("dev-toolbar-net"));+ fireEvent.click(await screen.findByText("/api/issues/issue-1/comments"));+ expect(screen.getByText(/^Body truncated to 2000 of \d+ characters\. Copy as curl is off/)).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Copy as curl" })).toBeDisabled();+ });++ it("counts console errors and lists them with the route they happened on", async () => {+ vi.spyOn(console, "error").mockImplementation(() => {});+ renderToolbar();+ console.error(new Error("Cannot read properties of undefined"));++ await waitFor(() => expect(screen.getByTestId("dev-toolbar-errors")).toHaveTextContent("Errors1"));+ fireEvent.click(screen.getByTestId("dev-toolbar-errors"));+ expect(await screen.findByText("Error: Cannot read properties of undefined")).toBeInTheDocument();+ });+});diff --git a/packages/views/dev-toolbar/dev-toolbar.tsx b/packages/views/dev-toolbar/dev-toolbar.tsxnew file mode 100644index 0000000000..072d7df740--- /dev/null+++ b/packages/views/dev-toolbar/dev-toolbar.tsx@@ -0,0 +1,218 @@+"use client";++import { useState, useSyncExternalStore, type ReactNode } from "react";+import { useQuery } from "@tanstack/react-query";+import { useAuthStore } from "@multica/core/auth";+import {+ getCurrentSlug,+ getCurrentWsId,+ subscribeToCurrentSlug,+} from "@multica/core/platform";+import { useWSStatus, type WSStatus } from "@multica/core/realtime";+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 {+ apiHost,+ formatBytes,+ jankTone,+ memoryTone,+ navTone,+ requestFailed,+ type MetricTone,+} from "./metrics";+import {+ ErrorsPanel,+ LongTaskPanel,+ MemoryPanel,+ NavigationPanel,+ NetworkPanel,+ SyncPanel,+ TONE_CLASS,+} from "./panels";+import { useDevRecorder, useMainThreadBlocked, useNavDuration, useNow } from "./use-dev-metrics";++export interface DevToolbarProps {+ /** Which client this is, e.g. `web` or `desktop · staging`. */+ build: string;+ /** Backend the client talks to. */+ apiUrl: string;+ /** Current route as the platform's router sees it. */+ route: string;+}++// App shells size themselves to the viewport (`h-svh`, `h-screen`), so a fixed+// bar would cover their bottom edge — the sidebar's account menu, composers.+// While the bar is shown these utilities give up its height, so the app ends+// where the bar begins. Unlayered, this beats Tailwind's layered utilities.+const BAR_HEIGHT_PX = 24;+const RESERVE_BAR_SPACE_CSS = (["svh", "dvh", "vh"] as const)+ .map((unit) => {+ const name = unit === "vh" ? "screen" : unit;+ const height = `calc(100${unit} - ${BAR_HEIGHT_PX}px)`;+ return `.h-${name}{height:${height}}.min-h-${name}{min-height:${height}}`;+ })+ .join("");++const SYNC_DOT_CLASS: Record<WSStatus, string> = {+ connected: "bg-success",+ connecting: "bg-warning",+ reconnecting: "bg-destructive",+ offline: "bg-muted-foreground/50",+};++function useCurrentWorkspace() {+ const slug = useSyncExternalStore(subscribeToCurrentSlug, getCurrentSlug, () => null);+ const wsId = useSyncExternalStore(subscribeToCurrentSlug, getCurrentWsId, () => null);+ const userId = useAuthStore((s) => s.user?.id ?? null);+ const { data: members } = useQuery({+ ...memberListOptions(wsId ?? ""),+ enabled: Boolean(wsId),+ });+ const role = members?.find((m) => m.user_id === userId)?.role ?? null;+ return { slug, role };+}++/** A bar reading that opens its detail panel. */+function Metric({+ label,+ value,+ tone = "normal",+ extra,+ wide,+ children,+}: {+ label: string;+ value: string;+ tone?: MetricTone;+ extra?: ReactNode;+ wide?: boolean;+ children: ReactNode;+}) {+ return (+ <Popover>+ <PopoverTrigger+ data-testid={`dev-toolbar-${label.toLowerCase()}`}+ className="flex h-5 items-center gap-1 whitespace-nowrap rounded-md px-1 hover:bg-accent hover:text-foreground data-[popup-open]:bg-accent data-[popup-open]:text-foreground"+ >+ <span>{label}</span>+ <span className={cn("tabular-nums", TONE_CLASS[tone])}>{value}</span>+ {extra}+ </PopoverTrigger>+ <PopoverContent side="top" align="end" sideOffset={6} className={cn("gap-0 overflow-hidden p-0 text-caption", wide ? "w-[600px]" : "w-[440px]")}>+ {children}+ </PopoverContent>+ </Popover>+ );+}++/**+ * Development-only status bar pinned to the bottom of the window: which+ * client and backend this is, who you are in the current workspace, and live+ * 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) {+ const [minimized, setMinimized] = useState(false);+ const sync = useWSStatus();+ const recording = useDevRecorder(route, sync);+ const now = useNow(1_000);+ const { slug, role } = useCurrentWorkspace();+ 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 syncDot = (+ <span className={cn("size-1.5 shrink-0 rounded-full", SYNC_DOT_CLASS[sync])} />+ );++ if (minimized) {+ return (+ <button+ type="button"+ data-testid="dev-toolbar-restore"+ onClick={() => setMinimized(false)}+ aria-label="Show dev toolbar"+ className="fixed bottom-0 left-1/2 z-[100] flex h-4 -translate-x-1/2 items-center gap-1 rounded-t-md border border-b-0 border-border bg-background px-2 font-mono text-micro text-muted-foreground hover:text-foreground"+ >+ {syncDot}+ <span>{build}</span>+ {errors > 0 && <span className="text-destructive">{errors}</span>}+ <ChevronUp className="size-3" />+ </button>+ );+ }++ return (+ <div+ data-testid="dev-toolbar"+ style={{ height: BAR_HEIGHT_PX }}+ className="fixed inset-x-0 bottom-0 z-[100] flex items-center gap-3 border-t border-border bg-background pl-2 pr-0.5 font-mono text-micro text-muted-foreground select-none"+ >+ <style>{RESERVE_BAR_SPACE_CSS}</style>+ <div className="flex min-w-0 items-center gap-3">+ <span className="flex items-center gap-1.5 text-foreground">+ {syncDot}+ {build}+ </span>+ <span className="whitespace-nowrap">{apiHost(apiUrl)}</span>+ {slug && <span className="truncate">{slug}</span>}+ {role && <span>{role}</span>}+ <span className="truncate">{route}</span>+ </div>+ <div className="ml-auto flex shrink-0 items-center gap-1">+ <Metric+ label="Mem"+ value={heap === null ? "—" : formatBytes(heap)}+ tone={heap === null ? "normal" : memoryTone(heap)}+ >+ <MemoryPanel recording={recording} />+ </Metric>+ <Metric+ label="Nav"+ value={nav === null ? "—" : `${Math.round(nav)}ms`}+ tone={nav === null ? "normal" : navTone(nav)}+ >+ <NavigationPanel recording={recording} />+ </Metric>+ <Metric+ label="Jank"+ value={blocked === null ? "—" : `${Math.round(blocked * 100)}%`}+ tone={blocked === null ? "normal" : jankTone(blocked)}+ >+ <LongTaskPanel recording={recording} blocked={blocked} />+ </Metric>+ <Metric+ label="Net"+ value={String(inFlight)}+ wide+ extra={failed > 0 && <span className="text-destructive">{`· ${failed} failed`}</span>}+ >+ <NetworkPanel recording={recording} apiUrl={apiUrl} workspaceSlug={slug} />+ </Metric>+ <Metric+ label="Sync"+ value={sync}+ tone={sync === "reconnecting" ? "bad" : sync === "connecting" ? "warn" : "normal"}+ >+ <SyncPanel recording={recording} status={sync} />+ </Metric>+ <Metric label="Errors" value={String(errors)} tone={errors > 0 ? "bad" : "normal"}>+ <ErrorsPanel recording={recording} />+ </Metric>+ <button+ type="button"+ onClick={() => setMinimized(true)}+ aria-label="Hide dev toolbar"+ className="flex size-5 items-center justify-center rounded-md hover:bg-accent hover:text-foreground"+ >+ <Minus className="size-3" />+ </button>+ </div>+ </div>+ );+}diff --git a/packages/views/dev-toolbar/index.ts b/packages/views/dev-toolbar/index.tsnew file mode 100644index 0000000000..77c41c1666--- /dev/null+++ b/packages/views/dev-toolbar/index.ts@@ -0,0 +1 @@+export { DevToolbar, type DevToolbarProps } from "./dev-toolbar";diff --git a/packages/views/dev-toolbar/metrics.test.ts b/packages/views/dev-toolbar/metrics.test.tsnew file mode 100644index 0000000000..783d70a6b4--- /dev/null+++ b/packages/views/dev-toolbar/metrics.test.ts@@ -0,0 +1,155 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import type { DevRequest } from "@multica/core/diagnostics";+import {+ apiHost,+ blockedRatio,+ curlCommand,+ firstStackFrame,+ formatBytes,+ jankTone,+ memoryTone,+ navDuration,+ navTone,+ percentile,+ requestFailed,+} from "./metrics";++const MB = 1024 * 1024;++describe("formatBytes", () => {+ it("shows megabytes below a gigabyte and gigabytes above", () => {+ expect(formatBytes(152.4 * MB)).toBe("152MB");+ expect(formatBytes(1536 * MB)).toBe("1.50GB");+ });+});++describe("memoryTone", () => {+ it("warns from 500MB and flags from 1GB", () => {+ expect(memoryTone(499 * MB)).toBe("normal");+ expect(memoryTone(500 * MB)).toBe("warn");+ expect(memoryTone(1024 * MB)).toBe("bad");+ });+});++describe("navDuration", () => {+ it("measures from the triggering input to the painted frame", () => {+ expect(navDuration(1_000, 1_542)).toBe(542);+ });++ it("ignores route changes no recent input explains", () => {+ expect(navDuration(null, 5_000)).toBeNull();+ expect(navDuration(1_000, 12_000)).toBeNull();+ expect(navDuration(2_000, 1_000)).toBeNull();+ });+});++describe("navTone", () => {+ it("warns from 300ms and flags from 1s", () => {+ expect(navTone(299)).toBe("normal");+ expect(navTone(300)).toBe("warn");+ expect(navTone(1_000)).toBe("bad");+ });+});++describe("blockedRatio", () => {+ it("counts only the part of each task inside the window", () => {+ const tasks = [+ { start: 0, end: 2_000 },+ { start: 9_000, end: 9_500 },+ { start: 19_000, end: 19_500 },+ ];+ // Window is [10_000, 20_000]: only the last task overlaps it.+ expect(blockedRatio(tasks, 20_000, 10_000)).toBeCloseTo(0.05);+ // Window is [1_000, 11_000]: 1_000ms of the first task plus the second.+ expect(blockedRatio(tasks, 11_000, 10_000)).toBeCloseTo(0.15);+ });++ it("is zero with no long tasks", () => {+ expect(blockedRatio([], 20_000)).toBe(0);+ });+});++describe("jankTone", () => {+ it("warns from 5% and flags from 20%", () => {+ expect(jankTone(0.049)).toBe("normal");+ expect(jankTone(0.05)).toBe("warn");+ expect(jankTone(0.2)).toBe("bad");+ });+});++describe("apiHost", () => {+ it("keeps host and port, and passes through what is not a URL", () => {+ expect(apiHost("http://localhost:18080")).toBe("localhost:18080");+ expect(apiHost("https://api.multica.ai/")).toBe("api.multica.ai");+ expect(apiHost("same-origin")).toBe("same-origin");+ });+});++function request(overrides: Partial<DevRequest>): DevRequest {+ return {+ requestId: "rid-1",+ method: "GET",+ path: "/api/issues",+ body: null,+ bodyNote: null,+ startedAt: 0,+ durationMs: 40,+ status: 200,+ error: null,+ ...overrides,+ };+}++describe("requestFailed", () => {+ it("fails error statuses and lost responses, but not in-flight or cancelled requests", () => {+ expect(requestFailed(request({ status: 500 }))).toBe(true);+ expect(requestFailed(request({ status: null, error: "TypeError: Failed to fetch" }))).toBe(true);+ expect(requestFailed(request({ status: 204 }))).toBe(false);+ expect(requestFailed(request({ status: null, durationMs: null }))).toBe(false);+ expect(requestFailed(request({ status: null, error: "aborted" }))).toBe(false);+ });+});++describe("percentile", () => {+ it("uses the nearest rank", () => {+ const values = Array.from({ length: 20 }, (_, i) => i + 1);+ expect(percentile(values, 95)).toBe(19);+ expect(percentile(values, 50)).toBe(10);+ expect(percentile([7], 95)).toBe(7);+ expect(percentile([], 95)).toBeNull();+ });+});++describe("curlCommand", () => {+ it("replays the request without embedding a credential", () => {+ const command = curlCommand(+ "http://localhost:18080/",+ request({ method: "POST", body: `{"title":"it's"}` }),+ "acme",+ );+ expect(command).toBe(+ [+ "curl -X POST 'http://localhost:18080/api/issues'",+ `-H "Authorization: Bearer $MULTICA_TOKEN"`,+ "-H 'X-Workspace-Slug: acme'",+ "-H 'Content-Type: application/json'",+ `--data '{"title":"it'\\''s"}'`,+ ].join(" \\\n "),+ );+ });+});++describe("curlCommand with an incomplete body", () => {+ it("refuses to build a command that would send a different request", () => {+ const truncated = request({ method: "POST", body: '{"content":"aaa…', bodyNote: "truncated to 2000 of 2113 characters" });+ expect(curlCommand("http://localhost:18080", truncated, "acme")).toBeNull();+ });+});++describe("firstStackFrame", () => {+ it("skips the message line", () => {+ expect(firstStackFrame("Error: boom\n at save (issue.tsx:12:3)\n at run")).toBe("at save (issue.tsx:12:3)");+ expect(firstStackFrame(null)).toBeNull();+ });+});diff --git a/packages/views/dev-toolbar/metrics.ts b/packages/views/dev-toolbar/metrics.tsnew file mode 100644index 0000000000..83460708a5--- /dev/null+++ b/packages/views/dev-toolbar/metrics.ts@@ -0,0 +1,127 @@+import type { DevRequest } from "@multica/core/diagnostics";++export type MetricTone = "normal" | "warn" | "bad";++export interface TimeSpan {+ start: number;+ end: number;+}++/** An input older than this did not cause the route change that followed it. */+export const NAV_INPUT_MAX_AGE_MS = 10_000;++export const JANK_WINDOW_MS = 10_000;++export function formatBytes(bytes: number): string {+ const mb = bytes / 1024 / 1024;+ if (mb < 1024) return `${Math.round(mb)}MB`;+ return `${(mb / 1024).toFixed(2)}GB`;+}++export function memoryTone(bytes: number): MetricTone {+ const mb = bytes / 1024 / 1024;+ if (mb >= 1024) return "bad";+ if (mb >= 500) return "warn";+ return "normal";+}++/**+ * Time from the input that triggered a route change to the frame that showed+ * it, or null when no recent input explains the change (a redirect or a+ * timer-driven navigation).+ */+export function navDuration(inputAt: number | null, paintedAt: number): number | null {+ if (inputAt === null) return null;+ const elapsed = paintedAt - inputAt;+ if (elapsed < 0 || elapsed > NAV_INPUT_MAX_AGE_MS) return null;+ return elapsed;+}++export function navTone(ms: number): MetricTone {+ if (ms >= 1000) return "bad";+ if (ms >= 300) return "warn";+ return "normal";+}++/** Share of the trailing window the main thread spent inside long tasks, 0–1. */+export function blockedRatio(+ tasks: readonly TimeSpan[],+ now: number,+ windowMs: number = JANK_WINDOW_MS,+): number {+ const windowStart = now - windowMs;+ let blocked = 0;+ for (const task of tasks) {+ const start = Math.max(task.start, windowStart);+ const end = Math.min(task.end, now);+ if (end > start) blocked += end - start;+ }+ return Math.min(1, blocked / windowMs);+}++export function jankTone(ratio: number): MetricTone {+ if (ratio >= 0.2) return "bad";+ if (ratio >= 0.05) return "warn";+ return "normal";+}++/** Host and port of an API URL, which is what tells two local backends apart. */+export function apiHost(url: string): string {+ try {+ return new URL(url).host;+ } catch {+ return url;+ }+}++/** Ended with an error status or no response. A request we cancelled did not fail. */+export function requestFailed(request: DevRequest): boolean {+ if (request.durationMs === null) return false;+ if (request.status === null) return request.error !== "aborted";+ return request.status >= 400;+}++/** Nearest-rank percentile; null for no values. */+export function percentile(values: readonly number[], p: number): number | null {+ if (values.length === 0) return null;+ const sorted = [...values].sort((a, b) => a - b);+ const rank = Math.ceil((p / 100) * sorted.length);+ return sorted[Math.min(sorted.length, Math.max(1, rank)) - 1]!;+}++function shellQuote(value: string): string {+ return `'${value.replace(/'/g, `'\\''`)}'`;+}++/**+ * The request as a curl command. The token stays a shell variable so the+ * command can be pasted into an issue without leaking a credential. Null when+ * the recorded body is incomplete: a cut body would replay as invalid JSON.+ */+export function curlCommand(apiUrl: string, request: DevRequest, workspaceSlug: string | null): string | null {+ if (request.bodyNote !== null) return null;+ const parts = [`curl -X ${request.method} ${shellQuote(`${apiUrl.replace(/\/$/, "")}${request.path}`)}`];+ parts.push(`-H "Authorization: Bearer $MULTICA_TOKEN"`);+ if (workspaceSlug) parts.push(`-H ${shellQuote(`X-Workspace-Slug: ${workspaceSlug}`)}`);+ if (request.body !== null) {+ parts.push(`-H 'Content-Type: application/json'`);+ parts.push(`--data ${shellQuote(request.body)}`);+ }+ return parts.join(" \\\n ");+}++/** The first `at …` line of a stack, which is usually where to look. */+export function firstStackFrame(stack: string | null): string | null {+ if (!stack) return null;+ const frame = stack.split("\n").find((line) => /^\s*at\s/.test(line));+ return frame ? frame.trim() : null;+}++/** Wall-clock `HH:MM:SS`, which lines up with the server's logs. */+export function formatClock(at: number): string {+ return new Date(at).toTimeString().slice(0, 8);+}++export function formatDuration(ms: number): string {+ return ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`;+}diff --git a/packages/views/dev-toolbar/panels.tsx b/packages/views/dev-toolbar/panels.tsxnew file mode 100644index 0000000000..83509f8049--- /dev/null+++ b/packages/views/dev-toolbar/panels.tsx@@ -0,0 +1,431 @@+"use client";++import { useState, type ReactNode } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import {+ clearDevErrors,+ clearDevRequests,+ DEV_RECORDING_WINDOW_MS,+ type DevRecording,+ type DevRequest,+} from "@multica/core/diagnostics";+import { ChevronDown, ChevronRight, Copy, Trash2 } from "@multica/ui/icons";+import { copyText } from "@multica/ui/lib/clipboard";+import { cn } from "@multica/ui/lib/utils";+import {+ curlCommand,+ firstStackFrame,+ formatBytes,+ formatClock,+ formatDuration,+ memoryTone,+ navTone,+ percentile,+ requestFailed,+ type MetricTone,+} from "./metrics";++export const TONE_CLASS: Record<MetricTone, string> = {+ normal: "text-foreground",+ warn: "text-warning",+ bad: "text-destructive",+};++function statusTone(request: DevRequest): MetricTone {+ if (requestFailed(request)) return "bad";+ if (request.durationMs !== null && request.durationMs >= 1000) return "warn";+ return "normal";+}++function longTaskTone(ms: number): MetricTone {+ if (ms >= 200) return "bad";+ if (ms >= 100) return "warn";+ return "normal";+}++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 }) {+ 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>+ <div className="ml-auto flex items-center gap-1">{children}</div>+ </div>+ );+}++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">+ <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>+ </div>+ ))}+ </div>+ );+}++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({+ onClick,+ children,+ active,+ disabled,+}: {+ onClick: () => void;+ children: ReactNode;+ active?: boolean;+ disabled?: boolean;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ disabled={disabled}+ className={cn(+ "flex h-6 items-center gap-1 rounded-md px-1.5 text-micro text-muted-foreground hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-50",+ active && "bg-accent text-foreground",+ )}+ >+ {children}+ </button>+ );+}++function Sparkline({ samples }: { samples: DevRecording["memory"] }) {+ if (samples.length < 2) {+ return <div className="grid h-16 place-items-center text-muted-foreground">Collecting samples…</div>;+ }+ const width = 400;+ const height = 64;+ const first = samples[0]!.at;+ const span = Math.max(1, samples.at(-1)!.at - first);+ const values = samples.map((s) => s.bytes);+ const min = Math.min(...values);+ const range = Math.max(1, Math.max(...values) - min);+ const points = samples+ .map((s) => `${((s.at - first) / span) * width},${height - 4 - ((s.bytes - min) / range) * (height - 8)}`)+ .join(" ");+ return (+ <svg viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none" className="h-16 w-full text-brand">+ <polyline points={points} fill="none" stroke="currentColor" strokeWidth={1.5} vectorEffect="non-scaling-stroke" />+ </svg>+ );+}++export function MemoryPanel({ recording }: { recording: DevRecording }) {+ const queries = useQueryClient().getQueryCache().getAll();+ const samples = recording.memory;+ const current = samples.at(-1)?.bytes ?? null;+ const peak = samples.length ? Math.max(...samples.map((s) => s.bytes)) : null;+ return (+ <>+ <PanelHeader title="Memory" />+ <Stats+ items={[+ { label: "JS heap", value: current === null ? "—" : formatBytes(current), tone: current === null ? "normal" : memoryTone(current) },+ { label: "Peak", value: peak === null ? "—" : formatBytes(peak) },+ { label: "Limit", value: recording.heapLimit === null ? "—" : formatBytes(recording.heapLimit) },+ ]}+ />+ <div className="border-b border-border px-3 py-2">+ {current === null ? (+ <div className="py-4 text-center text-muted-foreground">This engine does not report heap size.</div>+ ) : (+ <Sparkline samples={samples} />+ )}+ </div>+ <Stats+ items={[+ { label: "Cached queries", value: String(queries.length) },+ { label: "Stale", value: String(queries.filter((q) => q.isStale()).length) },+ { label: "Fetching", value: String(queries.filter((q) => q.state.fetchStatus === "fetching").length) },+ ]}+ />+ </>+ );+}++export function NavigationPanel({ recording }: { recording: DevRecording }) {+ const visits = recording.navigations.slice(-20).reverse();+ const timed = visits.filter((v) => v.durationMs !== null);+ const slowest = timed.reduce<(typeof timed)[number] | null>(+ (max, v) => (max === null || v.durationMs! > max.durationMs! ? v : max),+ null,+ );+ const median = percentile(timed.map((v) => v.durationMs!), 50);+ return (+ <>+ <PanelHeader title="Navigation" />+ <Stats+ items={[+ { label: "Route changes", value: String(recording.navigations.length) },+ { label: "Median", value: median === null ? "—" : formatDuration(median), tone: median === null ? "normal" : navTone(median) },+ {+ label: "Slowest",+ value: slowest ? formatDuration(slowest.durationMs!) : "—",+ tone: slowest ? navTone(slowest.durationMs!) : "normal",+ },+ ]}+ />+ <Rows empty="No route changes yet.">+ {visits.map((visit) => (+ <div+ key={`${visit.at}-${visit.route}`}+ className={cn("flex items-center gap-3 px-3 py-1 font-mono", visit === slowest && "bg-warning/10")}+ >+ <span className="shrink-0 text-muted-foreground">{formatClock(visit.at)}</span>+ <span className="min-w-0 flex-1 truncate">{visit.route}</span>+ <span+ className={cn(+ "shrink-0 tabular-nums",+ visit.durationMs === null ? "text-muted-foreground" : TONE_CLASS[navTone(visit.durationMs)],+ )}+ >+ {visit.durationMs === null ? "—" : formatDuration(visit.durationMs)}+ </span>+ </div>+ ))}+ </Rows>+ </>+ );+}++export function LongTaskPanel({ recording, blocked }: { recording: DevRecording; blocked: number | null }) {+ const tasks = [...recording.longTasks].reverse();+ const total = tasks.reduce((sum, task) => sum + task.durationMs, 0);+ return (+ <>+ <PanelHeader title="Long tasks" />+ <Stats+ items={[+ { label: "Blocked, last 10s", value: blocked === null ? "—" : `${Math.round(blocked * 100)}%` },+ { label: "Long tasks", value: String(tasks.length) },+ { label: "Total blocked", value: formatDuration(total) },+ ]}+ />+ <Rows empty={blocked === null ? "This engine does not report long tasks." : "No task has blocked the main thread for 50ms or more."}>+ {tasks.map((task) => (+ <div key={task.at} className="flex items-center gap-3 px-3 py-1 font-mono">+ <span className="shrink-0 text-muted-foreground">{formatClock(task.at)}</span>+ <span className="min-w-0 flex-1 truncate">{task.route ?? "—"}</span>+ <span className={cn("shrink-0 tabular-nums", TONE_CLASS[longTaskTone(task.durationMs)])}>+ {formatDuration(task.durationMs)}+ </span>+ </div>+ ))}+ </Rows>+ </>+ );+}++function RequestRow({+ request,+ apiUrl,+ workspaceSlug,+ expanded,+ onToggle,+}: {+ request: DevRequest;+ apiUrl: string;+ workspaceSlug: string | null;+ expanded: boolean;+ onToggle: () => void;+}) {+ const tone = statusTone(request);+ const curl = expanded ? curlCommand(apiUrl, request, workspaceSlug) : null;+ const Chevron = expanded ? ChevronDown : ChevronRight;+ return (+ <div className={cn(requestFailed(request) && "bg-destructive/5")}>+ <button+ type="button"+ onClick={onToggle}+ 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(request.startedAt)}</span>+ <span className="w-11 shrink-0">{request.method}</span>+ <span className="min-w-0 flex-1 truncate" title={request.path}>+ {request.path}+ </span>+ <span+ className={cn(+ "w-14 shrink-0 text-right tabular-nums",+ request.error === "aborted" ? "text-muted-foreground" : TONE_CLASS[tone],+ )}+ >+ {request.durationMs === null+ ? "…"+ : (request.status ?? (request.error === "aborted" ? "canceled" : "ERR"))}+ </span>+ <span className="w-14 shrink-0 text-right tabular-nums text-muted-foreground">+ {request.durationMs === null ? "" : formatDuration(request.durationMs)}+ </span>+ </button>+ {expanded && (+ <div className="flex flex-col gap-2 px-3 pt-1 pb-2 pl-8">+ <div className="font-mono break-all">{request.path}</div>+ {request.error && <div className="break-words text-destructive">{request.error}</div>}+ <div className="font-mono text-muted-foreground">X-Request-ID {request.requestId}</div>+ {request.body !== null && (+ <pre className="max-h-32 overflow-auto rounded-md bg-muted p-2 font-mono text-micro whitespace-pre-wrap break-all">+ {request.body}+ </pre>+ )}+ {request.bodyNote && (+ <div className="text-muted-foreground">+ {`Body ${request.bodyNote}. Copy as curl is off because the command would not send the same request.`}+ </div>+ )}+ <div className="flex gap-1">+ <SmallButton onClick={() => curl && void copy(curl, "curl")} disabled={curl === null}>+ <Copy className="size-3" />+ Copy as curl+ </SmallButton>+ <SmallButton onClick={() => void copy(request.requestId, "request ID")}>+ <Copy className="size-3" />+ Copy request ID+ </SmallButton>+ </div>+ </div>+ )}+ </div>+ );+}++export function NetworkPanel({+ recording,+ apiUrl,+ workspaceSlug,+}: {+ recording: DevRecording;+ apiUrl: string;+ workspaceSlug: string | null;+}) {+ const [failedOnly, setFailedOnly] = useState(false);+ const [expandedId, setExpandedId] = useState<string | null>(null);+ const requests = recording.requests;+ const failed = requests.filter(requestFailed);+ const durations = requests.flatMap((r) => (r.durationMs === null ? [] : [r.durationMs]));+ const p95 = percentile(durations, 95);+ const shown = (failedOnly ? failed : requests).slice(-100).reverse();+ return (+ <>+ <PanelHeader title="Network">+ <SmallButton onClick={() => setFailedOnly((v) => !v)} active={failedOnly}>+ Failed only+ </SmallButton>+ <SmallButton onClick={clearDevRequests}>+ <Trash2 className="size-3" />+ Clear+ </SmallButton>+ </PanelHeader>+ <Stats+ items={[+ { label: "Requests", value: String(requests.length) },+ { label: "In flight", value: String(requests.filter((r) => r.durationMs === null).length) },+ { label: "Failed", value: String(failed.length), tone: failed.length > 0 ? "bad" : "normal" },+ { label: "p95", value: p95 === null ? "—" : formatDuration(p95), tone: p95 !== null && p95 >= 1000 ? "warn" : "normal" },+ ]}+ />+ <Rows empty={failedOnly ? "No failed requests." : "No API requests yet."}>+ {shown.map((request) => (+ <RequestRow+ key={request.requestId}+ request={request}+ apiUrl={apiUrl}+ workspaceSlug={workspaceSlug}+ expanded={expandedId === request.requestId}+ onToggle={() => setExpandedId((id) => (id === request.requestId ? null : request.requestId))}+ />+ ))}+ </Rows>+ </>+ );+}++export function SyncPanel({ recording, status }: { recording: DevRecording; status: string }) {+ const changes = recording.sync;+ const reconnects = changes.filter((c) => c.status === "reconnecting").length;+ return (+ <>+ <PanelHeader title="Realtime" />+ <Stats+ items={[+ { label: "Status", value: status, tone: status === "reconnecting" ? "bad" : status === "connecting" ? "warn" : "normal" },+ { label: "Reconnects", value: String(reconnects), tone: reconnects > 0 ? "warn" : "normal" },+ ]}+ />+ <Rows empty="No connection changes yet.">+ {[...changes].reverse().map((change, i, list) => {+ const next = i === 0 ? null : list[i - 1]!;+ return (+ <div key={change.at} className="flex items-center gap-3 px-3 py-1 font-mono">+ <span className="shrink-0 text-muted-foreground">{formatClock(change.at)}</span>+ <span className="min-w-0 flex-1">{change.status}</span>+ <span className="shrink-0 tabular-nums text-muted-foreground">+ {next ? `for ${formatDuration(next.at - change.at)}` : "now"}+ </span>+ </div>+ );+ })}+ </Rows>+ </>+ );+}++export function ErrorsPanel({ recording }: { recording: DevRecording }) {+ const [expanded, setExpanded] = useState<number | null>(null);+ const errors = [...recording.errors].reverse();+ return (+ <>+ <PanelHeader title="Errors">+ <SmallButton onClick={clearDevErrors}>+ <Trash2 className="size-3" />+ Clear+ </SmallButton>+ </PanelHeader>+ <Rows empty="No errors. Console errors, uncaught exceptions and unhandled rejections show up here.">+ {errors.map((error) => {+ const frame = firstStackFrame(error.stack);+ const open = expanded === error.at;+ return (+ <button+ type="button"+ key={`${error.at}-${error.message}`}+ onClick={() => setExpanded(open ? null : error.at)}+ className="flex w-full flex-col gap-0.5 border-b border-border/50 px-3 py-1.5 text-left last:border-b-0 hover:bg-accent"+ >+ <span className="flex items-center gap-2 font-mono text-muted-foreground">+ <span>{formatClock(error.at)}</span>+ <span>{error.source}</span>+ <span className="min-w-0 truncate">{error.route}</span>+ </span>+ <span className={cn("break-words text-destructive", !open && "line-clamp-2")}>{error.message}</span>+ {open && error.stack ? (+ <pre className="max-h-40 overflow-auto font-mono text-micro whitespace-pre-wrap text-muted-foreground">+ {error.stack}+ </pre>+ ) : (+ frame && <span className="truncate font-mono text-micro text-muted-foreground">{frame}</span>+ )}+ </button>+ );+ })}+ </Rows>+ </>+ );+}diff --git a/packages/views/dev-toolbar/use-dev-metrics.ts b/packages/views/dev-toolbar/use-dev-metrics.tsnew file mode 100644index 0000000000..3f0ea6d070--- /dev/null+++ b/packages/views/dev-toolbar/use-dev-metrics.ts@@ -0,0 +1,81 @@+"use client";++import { useEffect, useRef, useState, useSyncExternalStore } from "react";+import {+ getDevRecording,+ installDevRecorder,+ recordDevNavigationDuration,+ recordDevRoute,+ recordDevSyncStatus,+ subscribeDevRecording,+ type DevRecording,+} from "@multica/core/diagnostics";+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(), []);+ useEffect(() => recordDevRoute(route), [route]);+ useEffect(() => recordDevSyncStatus(sync), [sync]);+ return useSyncExternalStore(subscribeDevRecording, getDevRecording, getDevRecording);+}++/** Wall clock, re-read every `intervalMs` so trailing windows keep moving. */+export function useNow(intervalMs: number): number {+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ const timer = setInterval(() => setNow(Date.now()), intervalMs);+ return () => clearInterval(timer);+ }, [intervalMs]);+ return now;+}++/** Share of the last 10s spent in long tasks; null where `longtask` is unsupported. */+export function useMainThreadBlocked(recording: DevRecording, now: number): number | null {+ const [supported] = useState(+ () => typeof PerformanceObserver !== "undefined" && Boolean(PerformanceObserver.supportedEntryTypes?.includes("longtask")),+ );+ if (!supported) return null;+ const tasks = recording.longTasks+ .filter((task) => task.at + task.durationMs > now - JANK_WINDOW_MS)+ .map((task) => ({ start: task.at, end: task.at + task.durationMs }));+ return blockedRatio(tasks, now);+}++/**+ * How long the last route change took, from the pointer or key press that+ * caused it to the first frame after the new route rendered.+ */+export function useNavDuration(route: string): number | null {+ const [duration, setDuration] = useState<number | null>(null);+ const lastInputAt = useRef<number | null>(null);+ const previousRoute = useRef(route);++ useEffect(() => {+ const record = (event: Event) => {+ lastInputAt.current = event.timeStamp;+ };+ window.addEventListener("pointerdown", record, true);+ window.addEventListener("keydown", record, true);+ return () => {+ window.removeEventListener("pointerdown", record, true);+ window.removeEventListener("keydown", record, true);+ };+ }, []);++ useEffect(() => {+ if (previousRoute.current === route) return;+ previousRoute.current = route;+ const inputAt = lastInputAt.current;+ lastInputAt.current = null;+ const frame = requestAnimationFrame(() => {+ const elapsed = navDuration(inputAt, performance.now());+ if (elapsed === null) return;+ setDuration(elapsed);+ recordDevNavigationDuration(route, elapsed);+ });+ return () => cancelAnimationFrame(frame);+ }, [route]);++ return duration;+}diff --git a/packages/views/eslint.config.mjs b/packages/views/eslint.config.mjsindex c40430258e..b211166112 100644--- a/packages/views/eslint.config.mjs+++ b/packages/views/eslint.config.mjs@@ -58,4 +58,13 @@ export default [],},},+ {+ // The dev toolbar only exists in development builds and speaks to the+ // people building Multica, so its copy is not translated.+ files: ["dev-toolbar/**/*.{ts,tsx}"],+ rules: {+ "i18next/no-literal-string": "off",+ "no-restricted-syntax": ["error", NO_ROUND_CONTROLS, NO_FULL_PAGE_NAVIGATION],+ },+ },];diff --git a/packages/views/package.json b/packages/views/package.jsonindex 534148cb9a..98c9bc9f11 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -10,6 +10,7 @@},"exports": {"./navigation": "./navigation/index.ts",+ "./dev-toolbar": "./dev-toolbar/index.ts","./common/actor-avatar": "./common/actor-avatar.tsx","./common/appearance-sync": "./common/appearance-sync.tsx","./common/cli-install-command": "./common/cli-install-command.tsx",diff --git a/turbo.json b/turbo.jsonindex e3eec62032..e5c03f61d8 100644--- a/turbo.json+++ b/turbo.json@@ -52,11 +52,18 @@// electron-vite) and signs the dev Desktop in (read by its main process).// Desktop's bundled CLI finds a custom dev-env registry through// MULTICA_DEV_HOME, or refuses its daemon inside an agent task.- "passThroughEnv": ["REMOTE_DEBUGGING_PORT", "MULTICA_DEV_AUTH_TOKEN", "MULTICA_DEV_HOME"]+ // VITE_DEV_TOOLBAR turns on the web/desktop dev status bar.+ "passThroughEnv": [+ "REMOTE_DEBUGGING_PORT",+ "MULTICA_DEV_AUTH_TOKEN",+ "MULTICA_DEV_HOME",+ "VITE_DEV_TOOLBAR"+ ]},"dev:staging": {"cache": false,- "persistent": true+ "persistent": true,+ "passThroughEnv": ["VITE_DEV_TOOLBAR"]},"typecheck": {"dependsOn": ["^typecheck", "mdx"]