Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(devtools): unify dev tools into a bottom DevDock (#17499)

Innei9bb3a1a5f305
diff --git a/apps/desktop/src/main/controllers/DevtoolsCtr.ts b/apps/desktop/src/main/controllers/DevtoolsCtr.ts
index bc6eb773554..a5b47b4fa20 100644
--- a/apps/desktop/src/main/controllers/DevtoolsCtr.ts
+++ b/apps/desktop/src/main/controllers/DevtoolsCtr.ts
@@ -1,3 +1,5 @@
+import { app } from 'electron';
+
import { ControllerModule, IpcMethod } from './index';
export default class DevtoolsCtr extends ControllerModule {
@@ -8,4 +10,11 @@ export default class DevtoolsCtr extends ControllerModule {
const devtoolsBrowser = this.app.browserManager.retrieveByIdentifier('devtools');
devtoolsBrowser.show();
}
+
+ @IpcMethod()
+ async getAppCpuUsage() {
+ const metrics = app.getAppMetrics();
+ const percent = metrics.reduce((sum, metric) => sum + metric.cpu.percentCPUUsage, 0);
+ return { percent };
+ }
}
diff --git a/apps/desktop/src/main/controllers/__tests__/DevtoolsCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/DevtoolsCtr.test.ts
index 9f1e5ecbfcc..7310713e555 100644
--- a/apps/desktop/src/main/controllers/__tests__/DevtoolsCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/DevtoolsCtr.test.ts
@@ -4,11 +4,15 @@ import type { App } from '@/core/App';
import DevtoolsCtr from '../DevtoolsCtr';
-const { ipcMainHandleMock } = vi.hoisted(() => ({
+const { getAppMetricsMock, ipcMainHandleMock } = vi.hoisted(() => ({
+ getAppMetricsMock: vi.fn(),
ipcMainHandleMock: vi.fn(),
}));
vi.mock('electron', () => ({
+ app: {
+ getAppMetrics: getAppMetricsMock,
+ },
ipcMain: {
handle: ipcMainHandleMock,
},
@@ -50,4 +54,22 @@ describe('DevtoolsCtr', () => {
expect(mockShow).toHaveBeenCalled();
});
});
+
+ describe('getAppCpuUsage', () => {
+ it('should sum percentCPUUsage across all app processes', async () => {
+ getAppMetricsMock.mockReturnValue([
+ { cpu: { percentCPUUsage: 1.5 } },
+ { cpu: { percentCPUUsage: 2.25 } },
+ { cpu: { percentCPUUsage: 0 } },
+ ]);
+
+ await expect(devtoolsCtr.getAppCpuUsage()).resolves.toEqual({ percent: 3.75 });
+ });
+
+ it('should return zero when there are no process metrics', async () => {
+ getAppMetricsMock.mockReturnValue([]);
+
+ await expect(devtoolsCtr.getAppCpuUsage()).resolves.toEqual({ percent: 0 });
+ });
+ });
});
diff --git a/src/features/AgentMockDevtools/Controls.tsx b/src/features/AgentMockDevtools/Controls.tsx
new file mode 100644
index 00000000000..209254eb27a
--- /dev/null
+++ b/src/features/AgentMockDevtools/Controls.tsx
@@ -0,0 +1,226 @@
+import { ActionIcon, Flexbox, toast } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { Pause, Play, Repeat, RotateCcw, SkipForward, Square } from 'lucide-react';
+import { memo, useCallback, useEffect, useRef, useState } from 'react';
+
+import { CaseTrigger } from './CaseTrigger';
+import { useAgentMockPlayer } from './hooks/useAgentMockPlayer';
+import { useAgentMockReplayTarget } from './hooks/useAgentMockReplayTarget';
+import { useMockCases } from './hooks/useMockCases';
+import { useAgentMockStore } from './store/agentMockStore';
+
+const styles = createStaticStyles(({ css }) => ({
+ counter: css`
+ font-size: 11px;
+ font-feature-settings: 'tnum';
+ color: ${cssVar.colorTextSecondary};
+ `,
+ progress: css`
+ touch-action: none;
+ cursor: pointer;
+
+ display: flex;
+ align-items: center;
+
+ height: 14px;
+
+ &:hover .agent-mock-progress-track {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ progressFill: css`
+ pointer-events: none;
+
+ position: absolute;
+ inset-block: 0;
+ inset-inline-start: 0;
+
+ height: 100%;
+ border-radius: inherit;
+
+ background: ${cssVar.colorText};
+
+ transition: width 0.16s linear;
+ `,
+ progressTrack: css`
+ position: relative;
+
+ overflow: hidden;
+ flex: 1;
+
+ height: 4px;
+ border-radius: 2px;
+
+ background: ${cssVar.colorFillSecondary};
+ `,
+ progressTrackScrubbing: css`
+ background: ${cssVar.colorFillTertiary} !important;
+ `,
+}));
+
+export const Controls = memo(() => {
+ const selectedCaseId = useAgentMockStore((s) => s.selectedCaseId);
+ const playback = useAgentMockStore((s) => s.playback);
+ const loop = useAgentMockStore((s) => s.loop);
+ const setLoop = useAgentMockStore((s) => s.setLoop);
+
+ const { all } = useMockCases();
+ const selected = all.find((c) => c.id === selectedCaseId);
+ const { pause, resume, seekToEventIndex, start, stepEvent, stop } = useAgentMockPlayer();
+ const resolveReplayTarget = useAgentMockReplayTarget();
+
+ const status = playback?.status;
+ const running = status === 'running';
+ const paused = status === 'paused';
+ const idleOrComplete = !playback || status === 'idle' || status === 'complete';
+ const disabled = !selected;
+ const stoppable = playback != null && status !== 'idle';
+
+ const progressRef = useRef<HTMLDivElement | null>(null);
+ const [scrubbing, setScrubbing] = useState(false);
+
+ const launchCase = useCallback(() => {
+ if (!selected) return;
+ const { agentId, threadId, topicId } = resolveReplayTarget();
+ if (!agentId) {
+ toast.warning('Open an agent conversation first.');
+ return;
+ }
+ if (!topicId) {
+ toast.warning('Open a topic before playing a mock case.');
+ return;
+ }
+ start({ agentId, case: selected, threadId, topicId });
+ }, [resolveReplayTarget, selected, start]);
+
+ const handlePlay = useCallback(() => {
+ if (idleOrComplete) {
+ launchCase();
+ return;
+ }
+ if (paused) resume();
+ else if (running) pause();
+ }, [idleOrComplete, launchCase, pause, paused, resume, running]);
+
+ const handleReplay = useCallback(() => {
+ if (!selected) return;
+ if (playback && status !== 'idle') seekToEventIndex(0);
+ launchCase();
+ }, [launchCase, playback, seekToEventIndex, selected, status]);
+
+ const seekFromClientX = useCallback(
+ (clientX: number) => {
+ const total = playback?.totalEvents;
+ if (!total) return;
+ const el = progressRef.current;
+ if (!el) return;
+ const rect = el.getBoundingClientRect();
+ if (rect.width <= 0) return;
+ const ratio = Math.min(1, Math.max(0, (clientX - rect.left) / rect.width));
+ seekToEventIndex(Math.round(ratio * total));
+ },
+ [playback?.totalEvents, seekToEventIndex],
+ );
+
+ const handleScrubStart = useCallback(
+ (e: React.PointerEvent<HTMLDivElement>) => {
+ if (!playback || !playback.totalEvents) return;
+ if (e.button !== 0) return;
+ e.preventDefault();
+ setScrubbing(true);
+ seekFromClientX(e.clientX);
+ },
+ [playback, seekFromClientX],
+ );
+
+ useEffect(() => {
+ if (!scrubbing) return;
+ const onMove = (e: PointerEvent) => seekFromClientX(e.clientX);
+ const onUp = () => setScrubbing(false);
+ window.addEventListener('pointermove', onMove);
+ window.addEventListener('pointerup', onUp);
+ window.addEventListener('pointercancel', onUp);
+ return () => {
+ window.removeEventListener('pointermove', onMove);
+ window.removeEventListener('pointerup', onUp);
+ window.removeEventListener('pointercancel', onUp);
+ };
+ }, [scrubbing, seekFromClientX]);
+
+ const pct = playback?.totalEvents
+ ? Math.min(100, (playback.currentEventIndex / playback.totalEvents) * 100)
+ : 0;
+
+ return (
+ <Flexbox gap={12}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <CaseTrigger placement={'topLeft'} />
+ <span style={{ flex: 1 }} />
+ <span className={styles.counter}>
+ {playback ? `${playback.currentEventIndex}/${playback.totalEvents}` : '—'}
+ </span>
+ </Flexbox>
+ <div
+ aria-valuemax={playback?.totalEvents ?? 0}
+ aria-valuemin={0}
+ aria-valuenow={playback?.currentEventIndex ?? 0}
+ className={styles.progress}
+ ref={progressRef}
+ role={'slider'}
+ tabIndex={0}
+ onPointerDown={handleScrubStart}
+ >
+ <div
+ className={`agent-mock-progress-track ${styles.progressTrack} ${
+ scrubbing ? styles.progressTrackScrubbing : ''
+ }`}
+ >
+ <div className={styles.progressFill} style={{ width: `${pct}%` }} />
+ </div>
+ </div>
+ <Flexbox horizontal align={'center'} gap={4}>
+ <ActionIcon
+ disabled={disabled}
+ icon={running ? Pause : Play}
+ size={'small'}
+ title={running ? 'Pause' : paused ? 'Resume' : 'Play'}
+ onClick={handlePlay}
+ />
+ <ActionIcon
+ disabled={disabled}
+ icon={SkipForward}
+ size={'small'}
+ title={'Next event'}
+ onClick={stepEvent}
+ />
+ <ActionIcon
+ disabled={disabled}
+ icon={RotateCcw}
+ size={'small'}
+ title={'Replay from start'}
+ onClick={handleReplay}
+ />
+ <ActionIcon
+ active={loop}
+ aria-pressed={loop}
+ icon={Repeat}
+ size={'small'}
+ title={loop ? 'Loop on' : 'Loop off'}
+ onClick={() => setLoop(!loop)}
+ />
+ <ActionIcon
+ danger
+ disabled={!stoppable}
+ icon={Square}
+ size={'small'}
+ title={'Stop playback'}
+ onClick={stop}
+ />
+ <span style={{ flex: 1 }} />
+ <span className={styles.counter}>{selected ? selected.name : 'No case selected'}</span>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+Controls.displayName = 'AgentMockControls';
diff --git a/src/features/AgentMockDevtools/Fab.tsx b/src/features/AgentMockDevtools/Fab.tsx
deleted file mode 100644
index af716d44b21..00000000000
--- a/src/features/AgentMockDevtools/Fab.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-import { Tooltip } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from 'antd-style';
-import { Bot } from 'lucide-react';
-import { memo } from 'react';
-
-import { useAgentMockStore } from './store/agentMockStore';
-
-const styles = createStaticStyles(({ css }) => ({
- fab: css`
- cursor: pointer;
- user-select: none;
-
- position: fixed;
- z-index: 1100;
- inset-block-end: 16px;
- inset-inline-end: 16px;
-
- display: flex;
- align-items: center;
- justify-content: center;
-
- width: 36px;
- height: 36px;
- border: 1px solid transparent;
- border-radius: 50%;
-
- color: ${cssVar.colorBgContainer};
-
- background: ${cssVar.colorText};
- box-shadow: 0 2px 8px rgb(0 0 0 / 12%);
-
- transition:
- transform 160ms ease,
- background 160ms ease,
- color 160ms ease,
- border-color 160ms ease;
-
- &:hover {
- transform: scale(1.04);
- }
- `,
- fabActive: css`
- border-color: ${cssVar.colorBorder};
- color: ${cssVar.colorText};
- background: ${cssVar.colorFillSecondary};
- `,
- ring: css`
- pointer-events: none;
-
- position: absolute;
- inset: -3px;
-
- border: 1.5px solid ${cssVar.colorText};
- border-radius: 50%;
-
- opacity: 0.4;
-
- animation: agent-mock-pulse 2.4s ease-in-out infinite;
-
- @keyframes agent-mock-pulse {
- 0%,
- 100% {
- opacity: 0.3;
- }
-
- 50% {
- opacity: 0.8;
- }
- }
- `,
-}));
-
-export const Fab = memo(() => {
- const popoverOpen = useAgentMockStore((s) => s.popoverOpen);
- const setPopoverOpen = useAgentMockStore((s) => s.setPopoverOpen);
- const modalOpen = useAgentMockStore((s) => s.modalOpen);
- const playback = useAgentMockStore((s) => s.playback);
- const playing = playback?.status === 'running';
-
- if (modalOpen) return null;
-
- return (
- <Tooltip title="Agent Mock (dev only)">
- <div
- className={`${styles.fab} ${popoverOpen ? styles.fabActive : ''}`}
- role="button"
- tabIndex={0}
- onClick={() => setPopoverOpen(!popoverOpen)}
- onKeyDown={(event) => {
- if (event.key === 'Enter' || event.key === ' ') {
- event.preventDefault();
- setPopoverOpen(!popoverOpen);
- }
- }}
- >
- <Bot size={18} />
- {playing && <span className={styles.ring} />}
- </div>
- </Tooltip>
- );
-});
-
-Fab.displayName = 'AgentMockFab';
diff --git a/src/features/AgentMockDevtools/Popover.tsx b/src/features/AgentMockDevtools/Popover.tsx
deleted file mode 100644
index 0400c8c70da..00000000000
--- a/src/features/AgentMockDevtools/Popover.tsx
+++ /dev/null
@@ -1,474 +0,0 @@
-import { ActionIcon, Flexbox, toast } from '@lobehub/ui';
-import { Button } from '@lobehub/ui/base-ui';
-import { createStaticStyles, cssVar } from 'antd-style';
-import {
- GripHorizontal,
- Maximize2,
- Pause,
- Play,
- Repeat,
- RotateCcw,
- SkipForward,
- Square,
- X,
-} from 'lucide-react';
-import { memo, useCallback, useEffect, useRef, useState } from 'react';
-
-import { CaseTrigger } from './CaseTrigger';
-import { useAgentMockPlayer } from './hooks/useAgentMockPlayer';
-import { useAgentMockReplayTarget } from './hooks/useAgentMockReplayTarget';
-import { useMockCases } from './hooks/useMockCases';
-import { useAgentMockStore } from './store/agentMockStore';
-
-const POPOVER_WIDTH = 320;
-const PANEL_HEIGHT_FALLBACK = 200;
-const VIEWPORT_INSET = 8;
-const POSITION_STORAGE_KEY = 'LOBE_AGENT_MOCK_POPOVER_POS';
-
-interface PanelPosition {
- x: number;
- y: number;
-}
-
-const readPersistedPosition = (): PanelPosition | null => {
- if (typeof localStorage === 'undefined') return null;
- try {
- const raw = localStorage.getItem(POSITION_STORAGE_KEY);
- if (!raw) return null;
- const parsed = JSON.parse(raw) as Partial<PanelPosition>;
- if (typeof parsed.x === 'number' && typeof parsed.y === 'number') {
- return { x: parsed.x, y: parsed.y };
- }
- return null;
- } catch {
- return null;
- }
-};
-
-const writePersistedPosition = (pos: PanelPosition | null) => {
- if (typeof localStorage === 'undefined') return;
- if (!pos) {
- localStorage.removeItem(POSITION_STORAGE_KEY);
- return;
- }
- localStorage.setItem(POSITION_STORAGE_KEY, JSON.stringify(pos));
-};
-
-const clampToViewport = (pos: PanelPosition, width: number, height: number): PanelPosition => {
- if (typeof window === 'undefined') return pos;
- const maxX = Math.max(VIEWPORT_INSET, window.innerWidth - width - VIEWPORT_INSET);
- const maxY = Math.max(VIEWPORT_INSET, window.innerHeight - height - VIEWPORT_INSET);
- return {
- x: Math.min(Math.max(VIEWPORT_INSET, pos.x), maxX),
- y: Math.min(Math.max(VIEWPORT_INSET, pos.y), maxY),
- };
-};
-
-const styles = createStaticStyles(({ css }) => ({
- body: css`
- padding: 12px;
- padding-block-start: 0;
- `,
- closeBtn: css`
- cursor: pointer;
-
- width: 22px;
- height: 22px;
- border-radius: 4px;
-
- color: ${cssVar.colorTextTertiary};
-
- &:hover {
- color: ${cssVar.colorText};
- background: ${cssVar.colorFillTertiary};
- }
- `,
- counter: css`
- font-size: 11px;
- font-feature-settings: 'tnum';
- color: ${cssVar.colorTextSecondary};
- `,
- footer: css`
- padding-block: 8px;
- padding-inline: 12px;
- border-block-start: 1px solid ${cssVar.colorBorderSecondary};
- background: ${cssVar.colorFillTertiary};
- `,
- grip: css`
- cursor: grab;
- user-select: none;
-
- display: inline-flex;
- align-items: center;
- justify-content: center;
-
- width: 20px;
- height: 22px;
- border-radius: 4px;
-
- color: ${cssVar.colorTextQuaternary};
-
- transition: color 120ms ease;
-
- &:hover {
- color: ${cssVar.colorTextSecondary};
- background: ${cssVar.colorFillTertiary};
- }
-
- &:active {
- cursor: grabbing;
- }
- `,
- gripDragging: css`
- cursor: grabbing;
- color: ${cssVar.colorText};
- `,
- header: css`
- padding-block: 8px;
- padding-inline: 10px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
- panel: css`
- position: fixed;
- z-index: 1099;
-
- overflow: hidden;
-
- width: ${POPOVER_WIDTH}px;
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 10px;
-
- background: ${cssVar.colorBgElevated};
- box-shadow: 0 12px 32px rgb(0 0 0 / 12%);
- `,
- progress: css`
- touch-action: none;
- cursor: pointer;
-
- display: flex;
- align-items: center;
-
- height: 14px;
- margin-block-end: 8px;
-
- &:hover .agent-mock-progress-track {
- background: ${cssVar.colorFillTertiary};
- }
- `,
- progressFill: css`
- pointer-events: none;
-
- position: absolute;
- inset-block: 0;
- inset-inline-start: 0;
-
- height: 100%;
- border-radius: inherit;
-
- background: ${cssVar.colorText};
-
- transition: width 0.16s linear;
- `,
- progressTrack: css`
- position: relative;
-
- overflow: hidden;
- flex: 1;
-
- height: 4px;
- border-radius: 2px;
-
- background: ${cssVar.colorFillSecondary};
- `,
- progressTrackScrubbing: css`
- background: ${cssVar.colorFillTertiary} !important;
- `,
-}));
-
-export const Popover = memo(() => {
- const popoverOpen = useAgentMockStore((s) => s.popoverOpen);
- const modalOpen = useAgentMockStore((s) => s.modalOpen);
- const setPopoverOpen = useAgentMockStore((s) => s.setPopoverOpen);
- const setModalOpen = useAgentMockStore((s) => s.setModalOpen);
- const selectedCaseId = useAgentMockStore((s) => s.selectedCaseId);
- const playback = useAgentMockStore((s) => s.playback);
- const loop = useAgentMockStore((s) => s.loop);
- const setLoop = useAgentMockStore((s) => s.setLoop);
-
- const { all } = useMockCases();
- const selected = all.find((c) => c.id === selectedCaseId);
- const { pause, resume, seekToEventIndex, start, stepEvent, stop } = useAgentMockPlayer();
- const resolveReplayTarget = useAgentMockReplayTarget();
-
- const status = playback?.status;
- const running = status === 'running';
- const paused = status === 'paused';
- const idleOrComplete = !playback || status === 'idle' || status === 'complete';
- const disabled = !selected;
- const stoppable = playback != null && status !== 'idle';
-
- const panelRef = useRef<HTMLDivElement | null>(null);
- const progressRef = useRef<HTMLDivElement | null>(null);
- const [position, setPosition] = useState<PanelPosition | null>(() => readPersistedPosition());
- const [dragging, setDragging] = useState(false);
- const [scrubbing, setScrubbing] = useState(false);
- const dragOriginRef = useRef<{
- panelLeft: number;
- panelTop: number;
- pointerX: number;
- pointerY: number;
- } | null>(null);
-
- const launchCase = useCallback(() => {
- if (!selected) return;
- const { agentId, threadId, topicId } = resolveReplayTarget();
- if (!agentId) {
- toast.warning('Open an agent conversation first.');
- return;
- }
- if (!topicId) {
- toast.warning('Open a topic before playing a mock case.');
- return;
- }
- start({ agentId, case: selected, threadId, topicId });
- }, [resolveReplayTarget, selected, start]);
-
- const handlePlay = useCallback(() => {
- if (idleOrComplete) {
- launchCase();
- return;
- }
- if (paused) resume();
- else if (running) pause();
- }, [idleOrComplete, launchCase, pause, paused, resume, running]);
-
- const handleReplay = useCallback(() => {
- if (!selected) return;
- if (playback && status !== 'idle') seekToEventIndex(0);
- launchCase();
- }, [launchCase, playback, seekToEventIndex, selected, status]);
-
- const handleOpenDevtools = useCallback(() => {
- setModalOpen(true);
- setPopoverOpen(false);
- }, [setModalOpen, setPopoverOpen]);
-
- const handleStop = useCallback(() => {
- stop();
- }, [stop]);
-
- useEffect(() => {
- if (!popoverOpen) return;
- const onKey = (e: KeyboardEvent) => {
- if (e.key === 'Escape') setPopoverOpen(false);
- };
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, [popoverOpen, setPopoverOpen]);
-
- useEffect(() => {
- if (!dragging) return;
- const onMove = (e: PointerEvent) => {
- const origin = dragOriginRef.current;
- if (!origin) return;
- const next: PanelPosition = {
- x: origin.panelLeft + (e.clientX - origin.pointerX),
- y: origin.panelTop + (e.clientY - origin.pointerY),
- };
- const height = panelRef.current?.offsetHeight ?? PANEL_HEIGHT_FALLBACK;
- setPosition(clampToViewport(next, POPOVER_WIDTH, height));
- };
- const onUp = () => {
- setDragging(false);
- dragOriginRef.current = null;
- };
- window.addEventListener('pointermove', onMove);
- window.addEventListener('pointerup', onUp);
- return () => {
- window.removeEventListener('pointermove', onMove);
- window.removeEventListener('pointerup', onUp);
- };
- }, [dragging]);
-
- useEffect(() => {
- if (dragging) return;
- writePersistedPosition(position);
- }, [dragging, position]);
-
- const handleDragStart = useCallback((e: React.PointerEvent<HTMLSpanElement>) => {
- if (!panelRef.current) return;
- e.preventDefault();
- const rect = panelRef.current.getBoundingClientRect();
- dragOriginRef.current = {
- panelLeft: rect.left,
- panelTop: rect.top,
- pointerX: e.clientX,
- pointerY: e.clientY,
- };
- setDragging(true);
- }, []);
-
- const seekFromClientX = useCallback(
- (clientX: number) => {
- const total = playback?.totalEvents;
- if (!total) return;
- const el = progressRef.current;
- if (!el) return;
- const rect = el.getBoundingClientRect();
- if (rect.width <= 0) return;
- const ratio = Math.min(1, Math.max(0, (clientX - rect.left) / rect.width));
- seekToEventIndex(Math.round(ratio * total));
- },
- [playback?.totalEvents, seekToEventIndex],
- );
-
- const handleScrubStart = useCallback(
- (e: React.PointerEvent<HTMLDivElement>) => {
- if (!playback || !playback.totalEvents) return;
- if (e.button !== 0) return;
- e.preventDefault();
- setScrubbing(true);
- seekFromClientX(e.clientX);
- },
- [playback, seekFromClientX],
- );
-
- useEffect(() => {
- if (!scrubbing) return;
- const onMove = (e: PointerEvent) => seekFromClientX(e.clientX);
- const onUp = () => setScrubbing(false);
- window.addEventListener('pointermove', onMove);
- window.addEventListener('pointerup', onUp);
- window.addEventListener('pointercancel', onUp);
- return () => {
- window.removeEventListener('pointermove', onMove);
- window.removeEventListener('pointerup', onUp);
- window.removeEventListener('pointercancel', onUp);
- };
- }, [scrubbing, seekFromClientX]);
-
- if (modalOpen || !popoverOpen) return null;
-
- const pct = playback?.totalEvents
- ? Math.min(100, (playback.currentEventIndex / playback.totalEvents) * 100)
- : 0;
-
- const positionStyle: React.CSSProperties = position
- ? { insetBlockStart: position.y, insetInlineStart: position.x }
- : { insetBlockEnd: 64, insetInlineEnd: 16 };
-
- return (
- <div
- aria-label="Agent Mock controls"
- className={styles.panel}
- ref={panelRef}
- role="dialog"
- style={positionStyle}
- >
- <Flexbox horizontal align="center" className={styles.header} gap={6}>
- <span
- aria-label="Drag"
- className={`${styles.grip} ${dragging ? styles.gripDragging : ''}`}
- role="presentation"
- onPointerDown={handleDragStart}
- >
- <GripHorizontal size={14} />
- </span>
- <CaseTrigger placement="topRight" />
- <span style={{ flex: 1 }} />
- <span className={styles.counter}>
- {playback ? `${playback.currentEventIndex}/${playback.totalEvents}` : '—'}
- </span>
- <span
- aria-label="Close"
- className={styles.closeBtn}
- role="button"
- style={{ alignItems: 'center', display: 'inline-flex', justifyContent: 'center' }}
- tabIndex={0}
- onClick={() => setPopoverOpen(false)}
- onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- setPopoverOpen(false);
- }
- }}
- >
- <X size={14} />
- </span>
- </Flexbox>
- <div className={styles.body}>
- <div
- aria-valuemax={playback?.totalEvents ?? 0}
- aria-valuemin={0}
- aria-valuenow={playback?.currentEventIndex ?? 0}
- className={styles.progress}
- ref={progressRef}
- role="slider"
- tabIndex={0}
- onPointerDown={handleScrubStart}
- >
- <div
- className={`agent-mock-progress-track ${styles.progressTrack} ${
- scrubbing ? styles.progressTrackScrubbing : ''
- }`}
- >
- <div className={styles.progressFill} style={{ width: `${pct}%` }} />
- </div>
- </div>
- <Flexbox horizontal align="center" gap={4}>
- <ActionIcon
- disabled={disabled}
- icon={running ? Pause : Play}
- size="small"
- title={running ? 'Pause' : paused ? 'Resume' : 'Play'}
- onClick={handlePlay}
- />
- <ActionIcon
- disabled={disabled}
- icon={SkipForward}
- size="small"
- title="Next event"
- onClick={stepEvent}
- />
- <ActionIcon
- disabled={disabled}
- icon={RotateCcw}
- size="small"
- title="Replay from start"
- onClick={handleReplay}
- />
- <ActionIcon
- active={loop}
- aria-pressed={loop}
- icon={Repeat}
- size="small"
- title={loop ? 'Loop on' : 'Loop off'}
- onClick={() => setLoop(!loop)}
- />
- <ActionIcon
- danger
- disabled={!stoppable}
- icon={Square}
- size="small"
- title="Stop playback"
- onClick={handleStop}
- />
- <span style={{ flex: 1 }} />
- <Button
- icon={<Maximize2 size={12} />}
- size="small"
- type="primary"
- onClick={handleOpenDevtools}
- >
- Open DevTools
- </Button>
- </Flexbox>
- </div>
- <Flexbox horizontal align="center" className={styles.footer} gap={8} justify="space-between">
- <span className={styles.counter}>{selected ? selected.name : 'No case selected'}</span>
- </Flexbox>
- </div>
- );
-});
-
-Popover.displayName = 'AgentMockPopover';
diff --git a/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.test.ts b/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.test.ts
index 20674fc89e6..6edbaeecdfa 100644
--- a/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.test.ts
+++ b/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.test.ts
@@ -115,11 +115,8 @@ describe('useAgentMockPlayer', () => {
vi.clearAllMocks();
useAgentMockStore.setState({
- activeTab: 'timeline',
loop: false,
- modalOpen: false,
playback: null,
- popoverOpen: false,
selectedCaseId: null,
speed: 1,
});
diff --git a/src/features/AgentMockDevtools/index.tsx b/src/features/AgentMockDevtools/index.tsx
index fad8b000ea6..40859f4a865 100644
--- a/src/features/AgentMockDevtools/index.tsx
+++ b/src/features/AgentMockDevtools/index.tsx
@@ -1,52 +1,25 @@
-import { memo, useEffect, useState } from 'react';
+import { Flexbox, Text } from '@lobehub/ui';
+import { memo } from 'react';
import { useMatches } from 'react-router';
-import ImperativeModal from '@/components/ImperativeModal';
+import { Controls } from './Controls';
-import { Fab } from './Fab';
-import { Popover } from './Popover';
-
-const STORAGE_KEY = 'LOBE_AGENT_MOCK_ENABLED';
-
-const useDevtoolsEnabled = (): boolean => {
- const [enabled, setEnabled] = useState(false);
- useEffect(() => {
- if (!__DEV__) return;
- setEnabled(localStorage.getItem(STORAGE_KEY) === '1');
- const onStorage = (e: StorageEvent) => {
- if (e.key === STORAGE_KEY) setEnabled(e.newValue === '1');
- };
- window.addEventListener('storage', onStorage);
- if (!localStorage.getItem(STORAGE_KEY)) {
- console.info(
- '[AgentMock] Dev tool available. Enable with: localStorage.LOBE_AGENT_MOCK_ENABLED = "1"',
- );
- }
- return () => window.removeEventListener('storage', onStorage);
- }, []);
- return enabled;
-};
-
-const useIsAgentTopicRoute = (): boolean => {
+const AgentMockPanel = memo(() => {
const matches = useMatches();
- // Check if any resolved route segment has a topicId param
- // This correctly distinguishes /agent/:topicId from /agent/page, /agent/profile, etc.
- return matches.some((m) => 'topicId' in m.params);
-};
+ const isAgentTopicRoute = matches.some((m) => 'topicId' in m.params);
-const AgentMockDevtools = memo(() => {
- const enabled = useDevtoolsEnabled();
- const isAgentTopicRoute = useIsAgentTopicRoute();
- if (!__DEV__ || !enabled || !isAgentTopicRoute) return null;
return (
- <>
- <Fab />
- <Popover />
- <ImperativeModal />
- </>
+ <Flexbox gap={12} padding={16} style={{ marginInline: 'auto', maxWidth: 560, width: '100%' }}>
+ {!isAgentTopicRoute && (
+ <Text fontSize={12} type={'secondary'}>
+ Open an agent topic conversation to replay mock cases into it.
+ </Text>
+ )}
+ <Controls />
+ </Flexbox>
);
});
-AgentMockDevtools.displayName = 'AgentMockDevtools';
+AgentMockPanel.displayName = 'AgentMockPanel';
-export default AgentMockDevtools;
+export default AgentMockPanel;
diff --git a/src/features/AgentMockDevtools/store/agentMockStore.ts b/src/features/AgentMockDevtools/store/agentMockStore.ts
index 4cd5e30ba68..37ba5c85805 100644
--- a/src/features/AgentMockDevtools/store/agentMockStore.ts
+++ b/src/features/AgentMockDevtools/store/agentMockStore.ts
@@ -1,8 +1,6 @@
import type { PlaybackState, SpeedMultiplier } from '@lobechat/agent-mock';
import { create } from 'zustand';
-export type DevtoolsTab = 'timeline' | 'fixture';
-
const LOOP_STORAGE_KEY = 'LOBE_AGENT_MOCK_LOOP';
const readPersistedLoop = (): boolean => {
@@ -16,37 +14,25 @@ const writePersistedLoop = (next: boolean) => {
};
export interface AgentMockStore {
- activeTab: DevtoolsTab;
loop: boolean;
- modalOpen: boolean;
playback: PlaybackState | null;
- popoverOpen: boolean;
selectedCaseId: string | null;
- setActiveTab: (t: DevtoolsTab) => void;
setLoop: (loop: boolean) => void;
- setModalOpen: (open: boolean) => void;
setPlayback: (p: PlaybackState | null) => void;
- setPopoverOpen: (open: boolean) => void;
setSelectedCaseId: (id: string | null) => void;
setSpeed: (s: SpeedMultiplier) => void;
speed: SpeedMultiplier;
}
export const useAgentMockStore = create<AgentMockStore>((set) => ({
- activeTab: 'timeline',
loop: readPersistedLoop(),
- modalOpen: false,
playback: null,
- popoverOpen: false,
selectedCaseId: null,
- setActiveTab: (activeTab) => set({ activeTab }),
setLoop: (loop) => {
writePersistedLoop(loop);
set({ loop });
},
- setModalOpen: (modalOpen) => set({ modalOpen }),
setPlayback: (playback) => set({ playback }),
- setPopoverOpen: (popoverOpen) => set({ popoverOpen }),
setSelectedCaseId: (selectedCaseId) => set({ selectedCaseId }),
setSpeed: (speed) => set({ speed }),
speed: 1,
diff --git a/src/features/Conversation/ChatList/components/AutoScroll/DebugInspector.tsx b/src/features/Conversation/ChatList/components/AutoScroll/DebugInspector.tsx
index 56a83d6b054..e1283910fdd 100644
--- a/src/features/Conversation/ChatList/components/AutoScroll/DebugInspector.tsx
+++ b/src/features/Conversation/ChatList/components/AutoScroll/DebugInspector.tsx
@@ -3,21 +3,70 @@
import { memo } from 'react';
import { createPortal } from 'react-dom';
+import { useDevDockStore } from '@/features/DevDock/store';
+
import { messageStateSelectors, useConversationStore, virtuaListSelectors } from '../../../store';
import { AT_BOTTOM_THRESHOLD } from './const';
-/**
- * Whether to enable the debug panel
- * Set to true to display scroll position debug information
- */
-export const OPEN_DEV_INSPECTOR = false;
+export const ScrollDebugThresholdOverlay = memo<{ atBottom: boolean }>(({ atBottom }) => {
+ const enabled = useDevDockStore((s) => s.scrollDebug);
+ if (!enabled) return null;
+
+ return (
+ <div
+ style={{
+ bottom: 0,
+ left: 0,
+ pointerEvents: 'none',
+ position: 'absolute',
+ right: 0,
+ }}
+ >
+ <div
+ style={{
+ background: atBottom ? '#22c55e' : '#ef4444',
+ height: 2,
+ left: 0,
+ opacity: 0.5,
+ position: 'absolute',
+ right: 0,
+ top: -AT_BOTTOM_THRESHOLD,
+ }}
+ />
+ <div
+ style={{
+ background: atBottom
+ ? 'linear-gradient(to top, rgba(34, 197, 94, 0.15), transparent)'
+ : 'linear-gradient(to top, rgba(239, 68, 68, 0.1), transparent)',
+ height: AT_BOTTOM_THRESHOLD,
+ left: 0,
+ position: 'absolute',
+ right: 0,
+ top: -AT_BOTTOM_THRESHOLD,
+ }}
+ />
+ <div
+ style={{
+ background: atBottom ? '#22c55e' : '#ef4444',
+ height: 2,
+ width: '100%',
+ }}
+ />
+ </div>
+ );
+});
+
+ScrollDebugThresholdOverlay.displayName = 'ScrollDebugThresholdOverlay';
const DebugInspector = memo(() => {
+ const enabled = useDevDockStore((s) => s.scrollDebug);
const atBottom = useConversationStore(virtuaListSelectors.atBottom);
const isScrolling = useConversationStore(virtuaListSelectors.isScrolling);
const isGenerating = useConversationStore(messageStateSelectors.isAIGenerating);
const virtuaScrollMethods = useConversationStore((s) => s.virtuaScrollMethods);
+ if (!enabled) return null;
+
const shouldAutoScroll = atBottom && isGenerating && !isScrolling;
const scrollOffset = virtuaScrollMethods?.getScrollOffset?.() ?? 0;
const scrollSize = virtuaScrollMethods?.getScrollSize?.() ?? 0;
diff --git a/src/features/Conversation/ChatList/components/BackBottom/index.tsx b/src/features/Conversation/ChatList/components/BackBottom/index.tsx
index 60499335a8f..4afdcdaee4d 100644
--- a/src/features/Conversation/ChatList/components/BackBottom/index.tsx
+++ b/src/features/Conversation/ChatList/components/BackBottom/index.tsx
@@ -4,8 +4,7 @@ import { ArrowDownIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { AT_BOTTOM_THRESHOLD } from '../AutoScroll/const';
-import { OPEN_DEV_INSPECTOR } from '../AutoScroll/DebugInspector';
+import { ScrollDebugThresholdOverlay } from '../AutoScroll/DebugInspector';
import { styles } from './style';
export interface BackBottomProps {
@@ -25,54 +24,7 @@ const BackBottom = memo<BackBottomProps>(
return (
<>
- {/* Debug: bottom indicator line */}
- {OPEN_DEV_INSPECTOR && (
- <div
- style={{
- bottom: 0,
- left: 0,
- pointerEvents: 'none',
- position: 'absolute',
- right: 0,
- }}
- >
- {/* Threshold area top boundary line */}
- <div
- style={{
- background: atBottom ? '#22c55e' : '#ef4444',
- height: 2,
- left: 0,
- opacity: 0.5,
- position: 'absolute',
- right: 0,
- top: -AT_BOTTOM_THRESHOLD,
- }}
- />
-
- {/* Threshold area mask - displayed above the indicator line */}
- <div
- style={{
- background: atBottom
- ? 'linear-gradient(to top, rgba(34, 197, 94, 0.15), transparent)'
- : 'linear-gradient(to top, rgba(239, 68, 68, 0.1), transparent)',
- height: AT_BOTTOM_THRESHOLD,
- left: 0,
- position: 'absolute',
- right: 0,
- top: -AT_BOTTOM_THRESHOLD,
- }}
- />
-
- {/* AutoScroll position indicator line (bottom) */}
- <div
- style={{
- background: atBottom ? '#22c55e' : '#ef4444',
- height: 2,
- width: '100%',
- }}
- />
- </div>
- )}
+ {__DEV__ && <ScrollDebugThresholdOverlay atBottom={atBottom} />}
<ActionIcon
glass
diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
index 371f3cc03b7..ec829075153 100644
--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx
+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
@@ -26,7 +26,7 @@ import { useSelectionMessageIds } from '../hooks/useSelectionMessageIds';
import { useTopicScrollPersist } from '../hooks/useTopicScrollPersist';
import AutoScroll from './AutoScroll';
import { AT_BOTTOM_THRESHOLD } from './AutoScroll/const';
-import DebugInspector, { OPEN_DEV_INSPECTOR } from './AutoScroll/DebugInspector';
+import DebugInspector from './AutoScroll/DebugInspector';
import { useAutoScrollEnabled } from './AutoScroll/useAutoScrollEnabled';
import BackBottom from './BackBottom';
@@ -306,7 +306,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
{/* Pinned to the list viewport top; only renders while multi-selecting */}
<MessageForwardSelectToHere />
{/* Debug Inspector - placed outside VList so it won't be recycled by the virtual list */}
- {OPEN_DEV_INSPECTOR && <DebugInspector />}
+ {__DEV__ && <DebugInspector />}
<VList
bufferSize={typeof window !== 'undefined' ? window.innerHeight : 0}
data={dataWithSlots}
diff --git a/src/features/DevDock/Bar.tsx b/src/features/DevDock/Bar.tsx
new file mode 100644
index 00000000000..c37a32030ba
--- /dev/null
+++ b/src/features/DevDock/Bar.tsx
@@ -0,0 +1,203 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { ChevronDown, Wrench } from 'lucide-react';
+import { Component, memo, type PropsWithChildren, Suspense } from 'react';
+
+import { BAR_HEIGHT, DOCK_Z_INDEX } from './const';
+import {
+ type DevDockPanelItem,
+ type DevDockWidgetItem,
+ getItemComponent,
+ useDevDockItems,
+} from './registry';
+import { useDevDockStore } from './store';
+
+const styles = createStaticStyles(({ css }) => ({
+ bar: css`
+ flex-shrink: 0;
+
+ width: 100%;
+ height: ${BAR_HEIGHT}px;
+ padding-inline: 8px;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+
+ font-size: 11px;
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorBgLayout};
+ `,
+ iconButton: css`
+ cursor: pointer;
+
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+
+ width: 20px;
+ height: 20px;
+ border: none;
+ border-radius: 4px;
+
+ color: ${cssVar.colorTextTertiary};
+
+ background: transparent;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ pill: css`
+ cursor: pointer;
+
+ position: fixed;
+ z-index: ${DOCK_Z_INDEX};
+ inset-block-end: 0;
+ inset-inline-start: 16px;
+
+ display: inline-flex;
+ gap: 4px;
+ align-items: center;
+
+ height: 18px;
+ padding-inline: 8px;
+ border: none;
+ border-start-start-radius: 6px;
+ border-start-end-radius: 6px;
+
+ font-size: 10px;
+ color: ${cssVar.colorBgContainer};
+
+ background: ${cssVar.colorText};
+
+ &:hover {
+ opacity: 0.85;
+ }
+ `,
+ tab: css`
+ cursor: pointer;
+
+ display: inline-flex;
+ gap: 5px;
+ align-items: center;
+
+ height: 20px;
+ padding-inline: 8px;
+ border: none;
+ border-radius: 4px;
+
+ font-size: 11px;
+ color: ${cssVar.colorTextSecondary};
+
+ background: transparent;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ tabActive: css`
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillSecondary};
+ `,
+}));
+
+class WidgetBoundary extends Component<PropsWithChildren, { failed?: boolean }> {
+ state = { failed: false };
+
+ static getDerivedStateFromError() {
+ return { failed: true };
+ }
+
+ render() {
+ return this.state.failed ? null : this.props.children;
+ }
+}
+
+const WidgetSlot = memo<{ item: DevDockWidgetItem }>(({ item }) => {
+ const Widget = getItemComponent(item);
+ return (
+ <WidgetBoundary>
+ <Suspense fallback={null}>
+ <Widget />
+ </Suspense>
+ </WidgetBoundary>
+ );
+});
+
+WidgetSlot.displayName = 'DevDockWidgetSlot';
+
+const PanelTab = memo<{ item: DevDockPanelItem }>(({ item }) => {
+ const active = useDevDockStore((s) => s.activePanelId === item.id);
+ const togglePanel = useDevDockStore((s) => s.togglePanel);
+ const Icon = item.icon;
+ const Badge = item.badge;
+ return (
+ <button
+ className={cx(styles.tab, active && styles.tabActive)}
+ type={'button'}
+ onClick={() => togglePanel(item.id)}
+ >
+ <Icon size={12} />
+ <span>{item.title}</span>
+ {Badge && <Badge />}
+ </button>
+ );
+});
+
+PanelTab.displayName = 'DevDockPanelTab';
+
+const Bar = memo(() => {
+ const expanded = useDevDockStore((s) => s.expanded);
+ const setExpanded = useDevDockStore((s) => s.setExpanded);
+ const items = useDevDockItems();
+
+ if (!expanded)
+ return (
+ <button
+ className={styles.pill}
+ title={'Open DevDock'}
+ type={'button'}
+ onClick={() => setExpanded(true)}
+ >
+ <Wrench size={10} />
+ <span>dev</span>
+ </button>
+ );
+
+ const panels = items.filter((item): item is DevDockPanelItem => item.type === 'panel');
+ const widgets = items.filter((item): item is DevDockWidgetItem => item.type === 'widget');
+ const leftWidgets = widgets.filter((item) => item.placement === 'left');
+ const rightWidgets = widgets.filter((item) => item.placement === 'right');
+
+ return (
+ <Flexbox horizontal align={'center'} className={styles.bar} gap={8}>
+ <button
+ className={styles.iconButton}
+ title={'Collapse DevDock'}
+ type={'button'}
+ onClick={() => setExpanded(false)}
+ >
+ <ChevronDown size={12} />
+ </button>
+ {leftWidgets.map((item) => (
+ <WidgetSlot item={item} key={item.id} />
+ ))}
+ <Flexbox horizontal align={'center'} gap={2}>
+ {panels.map((item) => (
+ <PanelTab item={item} key={item.id} />
+ ))}
+ </Flexbox>
+ <span style={{ flex: 1 }} />
+ {rightWidgets.map((item) => (
+ <WidgetSlot item={item} key={item.id} />
+ ))}
+ </Flexbox>
+ );
+});
+
+Bar.displayName = 'DevDockBar';
+
+export default Bar;
diff --git a/src/features/DevDock/PanelErrorBoundary.tsx b/src/features/DevDock/PanelErrorBoundary.tsx
new file mode 100644
index 00000000000..89c12cbbb19
--- /dev/null
+++ b/src/features/DevDock/PanelErrorBoundary.tsx
@@ -0,0 +1,32 @@
+import { Button } from '@lobehub/ui/base-ui';
+import { Component, type PropsWithChildren } from 'react';
+
+interface PanelErrorBoundaryState {
+ error?: Error;
+}
+
+class PanelErrorBoundary extends Component<PropsWithChildren, PanelErrorBoundaryState> {
+ state: PanelErrorBoundaryState = {};
+
+ static getDerivedStateFromError(error: Error): PanelErrorBoundaryState {
+ return { error };
+ }
+
+ render() {
+ if (!this.state.error) return this.props.children;
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: 16 }}>
+ <span style={{ fontSize: 12 }}>Panel crashed: {this.state.error.message}</span>
+ <Button
+ size={'small'}
+ style={{ alignSelf: 'flex-start' }}
+ onClick={() => this.setState({ error: undefined })}
+ >
+ Retry
+ </Button>
+ </div>
+ );
+ }
+}
+
+export default PanelErrorBoundary;
diff --git a/src/features/DevDock/PanelHost.tsx b/src/features/DevDock/PanelHost.tsx
new file mode 100644
index 00000000000..7b6a0d5434e
--- /dev/null
+++ b/src/features/DevDock/PanelHost.tsx
@@ -0,0 +1,151 @@
+'use client';
+
+import { ActionIcon, Flexbox } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { Maximize2, Minimize2, XIcon } from 'lucide-react';
+import { memo, Suspense, useCallback, useEffect, useRef, useState } from 'react';
+
+import { BAR_HEIGHT } from './const';
+import PanelErrorBoundary from './PanelErrorBoundary';
+import { type DevDockPanelItem, getItemComponent, useDevDockItems } from './registry';
+import { MIN_PANEL_HEIGHT, useDevDockStore } from './store';
+
+const styles = createStaticStyles(({ css }) => ({
+ content: css`
+ overflow: auto;
+ flex: 1;
+ min-height: 0;
+ `,
+ header: css`
+ flex-shrink: 0;
+
+ height: 30px;
+ padding-inline: 10px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ font-size: 11px;
+ font-weight: 500;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ host: css`
+ position: relative;
+
+ display: flex;
+ flex-direction: column;
+ flex-shrink: 0;
+
+ width: 100%;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+
+ background: ${cssVar.colorBgContainer};
+ `,
+ resizeHandle: css`
+ touch-action: none;
+ cursor: row-resize;
+
+ position: absolute;
+ z-index: 1;
+ inset-block-start: -3px;
+ inset-inline: 0;
+
+ height: 6px;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+}));
+
+const PanelHost = memo(() => {
+ const expanded = useDevDockStore((s) => s.expanded);
+ const activePanelId = useDevDockStore((s) => s.activePanelId);
+ const maximized = useDevDockStore((s) => s.maximized);
+ const panelHeight = useDevDockStore((s) => s.panelHeight);
+ const setMaximized = useDevDockStore((s) => s.setMaximized);
+ const setPanelHeight = useDevDockStore((s) => s.setPanelHeight);
+ const togglePanel = useDevDockStore((s) => s.togglePanel);
+ const items = useDevDockItems();
+
+ const [dragHeight, setDragHeight] = useState<number | null>(null);
+ const dragging = dragHeight !== null;
+ const dragOriginRef = useRef<{ height: number; pointerY: number } | null>(null);
+
+ const handleDragStart = useCallback(
+ (e: React.PointerEvent<HTMLDivElement>) => {
+ if (maximized) return;
+ e.preventDefault();
+ dragOriginRef.current = { height: panelHeight, pointerY: e.clientY };
+ setDragHeight(panelHeight);
+ },
+ [maximized, panelHeight],
+ );
+
+ useEffect(() => {
+ if (!dragging) return;
+ const onMove = (e: PointerEvent) => {
+ const origin = dragOriginRef.current;
+ if (!origin) return;
+ const next = origin.height + (origin.pointerY - e.clientY);
+ const max = window.innerHeight - BAR_HEIGHT - 60;
+ setDragHeight(Math.min(Math.max(MIN_PANEL_HEIGHT, next), max));
+ };
+ const onUp = () => {
+ setDragHeight((committed) => {
+ if (committed !== null) setPanelHeight(committed);
+ return null;
+ });
+ dragOriginRef.current = null;
+ };
+ window.addEventListener('pointermove', onMove);
+ window.addEventListener('pointerup', onUp);
+ return () => {
+ window.removeEventListener('pointermove', onMove);
+ window.removeEventListener('pointerup', onUp);
+ };
+ }, [dragging, setPanelHeight]);
+
+ const item = items.find(
+ (candidate): candidate is DevDockPanelItem =>
+ candidate.type === 'panel' && candidate.id === activePanelId,
+ );
+
+ if (!expanded || !item) return null;
+
+ const Content = getItemComponent(item);
+ const Icon = item.icon;
+ const height = maximized ? `calc(100dvh - ${BAR_HEIGHT}px)` : `${dragHeight ?? panelHeight}px`;
+
+ return (
+ <section className={styles.host} style={{ height }}>
+ {!maximized && <div className={styles.resizeHandle} onPointerDown={handleDragStart} />}
+ <Flexbox horizontal align={'center'} className={styles.header} gap={6}>
+ <Icon size={12} />
+ <span>{item.title}</span>
+ <span style={{ flex: 1 }} />
+ <ActionIcon
+ icon={maximized ? Minimize2 : Maximize2}
+ size={'small'}
+ title={maximized ? 'Restore' : 'Maximize'}
+ onClick={() => setMaximized(!maximized)}
+ />
+ <ActionIcon
+ icon={XIcon}
+ size={'small'}
+ title={'Close panel'}
+ onClick={() => togglePanel(item.id)}
+ />
+ </Flexbox>
+ <div className={styles.content}>
+ <PanelErrorBoundary key={item.id}>
+ <Suspense fallback={null}>
+ <Content />
+ </Suspense>
+ </PanelErrorBoundary>
+ </div>
+ </section>
+ );
+});
+
+PanelHost.displayName = 'DevDockPanelHost';
+
+export default PanelHost;
diff --git a/src/features/DevDock/ReactScanController.tsx b/src/features/DevDock/ReactScanController.tsx
new file mode 100644
index 00000000000..7dc0fb85993
--- /dev/null
+++ b/src/features/DevDock/ReactScanController.tsx
@@ -0,0 +1,32 @@
+'use client';
+
+import { memo, useEffect } from 'react';
+
+import { useDevDockStore } from './store';
+
+// REACT_SCAN=true boots scanning from initialize.ts before this mounts, so it
+// must count as touched — otherwise the dock toggle could never turn it off.
+let touched = typeof __REACT_SCAN__ !== 'undefined' && __REACT_SCAN__;
+
+const ReactScanController = memo(() => {
+ const enabled = useDevDockStore((s) => s.reactScan);
+
+ useEffect(() => {
+ if (!enabled && !touched) return;
+ touched = true;
+ let cancelled = false;
+ void import('react-scan').then(({ scan }) => {
+ if (cancelled) return;
+ scan({ enabled, showToolbar: enabled });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [enabled]);
+
+ return null;
+});
+
+ReactScanController.displayName = 'DevDockReactScanController';
+
+export default ReactScanController;
diff --git a/src/features/DevDock/const.ts b/src/features/DevDock/const.ts
new file mode 100644
index 00000000000..66512cff3b1
--- /dev/null
+++ b/src/features/DevDock/const.ts
@@ -0,0 +1,2 @@
+export const BAR_HEIGHT = 28;
+export const DOCK_Z_INDEX = 1100;
diff --git a/src/features/DevDock/index.tsx b/src/features/DevDock/index.tsx
new file mode 100644
index 00000000000..e1bb743ba83
--- /dev/null
+++ b/src/features/DevDock/index.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import { memo } from 'react';
+
+import FlagOverrideHydrator from '@/features/DevFeatureFlagPanel/Hydrator';
+
+import Bar from './Bar';
+import PanelHost from './PanelHost';
+import ReactScanController from './ReactScanController';
+import { registerBuiltinDevDockItems } from './registerBuiltinItems';
+
+registerBuiltinDevDockItems();
+
+const DevDock = memo(() => {
+ if (!__DEV__) return null;
+ return (
+ <>
+ <FlagOverrideHydrator />
+ <ReactScanController />
+ <PanelHost />
+ <Bar />
+ </>
+ );
+});
+
+DevDock.displayName = 'DevDock';
+
+export default DevDock;
diff --git a/src/features/DevDock/registerBuiltinItems.ts b/src/features/DevDock/registerBuiltinItems.ts
new file mode 100644
index 00000000000..a63be50cbf6
--- /dev/null
+++ b/src/features/DevDock/registerBuiltinItems.ts
@@ -0,0 +1,93 @@
+import { Bot, Flag, LayoutGrid } from 'lucide-react';
+
+import { isDesktop } from '@/const/version';
+import FlagOverrideBadge from '@/features/DevFeatureFlagPanel/Badge';
+
+import { type DevDockItem, registerDevDockItems } from './registry';
+
+export const registerBuiltinDevDockItems = () => {
+ const items: DevDockItem[] = [
+ {
+ id: 'route-path',
+ load: () => import('./widgets/RoutePathWidget'),
+ placement: 'left',
+ type: 'widget',
+ },
+ {
+ icon: Bot,
+ id: 'agent-mock',
+ load: () => import('@/features/AgentMockDevtools'),
+ title: 'Agent Mock',
+ type: 'panel',
+ },
+ {
+ badge: FlagOverrideBadge,
+ icon: Flag,
+ id: 'feature-flags',
+ load: () => import('@/features/DevFeatureFlagPanel'),
+ title: 'Feature Flags',
+ type: 'panel',
+ },
+ {
+ icon: LayoutGrid,
+ id: 'render-gallery',
+ load: () => import('@/features/DevPanel/RenderGallery'),
+ title: 'Render Gallery',
+ type: 'panel',
+ },
+ {
+ id: 'scroll-debug',
+ load: () => import('./widgets/ScrollDebugWidget'),
+ placement: 'right',
+ type: 'widget',
+ },
+ {
+ id: 'react-scan',
+ load: () => import('./widgets/ReactScanWidget'),
+ placement: 'right',
+ type: 'widget',
+ },
+ {
+ id: 'reload',
+ load: () => import('./widgets/ReloadWidget'),
+ placement: 'right',
+ type: 'widget',
+ },
+ {
+ id: 'fps',
+ load: () => import('./widgets/FpsWidget'),
+ placement: 'right',
+ type: 'widget',
+ },
+ isDesktop
+ ? {
+ id: 'cpu-usage',
+ load: () => import('./widgets/CpuUsageWidget'),
+ placement: 'right',
+ type: 'widget',
+ }
+ : {
+ id: 'cpu-pressure',
+ load: () => import('./widgets/CpuPressureWidget'),
+ placement: 'right',
+ type: 'widget',
+ },
+ {
+ id: 'memory',
+ load: () => import('./widgets/MemoryWidget'),
+ placement: 'right',
+ type: 'widget',
+ },
+ ];
+
+ if (isDesktop) {
+ items.push({
+ id: 'open-devtools',
+ load: () => import('./widgets/OpenDevtoolsWidget'),
+ placement: 'right',
+ type: 'widget',
+ });
+ }
+
+ registerDevDockItems(items);
+};
diff --git a/src/features/DevDock/registry.test.ts b/src/features/DevDock/registry.test.ts
new file mode 100644
index 00000000000..77726134e8e
--- /dev/null
+++ b/src/features/DevDock/registry.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ type DevDockItem,
+ getDevDockItemsSnapshot,
+ getItemComponent,
+ registerDevDockItems,
+} from './registry';
+
+const panelItem = (id: string): DevDockItem => ({
+ icon: (() => null) as never,
+ id,
+ load: async () => ({ default: () => null }),
+ title: id,
+ type: 'panel',
+});
+
+describe('DevDock registry', () => {
+ it('registers items and exposes them in the snapshot', () => {
+ registerDevDockItems([panelItem('a'), panelItem('b')]);
+
+ const ids = getDevDockItemsSnapshot().map((item) => item.id);
+ expect(ids).toEqual(['a', 'b']);
+ });
+
+ it('ignores duplicate ids on re-registration', () => {
+ registerDevDockItems([panelItem('a'), panelItem('c')]);
+
+ const ids = getDevDockItemsSnapshot().map((item) => item.id);
+ expect(ids).toEqual(['a', 'b', 'c']);
+ });
+
+ it('keeps the snapshot reference stable when nothing changes', () => {
+ const before = getDevDockItemsSnapshot();
+ registerDevDockItems([panelItem('a')]);
+ expect(getDevDockItemsSnapshot()).toBe(before);
+ });
+
+ it('caches lazy components per item id', () => {
+ const item = panelItem('a');
+ expect(getItemComponent(item)).toBe(getItemComponent(item));
+ });
+});
diff --git a/src/features/DevDock/registry.ts b/src/features/DevDock/registry.ts
new file mode 100644
index 00000000000..7bf5b87e94b
--- /dev/null
+++ b/src/features/DevDock/registry.ts
@@ -0,0 +1,59 @@
+import type { LucideIcon } from 'lucide-react';
+import { type ComponentType, lazy, useSyncExternalStore } from 'react';
+
+export interface DevDockPanelItem {
+ badge?: ComponentType;
+ icon: LucideIcon;
+ id: string;
+ load: () => Promise<{ default: ComponentType }>;
+ title: string;
+ type: 'panel';
+}
+
+export interface DevDockWidgetItem {
+ id: string;
+ load: () => Promise<{ default: ComponentType }>;
+ placement: 'left' | 'right';
+ type: 'widget';
+}
+
+export type DevDockItem = DevDockPanelItem | DevDockWidgetItem;
+
+const items: DevDockItem[] = [];
+let snapshot: DevDockItem[] = [];
+const listeners = new Set<() => void>();
+
+export const registerDevDockItems = (next: DevDockItem[]) => {
+ let changed = false;
+ for (const item of next) {
+ if (items.some((existing) => existing.id === item.id)) continue;
+ items.push(item);
+ changed = true;
+ }
+ if (!changed) return;
+ snapshot = [...items];
+ for (const listener of listeners) listener();
+};
+
+const subscribe = (listener: () => void) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+};
+
+export const getDevDockItemsSnapshot = (): DevDockItem[] => snapshot;
+
+export const useDevDockItems = (): DevDockItem[] =>
+ useSyncExternalStore(subscribe, getDevDockItemsSnapshot);
+
+const componentCache = new Map<string, ComponentType>();
+
+export const getItemComponent = (item: DevDockItem): ComponentType => {
+ let component = componentCache.get(item.id);
+ if (!component) {
+ component = lazy(item.load);
+ componentCache.set(item.id, component);
+ }
+ return component;
+};
diff --git a/src/features/DevDock/store.test.ts b/src/features/DevDock/store.test.ts
new file mode 100644
index 00000000000..98529f455da
--- /dev/null
+++ b/src/features/DevDock/store.test.ts
@@ -0,0 +1,51 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { MIN_PANEL_HEIGHT, useDevDockStore } from './store';
+
+const STORAGE_KEY = 'LOBE_DEV_DOCK_UI';
+
+const readPersisted = () => JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}');
+
+describe('DevDock store', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ useDevDockStore.setState({
+ activePanelId: null,
+ expanded: true,
+ maximized: false,
+ panelHeight: 360,
+ reactScan: false,
+ scrollDebug: false,
+ });
+ });
+
+ it('toggles a panel open and closed', () => {
+ useDevDockStore.getState().togglePanel('feature-flags');
+ expect(useDevDockStore.getState().activePanelId).toBe('feature-flags');
+
+ useDevDockStore.getState().togglePanel('feature-flags');
+ expect(useDevDockStore.getState().activePanelId).toBeNull();
+ });
+
+ it('switches between panels directly', () => {
+ useDevDockStore.getState().togglePanel('feature-flags');
+ useDevDockStore.getState().togglePanel('agent-mock');
+ expect(useDevDockStore.getState().activePanelId).toBe('agent-mock');
+ });
+
+ it('clamps panel height to the minimum', () => {
+ useDevDockStore.getState().setPanelHeight(10);
+ expect(useDevDockStore.getState().panelHeight).toBe(MIN_PANEL_HEIGHT);
+ });
+
+ it('persists UI state to localStorage', () => {
+ useDevDockStore.getState().setExpanded(false);
+ useDevDockStore.getState().setScrollDebug(true);
+ useDevDockStore.getState().setReactScan(true);
+
+ expect(readPersisted()).toMatchObject({ expanded: false, reactScan: true, scrollDebug: true });
+ });
+});
diff --git a/src/features/DevDock/store.ts b/src/features/DevDock/store.ts
new file mode 100644
index 00000000000..1f85b6903c5
--- /dev/null
+++ b/src/features/DevDock/store.ts
@@ -0,0 +1,68 @@
+import { create } from 'zustand';
+
+const STORAGE_KEY = 'LOBE_DEV_DOCK_UI';
+
+export const MIN_PANEL_HEIGHT = 180;
+
+interface DevDockUIState {
+ activePanelId: string | null;
+ expanded: boolean;
+ maximized: boolean;
+ panelHeight: number;
+ reactScan: boolean;
+ scrollDebug: boolean;
+}
+
+const bootReactScan = typeof __REACT_SCAN__ !== 'undefined' && __REACT_SCAN__;
+
+const DEFAULT_UI: DevDockUIState = {
+ activePanelId: null,
+ expanded: true,
+ maximized: false,
+ panelHeight: 360,
+ reactScan: bootReactScan,
+ scrollDebug: false,
+};
+
+const readPersisted = (): DevDockUIState => {
+ if (typeof localStorage === 'undefined') return DEFAULT_UI;
+ try {
+ const raw = localStorage.getItem(STORAGE_KEY);
+ if (!raw) return DEFAULT_UI;
+ return { ...DEFAULT_UI, ...(JSON.parse(raw) as Partial<DevDockUIState>) };
+ } catch {
+ return DEFAULT_UI;
+ }
+};
+
+export interface DevDockStore extends DevDockUIState {
+ setExpanded: (expanded: boolean) => void;
+ setMaximized: (maximized: boolean) => void;
+ setPanelHeight: (panelHeight: number) => void;
+ setReactScan: (reactScan: boolean) => void;
+ setScrollDebug: (scrollDebug: boolean) => void;
+ togglePanel: (id: string) => void;
+}
+
+export const useDevDockStore = create<DevDockStore>((set, get) => {
+ const update = (patch: Partial<DevDockUIState>) => {
+ set(patch);
+ if (typeof localStorage === 'undefined') return;
+ const { activePanelId, expanded, maximized, panelHeight, reactScan, scrollDebug } = get();
+ localStorage.setItem(
+ STORAGE_KEY,
+ JSON.stringify({ activePanelId, expanded, maximized, panelHeight, reactScan, scrollDebug }),
+ );
+ };
+
+ return {
+ ...readPersisted(),
+ setExpanded: (expanded) => update({ expanded }),
+ setMaximized: (maximized) => update({ maximized }),
+ setPanelHeight: (panelHeight) =>
+ update({ panelHeight: Math.max(MIN_PANEL_HEIGHT, panelHeight) }),
+ setReactScan: (reactScan) => update({ reactScan }),
+ setScrollDebug: (scrollDebug) => update({ scrollDebug }),
+ togglePanel: (id) => update({ activePanelId: get().activePanelId === id ? null : id }),
+ };
+});
diff --git a/src/features/DevDock/widgets/BarButton.tsx b/src/features/DevDock/widgets/BarButton.tsx
new file mode 100644
index 00000000000..787b087b89c
--- /dev/null
+++ b/src/features/DevDock/widgets/BarButton.tsx
@@ -0,0 +1,47 @@
+'use client';
+
+import { createStaticStyles, cssVar } from 'antd-style';
+import type { LucideIcon } from 'lucide-react';
+import { memo } from 'react';
+
+const styles = createStaticStyles(({ css }) => ({
+ button: css`
+ cursor: pointer;
+
+ display: inline-flex;
+ gap: 4px;
+ align-items: center;
+
+ height: 20px;
+ padding-inline: 6px;
+ border: none;
+ border-radius: 4px;
+
+ font-size: 11px;
+ color: ${cssVar.colorTextSecondary};
+
+ background: transparent;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+}));
+
+interface BarButtonProps {
+ icon: LucideIcon;
+ label: string;
+ onClick: () => void;
+}
+
+const BarButton = memo<BarButtonProps>(({ icon: Icon, label, onClick }) => (
+ <button className={styles.button} type={'button'} onClick={onClick}>
+ <Icon size={11} />
+ <span>{label}</span>
+ </button>
+));
+
+BarButton.displayName = 'DevDockBarButton';
+
+export default BarButton;
diff --git a/src/features/DevDock/widgets/CpuPressureWidget.tsx b/src/features/DevDock/widgets/CpuPressureWidget.tsx
new file mode 100644
index 00000000000..e488f2342c9
--- /dev/null
+++ b/src/features/DevDock/widgets/CpuPressureWidget.tsx
@@ -0,0 +1,76 @@
+'use client';
+
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { memo, useEffect, useState } from 'react';
+
+type PressureState = 'critical' | 'fair' | 'nominal' | 'serious';
+
+interface PressureRecord {
+ source: string;
+ state: PressureState;
+ time: number;
+}
+
+interface PressureObserverLike {
+ disconnect: () => void;
+ observe: (source: string, options?: { sampleInterval?: number }) => Promise<void>;
+}
+
+type PressureObserverConstructor = new (
+ callback: (records: PressureRecord[]) => void,
+) => PressureObserverLike;
+
+const getPressureObserverCtor = (): PressureObserverConstructor | undefined =>
+ (globalThis as { PressureObserver?: PressureObserverConstructor }).PressureObserver;
+
+const styles = createStaticStyles(({ css }) => ({
+ critical: css`
+ color: ${cssVar.colorError};
+ `,
+ serious: css`
+ color: ${cssVar.colorWarning};
+ `,
+ text: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 11px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
+const STATE_CLASS: Partial<Record<PressureState, string>> = {
+ critical: styles.critical,
+ serious: styles.serious,
+};
+
+const CpuPressureWidget = memo(() => {
+ const [state, setState] = useState<PressureState | null>(null);
+
+ useEffect(() => {
+ const PressureObserverCtor = getPressureObserverCtor();
+ if (!PressureObserverCtor) return;
+
+ let disposed = false;
+ const observer = new PressureObserverCtor((records) => {
+ const latest = records.at(-1);
+ if (latest && !disposed) setState(latest.state);
+ });
+ void observer.observe('cpu', { sampleInterval: 2000 }).catch(() => {});
+
+ return () => {
+ disposed = true;
+ observer.disconnect();
+ };
+ }, []);
+
+ if (!state) return null;
+
+ return (
+ <span className={cx(styles.text, STATE_CLASS[state])} title={'Compute Pressure (CPU)'}>
+ CPU {state}
+ </span>
+ );
+});
+
+CpuPressureWidget.displayName = 'DevDockCpuPressureWidget';
+
+export default CpuPressureWidget;
diff --git a/src/features/DevDock/widgets/CpuUsageWidget.tsx b/src/features/DevDock/widgets/CpuUsageWidget.tsx
new file mode 100644
index 00000000000..5e7b4cca4ae
--- /dev/null
+++ b/src/features/DevDock/widgets/CpuUsageWidget.tsx
@@ -0,0 +1,71 @@
+'use client';
+
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { memo, useEffect, useState } from 'react';
+
+import { electronDevtoolsService } from '@/services/electron/devtools';
+
+const styles = createStaticStyles(({ css }) => ({
+ high: css`
+ color: ${cssVar.colorError};
+ `,
+ mid: css`
+ color: ${cssVar.colorWarning};
+ `,
+ text: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 11px;
+ font-feature-settings: 'tnum';
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
+const CpuUsageWidget = memo(() => {
+ const [percent, setPercent] = useState<number | null>(null);
+
+ useEffect(() => {
+ let disposed = false;
+ // Electron reports usage since the previous getAppMetrics call, so the
+ // first sample is meaningless — prime once and only render from the second.
+ let primed = false;
+
+ const tick = async () => {
+ try {
+ const usage = await electronDevtoolsService.getAppCpuUsage();
+ if (disposed) return;
+ if (!primed) {
+ primed = true;
+ return;
+ }
+ setPercent(usage.percent);
+ } catch {
+ /* ipc unavailable — keep the widget hidden */
+ }
+ };
+
+ void tick();
+ const timer = setInterval(tick, 2000);
+ return () => {
+ disposed = true;
+ clearInterval(timer);
+ };
+ }, []);
+
+ if (percent === null) return null;
+
+ return (
+ <span
+ title={'App CPU usage (sum across processes, 100% = one core)'}
+ className={cx(
+ styles.text,
+ percent >= 200 ? styles.high : percent >= 100 ? styles.mid : undefined,
+ )}
+ >
+ CPU {percent.toFixed(1)}%
+ </span>
+ );
+});
+
+CpuUsageWidget.displayName = 'DevDockCpuUsageWidget';
+
+export default CpuUsageWidget;
diff --git a/src/features/DevDock/widgets/FpsWidget.tsx b/src/features/DevDock/widgets/FpsWidget.tsx
new file mode 100644
index 00000000000..2b0c54689a8
--- /dev/null
+++ b/src/features/DevDock/widgets/FpsWidget.tsx
@@ -0,0 +1,58 @@
+'use client';
+
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { memo, useEffect, useState } from 'react';
+
+const styles = createStaticStyles(({ css }) => ({
+ low: css`
+ color: ${cssVar.colorError};
+ `,
+ mid: css`
+ color: ${cssVar.colorWarning};
+ `,
+ text: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 11px;
+ font-feature-settings: 'tnum';
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
+const FpsWidget = memo(() => {
+ const [fps, setFps] = useState<number | null>(null);
+
+ useEffect(() => {
+ let raf = 0;
+ let frames = 0;
+ let windowStart = performance.now();
+
+ const loop = (now: number) => {
+ frames += 1;
+ const elapsed = now - windowStart;
+ if (elapsed >= 500) {
+ setFps(Math.round((frames * 1000) / elapsed));
+ frames = 0;
+ windowStart = now;
+ }
+ raf = requestAnimationFrame(loop);
+ };
+
+ raf = requestAnimationFrame(loop);
+ return () => cancelAnimationFrame(raf);
+ }, []);
+
+ if (fps === null) return null;
+
+ return (
+ <span
+ className={cx(styles.text, fps < 30 ? styles.low : fps < 50 ? styles.mid : undefined)}
+ title={'Frames per second'}
+ >
+ {fps} FPS
+ </span>
+ );
+});
+
+FpsWidget.displayName = 'DevDockFpsWidget';
+
+export default FpsWidget;
diff --git a/src/features/DevDock/widgets/MemoryWidget.tsx b/src/features/DevDock/widgets/MemoryWidget.tsx
new file mode 100644
index 00000000000..b487178314a
--- /dev/null
+++ b/src/features/DevDock/widgets/MemoryWidget.tsx
@@ -0,0 +1,53 @@
+'use client';
+
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo, useEffect, useState } from 'react';
+
+const styles = createStaticStyles(({ css }) => ({
+ text: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 11px;
+ font-feature-settings: 'tnum';
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
+interface HeapSample {
+ limit: number;
+ used: number;
+}
+
+const readHeap = (): HeapSample | null => {
+ const memory = (
+ performance as Performance & {
+ memory?: { jsHeapSizeLimit: number; usedJSHeapSize: number };
+ }
+ ).memory;
+ if (!memory) return null;
+ return { limit: memory.jsHeapSizeLimit, used: memory.usedJSHeapSize };
+};
+
+const MemoryWidget = memo(() => {
+ const [heap, setHeap] = useState<HeapSample | null>(() => readHeap());
+
+ useEffect(() => {
+ if (!readHeap()) return;
+ const timer = setInterval(() => setHeap(readHeap()), 2000);
+ return () => clearInterval(timer);
+ }, []);
+
+ if (!heap) return null;
+
+ const usedMB = Math.round(heap.used / 1_048_576);
+ const percent = ((heap.used / heap.limit) * 100).toFixed(1);
+
+ return (
+ <span className={styles.text} title={'JS heap used / limit'}>
+ {usedMB} MB · {percent}%
+ </span>
+ );
+});
+
+MemoryWidget.displayName = 'DevDockMemoryWidget';
+
+export default MemoryWidget;
diff --git a/src/features/DevDock/widgets/OpenDevtoolsWidget.tsx b/src/features/DevDock/widgets/OpenDevtoolsWidget.tsx
new file mode 100644
index 00000000000..eb61efc5dac
--- /dev/null
+++ b/src/features/DevDock/widgets/OpenDevtoolsWidget.tsx
@@ -0,0 +1,20 @@
+'use client';
+
+import { Terminal } from 'lucide-react';
+import { memo } from 'react';
+
+import { electronDevtoolsService } from '@/services/electron/devtools';
+
+import BarButton from './BarButton';
+
+const OpenDevtoolsWidget = memo(() => (
+ <BarButton
+ icon={Terminal}
+ label={'DevTools'}
+ onClick={() => electronDevtoolsService.openDevtools()}
+ />
+));
+
+OpenDevtoolsWidget.displayName = 'DevDockOpenDevtoolsWidget';
+
+export default OpenDevtoolsWidget;
diff --git a/src/features/DevDock/widgets/ReactScanWidget.tsx b/src/features/DevDock/widgets/ReactScanWidget.tsx
new file mode 100644
index 00000000000..721ef85abc2
--- /dev/null
+++ b/src/features/DevDock/widgets/ReactScanWidget.tsx
@@ -0,0 +1,21 @@
+'use client';
+
+import { Switch } from '@lobehub/ui/base-ui';
+import { memo } from 'react';
+
+import { useDevDockStore } from '../store';
+
+const ReactScanWidget = memo(() => {
+ const reactScan = useDevDockStore((s) => s.reactScan);
+ const setReactScan = useDevDockStore((s) => s.setReactScan);
+ return (
+ <label style={{ alignItems: 'center', cursor: 'pointer', display: 'inline-flex', gap: 5 }}>
+ <Switch checked={reactScan} size={'small'} onChange={setReactScan} />
+ <span>React Scan</span>
+ </label>
+ );
+});
+
+ReactScanWidget.displayName = 'DevDockReactScanWidget';
+
+export default ReactScanWidget;
diff --git a/src/features/DevDock/widgets/ReloadWidget.tsx b/src/features/DevDock/widgets/ReloadWidget.tsx
new file mode 100644
index 00000000000..5b041462cc4
--- /dev/null
+++ b/src/features/DevDock/widgets/ReloadWidget.tsx
@@ -0,0 +1,14 @@
+'use client';
+
+import { RotateCw } from 'lucide-react';
+import { memo } from 'react';
+
+import BarButton from './BarButton';
+
+const ReloadWidget = memo(() => (
+ <BarButton icon={RotateCw} label={'Reload'} onClick={() => window.location.reload()} />
+));
+
+ReloadWidget.displayName = 'DevDockReloadWidget';
+
+export default ReloadWidget;
diff --git a/src/features/DevDock/widgets/RoutePathWidget.tsx b/src/features/DevDock/widgets/RoutePathWidget.tsx
new file mode 100644
index 00000000000..e35ff96bdd4
--- /dev/null
+++ b/src/features/DevDock/widgets/RoutePathWidget.tsx
@@ -0,0 +1,32 @@
+'use client';
+
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo } from 'react';
+import { useLocation } from 'react-router';
+
+const styles = createStaticStyles(({ css }) => ({
+ path: css`
+ overflow: hidden;
+
+ max-width: 320px;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 11px;
+ color: ${cssVar.colorTextTertiary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+}));
+
+const RoutePathWidget = memo(() => {
+ const { pathname } = useLocation();
+ return (
+ <span className={styles.path} title={pathname}>
+ {pathname}
+ </span>
+ );
+});
+
+RoutePathWidget.displayName = 'DevDockRoutePathWidget';
+
+export default RoutePathWidget;
diff --git a/src/features/DevDock/widgets/ScrollDebugWidget.tsx b/src/features/DevDock/widgets/ScrollDebugWidget.tsx
new file mode 100644
index 00000000000..c5ed82cef09
--- /dev/null
+++ b/src/features/DevDock/widgets/ScrollDebugWidget.tsx
@@ -0,0 +1,21 @@
+'use client';
+
+import { Switch } from '@lobehub/ui/base-ui';
+import { memo } from 'react';
+
+import { useDevDockStore } from '../store';
+
+const ScrollDebugWidget = memo(() => {
+ const scrollDebug = useDevDockStore((s) => s.scrollDebug);
+ const setScrollDebug = useDevDockStore((s) => s.setScrollDebug);
+ return (
+ <label style={{ alignItems: 'center', cursor: 'pointer', display: 'inline-flex', gap: 5 }}>
+ <Switch checked={scrollDebug} size={'small'} onChange={setScrollDebug} />
+ <span>Scroll debug</span>
+ </label>
+ );
+});
+
+ScrollDebugWidget.displayName = 'DevDockScrollDebugWidget';
+
+export default ScrollDebugWidget;
diff --git a/src/features/DevFeatureFlagPanel/Badge.tsx b/src/features/DevFeatureFlagPanel/Badge.tsx
new file mode 100644
index 00000000000..38b731f56fb
--- /dev/null
+++ b/src/features/DevFeatureFlagPanel/Badge.tsx
@@ -0,0 +1,36 @@
+'use client';
+
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo } from 'react';
+
+import { useServerConfigStore } from '@/store/serverConfig';
+
+const styles = createStaticStyles(({ css }) => ({
+ badge: css`
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+
+ min-width: 14px;
+ height: 14px;
+ padding-inline: 4px;
+ border-radius: 7px;
+
+ font-size: 10px;
+ font-weight: 600;
+ line-height: 1;
+ color: ${cssVar.colorBgContainer};
+
+ background: ${cssVar.colorWarning};
+ `,
+}));
+
+const FlagOverrideBadge = memo(() => {
+ const overrideCount = useServerConfigStore((s) => Object.keys(s._featureFlagOverrides).length);
+ if (overrideCount === 0) return null;
+ return <span className={styles.badge}>{overrideCount}</span>;
+});
+
+FlagOverrideBadge.displayName = 'DevFeatureFlagPanel/Badge';
+
+export default FlagOverrideBadge;
diff --git a/src/features/DevFeatureFlagPanel/Fab.tsx b/src/features/DevFeatureFlagPanel/Fab.tsx
deleted file mode 100644
index 9b316387ef9..00000000000
--- a/src/features/DevFeatureFlagPanel/Fab.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-'use client';
-
-import { Tooltip } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from 'antd-style';
-import { FlagIcon } from 'lucide-react';
-import { memo } from 'react';
-
-import { useServerConfigStore } from '@/store/serverConfig';
-
-const styles = createStaticStyles(({ css }) => ({
- badge: css`
- pointer-events: none;
-
- position: absolute;
- inset-block-start: -4px;
- inset-inline-end: -4px;
-
- min-width: 16px;
- height: 16px;
- padding-inline: 4px;
- border: 1.5px solid ${cssVar.colorBgContainer};
- border-radius: 8px;
-
- font-size: 10px;
- font-weight: 600;
- line-height: 13px;
- color: ${cssVar.colorBgContainer};
- text-align: center;
-
- background: ${cssVar.colorWarning};
- `,
- fab: css`
- cursor: pointer;
- user-select: none;
-
- position: fixed;
- z-index: 1100;
- inset-block-end: 64px;
- inset-inline-end: 16px;
-
- display: flex;
- align-items: center;
- justify-content: center;
-
- width: 36px;
- height: 36px;
- border: 1px solid transparent;
- border-radius: 50%;
-
- color: ${cssVar.colorBgContainer};
-
- background: ${cssVar.colorText};
- box-shadow: 0 2px 8px rgb(0 0 0 / 12%);
-
- transition:
- transform 160ms ease,
- background 160ms ease,
- color 160ms ease,
- border-color 160ms ease;
-
- &:hover {
- transform: scale(1.04);
- }
- `,
- fabActive: css`
- border-color: ${cssVar.colorBorder};
- color: ${cssVar.colorText};
- background: ${cssVar.colorFillSecondary};
- `,
-}));
-
-interface FabProps {
- active: boolean;
- onToggle: () => void;
-}
-
-const Fab = memo<FabProps>(({ active, onToggle }) => {
- const overrideCount = useServerConfigStore((s) => Object.keys(s._featureFlagOverrides).length);
-
- return (
- <Tooltip placement={'left'} title={'Feature Flag Overrides (dev only)'}>
- <div
- className={`${styles.fab} ${active ? styles.fabActive : ''}`}
- role={'button'}
- tabIndex={0}
- onClick={onToggle}
- onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- onToggle();
- }
- }}
- >
- <FlagIcon size={18} />
- {overrideCount > 0 && <span className={styles.badge}>{overrideCount}</span>}
- </div>
- </Tooltip>
- );
-});
-
-Fab.displayName = 'DevFeatureFlagPanel/Fab';
-
-export default Fab;
diff --git a/src/features/DevFeatureFlagPanel/Panel.tsx b/src/features/DevFeatureFlagPanel/Panel.tsx
index a1ce94b3353..d009f3e9850 100644
--- a/src/features/DevFeatureFlagPanel/Panel.tsx
+++ b/src/features/DevFeatureFlagPanel/Panel.tsx
@@ -1,10 +1,10 @@
'use client';
-import { ActionIcon, Flexbox, Input, Text } from '@lobehub/ui';
+import { Flexbox, Input, Text } from '@lobehub/ui';
import { Button, Switch } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { snakeCase } from 'es-toolkit/compat';
-import { ListRestartIcon, XIcon } from 'lucide-react';
+import { ListRestartIcon } from 'lucide-react';
import { memo, useMemo, useState } from 'react';
import { useServerConfigStore } from '@/store/serverConfig';
@@ -16,25 +16,19 @@ const styles = createStaticStyles(({ css }) => ({
body: css`
overflow: auto;
flex: 1;
+
+ min-height: 0;
padding-block: 4px;
padding-inline: 4px;
`,
container: css`
- position: fixed;
- z-index: 1099;
- inset-block-end: 112px;
- inset-inline-end: 16px;
-
display: flex;
flex-direction: column;
- width: 380px;
- height: min(70vh, 600px);
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 12px;
-
- background: ${cssVar.colorBgElevated};
- box-shadow: 0 8px 24px rgb(0 0 0 / 12%);
+ width: 100%;
+ max-width: 720px;
+ height: 100%;
+ margin-inline: auto;
`,
empty: css`
padding-block: 32px;
@@ -52,20 +46,10 @@ const styles = createStaticStyles(({ css }) => ({
padding-inline: 12px;
border-block-start: 1px solid ${cssVar.colorBorderSecondary};
`,
- header: css`
- display: flex;
- gap: 8px;
- align-items: center;
- justify-content: space-between;
-
- padding-block: 10px;
- padding-inline: 12px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
- `,
toolbar: css`
display: flex;
- flex-direction: column;
- gap: 8px;
+ gap: 12px;
+ align-items: center;
padding-block: 8px;
padding-inline: 12px;
@@ -73,11 +57,7 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-interface PanelProps {
- onClose: () => void;
-}
-
-const Panel = memo<PanelProps>(({ onClose }) => {
+const Panel = memo(() => {
const originalFlags = useServerConfigStore((s) => s._originalFeatureFlags);
const overrideCount = useServerConfigStore((s) => Object.keys(s._featureFlagOverrides).length);
const overrides = useServerConfigStore((s) => s._featureFlagOverrides);
@@ -100,33 +80,23 @@ const Panel = memo<PanelProps>(({ onClose }) => {
});
}, [flagKeys, overrides, overriddenOnly, search]);
- if (!originalFlags) return null;
+ if (!originalFlags)
+ return <div className={styles.empty}>Server feature flags are not loaded yet.</div>;
return (
<div className={styles.container}>
- <div className={styles.header}>
- <Flexbox gap={2}>
- <Text strong style={{ fontSize: 13 }}>
- Feature Flag Overrides
- </Text>
- <Text style={{ fontSize: 11 }} type={'secondary'}>
- dev only · client-side · localStorage persisted
- </Text>
- </Flexbox>
- <ActionIcon icon={XIcon} size={'small'} onClick={onClose} />
- </div>
-
<div className={styles.toolbar}>
<Input
allowClear
placeholder={'Search flag name…'}
size={'small'}
+ style={{ flex: 1 }}
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
<Flexbox horizontal align={'center'} gap={6}>
<Switch checked={overriddenOnly} size={'small'} onChange={setOverriddenOnly} />
- <Text style={{ fontSize: 12 }} type={'secondary'}>
+ <Text style={{ fontSize: 12, whiteSpace: 'nowrap' }} type={'secondary'}>
overridden only
</Text>
</Flexbox>
@@ -142,7 +112,8 @@ const Panel = memo<PanelProps>(({ onClose }) => {
<div className={styles.footer}>
<Text style={{ fontSize: 11 }} type={'secondary'}>
- {overrideCount} active override{overrideCount === 1 ? '' : 's'}
+ {overrideCount} active override{overrideCount === 1 ? '' : 's'} · client-side ·
+ localStorage persisted
</Text>
<Button
disabled={overrideCount === 0}
diff --git a/src/features/DevFeatureFlagPanel/index.tsx b/src/features/DevFeatureFlagPanel/index.tsx
index b016f7e7091..be4aac3ceb7 100644
--- a/src/features/DevFeatureFlagPanel/index.tsx
+++ b/src/features/DevFeatureFlagPanel/index.tsx
@@ -1,61 +1,3 @@
'use client';
-import { lazy, memo, Suspense, useEffect, useState } from 'react';
-
-import { useServerConfigStore } from '@/store/serverConfig';
-
-import Fab from './Fab';
-import Hydrator from './Hydrator';
-
-const Panel = lazy(() => import('./Panel'));
-
-const isDevEnv = process.env.NODE_ENV === 'development';
-const STORAGE_KEY = 'LOBE_DEV_FEATURE_FLAG_PANEL_ENABLED';
-
-const useDevPanelEnabled = (): boolean => {
- const [enabled, setEnabled] = useState(false);
-
- useEffect(() => {
- if (!isDevEnv) return;
- setEnabled(window.localStorage.getItem(STORAGE_KEY) === '1');
-
- const onStorage = (e: StorageEvent) => {
- if (e.key === STORAGE_KEY) setEnabled(e.newValue === '1');
- };
- window.addEventListener('storage', onStorage);
-
- if (!window.localStorage.getItem(STORAGE_KEY)) {
- console.info(
- `[DevFeatureFlagPanel] Dev tool available. Enable with: localStorage.${STORAGE_KEY} = "1"`,
- );
- }
-
- return () => window.removeEventListener('storage', onStorage);
- }, []);
-
- return enabled;
-};
-
-const DevFeatureFlagPanel = memo(() => {
- const enabled = useDevPanelEnabled();
- const [open, setOpen] = useState(false);
- const originalFlags = useServerConfigStore((s) => s._originalFeatureFlags);
-
- if (!isDevEnv || !enabled) return null;
-
- return (
- <>
- <Hydrator />
- {originalFlags && <Fab active={open} onToggle={() => setOpen((v) => !v)} />}
- {open && (
- <Suspense fallback={null}>
- <Panel onClose={() => setOpen(false)} />
- </Suspense>
- )}
- </>
- );
-});
-
-DevFeatureFlagPanel.displayName = 'DevFeatureFlagPanel';
-
-export default DevFeatureFlagPanel;
+export { default } from './Panel';
diff --git a/src/features/DevPanel/RenderGallery/IndexPage.tsx b/src/features/DevPanel/RenderGallery/IndexPage.tsx
deleted file mode 100644
index 56977b49c71..00000000000
--- a/src/features/DevPanel/RenderGallery/IndexPage.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-'use client';
-
-import { Flexbox } from '@lobehub/ui';
-import { createStaticStyles } from 'antd-style';
-import { Navigate } from 'react-router';
-
-import { toToolsetPath, useDevtoolsEntries } from './useDevtoolsEntries';
-
-const styles = createStaticStyles(({ css, cssVar }) => ({
- empty: css`
- flex: 1;
- align-items: center;
- justify-content: center;
-
- font-size: 14px;
- color: ${cssVar.colorTextTertiary};
- `,
-}));
-
-const DevtoolsIndex = () => {
- const { defaultToolset } = useDevtoolsEntries();
-
- if (defaultToolset) {
- return <Navigate replace to={toToolsetPath(defaultToolset.identifier)} />;
- }
-
- return <Flexbox className={styles.empty}>No builtin tool renders registered.</Flexbox>;
-};
-
-export default DevtoolsIndex;
diff --git a/src/features/DevPanel/RenderGallery/ToolPage.tsx b/src/features/DevPanel/RenderGallery/ToolPage.tsx
index 3d66b594700..8235d3dc829 100644
--- a/src/features/DevPanel/RenderGallery/ToolPage.tsx
+++ b/src/features/DevPanel/RenderGallery/ToolPage.tsx
@@ -4,13 +4,12 @@ import { Flexbox, Tag, Text } from '@lobehub/ui';
import { Tabs } from '@lobehub/ui/base-ui';
import { createStaticStyles } from 'antd-style';
import { useEffect, useRef, useState } from 'react';
-import { useParams } from 'react-router';
import ApiList from './ApiList';
import { LIFECYCLE_MODE_LABEL, LIFECYCLE_MODES, type LifecycleMode } from './lifecycleMode';
import MessageList from './MessageList';
import ToolPreview from './ToolPreview';
-import { toApiAnchor, useDevtoolsEntries } from './useDevtoolsEntries';
+import { toApiAnchor, type ToolsetEntry } from './useDevtoolsEntries';
const MODE_STORAGE_KEY = 'devtools-render-gallery:lifecycle-mode';
const VIEW_STORAGE_KEY = 'devtools-render-gallery:view';
@@ -73,11 +72,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
-const DevtoolsToolPage = () => {
- const { toolsetMap } = useDevtoolsEntries();
- const { identifier } = useParams<{ identifier: string }>();
- const toolset = identifier ? toolsetMap.get(identifier) : undefined;
+interface DevtoolsToolPageProps {
+ toolset: ToolsetEntry;
+}
+const DevtoolsToolPage = ({ toolset }: DevtoolsToolPageProps) => {
const [mode, setMode] = useState<LifecycleMode>('success');
const [view, setView] = useState<GalleryView>('api');
const [activeApi, setActiveApi] = useState<string>();
@@ -110,7 +109,7 @@ const DevtoolsToolPage = () => {
// card sits above it, so both ends are pinned explicitly.
useEffect(() => {
const root = scrollRef.current;
- if (!root || !toolset || view !== 'api') return;
+ if (!root || view !== 'api') return;
const apiNames = toolset.apis.map((api) => api.apiName);
@@ -167,19 +166,6 @@ const DevtoolsToolPage = () => {
window.history.replaceState(null, '', `#${toApiAnchor(apiName)}`);
};
- if (!toolset) {
- return (
- <Flexbox className={styles.empty}>
- <Text fontSize={14} weight={500}>
- Unknown toolset
- </Text>
- <Text fontSize={12} type={'secondary'}>
- {identifier}
- </Text>
- </Flexbox>
- );
- }
-
return (
<Flexbox horizontal height={'100%'} style={{ overflow: 'hidden' }} width={'100%'}>
{view === 'api' && (
diff --git a/src/features/DevPanel/RenderGallery/index.tsx b/src/features/DevPanel/RenderGallery/index.tsx
index 32fb72a14eb..6d744e8f46d 100644
--- a/src/features/DevPanel/RenderGallery/index.tsx
+++ b/src/features/DevPanel/RenderGallery/index.tsx
@@ -2,10 +2,8 @@
import { Flexbox } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
-import { useEffect } from 'react';
-import { Outlet, useParams } from 'react-router';
+import { useEffect, useState } from 'react';
-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAgentStore } from '@/store/agent';
import { useAgentGroupStore } from '@/store/agentGroup';
@@ -16,9 +14,18 @@ import {
DEVTOOLS_GROUP_ID,
} from './fixtures';
import Sidebar from './Sidebar';
-import { toToolsetPath, useDevtoolsEntries } from './useDevtoolsEntries';
+import ToolPage from './ToolPage';
+import { useDevtoolsEntries } from './useDevtoolsEntries';
const styles = createStaticStyles(({ css, cssVar }) => ({
+ empty: css`
+ flex: 1;
+ align-items: center;
+ justify-content: center;
+
+ font-size: 14px;
+ color: ${cssVar.colorTextTertiary};
+ `,
main: css`
overflow: hidden;
flex: 1;
@@ -33,17 +40,14 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
page: css`
overflow: hidden;
width: 100%;
-
- /* Bind to the viewport directly so the columns scroll internally regardless
- of whether the mounting route provides a bounded height. */
- height: 100dvh;
+ height: 100%;
`,
}));
-const DevtoolsLayout = () => {
- const { menuItems } = useDevtoolsEntries();
- const { identifier } = useParams<{ identifier: string }>();
- const navigate = useWorkspaceAwareNavigate();
+const RenderGallery = () => {
+ const { defaultToolset, menuItems, toolsetMap } = useDevtoolsEntries();
+ const [identifier, setIdentifier] = useState<string | undefined>(defaultToolset?.identifier);
+ const toolset = identifier ? toolsetMap.get(identifier) : undefined;
useEffect(() => {
const previousGroupState = useAgentGroupStore.getState();
@@ -74,16 +78,16 @@ const DevtoolsLayout = () => {
return (
<Flexbox horizontal className={styles.page}>
- <Sidebar
- items={menuItems}
- selectedKey={identifier}
- onSelect={(key) => navigate(toToolsetPath(key))}
- />
+ <Sidebar items={menuItems} selectedKey={identifier} onSelect={setIdentifier} />
<Flexbox className={styles.main}>
- <Outlet />
+ {toolset ? (
+ <ToolPage toolset={toolset} />
+ ) : (
+ <Flexbox className={styles.empty}>No builtin tool renders registered.</Flexbox>
+ )}
</Flexbox>
</Flexbox>
);
};
-export default DevtoolsLayout;
+export default RenderGallery;
diff --git a/src/features/DevPanel/RenderGallery/useDevtoolsEntries.ts b/src/features/DevPanel/RenderGallery/useDevtoolsEntries.ts
index bf2fdf64406..02c6f72e1bd 100644
--- a/src/features/DevPanel/RenderGallery/useDevtoolsEntries.ts
+++ b/src/features/DevPanel/RenderGallery/useDevtoolsEntries.ts
@@ -54,8 +54,6 @@ const DEPRECATED_TOOLSETS = new Set(['lobe-notebook']);
const isDeprecatedApi = (identifier: string, apiName: string) =>
identifier === 'lobe-local-system' && apiName.includes('Local');
-export const toToolsetPath = (identifier: string) => `/devtools/${encodeURIComponent(identifier)}`;
-
export const toApiAnchor = (apiName: string) => `api-${apiName}`;
export const useDevtoolsEntries = (): DevtoolsEntries =>
diff --git a/src/layout/SPAGlobalProvider/index.test.tsx b/src/layout/SPAGlobalProvider/index.test.tsx
index d28f8eb588f..0a3ee48a332 100644
--- a/src/layout/SPAGlobalProvider/index.test.tsx
+++ b/src/layout/SPAGlobalProvider/index.test.tsx
@@ -71,11 +71,7 @@ vi.mock('@/const/version', () => ({
isDesktop: false,
}));
-vi.mock('@/features/AgentMockDevtools', () => ({
- default: () => null,
-}));
-
-vi.mock('@/features/DevFeatureFlagPanel', () => ({
+vi.mock('@/features/DevDock', () => ({
default: () => null,
}));
diff --git a/src/layout/SPAGlobalProvider/index.tsx b/src/layout/SPAGlobalProvider/index.tsx
index f2cd893d968..d60d5e75193 100644
--- a/src/layout/SPAGlobalProvider/index.tsx
+++ b/src/layout/SPAGlobalProvider/index.tsx
@@ -3,13 +3,11 @@
import { TooltipGroup } from '@lobehub/ui';
import { StyleProvider } from 'antd-style';
import { domMax, LazyMotion } from 'motion/react';
-import { lazy, memo, type PropsWithChildren, Suspense } from 'react';
+import { type CSSProperties, lazy, memo, type PropsWithChildren, Suspense } from 'react';
import { LobeAnalyticsProviderWrapper } from '@/components/Analytics/LobeAnalyticsProviderWrapper';
import { DragUploadProvider } from '@/components/DragUploadZone/DragUploadProvider';
import { isDesktop } from '@/const/version';
-import AgentMockDevtools from '@/features/AgentMockDevtools';
-import DevFeatureFlagPanel from '@/features/DevFeatureFlagPanel';
import AuthProvider from '@/layout/AuthProvider';
import { MarketAuthProvider } from '@/layout/AuthProvider/MarketAuth';
import AppTheme from '@/layout/GlobalProvider/AppTheme';
@@ -33,6 +31,16 @@ const ToastHost = lazy(() => import('@lobehub/ui/base-ui').then((m) => ({ defaul
const ContextMenuHost = lazy(() =>
import('@lobehub/ui').then((m) => ({ default: m.ContextMenuHost })),
);
+const DevDock = lazy(() => import('@/features/DevDock'));
+
+const devDockLayoutStyle: CSSProperties = {
+ alignItems: 'center',
+ display: 'flex',
+ flex: 1,
+ flexDirection: 'column',
+ minHeight: 0,
+ width: '100%',
+};
const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {
const serverConfig: SPAServerConfig | undefined = window.__SERVER_CONFIG__;
@@ -41,6 +49,40 @@ const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {
const isMobile =
(serverConfig?.isMobile ?? typeof __MOBILE__ !== 'undefined') ? __MOBILE__ : false;
+ const content = (
+ <QueryProvider>
+ <AuthProvider>
+ <MarketAuthProvider isDesktop={isDesktop}>
+ <StoreInitialization />
+
+ {isDesktop && <ServerVersionOutdatedAlert />}
+ <FaviconProvider>
+ <DynamicFavicon />
+ <GroupWizardProvider>
+ <DragUploadProvider>
+ <LazyMotion features={domMax}>
+ <TooltipGroup layoutAnimation={false}>
+ <StyleProvider speedy={import.meta.env.PROD}>
+ <LobeAnalyticsProviderWrapper>
+ <CacheHydrationGate>{children}</CacheHydrationGate>
+ </LobeAnalyticsProviderWrapper>
+ </StyleProvider>
+ </TooltipGroup>
+ <Suspense>
+ <ModalHost />
+ <BaseModalHost />
+ <ToastHost />
+ <ContextMenuHost />
+ </Suspense>
+ </LazyMotion>
+ </DragUploadProvider>
+ </GroupWizardProvider>
+ </FaviconProvider>
+ </MarketAuthProvider>
+ </AuthProvider>
+ </QueryProvider>
+ );
+
return (
<Locale defaultLang={locale}>
<AppTheme>
@@ -49,46 +91,16 @@ const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {
isMobile={isMobile}
serverConfig={serverConfig?.config}
>
- <QueryProvider>
- <AuthProvider>
- <MarketAuthProvider isDesktop={isDesktop}>
- <StoreInitialization />
-
- {isDesktop && <ServerVersionOutdatedAlert />}
- <FaviconProvider>
- <DynamicFavicon />
- <GroupWizardProvider>
- <DragUploadProvider>
- <LazyMotion features={domMax}>
- <TooltipGroup layoutAnimation={false}>
- <StyleProvider speedy={import.meta.env.PROD}>
- <LobeAnalyticsProviderWrapper>
- <CacheHydrationGate>{children}</CacheHydrationGate>
- </LobeAnalyticsProviderWrapper>
- </StyleProvider>
- </TooltipGroup>
- <Suspense>
- <ModalHost />
- <BaseModalHost />
- <ToastHost />
- <ContextMenuHost />
- </Suspense>
- </LazyMotion>
- </DragUploadProvider>
- </GroupWizardProvider>
- </FaviconProvider>
- </MarketAuthProvider>
- </AuthProvider>
- </QueryProvider>
- <Suspense>
- {/* DevPanel disabled in SPA: depends on node:fs */}
- {__DEV__ && (
- <>
- <AgentMockDevtools />
- <DevFeatureFlagPanel />
- </>
- )}
- </Suspense>
+ {__DEV__ ? (
+ <>
+ <div style={devDockLayoutStyle}>{content}</div>
+ <Suspense>
+ <DevDock />
+ </Suspense>
+ </>
+ ) : (
+ content
+ )}
</ServerConfigStoreProvider>
</AppTheme>
</Locale>
diff --git a/src/routes/(main)/devtools/[identifier]/index.tsx b/src/routes/(main)/devtools/[identifier]/index.tsx
deleted file mode 100644
index 0ea85d9ad0f..00000000000
--- a/src/routes/(main)/devtools/[identifier]/index.tsx
+++ /dev/null
@@ -1,3 +0,0 @@
-'use client';
-
-export { default } from '@/features/DevPanel/RenderGallery/ToolPage';
diff --git a/src/routes/(main)/devtools/_layout/index.tsx b/src/routes/(main)/devtools/_layout/index.tsx
deleted file mode 100644
index a7d19f41b2b..00000000000
--- a/src/routes/(main)/devtools/_layout/index.tsx
+++ /dev/null
@@ -1,3 +0,0 @@
-'use client';
-
-export { default } from '@/features/DevPanel/RenderGallery';
diff --git a/src/routes/(main)/devtools/index.tsx b/src/routes/(main)/devtools/index.tsx
deleted file mode 100644
index 9cfc907802e..00000000000
--- a/src/routes/(main)/devtools/index.tsx
+++ /dev/null
@@ -1,3 +0,0 @@
-'use client';
-
-export { default } from '@/features/DevPanel/RenderGallery/IndexPage';
diff --git a/src/services/electron/__tests__/devtools.test.ts b/src/services/electron/__tests__/devtools.test.ts
index 2e12d5ca37e..35d7f17c5a3 100644
--- a/src/services/electron/__tests__/devtools.test.ts
+++ b/src/services/electron/__tests__/devtools.test.ts
@@ -2,10 +2,11 @@ import { describe, expect, it, vi } from 'vitest';
import { electronDevtoolsService } from '../devtools';
+const getAppCpuUsageMock = vi.fn();
const openDevtoolsMock = vi.fn();
vi.mock('@/utils/electron/ipc', () => ({
ensureElectronIpc: vi.fn(() => ({
- devtools: { openDevtools: openDevtoolsMock },
+ devtools: { getAppCpuUsage: getAppCpuUsageMock, openDevtools: openDevtoolsMock },
})),
}));
const { ensureElectronIpc } = await import('@/utils/electron/ipc');
@@ -35,4 +36,13 @@ describe('DevtoolsService', () => {
await expect(electronDevtoolsService.openDevtools()).rejects.toThrow(error);
});
});
+
+ describe('getAppCpuUsage', () => {
+ it('should return the cpu usage reported over ipc', async () => {
+ getAppCpuUsageMock.mockResolvedValueOnce({ percent: 12.5 });
+
+ await expect(electronDevtoolsService.getAppCpuUsage()).resolves.toEqual({ percent: 12.5 });
+ expect(getAppCpuUsageMock).toHaveBeenCalled();
+ });
+ });
});
diff --git a/src/services/electron/devtools.ts b/src/services/electron/devtools.ts
index 022a123dd11..14f058377fe 100644
--- a/src/services/electron/devtools.ts
+++ b/src/services/electron/devtools.ts
@@ -4,6 +4,10 @@ class DevtoolsService {
async openDevtools(): Promise<void> {
return ensureElectronIpc().devtools.openDevtools();
}
+
+ async getAppCpuUsage(): Promise<{ percent: number }> {
+ return ensureElectronIpc().devtools.getAppCpuUsage();
+ }
}
export const electronDevtoolsService = new DevtoolsService();
diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsx
index f435d017c13..a918bd01a51 100644
--- a/src/spa/router/desktopRouter.config.desktop.tsx
+++ b/src/spa/router/desktopRouter.config.desktop.tsx
@@ -95,9 +95,6 @@ import CommunityListModelLayout from '@/routes/(main)/community/(list)/model/_la
import CommunityListProviderPage from '@/routes/(main)/community/(list)/provider';
import CommunityListSkillPage from '@/routes/(main)/community/(list)/skill';
import CommunityListSkillLayout from '@/routes/(main)/community/(list)/skill/_layout';
-import DevtoolsIndexPage from '@/routes/(main)/devtools';
-import DevtoolsLayout from '@/routes/(main)/devtools/_layout';
-import DevtoolsToolPage from '@/routes/(main)/devtools/[identifier]';
import DownloadsPage from '@/routes/(main)/downloads';
import EvalOverviewPage from '@/routes/(main)/eval';
import EvalLayout from '@/routes/(main)/eval/_layout';
@@ -832,21 +829,6 @@ export const desktopRoutes: RouteObject[] = [
handle: { meta: acceptanceRouteMeta },
path: '/acceptance',
},
-
- // Devtools route (outside main layout, dev-only)
- ...(__DEV__
- ? [
- {
- children: [
- { element: <DevtoolsIndexPage />, index: true },
- { element: <DevtoolsToolPage />, path: ':identifier' },
- ],
- element: <DevtoolsLayout />,
- errorElement: <ErrorBoundary />,
- path: '/devtools',
- },
- ]
- : []),
];
// Desktop owns its onboarding flow. Web-only onboarding routes are intentionally
diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsx
index c2e497545a0..ac5896ea675 100644
--- a/src/spa/router/desktopRouter.config.tsx
+++ b/src/spa/router/desktopRouter.config.tsx
@@ -1096,36 +1096,6 @@ export const desktopRoutes: RouteObject[] = [
handle: { meta: acceptanceRouteMeta },
path: '/acceptance',
},
-
- // Devtools route (outside main layout, dev-only)
- ...(__DEV__
- ? [
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/devtools'),
- 'Desktop > Devtools > Index',
- ),
- index: true,
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/devtools/[identifier]'),
- 'Desktop > Devtools > Toolset',
- ),
- path: ':identifier',
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/devtools/_layout'),
- 'Desktop > Devtools > Layout',
- ),
- errorElement: <ErrorBoundary />,
- path: '/devtools',
- },
- ]
- : []),
];
desktopRoutes.push({