Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9120 feat(desktop): toggle the dev toolbar from the View menu (#10492)
Jiayuan Zhang8bf95ff7a308
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 8cc139364e..89d93bd3f2 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -600,7 +600,7 @@ Set `VITE_DEV_TOOLBAR=1` to pin a status bar to the bottom of the Web and DesktoVITE_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.+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. In Desktop, **View → Show Dev Toolbar** turns it off and on without a restart, and the choice is remembered; while it is off, nothing is recorded, and turning it back on starts a new recording.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).diff --git a/apps/desktop/src/main/dev-toolbar-toggle.test.ts b/apps/desktop/src/main/dev-toolbar-toggle.test.tsnew file mode 100644index 0000000000..c72b689387--- /dev/null+++ b/apps/desktop/src/main/dev-toolbar-toggle.test.ts@@ -0,0 +1,134 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs";+import { tmpdir } from "os";+import { join } from "path";++type FakeMenuItem = {+ label?: string;+ type?: string;+ role?: string;+ checked?: boolean;+ click?: (item: FakeMenuItem) => void;+ submenu?: { items: FakeMenuItem[]; append: (item: FakeMenuItem) => void };+};++const ctx = vi.hoisted(() => ({+ ipcHandlers: new Map<string, (event: { returnValue?: unknown }) => void>(),+ appMenu: null as { items: FakeMenuItem[] } | null,+ setApplicationMenu: vi.fn(),+ sent: [] as Array<{ channel: string; payload: unknown }>,+}));++vi.mock("electron", () => ({+ ipcMain: {+ on: (channel: string, handler: (event: { returnValue?: unknown }) => void) =>+ ctx.ipcHandlers.set(channel, handler),+ },+ Menu: {+ getApplicationMenu: () => ctx.appMenu,+ setApplicationMenu: ctx.setApplicationMenu,+ },+ MenuItem: class {+ constructor(options: FakeMenuItem) {+ Object.assign(this, options);+ }+ },+ BrowserWindow: {+ getAllWindows: () => [+ {+ webContents: {+ send: (channel: string, payload: unknown) => ctx.sent.push({ channel, payload }),+ },+ },+ ],+ },+}));++import {+ DEV_TOOLBAR_MENU_LABEL,+ devToolbarPreferencesPath,+ installDevToolbarToggle,+} from "./dev-toolbar-toggle";+import {+ DEV_TOOLBAR_VISIBLE_CHANGED_CHANNEL,+ DEV_TOOLBAR_VISIBLE_GET_CHANNEL,+} from "../shared/dev-toolbar";++function submenu(items: FakeMenuItem[] = []) {+ return { items, append: (item: FakeMenuItem) => items.push(item) };+}++function readVisible(): unknown {+ const event: { returnValue?: unknown } = {};+ ctx.ipcHandlers.get(DEV_TOOLBAR_VISIBLE_GET_CHANNEL)?.(event);+ return event.returnValue;+}++let dir: string;+let viewMenu: ReturnType<typeof submenu>;++beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), "dev-toolbar-"));+ viewMenu = submenu([{ label: "Reload" }]);+ ctx.appMenu = {+ items: [+ { role: "filemenu", submenu: submenu() },+ { role: "viewmenu", submenu: viewMenu },+ ],+ };+ ctx.ipcHandlers.clear();+ ctx.setApplicationMenu.mockClear();+ ctx.sent.length = 0;+});++afterEach(() => {+ rmSync(dir, { recursive: true, force: true });+});++describe("installDevToolbarToggle", () => {+ it("adds a checked View item by default and saves each toggle", () => {+ const preferencesPath = devToolbarPreferencesPath(dir);+ installDevToolbarToggle({ enabled: true, preferencesPath });++ const item = viewMenu.items.find((i) => i.label === DEV_TOOLBAR_MENU_LABEL)!;+ expect(item).toMatchObject({ type: "checkbox", checked: true });+ expect(ctx.setApplicationMenu).toHaveBeenCalledWith(ctx.appMenu);+ expect(readVisible()).toBe(true);++ // Electron flips `checked` before calling click.+ item.checked = false;+ item.click!(item);++ expect(readVisible()).toBe(false);+ expect(ctx.sent).toEqual([{ channel: DEV_TOOLBAR_VISIBLE_CHANGED_CHANNEL, payload: false }]);+ expect(JSON.parse(readFileSync(preferencesPath, "utf-8"))).toEqual({ visible: false });+ });++ it("restores a hidden toolbar from the saved preference", () => {+ const preferencesPath = devToolbarPreferencesPath(dir);+ writeFileSync(preferencesPath, JSON.stringify({ visible: false }));+ installDevToolbarToggle({ enabled: true, preferencesPath });++ expect(viewMenu.items.find((i) => i.label === DEV_TOOLBAR_MENU_LABEL)?.checked).toBe(false);+ expect(readVisible()).toBe(false);+ });++ it("treats an unreadable preference as shown", () => {+ const preferencesPath = devToolbarPreferencesPath(dir);+ writeFileSync(preferencesPath, "{not json");+ installDevToolbarToggle({ enabled: true, preferencesPath });++ expect(readVisible()).toBe(true);+ });++ it("leaves the menu alone and answers false when the toolbar is not built in", () => {+ const preferencesPath = devToolbarPreferencesPath(dir);+ writeFileSync(preferencesPath, JSON.stringify({ visible: true }));+ installDevToolbarToggle({ enabled: false, preferencesPath });++ expect(viewMenu.items.map((i) => i.label)).toEqual(["Reload"]);+ expect(ctx.setApplicationMenu).not.toHaveBeenCalled();+ expect(readVisible()).toBe(false);+ });+});diff --git a/apps/desktop/src/main/dev-toolbar-toggle.ts b/apps/desktop/src/main/dev-toolbar-toggle.tsnew file mode 100644index 0000000000..e8fdec3499--- /dev/null+++ b/apps/desktop/src/main/dev-toolbar-toggle.ts@@ -0,0 +1,70 @@+import { BrowserWindow, ipcMain, Menu, MenuItem } from "electron";+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";+import {+ DEV_TOOLBAR_VISIBLE_CHANGED_CHANNEL,+ DEV_TOOLBAR_VISIBLE_GET_CHANNEL,+} from "../shared/dev-toolbar";++export const DEV_TOOLBAR_MENU_LABEL = "Show Dev Toolbar";++export function devToolbarPreferencesPath(userDataPath: string): string {+ return join(userDataPath, "dev-toolbar.json");+}++export function loadDevToolbarVisible(filePath: string): boolean {+ try {+ const parsed = JSON.parse(readFileSync(filePath, "utf-8")) as { visible?: unknown } | null;+ return typeof parsed?.visible === "boolean" ? parsed.visible : true;+ } catch {+ return true;+ }+}++export function saveDevToolbarVisible(filePath: string, visible: boolean): void {+ try {+ mkdirSync(dirname(filePath), { recursive: true });+ writeFileSync(filePath, JSON.stringify({ visible }, null, 2), "utf-8");+ } catch (err) {+ console.warn("[dev-toolbar] could not save the toolbar preference", err);+ }+}++/**+ * Owns whether the opt-in dev toolbar is shown. When the toolbar is built in+ * (`enabled`), View gets a "Show Dev Toolbar" checkbox whose state survives+ * restarts. Register before any window loads: preload reads the value+ * synchronously, and the handler answers `false` when the toolbar is off.+ */+export function installDevToolbarToggle(options: {+ enabled: boolean;+ preferencesPath: string;+}): void {+ let visible = options.enabled && loadDevToolbarVisible(options.preferencesPath);+ ipcMain.on(DEV_TOOLBAR_VISIBLE_GET_CHANNEL, (event) => {+ event.returnValue = visible;+ });+ if (!options.enabled) return;++ // Electron reports roles in lower case at runtime ("viewmenu").+ const menu = Menu.getApplicationMenu();+ const viewMenu = menu?.items.find((item) => item.role?.toLowerCase() === "viewmenu")?.submenu;+ if (!menu || !viewMenu) return;++ viewMenu.append(new MenuItem({ type: "separator" }));+ viewMenu.append(+ new MenuItem({+ label: DEV_TOOLBAR_MENU_LABEL,+ type: "checkbox",+ checked: visible,+ click: (item) => {+ visible = item.checked;+ saveDevToolbarVisible(options.preferencesPath, visible);+ for (const window of BrowserWindow.getAllWindows()) {+ window.webContents.send(DEV_TOOLBAR_VISIBLE_CHANGED_CHANNEL, visible);+ }+ },+ }),+ );+ Menu.setApplicationMenu(menu);+}diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex 39492643c3..668f77d270 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -24,6 +24,7 @@ import { setupThemeFolder } from "./theme-folder";import { configureLinuxFileDialogs } from "./linux-file-dialog";import { openExternalSafely, downloadURLSafely } from "./external-url";import { installContextMenu } from "./context-menu";+import { devToolbarPreferencesPath, installDevToolbarToggle } from "./dev-toolbar-toggle";import { handleAppShortcut } from "./keyboard-shortcuts";import { installNavigationGestures } from "./navigation-gestures";import { installNavigationGuard } from "./navigation-guard";@@ -777,6 +778,7 @@ if (!gotTheLock) {readonly VITE_API_URL?: string;readonly VITE_WS_URL?: string;readonly VITE_APP_URL?: string;+ readonly VITE_DEV_TOOLBAR?: string;};runtimeConfigResult = await loadRuntimeConfig({@@ -877,6 +879,11 @@ if (!gotTheLock) {event.returnValue = runtimeConfigResult;});+ installDevToolbarToggle({+ enabled: is.dev && Boolean(viteEnv.VITE_DEV_TOOLBAR),+ preferencesPath: devToolbarPreferencesPath(app.getPath("userData")),+ });+ipcMain.on(RENDERER_ROUTE_CONTEXT_CHANNEL, (event, context: unknown) => {if (!BrowserWindow.fromWebContents(event.sender)) return;const sanitized = sanitizeRendererRouteContext(context);diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.tsindex d4002d0baf..a3bd0a813e 100644--- a/apps/desktop/src/preload/index.d.ts+++ b/apps/desktop/src/preload/index.d.ts@@ -167,6 +167,10 @@ interface DesktopAPI {/** Listen for Cmd/Ctrl+Shift+N new-window requests. Returns an* unsubscribe function. */onNewWindowShortcut: (callback: () => void) => () => void;+ /** Whether View → Show Dev Toolbar is checked; false unless VITE_DEV_TOOLBAR is set. */+ getDevToolbarVisible: () => boolean;+ /** Listen for View → Show Dev Toolbar being toggled. Returns an unsubscribe function. */+ onDevToolbarVisibleChange: (callback: (visible: boolean) => void) => () => void;}type DaemonReauthResult =diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex 9e54738dd4..6b141dcda2 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -20,6 +20,10 @@ import {type IssueWindowRequest,} from "../shared/issue-window";import { AUTH_SESSION_STATE_CHANNEL } from "../shared/auth-session";+import {+ DEV_TOOLBAR_VISIBLE_CHANGED_CHANNEL,+ DEV_TOOLBAR_VISIBLE_GET_CHANNEL,+} from "../shared/dev-toolbar";import {CONTEXT_MENU_COMMAND_CHANNEL,CONTEXT_MENU_REQUEST_CHANNEL,@@ -356,6 +360,25 @@ const desktopAPI = {/** Listen for Cmd/Ctrl+Shift+N new-window requests. */onNewWindowShortcut: (callback: () => void) =>subscribeToMainRendererChannel(NEW_WINDOW_SHORTCUT_CHANNEL, () => callback()),+ /** Whether View → Show Dev Toolbar is checked. Always false unless the+ * dev build was started with VITE_DEV_TOOLBAR. */+ getDevToolbarVisible: (): boolean => {+ try {+ return ipcRenderer.sendSync(DEV_TOOLBAR_VISIBLE_GET_CHANNEL) === true;+ } catch {+ return false;+ }+ },+ /** Listen for View → Show Dev Toolbar being toggled. Returns an unsubscribe fn. */+ onDevToolbarVisibleChange: (callback: (visible: boolean) => void) => {+ const handler = (_event: Electron.IpcRendererEvent, visible: unknown) => {+ if (typeof visible === "boolean") callback(visible);+ };+ ipcRenderer.on(DEV_TOOLBAR_VISIBLE_CHANGED_CHANNEL, handler);+ return () => {+ ipcRenderer.removeListener(DEV_TOOLBAR_VISIBLE_CHANGED_CHANNEL, handler);+ };+ },};type DaemonReauthResult =diff --git a/apps/desktop/src/renderer/src/components/desktop-dev-toolbar.tsx b/apps/desktop/src/renderer/src/components/desktop-dev-toolbar.tsxindex ec57163313..c47dec8bdc 100644--- a/apps/desktop/src/renderer/src/components/desktop-dev-toolbar.tsx+++ b/apps/desktop/src/renderer/src/components/desktop-dev-toolbar.tsx@@ -1,3 +1,4 @@+import { useEffect, useState } from "react";import { DevToolbar } from "@multica/views/dev-toolbar";import { useActiveTabUrl } from "@/stores/tab-store";import { routeContentLinkPath } from "@/platform/navigation";@@ -6,6 +7,9 @@ const BUILD =import.meta.env.MODE === "development" ? "desktop" : `desktop · ${import.meta.env.MODE}`;export function DesktopDevToolbar({ apiUrl }: { apiUrl: string }) {+ const [visible, setVisible] = useState(() => window.desktopAPI.getDevToolbarVisible());+ useEffect(() => window.desktopAPI.onDevToolbarVisibleChange(setVisible), []);const route = useActiveTabUrl() ?? "/";+ if (!visible) return null;return <DevToolbar build={BUILD} apiUrl={apiUrl} route={route} onNavigate={routeContentLinkPath} />;}diff --git a/apps/desktop/src/shared/dev-toolbar.ts b/apps/desktop/src/shared/dev-toolbar.tsnew file mode 100644index 0000000000..1655102bd9--- /dev/null+++ b/apps/desktop/src/shared/dev-toolbar.ts@@ -0,0 +1,2 @@+export const DEV_TOOLBAR_VISIBLE_GET_CHANNEL = "dev-toolbar:get-visible";+export const DEV_TOOLBAR_VISIBLE_CHANGED_CHANNEL = "dev-toolbar:visible-changed";diff --git a/packages/core/diagnostics/dev-recorder.test.ts b/packages/core/diagnostics/dev-recorder.test.tsindex d119de6e93..87778c6f38 100644--- a/packages/core/diagnostics/dev-recorder.test.ts+++ b/packages/core/diagnostics/dev-recorder.test.ts@@ -140,6 +140,36 @@ describe("dev recorder", () => {expect(console.error).toBe(patched);expect(getApiRequestObserver()).toBeNull();});++ it("removes its hooks and drops the recording when stopped, so a restart begins empty", () => {+ const patched = console.error;+ const stop = installDevRecorder();+ recordDevRoute("/acme/issues");+ console.error("before stop");+ expect(getDevRecording().errors).toHaveLength(1);++ stop();+ expect(console.error).toBe(patched);+ expect(getApiRequestObserver()).toBeNull();+ expect(vi.getTimerCount()).toBe(0);+ console.error("while stopped");+ window.dispatchEvent(new ErrorEvent("error", { message: "boom" }));+ expect(getDevRecording().errors).toEqual([]);+ expect(getDevRecording().navigations).toEqual([]);++ installDevRecorder();+ recordDevRoute("/acme/issues");+ expect(getDevRecording().navigations.map((n) => n.route)).toEqual(["/acme/issues"]);+ expect(getDevRecording().errors).toEqual([]);+ });++ it("leaves a running recording alone when a second install is stopped", () => {+ installDevRecorder();+ const stopSecond = installDevRecorder();+ stopSecond();+ console.error("still recording");+ expect(getDevRecording().errors).toHaveLength(1);+ });});describe("formatConsoleArgs", () => {diff --git a/packages/core/diagnostics/dev-recorder.ts b/packages/core/diagnostics/dev-recorder.tsindex 6b5721cbd6..3c98dfb3a5 100644--- a/packages/core/diagnostics/dev-recorder.ts+++ b/packages/core/diagnostics/dev-recorder.ts@@ -503,11 +503,14 @@ function refuseReplayWrite({ method, readOnly }: { method: string; readOnly: boo}/**- * Start recording. Idempotent, and a no-op outside the browser. With a query- * client, realtime events are tagged with the cache changes they caused.+ * Start recording. With a query client, realtime events are tagged with the+ * cache changes they caused. Returns a function that removes every hook the+ * recorder installed and drops what it recorded, so the next start is fresh.+ * A no-op outside the browser, or while a recording is already running (the+ * returned function then leaves that recording alone).*/-export function installDevRecorder(queryClient?: QueryClient): void {- if (teardown || typeof window === "undefined") return;+export function installDevRecorder(queryClient?: QueryClient): () => void {+ if (teardown || typeof window === "undefined") return () => {};const cleanups: (() => void)[] = [];setRealtimeObserver({ onEvent: recordFrame, onReconnect: recordReconnect });@@ -598,7 +601,25 @@ export function installDevRecorder(queryClient?: QueryClient): void {clearInterval(pruneTimer);});- teardown = () => cleanups.forEach((cleanup) => cleanup());+ const stop = () => cleanups.forEach((cleanup) => cleanup());+ teardown = stop;+ return () => {+ if (teardown === stop) stopDevRecorder();+ };+}++function stopDevRecorder(): void {+ teardown?.();+ teardown = null;+ if (notifyTimer) clearTimeout(notifyTimer);+ notifyTimer = null;+ recording = EMPTY;+ currentRoute = null;+ nextEventId = 1;+ eventMessages.clear();+ replayIds.clear();+ cacheEffects.clear();+ dirtyEffects.clear();}/** The current route, so later entries say where they happened. */@@ -671,16 +692,6 @@ export function getDevRecording(): DevRecording {/** 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;+ stopDevRecorder();listeners.clear();- nextEventId = 1;- eventMessages.clear();- replayIds.clear();- cacheEffects.clear();- dirtyEffects.clear();}diff --git a/packages/views/dev-toolbar/use-dev-metrics.test.tsx b/packages/views/dev-toolbar/use-dev-metrics.test.tsxnew file mode 100644index 0000000000..f429cc68a6--- /dev/null+++ b/packages/views/dev-toolbar/use-dev-metrics.test.tsx@@ -0,0 +1,56 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { renderHook } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { ReactNode } from "react";+import { ApiClient } from "@multica/core/api/client";+import { getDevRecording, resetDevRecorder } from "@multica/core/diagnostics";+import { useDevRecorder } from "./use-dev-metrics";++let queryClient: QueryClient;++beforeEach(() => {+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ vi.spyOn(console, "error").mockImplementation(() => {});+ vi.stubGlobal("fetch", vi.fn().mockImplementation(() => Promise.resolve(new Response("[]", { status: 200 }))));+});++afterEach(() => {+ resetDevRecorder();+ queryClient.clear();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++function wrapper({ children }: { children: ReactNode }) {+ return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;+}++describe("useDevRecorder", () => {+ it("stops recording requests and errors after the toolbar unmounts", async () => {+ const view = renderHook(() => useDevRecorder("/acme/issues", "connected"), { wrapper });+ view.unmount();+ console.error("while toolbar is off");+ await new ApiClient("http://localhost:18080").listMembers("ws-1");+ expect({ requests: getDevRecording().requests.length, errors: getDevRecording().errors.length }).toEqual({+ requests: 0,+ errors: 0,+ });+ });++ it("starts a fresh recording when the toolbar is shown again", async () => {+ const first = renderHook(() => useDevRecorder("/acme/issues", "connected"), { wrapper });+ console.error("from previous visible session");+ expect(getDevRecording().errors).toHaveLength(1);+ first.unmount();++ console.error("while toolbar is off");+ await new ApiClient("http://localhost:18080").listMembers("ws-1");++ const second = renderHook(() => useDevRecorder("/acme/issues", "connected"), { wrapper });+ const recording = getDevRecording();+ second.unmount();+ expect(recording.errors).toEqual([]);+ expect(recording.requests).toEqual([]);+ expect(recording.navigations.map((n) => n.route)).toEqual(["/acme/issues"]);+ });+});