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(agent-mock): add agent mock devtools with playback & fixture viewer (#14436)

Inneif30d9da5a9e1
diff --git a/.agents/skills/source-command-dedupe/SKILL.md b/.agents/skills/source-command-dedupe/SKILL.md
new file mode 100644
index 00000000000..53fc966c7e9
--- /dev/null
+++ b/.agents/skills/source-command-dedupe/SKILL.md
@@ -0,0 +1,44 @@
+---
+name: 'source-command-dedupe'
+description: 'Find duplicate GitHub issues'
+---
+
+# source-command-dedupe
+
+Use this skill when the user asks to run the migrated source command `dedupe`.
+
+## Command Template
+
+Find up to 3 likely duplicate issues for a given GitHub issue.
+
+To do this, follow these steps precisely:
+
+1. Use an agent to check if the Github issue (a) is closed, (b) does not need to be deduped (eg. because it is broad product feedback without a specific solution, or positive feedback), or (c) already has a duplicates comment that you made earlier. If so, do not proceed.
+2. Use an agent to view a Github issue, and ask the agent to return a summary of the issue
+3. Then, launch 5 parallel agents to search Github for duplicates of this issue, using diverse keywords and search approaches, using the summary from #1
+4. Next, feed the results from #1 and #2 into another agent, so that it can filter out false positives, that are likely not actually duplicates of the original issue. If there are no duplicates remaining, do not proceed.
+5. Finally, comment back on the issue with a list of up to three duplicate issues (or zero, if there are no likely duplicates)
+
+Notes (be sure to tell this to your agents, too):
+
+- Use `gh` to interact with Github, rather than web fetch
+- Do not use other tools, beyond `gh` (eg. don't use other MCP servers, file edit, etc.)
+- Make a todo list first
+- For your comment, follow the following format precisely (assuming for this example that you found 3 suspected duplicates):
+
+---
+
+Found 3 possible duplicate issues:
+
+1. <link to issue>
+2. <link to issue>
+3. <link to issue>
+
+This issue will be automatically closed as a duplicate in 3 days.
+
+- If your issue is a duplicate, please close it and 👍 the existing issue instead
+- To prevent auto-closure, add a comment or 👎 this comment
+
+> 🤖 Generated with Codex
+
+---
diff --git a/package.json b/package.json
index 43057121f05..4afa1acba39 100644
--- a/package.json
+++ b/package.json
@@ -201,6 +201,7 @@
"@larksuiteoapi/node-sdk": "^1.60.0",
"@lexical/utils": "^0.42.0",
"@lobechat/agent-gateway-client": "workspace:*",
+ "@lobechat/agent-mock": "workspace:*",
"@lobechat/agent-runtime": "workspace:*",
"@lobechat/agent-signal": "workspace:*",
"@lobechat/agent-templates": "workspace:*",
diff --git a/packages/agent-mock/README.md b/packages/agent-mock/README.md
new file mode 100644
index 00000000000..48c5ea568a3
--- /dev/null
+++ b/packages/agent-mock/README.md
@@ -0,0 +1,3 @@
+# @lobechat/agent-mock
+
+Dev-only tooling for replaying Agent conversation streams in the SPA. See `docs/superpowers/specs/2026-05-01-agent-mock-devtools-design.md`.
diff --git a/packages/agent-mock/package.json b/packages/agent-mock/package.json
new file mode 100644
index 00000000000..75fccd69c12
--- /dev/null
+++ b/packages/agent-mock/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@lobechat/agent-mock",
+ "version": "0.0.1",
+ "private": true,
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "scripts": {
+ "test": "vitest run --silent='passed-only'"
+ },
+ "dependencies": {
+ "@lobechat/agent-gateway-client": "workspace:*",
+ "@lobechat/agent-tracing": "workspace:*"
+ },
+ "devDependencies": {
+ "vitest": "^3.0.0"
+ }
+}
diff --git a/packages/agent-mock/src/builders/defineCase.test.ts b/packages/agent-mock/src/builders/defineCase.test.ts
new file mode 100644
index 00000000000..e97c1b95a5f
--- /dev/null
+++ b/packages/agent-mock/src/builders/defineCase.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest';
+
+import { defineCase, errorStep, llmStep, toolStep } from './defineCase';
+
+describe('defineCase', () => {
+ it('wraps llmStep into stream_start → chunks → stream_end', () => {
+ const c = defineCase({
+ id: 'simple',
+ name: 'Simple LLM',
+ steps: [llmStep({ text: 'Hello world', durationMs: 100 })],
+ });
+ expect(c.id).toBe('simple');
+ expect(c.source.type).toBe('fixture');
+ const events = c.source.type === 'fixture' ? c.source.events : [];
+ const types = events.map((e) => e.type);
+ expect(types[0]).toBe('agent_runtime_init');
+ expect(types).toContain('stream_start');
+ expect(types).toContain('stream_end');
+ expect(types.at(-1)).toBe('agent_runtime_end');
+ });
+
+ it('wraps toolStep into tool_start → tool_end', () => {
+ const c = defineCase({
+ id: 'tool-only',
+ name: 'Tool only',
+ steps: [
+ toolStep({
+ identifier: 'lobe-todo-write',
+ apiName: 'addTodo',
+ arguments: '{}',
+ result: { success: true },
+ durationMs: 100,
+ }),
+ ],
+ });
+ const events = c.source.type === 'fixture' ? c.source.events : [];
+ const toolTypes = events
+ .map((e) => e.type)
+ .filter((t) => t === 'tool_start' || t === 'tool_end');
+ expect(toolTypes).toEqual(['tool_start', 'tool_end']);
+ });
+
+ it('counts toolCount and stepCount in meta', () => {
+ const c = defineCase({
+ id: 'meta',
+ name: 'meta',
+ steps: [
+ llmStep({ text: 'a', durationMs: 100 }),
+ toolStep({ identifier: 'x', apiName: 'y', arguments: '{}', result: {}, durationMs: 100 }),
+ toolStep({ identifier: 'x', apiName: 'y', arguments: '{}', result: {}, durationMs: 100 }),
+ ],
+ });
+ expect(c.meta?.stepCount).toBe(3);
+ expect(c.meta?.toolCount).toBe(2);
+ });
+
+ it('errorStep emits error event', () => {
+ const c = defineCase({
+ id: 'err',
+ name: 'err',
+ steps: [errorStep({ message: 'boom' })],
+ });
+ const events = c.source.type === 'fixture' ? c.source.events : [];
+ expect(events.some((e) => e.type === 'error')).toBe(true);
+ });
+});
diff --git a/packages/agent-mock/src/builders/defineCase.ts b/packages/agent-mock/src/builders/defineCase.ts
new file mode 100644
index 00000000000..1325b284dc3
--- /dev/null
+++ b/packages/agent-mock/src/builders/defineCase.ts
@@ -0,0 +1,183 @@
+import { splitTextIntoChunks } from '../snapshot/chunkSplitter';
+import type { MockCase, MockEvent } from '../types';
+import { endEvent, initEvent, stepComplete, stepStart } from './helpers';
+
+export interface LlmStepInput {
+ chunkSize?: number;
+ durationMs: number;
+ reasoning?: string;
+ text?: string;
+ toolsCalling?: Array<{ identifier: string; apiName: string; arguments: string; id?: string }>;
+}
+
+export interface ToolStepInput {
+ apiName: string;
+ arguments: string;
+ durationMs: number;
+ error?: { message: string; type?: string };
+ identifier: string;
+ isClientTool?: boolean;
+ result?: unknown;
+}
+
+export interface ErrorStepInput {
+ message: string;
+ type?: string;
+}
+
+interface InternalStep {
+ __kind: 'llm' | 'tool' | 'error';
+ build: (stepIndex: number, ctx: { assistantMessageId: string }) => MockEvent[];
+ toolCount: number;
+}
+
+export function llmStep(input: LlmStepInput): InternalStep {
+ return {
+ __kind: 'llm',
+ toolCount: 0,
+ build(stepIndex, ctx) {
+ const chunkSize = input.chunkSize ?? 30;
+ const reasoningChunks = input.reasoning
+ ? splitTextIntoChunks(input.reasoning, { targetChunkChars: chunkSize, jitter: 0.15 })
+ : [];
+ const textChunks = input.text
+ ? splitTextIntoChunks(input.text, { targetChunkChars: chunkSize, jitter: 0.15 })
+ : [];
+ const toolsCallingCount = input.toolsCalling?.length ? 1 : 0;
+ const totalChunks = reasoningChunks.length + textChunks.length + toolsCallingCount;
+ const perDelay =
+ totalChunks > 0 ? Math.max(1, Math.floor(input.durationMs / totalChunks)) : 0;
+
+ const events: MockEvent[] = [
+ stepStart(stepIndex, 'call_llm'),
+ {
+ type: 'stream_start',
+ data: { assistantMessage: { id: ctx.assistantMessageId } },
+ delay: 0,
+ },
+ ];
+ for (const r of reasoningChunks)
+ events.push({
+ type: 'stream_chunk',
+ data: { chunkType: 'reasoning', reasoning: r },
+ delay: perDelay,
+ });
+ for (const t of textChunks)
+ events.push({
+ type: 'stream_chunk',
+ data: { chunkType: 'text', content: t },
+ delay: perDelay,
+ });
+ if (input.toolsCalling?.length) {
+ events.push({
+ type: 'stream_chunk',
+ data: { chunkType: 'tools_calling', toolsCalling: input.toolsCalling },
+ delay: perDelay,
+ });
+ }
+ events.push({ type: 'stream_end', data: {}, delay: 0 }, stepComplete(stepIndex, 'call_llm'));
+ return events;
+ },
+ };
+}
+
+export function toolStep(input: ToolStepInput): InternalStep {
+ return {
+ __kind: 'tool',
+ toolCount: 1,
+ build(stepIndex) {
+ const toolCallId = `mock-tc-${stepIndex}-0`;
+ const events: MockEvent[] = [
+ stepStart(stepIndex, 'call_tool'),
+ {
+ type: 'tool_start',
+ data: {
+ parentMessageId: `mock-msg-${stepIndex - 1}`,
+ toolCalling: { id: toolCallId, identifier: input.identifier, apiName: input.apiName },
+ },
+ delay: 0,
+ },
+ ];
+ if (input.isClientTool) {
+ events.push({
+ type: 'tool_execute',
+ data: {
+ identifier: input.identifier,
+ apiName: input.apiName,
+ arguments: input.arguments,
+ toolCallId,
+ executionTimeoutMs: 30_000,
+ },
+ delay: 0,
+ });
+ }
+ events.push({
+ type: 'tool_end',
+ data: {
+ isSuccess: !input.error,
+ result: input.result,
+ payload: { state: input.result },
+ ...(input.error ? { error: input.error } : {}),
+ },
+ delay: input.durationMs,
+ label: `tool:${input.apiName}`,
+ });
+ events.push(stepComplete(stepIndex, 'call_tool'));
+ return events;
+ },
+ };
+}
+
+export function errorStep(input: ErrorStepInput): InternalStep {
+ return {
+ __kind: 'error',
+ toolCount: 0,
+ build() {
+ return [
+ {
+ type: 'error',
+ data: { message: input.message, type: input.type ?? 'AgentRuntimeError' },
+ delay: 0,
+ },
+ ];
+ },
+ };
+}
+
+export interface DefineCaseInput {
+ description?: string;
+ id: string;
+ name: string;
+ steps: InternalStep[];
+ tags?: string[];
+}
+
+export function defineCase(input: DefineCaseInput): MockCase {
+ const events: MockEvent[] = [initEvent()];
+
+ let toolCount = 0;
+ const assistantMessageId = `mock-msg-${input.id}-0`;
+ let totalMs = 0;
+
+ input.steps.forEach((step, idx) => {
+ const built = step.build(idx, { assistantMessageId });
+ events.push(...built);
+ toolCount += step.toolCount;
+ totalMs += built.reduce((s, e) => s + (e.delay ?? 0), 0);
+ });
+
+ events.push(endEvent());
+
+ return {
+ id: input.id,
+ name: input.name,
+ description: input.description,
+ tags: input.tags,
+ source: { type: 'fixture', events },
+ meta: {
+ stepCount: input.steps.length,
+ toolCount,
+ estimatedDurationMs: totalMs,
+ },
+ };
+}
diff --git a/packages/agent-mock/src/builders/helpers.ts b/packages/agent-mock/src/builders/helpers.ts
new file mode 100644
index 00000000000..585e9d11f10
--- /dev/null
+++ b/packages/agent-mock/src/builders/helpers.ts
@@ -0,0 +1,25 @@
+import type { MockEvent } from '../types';
+
+export const initEvent = (): MockEvent => ({
+ type: 'agent_runtime_init',
+ data: {},
+ delay: 0,
+});
+
+export const endEvent = (reason: string = 'done'): MockEvent => ({
+ type: 'agent_runtime_end',
+ data: { reason },
+ delay: 0,
+});
+
+export const stepStart = (stepIndex: number, stepType: 'call_llm' | 'call_tool'): MockEvent => ({
+ type: 'step_start',
+ data: { stepIndex, stepType },
+ delay: 0,
+});
+
+export const stepComplete = (stepIndex: number, phase: string): MockEvent => ({
+ type: 'step_complete',
+ data: { stepIndex, phase, reason: 'completed' },
+ delay: 0,
+});
diff --git a/packages/agent-mock/src/cases/builtins/error-mid-stream.ts b/packages/agent-mock/src/cases/builtins/error-mid-stream.ts
new file mode 100644
index 00000000000..56ceee6bd35
--- /dev/null
+++ b/packages/agent-mock/src/cases/builtins/error-mid-stream.ts
@@ -0,0 +1,19 @@
+import { defineCase, errorStep, llmStep, toolStep } from '../../builders/defineCase';
+
+export const errorMidStream = defineCase({
+ id: 'error-mid-stream',
+ name: 'Error mid-stream',
+ description: 'Tool call fails halfway, then runtime errors',
+ tags: ['error', 'builtin'],
+ steps: [
+ llmStep({ text: '尝试调用工具。', durationMs: 400 }),
+ toolStep({
+ identifier: 'lobe-todo-write',
+ apiName: 'addTodo',
+ arguments: JSON.stringify({ title: 'fails' }),
+ error: { message: 'Permission denied', type: 'ToolExecutionError' },
+ durationMs: 200,
+ }),
+ errorStep({ message: 'Agent runtime aborted: tool failed' }),
+ ],
+});
diff --git a/packages/agent-mock/src/cases/builtins/long-reasoning.ts b/packages/agent-mock/src/cases/builtins/long-reasoning.ts
new file mode 100644
index 00000000000..74b0e66ab41
--- /dev/null
+++ b/packages/agent-mock/src/cases/builtins/long-reasoning.ts
@@ -0,0 +1,15 @@
+import { defineCase, llmStep } from '../../builders/defineCase';
+
+export const longReasoning = defineCase({
+ id: 'long-reasoning',
+ name: 'Long reasoning',
+ description: '5000 character reasoning before short answer',
+ tags: ['reasoning', 'builtin'],
+ steps: [
+ llmStep({
+ reasoning: '思路'.repeat(1250),
+ text: '综上所述,结论是:A。',
+ durationMs: 6000,
+ }),
+ ],
+});
diff --git a/packages/agent-mock/src/cases/builtins/mixed-tools.ts b/packages/agent-mock/src/cases/builtins/mixed-tools.ts
new file mode 100644
index 00000000000..57cfcb5ef4d
--- /dev/null
+++ b/packages/agent-mock/src/cases/builtins/mixed-tools.ts
@@ -0,0 +1,33 @@
+import { defineCase, llmStep, toolStep } from '../../builders/defineCase';
+
+export const mixedTools = defineCase({
+ id: 'mixed-tools',
+ name: 'Mixed tools',
+ description: 'TodoWrite + Memory + Calculator interleaved',
+ tags: ['mixed', 'builtin'],
+ steps: [
+ llmStep({ text: '先记忆,再计算,最后规划。', durationMs: 500 }),
+ toolStep({
+ identifier: 'lobe-memory',
+ apiName: 'remember',
+ arguments: JSON.stringify({ key: 'k', value: 'v' }),
+ result: { success: true },
+ durationMs: 150,
+ }),
+ toolStep({
+ identifier: 'lobe-calculator',
+ apiName: 'calculate',
+ arguments: JSON.stringify({ expr: '2+2' }),
+ result: { value: 4 },
+ durationMs: 80,
+ }),
+ toolStep({
+ identifier: 'lobe-todo-write',
+ apiName: 'addTodo',
+ arguments: JSON.stringify({ title: '验证结果' }),
+ result: { success: true, id: 'todo-1' },
+ durationMs: 100,
+ }),
+ llmStep({ text: '完成。', durationMs: 200 }),
+ ],
+});
diff --git a/packages/agent-mock/src/cases/builtins/todo-write-stress.ts b/packages/agent-mock/src/cases/builtins/todo-write-stress.ts
new file mode 100644
index 00000000000..d8abf6a5517
--- /dev/null
+++ b/packages/agent-mock/src/cases/builtins/todo-write-stress.ts
@@ -0,0 +1,25 @@
+import { defineCase, llmStep, toolStep } from '../../builders/defineCase';
+
+export const todoWriteStress = defineCase({
+ id: 'todo-write-stress',
+ name: 'TodoWrite × 50',
+ description: '50 sequential addTodo tool calls bracketed by short LLM steps',
+ tags: ['stress', 'todo', 'builtin'],
+ steps: [
+ llmStep({
+ text: '我将逐步规划 50 项任务,分为五个主题:环境、需求、设计、实现、验收。',
+ reasoning: '按主题分组,每组 10 项;先思路后枚举。',
+ durationMs: 800,
+ }),
+ ...Array.from({ length: 50 }, (_, i) =>
+ toolStep({
+ identifier: 'lobe-todo-write',
+ apiName: 'addTodo',
+ arguments: JSON.stringify({ title: `任务 ${i + 1}` }),
+ result: { success: true, id: `todo-${i}`, title: `任务 ${i + 1}` },
+ durationMs: 120,
+ }),
+ ),
+ llmStep({ text: '已完成 50 项任务规划。', durationMs: 400 }),
+ ],
+});
diff --git a/packages/agent-mock/src/cases/generators/long-reasoning.ts b/packages/agent-mock/src/cases/generators/long-reasoning.ts
new file mode 100644
index 00000000000..3c90be28183
--- /dev/null
+++ b/packages/agent-mock/src/cases/generators/long-reasoning.ts
@@ -0,0 +1,27 @@
+import { defineCase, llmStep } from '../../builders/defineCase';
+import { defineGenerator } from './registry';
+
+export interface LongReasoningParams {
+ reasoningChars: number;
+ textChars: number;
+}
+
+export const longReasoningGenerator = defineGenerator<LongReasoningParams>({
+ id: 'long-reasoning',
+ name: 'Long Reasoning',
+ description: 'Reasoning of N chars before short answer',
+ defaultParams: { reasoningChars: 5000, textChars: 200 },
+ factory: ({ reasoningChars, textChars }) =>
+ defineCase({
+ id: `long-reasoning-${reasoningChars}`,
+ name: `Long reasoning ${reasoningChars}c`,
+ tags: ['reasoning', 'generated'],
+ steps: [
+ llmStep({
+ reasoning: 'x'.repeat(reasoningChars),
+ text: 'y'.repeat(textChars),
+ durationMs: Math.max(1000, reasoningChars * 2),
+ }),
+ ],
+ }),
+});
diff --git a/packages/agent-mock/src/cases/generators/registry.ts b/packages/agent-mock/src/cases/generators/registry.ts
new file mode 100644
index 00000000000..d808673f585
--- /dev/null
+++ b/packages/agent-mock/src/cases/generators/registry.ts
@@ -0,0 +1,22 @@
+import type { MockCase } from '../../types';
+
+export interface GeneratorDef<TParams = unknown> {
+ defaultParams: TParams;
+ description?: string;
+ factory: (params: TParams) => MockCase;
+ id: string;
+ name: string;
+}
+
+const registry = new Map<string, GeneratorDef<any>>();
+
+export function defineGenerator<T>(def: GeneratorDef<T>): GeneratorDef<T> {
+ registry.set(def.id, def);
+ return def;
+}
+
+export function getGenerator(id: string): GeneratorDef | undefined {
+ return registry.get(id);
+}
+
+export const GENERATORS = registry;
diff --git a/packages/agent-mock/src/cases/generators/subagent-tree.ts b/packages/agent-mock/src/cases/generators/subagent-tree.ts
new file mode 100644
index 00000000000..7cbb1547a5c
--- /dev/null
+++ b/packages/agent-mock/src/cases/generators/subagent-tree.ts
@@ -0,0 +1,35 @@
+import { defineCase, llmStep, toolStep } from '../../builders/defineCase';
+import { defineGenerator } from './registry';
+
+export interface SubagentTreeParams {
+ depth: number;
+ fanout: number;
+}
+
+export const subagentTreeGenerator = defineGenerator<SubagentTreeParams>({
+ id: 'subagent-tree',
+ name: 'Subagent Tree',
+ description: 'Nested callAgent tool calls of depth × fanout',
+ defaultParams: { depth: 3, fanout: 2 },
+ factory: ({ depth, fanout }) => {
+ const calls = depth * fanout;
+ return defineCase({
+ id: `subagent-tree-d${depth}-f${fanout}`,
+ name: `Subagent ${depth}×${fanout}`,
+ tags: ['subagent', 'generated'],
+ steps: [
+ llmStep({ text: `Spawning ${calls} subagents.`, durationMs: 300 }),
+ ...Array.from({ length: calls }, (_, i) =>
+ toolStep({
+ identifier: 'lobe-call-agent',
+ apiName: 'callAgent',
+ arguments: JSON.stringify({ agentId: `sub-${i}` }),
+ result: { success: true, output: `子代理 ${i} 完成` },
+ durationMs: 600,
+ }),
+ ),
+ llmStep({ text: '所有子代理完成。', durationMs: 200 }),
+ ],
+ });
+ },
+});
diff --git a/packages/agent-mock/src/cases/generators/tool-stress.ts b/packages/agent-mock/src/cases/generators/tool-stress.ts
new file mode 100644
index 00000000000..00fda8c8dc4
--- /dev/null
+++ b/packages/agent-mock/src/cases/generators/tool-stress.ts
@@ -0,0 +1,51 @@
+import { defineCase, llmStep, toolStep } from '../../builders/defineCase';
+import { defineGenerator } from './registry';
+
+export interface ToolStressParams {
+ count: number;
+ durationPerToolMs?: number;
+ toolMix?: Array<{ identifier: string; apiName: string; weight: number }>;
+}
+
+export const toolStressGenerator = defineGenerator<ToolStressParams>({
+ id: 'tool-stress',
+ name: 'Tool Stress',
+ description: 'Generate N tool calls bracketed by LLM steps',
+ defaultParams: { count: 50, durationPerToolMs: 120 },
+ factory: (params) => {
+ const mix = params.toolMix ?? [
+ { identifier: 'lobe-todo-write', apiName: 'addTodo', weight: 1 },
+ ];
+ const totalWeight = mix.reduce((s, m) => s + m.weight, 0);
+ const pickTool = () => {
+ let r = Math.random() * totalWeight;
+ for (const m of mix) {
+ r -= m.weight;
+ if (r <= 0) return m;
+ }
+ return mix[0];
+ };
+
+ const tools = Array.from({ length: params.count }, (_, i) => {
+ const m = pickTool();
+ return toolStep({
+ identifier: m.identifier,
+ apiName: m.apiName,
+ arguments: JSON.stringify({ index: i }),
+ result: { success: true, index: i },
+ durationMs: params.durationPerToolMs ?? 120,
+ });
+ });
+
+ return defineCase({
+ id: `tool-stress-${params.count}`,
+ name: `Tool Stress × ${params.count}`,
+ tags: ['stress', 'generated'],
+ steps: [
+ llmStep({ text: `Stress run with ${params.count} tools.`, durationMs: 300 }),
+ ...tools,
+ llmStep({ text: 'Stress run complete.', durationMs: 200 }),
+ ],
+ });
+ },
+});
diff --git a/packages/agent-mock/src/cases/registry.ts b/packages/agent-mock/src/cases/registry.ts
new file mode 100644
index 00000000000..3c716668431
--- /dev/null
+++ b/packages/agent-mock/src/cases/registry.ts
@@ -0,0 +1,12 @@
+import type { MockCase } from '../types';
+import { errorMidStream } from './builtins/error-mid-stream';
+import { longReasoning } from './builtins/long-reasoning';
+import { mixedTools } from './builtins/mixed-tools';
+import { todoWriteStress } from './builtins/todo-write-stress';
+
+export const BUILTIN_CASES: MockCase[] = [
+ todoWriteStress,
+ longReasoning,
+ mixedTools,
+ errorMidStream,
+];
diff --git a/packages/agent-mock/src/executor/executeMockStream.ts b/packages/agent-mock/src/executor/executeMockStream.ts
new file mode 100644
index 00000000000..aad549b5826
--- /dev/null
+++ b/packages/agent-mock/src/executor/executeMockStream.ts
@@ -0,0 +1,36 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+
+import { MockPlayer } from '../player/MockPlayer';
+import type { MockCase, SpeedMultiplier } from '../types';
+
+export interface ExecuteMockStreamOptions {
+ case: MockCase;
+ onEvent: (event: AgentStreamEvent) => void;
+ operationId: string;
+ speedMultiplier?: SpeedMultiplier;
+}
+
+export interface MockStreamHandle {
+ player: MockPlayer;
+ start: () => void;
+ stop: () => void;
+}
+
+export function executeMockStream(opts: ExecuteMockStreamOptions): MockStreamHandle {
+ const player = new MockPlayer({
+ case: opts.case,
+ onEvent: opts.onEvent,
+ operationId: opts.operationId,
+ speedMultiplier: opts.speedMultiplier,
+ });
+
+ return {
+ player,
+ start() {
+ player.play();
+ },
+ stop() {
+ player.stop();
+ },
+ };
+}
diff --git a/packages/agent-mock/src/index.ts b/packages/agent-mock/src/index.ts
new file mode 100644
index 00000000000..af340850ac0
--- /dev/null
+++ b/packages/agent-mock/src/index.ts
@@ -0,0 +1,8 @@
+export { defineCase, errorStep, llmStep, toolStep } from './builders/defineCase';
+export { GENERATORS } from './cases/generators/registry';
+export { BUILTIN_CASES } from './cases/registry';
+export { executeMockStream } from './executor/executeMockStream';
+export { MockPlayer } from './player/MockPlayer';
+export { snapshotToMockCase } from './snapshot/loadSnapshot';
+export { snapshotToEvents } from './snapshot/snapshotToEvents';
+export * from './types';
diff --git a/packages/agent-mock/src/player/MockPlayer.test.ts b/packages/agent-mock/src/player/MockPlayer.test.ts
new file mode 100644
index 00000000000..a93b619d7de
--- /dev/null
+++ b/packages/agent-mock/src/player/MockPlayer.test.ts
@@ -0,0 +1,100 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { defineCase, llmStep, toolStep } from '../builders/defineCase';
+import { MockPlayer } from './MockPlayer';
+
+const fixture = () =>
+ defineCase({
+ id: 't',
+ name: 't',
+ steps: [
+ llmStep({ text: 'hi', durationMs: 100 }),
+ toolStep({
+ identifier: 'x',
+ apiName: 'y',
+ arguments: '{}',
+ result: {},
+ durationMs: 100,
+ }),
+ ],
+ });
+
+describe('MockPlayer', () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it('emits no events when idle', () => {
+ const onEvent = vi.fn();
+ const p = new MockPlayer({ case: fixture(), onEvent, operationId: 'op' });
+ expect(p.getState().status).toBe('idle');
+ expect(onEvent).not.toHaveBeenCalled();
+ });
+
+ it('plays through all events at instant speed', async () => {
+ const onEvent = vi.fn();
+ const p = new MockPlayer({
+ case: fixture(),
+ onEvent,
+ operationId: 'op',
+ speedMultiplier: 'instant',
+ });
+ p.play();
+ await vi.runAllTimersAsync();
+ expect(p.getState().status).toBe('complete');
+ expect(onEvent.mock.calls.length).toBeGreaterThan(0);
+ expect(onEvent.mock.calls[0][0].type).toBe('agent_runtime_init');
+ expect(onEvent.mock.calls.at(-1)?.[0].type).toBe('agent_runtime_end');
+ });
+
+ it('pause halts dispatch; resume continues', async () => {
+ const onEvent = vi.fn();
+ const p = new MockPlayer({
+ case: fixture(),
+ onEvent,
+ operationId: 'op',
+ speedMultiplier: 1,
+ });
+ p.play();
+ await vi.advanceTimersByTimeAsync(0);
+ p.pause();
+ const dispatchedAtPause = onEvent.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(onEvent.mock.calls.length).toBe(dispatchedAtPause);
+ p.resume();
+ await vi.runAllTimersAsync();
+ expect(p.getState().status).toBe('complete');
+ });
+
+ it('stop transitions to idle and discards remaining events', async () => {
+ const onEvent = vi.fn();
+ const p = new MockPlayer({
+ case: fixture(),
+ onEvent,
+ operationId: 'op',
+ speedMultiplier: 1,
+ });
+ p.play();
+ await vi.advanceTimersByTimeAsync(0);
+ p.stop();
+ const after = onEvent.mock.calls.length;
+ await vi.runAllTimersAsync();
+ expect(p.getState().status).toBe('idle');
+ expect(onEvent.mock.calls.length).toBe(after);
+ });
+
+ it('decorates each emitted event with operationId, stepIndex, timestamp', () => {
+ const onEvent = vi.fn();
+ const p = new MockPlayer({
+ case: fixture(),
+ onEvent,
+ operationId: 'op',
+ speedMultiplier: 'instant',
+ });
+ p.play();
+ vi.runAllTimers();
+ const calls = onEvent.mock.calls;
+ expect(calls[0][0].operationId).toBe('op');
+ expect(typeof calls[0][0].timestamp).toBe('number');
+ expect(typeof calls[0][0].stepIndex).toBe('number');
+ });
+});
diff --git a/packages/agent-mock/src/player/MockPlayer.ts b/packages/agent-mock/src/player/MockPlayer.ts
new file mode 100644
index 00000000000..1658e7239e2
--- /dev/null
+++ b/packages/agent-mock/src/player/MockPlayer.ts
@@ -0,0 +1,191 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+
+import type { MockCase, MockEvent, PlaybackState, SpeedMultiplier } from '../types';
+import { applySpeed } from './timing';
+
+export interface MockPlayerOptions {
+ case: MockCase;
+ onEvent: (event: AgentStreamEvent) => void;
+ operationId: string;
+ speedMultiplier?: SpeedMultiplier;
+}
+
+type Listener = (state: PlaybackState) => void;
+
+const eventsOf = (c: MockCase): MockEvent[] => {
+ if (c.source.type === 'fixture') return c.source.events;
+ if (c.source.type === 'snapshot') return c.source.events ?? [];
+ if (c.source.type === 'generator') return c.source.events ?? [];
+ return [];
+};
+
+const countTools = (events: MockEvent[]) => events.filter((e) => e.type === 'tool_start').length;
+const countSteps = (events: MockEvent[]) => events.filter((e) => e.type === 'step_start').length;
+const totalDuration = (events: MockEvent[]) => events.reduce((s, e) => s + (e.delay ?? 0), 0);
+
+export class MockPlayer {
+ private events: MockEvent[];
+ private cursor = 0;
+ private elapsedMs = 0;
+ private currentStepIndex = -1;
+ private toolsExecuted = 0;
+ private state: PlaybackState;
+ private speed: SpeedMultiplier;
+ private timer: ReturnType<typeof setTimeout> | null = null;
+ private listeners = new Set<Listener>();
+
+ constructor(private opts: MockPlayerOptions) {
+ this.events = eventsOf(opts.case);
+ this.speed = opts.speedMultiplier ?? 1;
+ this.state = {
+ status: 'idle',
+ currentEventIndex: 0,
+ totalEvents: this.events.length,
+ currentStepIndex: 0,
+ totalSteps: countSteps(this.events),
+ toolsExecuted: 0,
+ totalTools: countTools(this.events),
+ elapsedMs: 0,
+ totalDurationMs: totalDuration(this.events),
+ speedMultiplier: this.speed,
+ };
+ }
+
+ play() {
+ if (this.state.status === 'running') return;
+ this.setState({ status: 'running' });
+ this.scheduleNext();
+ }
+
+ pause() {
+ if (this.state.status !== 'running') return;
+ this.clearTimer();
+ this.setState({ status: 'paused' });
+ }
+
+ resume() {
+ if (this.state.status !== 'paused') return;
+ this.setState({ status: 'running' });
+ this.scheduleNext();
+ }
+
+ stop() {
+ this.clearTimer();
+ this.cursor = 0;
+ this.elapsedMs = 0;
+ this.currentStepIndex = -1;
+ this.toolsExecuted = 0;
+ this.setState({
+ status: 'idle',
+ currentEventIndex: 0,
+ currentStepIndex: 0,
+ toolsExecuted: 0,
+ elapsedMs: 0,
+ });
+ }
+
+ setSpeed(speed: SpeedMultiplier) {
+ this.speed = speed;
+ this.setState({ speedMultiplier: speed });
+ if (this.state.status === 'running') {
+ this.clearTimer();
+ this.scheduleNext();
+ }
+ }
+
+ getState(): PlaybackState {
+ return this.state;
+ }
+
+ subscribe(listener: Listener): () => void {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ }
+
+ stepNextEvent() {
+ if (this.cursor >= this.events.length) return;
+ this.dispatch(this.events[this.cursor]);
+ this.cursor += 1;
+ if (this.cursor >= this.events.length) this.setState({ status: 'complete' });
+ }
+
+ stepNextStep() {
+ while (this.cursor < this.events.length) {
+ const ev = this.events[this.cursor];
+ this.dispatch(ev);
+ this.cursor += 1;
+ if (ev.type === 'step_complete') break;
+ }
+ if (this.cursor >= this.events.length) this.setState({ status: 'complete' });
+ }
+
+ stepNextTool() {
+ while (this.cursor < this.events.length) {
+ const ev = this.events[this.cursor];
+ this.dispatch(ev);
+ this.cursor += 1;
+ if (ev.type === 'tool_end') break;
+ }
+ if (this.cursor >= this.events.length) this.setState({ status: 'complete' });
+ }
+
+ seekToEventIndex(idx: number) {
+ if (idx < 0 || idx > this.events.length) return;
+ this.clearTimer();
+ if (idx < this.cursor) {
+ this.stop();
+ }
+ while (this.cursor < idx) {
+ this.dispatch(this.events[this.cursor]);
+ this.cursor += 1;
+ }
+ }
+
+ private scheduleNext = () => {
+ if (this.state.status !== 'running') return;
+ if (this.cursor >= this.events.length) {
+ this.setState({ status: 'complete' });
+ return;
+ }
+ const ev = this.events[this.cursor];
+ const delay = applySpeed(ev.delay ?? 0, this.speed);
+ this.timer = setTimeout(() => {
+ this.dispatch(ev);
+ this.cursor += 1;
+ this.scheduleNext();
+ }, delay);
+ };
+
+ private dispatch(ev: MockEvent) {
+ if (ev.type === 'step_start') this.currentStepIndex += 1;
+ if (ev.type === 'tool_end') this.toolsExecuted += 1;
+ this.elapsedMs += ev.delay ?? 0;
+
+ const decorated: AgentStreamEvent = {
+ type: ev.type,
+ data: ev.data,
+ operationId: this.opts.operationId,
+ stepIndex: Math.max(0, this.currentStepIndex),
+ timestamp: Date.now(),
+ };
+ this.opts.onEvent(decorated);
+ this.setState({
+ currentEventIndex: this.cursor + 1,
+ currentStepIndex: Math.max(0, this.currentStepIndex),
+ toolsExecuted: this.toolsExecuted,
+ elapsedMs: this.elapsedMs,
+ });
+ }
+
+ private setState(patch: Partial<PlaybackState>) {
+ this.state = { ...this.state, ...patch };
+ for (const l of this.listeners) l(this.state);
+ }
+
+ private clearTimer() {
+ if (this.timer != null) {
+ clearTimeout(this.timer);
+ this.timer = null;
+ }
+ }
+}
diff --git a/packages/agent-mock/src/player/timing.ts b/packages/agent-mock/src/player/timing.ts
new file mode 100644
index 00000000000..8a698b7b9bd
--- /dev/null
+++ b/packages/agent-mock/src/player/timing.ts
@@ -0,0 +1,6 @@
+import type { SpeedMultiplier } from '../types';
+
+export function applySpeed(delayMs: number, speed: SpeedMultiplier): number {
+ if (speed === 'instant') return 0;
+ return Math.max(0, Math.round(delayMs / speed));
+}
diff --git a/packages/agent-mock/src/snapshot/chunkSplitter.test.ts b/packages/agent-mock/src/snapshot/chunkSplitter.test.ts
new file mode 100644
index 00000000000..04101537f80
--- /dev/null
+++ b/packages/agent-mock/src/snapshot/chunkSplitter.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+
+import { splitTextIntoChunks } from './chunkSplitter';
+
+describe('splitTextIntoChunks', () => {
+ it('splits ASCII text into ~targetChunkChars-sized chunks', () => {
+ const text = 'a'.repeat(100);
+ const chunks = splitTextIntoChunks(text, { targetChunkChars: 20 });
+ expect(chunks.length).toBe(5);
+ expect(chunks.every((c) => c.length === 20)).toBe(true);
+ expect(chunks.join('')).toBe(text);
+ });
+
+ it('respects code points and does not break CJK characters', () => {
+ const text = '你好世界'.repeat(10); // 40 code points
+ const chunks = splitTextIntoChunks(text, { targetChunkChars: 8 });
+ expect(chunks.join('')).toBe(text);
+ chunks.forEach((c) => {
+ expect(c).toBe([...c].join(''));
+ });
+ });
+
+ it('returns single chunk for empty/short text', () => {
+ expect(splitTextIntoChunks('', { targetChunkChars: 30 })).toEqual([]);
+ expect(splitTextIntoChunks('hi', { targetChunkChars: 30 })).toEqual(['hi']);
+ });
+
+ it('applies jitter within ±15% when jitter enabled', () => {
+ const text = 'a'.repeat(1000);
+ const chunks = splitTextIntoChunks(text, { targetChunkChars: 30, jitter: 0.15 });
+ chunks.forEach((c) => {
+ expect(c.length).toBeGreaterThanOrEqual(Math.floor(30 * 0.85));
+ expect(c.length).toBeLessThanOrEqual(Math.ceil(30 * 1.15));
+ });
+ expect(chunks.join('')).toBe(text);
+ });
+});
diff --git a/packages/agent-mock/src/snapshot/chunkSplitter.ts b/packages/agent-mock/src/snapshot/chunkSplitter.ts
new file mode 100644
index 00000000000..9acebbf3f3d
--- /dev/null
+++ b/packages/agent-mock/src/snapshot/chunkSplitter.ts
@@ -0,0 +1,51 @@
+export interface SplitOptions {
+ /** Random jitter, e.g. 0.15 means each chunk size varies ±15%. Default 0 (deterministic). */
+ jitter?: number;
+ targetChunkChars: number;
+}
+
+export function splitTextIntoChunks(text: string, opts: SplitOptions): string[] {
+ if (!text) return [];
+ const codePoints = [...text]; // splits by code point, not UTF-16 unit
+ if (codePoints.length <= opts.targetChunkChars) return [text];
+
+ const { targetChunkChars, jitter = 0 } = opts;
+ const minSize = jitter > 0 ? Math.floor(targetChunkChars * (1 - jitter)) : 1;
+ const maxSize = jitter > 0 ? Math.ceil(targetChunkChars * (1 + jitter)) : targetChunkChars;
+ const total = codePoints.length;
+
+ // Decide chunk count up-front so every chunk can satisfy [minSize, maxSize].
+ // Prefer the count that puts the average closest to targetChunkChars.
+ const minCount = Math.max(1, Math.ceil(total / maxSize));
+ const maxCount = Math.max(minCount, Math.floor(total / minSize));
+ const idealCount = Math.max(1, Math.round(total / targetChunkChars));
+ const count = Math.min(maxCount, Math.max(minCount, idealCount));
+
+ // Generate `count` jittered sizes that sum to `total` and each lies within [minSize, maxSize].
+ const sizes: number[] = [];
+ let remaining = total;
+ for (let k = 0; k < count; k++) {
+ const slotsLeft = count - k;
+ if (slotsLeft === 1) {
+ sizes.push(remaining);
+ break;
+ }
+ const variance = jitter > 0 ? (Math.random() * 2 - 1) * jitter : 0;
+ let size = Math.max(1, Math.round(targetChunkChars * (1 + variance)));
+ // Bound so the remaining slots can still each receive a value in [minSize, maxSize].
+ const maxAllowed = Math.min(maxSize, remaining - (slotsLeft - 1) * minSize);
+ const minAllowed = Math.max(minSize, remaining - (slotsLeft - 1) * maxSize);
+ if (size > maxAllowed) size = maxAllowed;
+ if (size < minAllowed) size = minAllowed;
+ sizes.push(size);
+ remaining -= size;
+ }
+
+ const result: string[] = [];
+ let i = 0;
+ for (const size of sizes) {
+ result.push(codePoints.slice(i, i + size).join(''));
+ i += size;
+ }
+ return result;
+}
diff --git a/packages/agent-mock/src/snapshot/loadSnapshot.ts b/packages/agent-mock/src/snapshot/loadSnapshot.ts
new file mode 100644
index 00000000000..40a1f759aec
--- /dev/null
+++ b/packages/agent-mock/src/snapshot/loadSnapshot.ts
@@ -0,0 +1,25 @@
+import type { ExecutionSnapshot } from '@lobechat/agent-tracing';
+
+import type { MockCase } from '../types';
+import { snapshotToEvents } from './snapshotToEvents';
+
+/**
+ * Convert a raw ExecutionSnapshot JSON object into a MockCase.
+ */
+export function snapshotToMockCase(
+ snapshot: ExecutionSnapshot,
+ meta: { id: string; name?: string; path: string },
+): MockCase {
+ const events = snapshotToEvents(snapshot);
+ const toolCount = events.filter((e) => e.type === 'tool_start').length;
+ const stepCount = events.filter((e) => e.type === 'step_start').length;
+ const totalMs = events.reduce((s, e) => s + (e.delay ?? 0), 0);
+
+ return {
+ id: meta.id,
+ name: meta.name ?? meta.id,
+ tags: ['snapshot'],
+ source: { type: 'snapshot', path: meta.path, events },
+ meta: { toolCount, stepCount, estimatedDurationMs: totalMs },
+ };
+}
diff --git a/packages/agent-mock/src/snapshot/snapshotToEvents.test.ts b/packages/agent-mock/src/snapshot/snapshotToEvents.test.ts
new file mode 100644
index 00000000000..cfc725033a9
--- /dev/null
+++ b/packages/agent-mock/src/snapshot/snapshotToEvents.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it } from 'vitest';
+
+import type { MockEvent } from '../types';
+import { snapshotToEvents } from './snapshotToEvents';
+
+const minimalSnapshot = {
+ operationId: 'op-1',
+ traceId: 'tr-1',
+ startedAt: 1_000_000,
+ totalSteps: 2,
+ totalTokens: 0,
+ totalCost: 0,
+ steps: [
+ {
+ stepIndex: 0,
+ stepType: 'call_llm' as const,
+ content: 'Hello there.',
+ reasoning: 'Plan',
+ startedAt: 1_000_000,
+ completedAt: 1_000_500,
+ executionTimeMs: 500,
+ totalTokens: 0,
+ totalCost: 0,
+ toolsCalling: [{ identifier: 'lobe-todo-write', apiName: 'addTodo', arguments: '{}' }],
+ },
+ {
+ stepIndex: 1,
+ stepType: 'call_tool' as const,
+ startedAt: 1_000_500,
+ completedAt: 1_000_700,
+ executionTimeMs: 200,
+ totalTokens: 0,
+ totalCost: 0,
+ toolsResult: [
+ {
+ identifier: 'lobe-todo-write',
+ apiName: 'addTodo',
+ state: { success: true },
+ },
+ ],
+ },
+ ],
+};
+
+const typesOf = (events: MockEvent[]) => events.map((e) => e.type);
+
+describe('snapshotToEvents', () => {
+ it('emits agent_runtime_init at start and agent_runtime_end at end', () => {
+ const events = snapshotToEvents(minimalSnapshot as any, { targetChunkChars: 5 });
+ expect(events[0].type).toBe('agent_runtime_init');
+ expect(events.at(-1)?.type).toBe('agent_runtime_end');
+ });
+
+ it('expands call_llm into stream_start → chunks → stream_end', () => {
+ const events = snapshotToEvents(minimalSnapshot as any, { targetChunkChars: 5 });
+ const llmStep = events.filter((e) => e.type.startsWith('stream_'));
+ expect(llmStep[0].type).toBe('stream_start');
+ expect(llmStep.at(-1)?.type).toBe('stream_end');
+ const chunks = llmStep.filter((e) => e.type === 'stream_chunk');
+ expect(chunks.length).toBeGreaterThan(0);
+ });
+
+ it('emits tools_calling chunk near end of LLM step', () => {
+ const events = snapshotToEvents(minimalSnapshot as any, { targetChunkChars: 5 });
+ const toolsCallingChunk = events.find(
+ (e) =>
+ e.type === 'stream_chunk' &&
+ (e.data as { chunkType: string }).chunkType === 'tools_calling',
+ );
+ expect(toolsCallingChunk).toBeDefined();
+ });
+
+ it('expands call_tool into tool_start → tool_end per tool', () => {
+ const events = snapshotToEvents(minimalSnapshot as any, { targetChunkChars: 5 });
+ const toolEvents = events.filter((e) => e.type === 'tool_start' || e.type === 'tool_end');
+ expect(toolEvents.map((e) => e.type)).toEqual(['tool_start', 'tool_end']);
+ });
+
+ it('wraps step with step_start and step_complete', () => {
+ const events = snapshotToEvents(minimalSnapshot as any, { targetChunkChars: 5 });
+ expect(typesOf(events)).toContain('step_start');
+ expect(typesOf(events).filter((t) => t === 'step_complete').length).toBe(2);
+ });
+
+ it('preserves stepIndex on all events of a step', () => {
+ const events = snapshotToEvents(minimalSnapshot as any, { targetChunkChars: 5 });
+ const step1Events = events.filter((e) => (e as any).stepIndex === 1);
+ expect(step1Events.every((e) => (e as any).stepIndex === 1)).toBe(true);
+ });
+
+ it('computes per-event delay so step duration ~= executionTimeMs', () => {
+ const events = snapshotToEvents(minimalSnapshot as any, { targetChunkChars: 5 });
+ const totalDelay = events.reduce((sum, e) => sum + (e.delay ?? 0), 0);
+ // 500ms LLM + 200ms tool = 700ms
+ expect(totalDelay).toBeGreaterThanOrEqual(600);
+ expect(totalDelay).toBeLessThanOrEqual(800);
+ });
+});
diff --git a/packages/agent-mock/src/snapshot/snapshotToEvents.ts b/packages/agent-mock/src/snapshot/snapshotToEvents.ts
new file mode 100644
index 00000000000..c8ffa7efc22
--- /dev/null
+++ b/packages/agent-mock/src/snapshot/snapshotToEvents.ts
@@ -0,0 +1,159 @@
+import type { ExecutionSnapshot, StepSnapshot } from '@lobechat/agent-tracing';
+
+import type { MockEvent } from '../types';
+import { splitTextIntoChunks } from './chunkSplitter';
+
+export interface SnapshotToEventsOptions {
+ jitter?: number;
+ targetChunkChars?: number;
+}
+
+const CLIENT_TOOL_IDENTIFIERS = new Set(['lobe-local-system', 'lobe-page-agent']);
+
+const isClientTool = (identifier: string) => CLIENT_TOOL_IDENTIFIERS.has(identifier);
+
+export function snapshotToEvents(
+ snapshot: ExecutionSnapshot,
+ opts: SnapshotToEventsOptions = {},
+): MockEvent[] {
+ const targetChunkChars = opts.targetChunkChars ?? 30;
+ const jitter = opts.jitter ?? 0.15;
+ const events: MockEvent[] = [];
+
+ const operationId = snapshot.operationId;
+ const assistantMessageId = `mock-msg-${operationId}-0`;
+
+ events.push({
+ type: 'agent_runtime_init',
+ data: { operationId },
+ delay: 0,
+ });
+
+ for (let i = 0; i < snapshot.steps.length; i++) {
+ const step = snapshot.steps[i];
+ const isLast = i === snapshot.steps.length - 1;
+ appendStep(events, step, { assistantMessageId, targetChunkChars, jitter });
+ if (isLast) {
+ events.push({ type: 'agent_runtime_end', data: { reason: 'done' }, delay: 0 });
+ }
+ }
+
+ return events;
+}
+
+interface AppendCtx {
+ assistantMessageId: string;
+ jitter: number;
+ targetChunkChars: number;
+}
+
+function appendStep(out: MockEvent[], step: StepSnapshot, ctx: AppendCtx) {
+ out.push({
+ type: 'step_start',
+ data: { stepIndex: step.stepIndex, stepType: step.stepType },
+ delay: 0,
+ });
+
+ if (step.stepType === 'call_llm') {
+ appendLlmStep(out, step, ctx);
+ } else {
+ appendToolStep(out, step);
+ }
+
+ out.push({
+ type: 'step_complete',
+ data: { stepIndex: step.stepIndex, phase: step.stepType, reason: 'completed' },
+ delay: 0,
+ });
+}
+
+function appendLlmStep(out: MockEvent[], step: StepSnapshot, ctx: AppendCtx) {
+ out.push({
+ type: 'stream_start',
+ data: { assistantMessage: { id: ctx.assistantMessageId } },
+ delay: 0,
+ });
+
+ const reasoningChunks = step.reasoning
+ ? splitTextIntoChunks(step.reasoning, {
+ targetChunkChars: ctx.targetChunkChars,
+ jitter: ctx.jitter,
+ })
+ : [];
+ const textChunks = step.content
+ ? splitTextIntoChunks(step.content, {
+ targetChunkChars: ctx.targetChunkChars,
+ jitter: ctx.jitter,
+ })
+ : [];
+
+ const toolsCallingChunkCount = step.toolsCalling?.length ? 1 : 0;
+ const totalChunks = reasoningChunks.length + textChunks.length + toolsCallingChunkCount;
+ const perChunkDelay =
+ totalChunks > 0 ? Math.max(1, Math.floor(step.executionTimeMs / totalChunks)) : 0;
+
+ for (const r of reasoningChunks) {
+ out.push({
+ type: 'stream_chunk',
+ data: { chunkType: 'reasoning', reasoning: r },
+ delay: perChunkDelay,
+ });
+ }
+ for (const t of textChunks) {
+ out.push({
+ type: 'stream_chunk',
+ data: { chunkType: 'text', content: t },
+ delay: perChunkDelay,
+ });
+ }
+ if (step.toolsCalling?.length) {
+ out.push({
+ type: 'stream_chunk',
+ data: { chunkType: 'tools_calling', toolsCalling: step.toolsCalling },
+ delay: perChunkDelay,
+ });
+ }
+
+ out.push({ type: 'stream_end', data: {}, delay: 0 });
+}
+
+function appendToolStep(out: MockEvent[], step: StepSnapshot) {
+ const tools = step.toolsResult ?? [];
+ const perToolDelay =
+ tools.length > 0 ? Math.max(1, Math.floor(step.executionTimeMs / tools.length)) : 0;
+
+ tools.forEach((t, idx) => {
+ const toolCallId = `mock-tc-${step.stepIndex}-${idx}`;
+ out.push({
+ type: 'tool_start',
+ data: {
+ parentMessageId: `mock-msg-${step.stepIndex - 1}`,
+ toolCalling: { id: toolCallId, identifier: t.identifier, apiName: t.apiName },
+ },
+ delay: 0,
+ });
+ if (isClientTool(t.identifier)) {
+ out.push({
+ type: 'tool_execute',
+ data: {
+ identifier: t.identifier,
+ apiName: t.apiName,
+ arguments: '{}',
+ toolCallId,
+ executionTimeoutMs: 30_000,
+ },
+ delay: 0,
+ });
+ }
+ out.push({
+ type: 'tool_end',
+ data: {
+ isSuccess: !(t as any).error,
+ result: (t as any).state,
+ payload: { state: (t as any).state },
+ },
+ delay: perToolDelay,
+ label: `tool:${t.apiName}#${idx}`,
+ });
+ });
+}
diff --git a/packages/agent-mock/src/types.ts b/packages/agent-mock/src/types.ts
new file mode 100644
index 00000000000..001f69d8ceb
--- /dev/null
+++ b/packages/agent-mock/src/types.ts
@@ -0,0 +1,45 @@
+import type { AgentStreamEventType } from '@lobechat/agent-gateway-client';
+
+export interface MockCase {
+ description?: string;
+ id: string;
+ meta?: {
+ toolCount?: number;
+ stepCount?: number;
+ estimatedDurationMs?: number;
+ };
+ name: string;
+ source: MockCaseSource;
+ tags?: string[];
+}
+
+export type MockCaseSource =
+ | { type: 'snapshot'; path: string; events?: MockEvent[] }
+ | { type: 'fixture'; events: MockEvent[] }
+ | { type: 'generator'; factoryId: string; params: unknown; events?: MockEvent[] };
+
+export interface MockEvent {
+ data: unknown;
+ /** ms relative to previous event */
+ delay?: number;
+ /** label for timeline jumps, e.g. 'tool:TodoWrite#3' */
+ label?: string;
+ type: AgentStreamEventType;
+}
+
+export type PlaybackStatus = 'idle' | 'running' | 'paused' | 'complete' | 'error';
+export type SpeedMultiplier = 0.5 | 1 | 2 | 5 | 'instant';
+
+export interface PlaybackState {
+ currentEventIndex: number;
+ currentStepIndex: number;
+ elapsedMs: number;
+ errorMessage?: string;
+ speedMultiplier: SpeedMultiplier;
+ status: PlaybackStatus;
+ toolsExecuted: number;
+ totalDurationMs: number;
+ totalEvents: number;
+ totalSteps: number;
+ totalTools: number;
+}
diff --git a/packages/agent-mock/tsconfig.json b/packages/agent-mock/tsconfig.json
new file mode 100644
index 00000000000..1b9d693dc98
--- /dev/null
+++ b/packages/agent-mock/tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "compilerOptions": {
+ "outDir": "./dist"
+ },
+ "extends": "../../tsconfig.json",
+ "include": ["src/**/*.ts"]
+}
diff --git a/packages/agent-mock/vitest.config.mts b/packages/agent-mock/vitest.config.mts
new file mode 100644
index 00000000000..8c4481a3756
--- /dev/null
+++ b/packages/agent-mock/vitest.config.mts
@@ -0,0 +1,18 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ coverage: {
+ exclude: [
+ 'coverage/**',
+ 'dist/**',
+ '**/node_modules/**',
+ '**/*.d.ts',
+ '**/*.config.*',
+ '**/index.ts',
+ ],
+ reporter: ['text', 'json', 'lcov', 'text-summary'],
+ },
+ environment: 'happy-dom',
+ },
+});
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 73431d841b4..511c8a9a1c4 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -5,8 +5,9 @@ packages:
- apps/desktop/src/main
onlyBuiltDependencies:
- - '@vercel/speed-insights'
+ - '@google/genai'
- '@lobehub/editor'
+ - '@vercel/speed-insights'
overrides:
jose: ^6.1.3
diff --git a/src/app/(backend)/api/dev/agent-tracing/route.ts b/src/app/(backend)/api/dev/agent-tracing/route.ts
new file mode 100644
index 00000000000..b7ef9525c96
--- /dev/null
+++ b/src/app/(backend)/api/dev/agent-tracing/route.ts
@@ -0,0 +1,37 @@
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+
+import { NextResponse } from 'next/server';
+
+const TRACING_DIR = '.agent-tracing';
+
+export async function GET(req: Request) {
+ if (process.env.NODE_ENV !== 'development') {
+ return NextResponse.json({ error: 'dev only' }, { status: 404 });
+ }
+
+ const url = new URL(req.url);
+ const file = url.searchParams.get('file');
+ const root = path.resolve(process.cwd(), TRACING_DIR);
+
+ if (file) {
+ const safe = path.basename(file);
+ const fullPath = path.join(root, safe);
+ try {
+ const content = await fs.readFile(fullPath, 'utf8');
+ return new NextResponse(content, {
+ headers: { 'content-type': 'application/json' },
+ });
+ } catch {
+ return NextResponse.json({ error: 'not found' }, { status: 404 });
+ }
+ }
+
+ try {
+ const files = await fs.readdir(root);
+ const items = files.filter((f) => f.endsWith('.json') && f !== 'latest.json');
+ return NextResponse.json({ files: items });
+ } catch {
+ return NextResponse.json({ files: [] });
+ }
+}
diff --git a/src/features/AgentMockDevtools/CaseTrigger.tsx b/src/features/AgentMockDevtools/CaseTrigger.tsx
new file mode 100644
index 00000000000..0c648e2c037
--- /dev/null
+++ b/src/features/AgentMockDevtools/CaseTrigger.tsx
@@ -0,0 +1,229 @@
+import type { MockCase } from '@lobechat/agent-mock';
+import { Flexbox, Input, Popover, Text, usePopoverContext } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { ChevronDown } from 'lucide-react';
+import { memo, type ReactNode, useMemo, useState } from 'react';
+
+import { useMockCases } from './hooks/useMockCases';
+import { useAgentMockStore } from './store/agentMockStore';
+
+const styles = createStaticStyles(({ css }) => ({
+ empty: css`
+ padding: 16px;
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ text-align: center;
+ `,
+ group: css`
+ padding-block: 8px 4px;
+ padding-inline: 12px;
+
+ font-size: 11px;
+ font-weight: 500;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ item: css`
+ cursor: pointer;
+
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ justify-content: space-between;
+
+ padding-block: 6px;
+ padding-inline: 12px;
+ border-inline-start: 1px solid transparent;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ itemActive: css`
+ border-inline-start-color: ${cssVar.colorText};
+ font-weight: 500;
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillSecondary};
+ `,
+ itemMeta: css`
+ flex-shrink: 0;
+ font-size: 11px;
+ font-feature-settings: 'tnum';
+ color: ${cssVar.colorTextTertiary};
+ `,
+ itemName: css`
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ list: css`
+ overflow-y: auto;
+ max-height: 360px;
+ padding-block: 4px;
+ `,
+ panel: css`
+ width: 320px;
+ `,
+ search: css`
+ padding-block: 8px 4px;
+ padding-inline: 8px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ trigger: css`
+ cursor: pointer;
+ user-select: none;
+
+ display: inline-flex;
+ gap: 6px;
+ align-items: center;
+
+ max-width: 240px;
+ padding-block: 4px;
+ padding-inline: 8px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 6px;
+
+ font-size: 12px;
+ font-weight: 500;
+ color: ${cssVar.colorText};
+
+ background: ${cssVar.colorBgContainer};
+
+ &:hover {
+ border-color: ${cssVar.colorBorder};
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ triggerName: css`
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ triggerPlaceholder: css`
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
+const countTools = (c: MockCase): number => {
+ if (typeof c.meta?.toolCount === 'number') return c.meta.toolCount;
+ const events = sourceEvents(c);
+ return events.filter((e) => e.type === 'tool_start').length;
+};
+
+const sourceEvents = (c: MockCase) => {
+ if (c.source.type === 'fixture') return c.source.events;
+ if (c.source.type === 'snapshot') return c.source.events ?? [];
+ if (c.source.type === 'generator') return c.source.events ?? [];
+ return [];
+};
+
+interface CasePanelProps {
+ selectedCaseId: string | null;
+ setSelectedCaseId: (id: string) => void;
+}
+
+const CasePanel = memo<CasePanelProps>(({ selectedCaseId, setSelectedCaseId }) => {
+ const { builtins, snapshots, generated } = useMockCases();
+ const { close } = usePopoverContext();
+ const [query, setQuery] = useState('');
+
+ const groups = useMemo(() => {
+ const needle = query.toLowerCase();
+ const match = (arr: MockCase[]) =>
+ needle ? arr.filter((c) => c.name.toLowerCase().includes(needle)) : arr;
+ return [
+ { items: match(builtins), key: 'builtin', label: 'Builtin' },
+ { items: match(snapshots), key: 'snapshots', label: 'Snapshots' },
+ { items: match(generated), key: 'generated', label: 'Generated' },
+ ];
+ }, [builtins, snapshots, generated, query]);
+
+ const totalVisible = groups.reduce((sum, g) => sum + g.items.length, 0);
+
+ const handlePick = (id: string) => {
+ setSelectedCaseId(id);
+ close();
+ };
+
+ return (
+ <div className={styles.panel}>
+ <div className={styles.search}>
+ <Input
+ autoFocus
+ placeholder="Search cases…"
+ size="small"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ />
+ </div>
+ <div className={styles.list}>
+ {totalVisible === 0 && <div className={styles.empty}>No cases match.</div>}
+ {groups.map((group) =>
+ group.items.length === 0 ? null : (
+ <Flexbox key={group.key} style={{ paddingBlockEnd: 4 }}>
+ <div className={styles.group}>
+ {group.label} ({group.items.length})
+ </div>
+ {group.items.map((c) => {
+ const active = selectedCaseId === c.id;
+ const events = sourceEvents(c).length;
+ const tools = countTools(c);
+ return (
+ <div
+ className={`${styles.item} ${active ? styles.itemActive : ''}`}
+ key={c.id}
+ onClick={() => handlePick(c.id)}
+ >
+ <span className={styles.itemName}>{c.name}</span>
+ <span className={styles.itemMeta}>
+ {events}e · {tools}t
+ </span>
+ </div>
+ );
+ })}
+ </Flexbox>
+ ),
+ )}
+ </div>
+ </div>
+ );
+});
+
+CasePanel.displayName = 'AgentMockCasePanel';
+
+interface CaseTriggerProps {
+ children?: ReactNode;
+ placement?: 'bottomLeft' | 'bottomRight' | 'topLeft' | 'topRight';
+}
+
+export const CaseTrigger = memo<CaseTriggerProps>(({ children, placement = 'bottomLeft' }) => {
+ const selectedCaseId = useAgentMockStore((s) => s.selectedCaseId);
+ const setSelectedCaseId = useAgentMockStore((s) => s.setSelectedCaseId);
+ const { all } = useMockCases();
+ const current = all.find((c) => c.id === selectedCaseId);
+
+ return (
+ <Popover
+ arrow={false}
+ content={<CasePanel selectedCaseId={selectedCaseId} setSelectedCaseId={setSelectedCaseId} />}
+ placement={placement}
+ styles={{ content: { padding: 0 } }}
+ trigger={['click']}
+ >
+ {children ?? (
+ <span className={styles.trigger}>
+ {current ? (
+ <span className={styles.triggerName}>{current.name}</span>
+ ) : (
+ <Text className={styles.triggerPlaceholder}>Pick a case</Text>
+ )}
+ <ChevronDown size={12} />
+ </span>
+ )}
+ </Popover>
+ );
+});
+
+CaseTrigger.displayName = 'AgentMockCaseTrigger';
diff --git a/src/features/AgentMockDevtools/DevtoolsLayout.tsx b/src/features/AgentMockDevtools/DevtoolsLayout.tsx
new file mode 100644
index 00000000000..d86458fe0e0
--- /dev/null
+++ b/src/features/AgentMockDevtools/DevtoolsLayout.tsx
@@ -0,0 +1,166 @@
+import { Flexbox, Segmented, Tag, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
+
+import { CaseTrigger } from './CaseTrigger';
+import { StatsStrip } from './components/StatsStrip';
+import { StatusPill } from './components/StatusPill';
+import { TransportBar } from './components/TransportBar';
+import { useAgentMockPlayer } from './hooks/useAgentMockPlayer';
+import { useAgentMockReplayTarget } from './hooks/useAgentMockReplayTarget';
+import { useMockCases } from './hooks/useMockCases';
+import { type DevtoolsTab, useAgentMockStore } from './store/agentMockStore';
+import { FixtureView } from './views/FixtureView';
+import { TimelineView } from './views/TimelineView';
+
+const TAB_OPTIONS: Array<{ label: string; value: DevtoolsTab }> = [
+ { label: 'Timeline', value: 'timeline' },
+ { label: 'Fixture', value: 'fixture' },
+];
+
+const styles = createStaticStyles(({ css }) => ({
+ body: css`
+ overflow: hidden;
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ gap: 12px;
+
+ padding: 16px;
+ `,
+ hint: css`
+ font-size: 11px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ layout: css`
+ display: flex;
+ flex-direction: column;
+ height: min(720px, 80vh);
+ min-height: 480px;
+ `,
+ meta: css`
+ overflow: hidden;
+ flex: 1;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ rowOne: css`
+ padding-block: 12px;
+ padding-inline: 16px;
+ `,
+ rowTwo: css`
+ padding-block: 8px;
+ padding-inline: 16px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ view: css`
+ overflow: hidden;
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+
+ min-height: 0;
+ `,
+}));
+
+export const DevtoolsLayout = memo(() => {
+ const activeTab = useAgentMockStore((s) => s.activeTab);
+ const setActiveTab = useAgentMockStore((s) => s.setActiveTab);
+ const playback = useAgentMockStore((s) => s.playback);
+ const speed = useAgentMockStore((s) => s.speed);
+ const selectedCaseId = useAgentMockStore((s) => s.selectedCaseId);
+ const loop = useAgentMockStore((s) => s.loop);
+
+ const { all } = useMockCases();
+ const selected = all.find((c) => c.id === selectedCaseId);
+
+ const { start } = useAgentMockPlayer();
+ const resolveReplayTarget = useAgentMockReplayTarget();
+
+ const lastReplayedId = useRef<string | null>(null);
+
+ const launchCase = useCallback(() => {
+ if (!selected) return;
+ const { agentId, threadId, topicId } = resolveReplayTarget();
+ if (!agentId || !topicId) return;
+ start({ agentId, case: selected, threadId, topicId });
+ }, [resolveReplayTarget, selected, start]);
+
+ useEffect(() => {
+ if (!loop) {
+ lastReplayedId.current = null;
+ return;
+ }
+ if (!playback || playback.status !== 'complete') return;
+ if (!selected) return;
+ if (lastReplayedId.current === selected.id) return;
+ lastReplayedId.current = selected.id;
+ launchCase();
+ }, [loop, playback, selected, launchCase]);
+
+ useEffect(() => {
+ if (playback?.status === 'running') {
+ lastReplayedId.current = null;
+ }
+ }, [playback?.status]);
+
+ const meta = useMemo(() => {
+ if (!selected) return null;
+ const events =
+ selected.source.type === 'fixture'
+ ? selected.source.events.length
+ : (selected.source.events?.length ?? 0);
+ const tools = selected.meta?.toolCount;
+ const totalSec = selected.meta?.estimatedDurationMs
+ ? `~${(selected.meta.estimatedDurationMs / 1000).toFixed(1)}s`
+ : null;
+ return [`${events} events`, tools != null ? `${tools} tools` : null, totalSec]
+ .filter(Boolean)
+ .join(' · ');
+ }, [selected]);
+
+ return (
+ <div className={styles.layout}>
+ <Flexbox horizontal align="center" className={styles.rowOne} gap={12}>
+ <CaseTrigger />
+ <span className={styles.meta}>
+ {selected ? (
+ <Flexbox horizontal align="center" gap={8}>
+ {selected.tags?.map((t) => (
+ <Tag key={t}>{t}</Tag>
+ ))}
+ {meta && <Text type="secondary">{meta}</Text>}
+ </Flexbox>
+ ) : (
+ <Text type="secondary">No case selected</Text>
+ )}
+ </span>
+ <StatusPill playback={playback} speed={speed} />
+ </Flexbox>
+
+ <Flexbox horizontal align="center" className={styles.rowTwo} justify="space-between">
+ <Segmented
+ options={TAB_OPTIONS}
+ size="small"
+ value={activeTab}
+ onChange={(value) => setActiveTab(value as DevtoolsTab)}
+ />
+ <span className={styles.hint}>⌘K open palette</span>
+ </Flexbox>
+
+ <div className={styles.body}>
+ <StatsStrip />
+ <div className={styles.view}>
+ {activeTab === 'timeline' ? <TimelineView /> : <FixtureView />}
+ </div>
+ </div>
+
+ <TransportBar />
+ </div>
+ );
+});
+
+DevtoolsLayout.displayName = 'AgentMockDevtoolsLayout';
diff --git a/src/features/AgentMockDevtools/Fab.tsx b/src/features/AgentMockDevtools/Fab.tsx
new file mode 100644
index 00000000000..af716d44b21
--- /dev/null
+++ b/src/features/AgentMockDevtools/Fab.tsx
@@ -0,0 +1,103 @@
+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/Modal.tsx b/src/features/AgentMockDevtools/Modal.tsx
new file mode 100644
index 00000000000..9ac57b34822
--- /dev/null
+++ b/src/features/AgentMockDevtools/Modal.tsx
@@ -0,0 +1,36 @@
+import type { ModalInstance } from '@lobehub/ui/base-ui';
+import { createModal } from '@lobehub/ui/base-ui';
+import { memo, useEffect, useRef } from 'react';
+
+import { DevtoolsLayout } from './DevtoolsLayout';
+import { useAgentMockStore } from './store/agentMockStore';
+
+export const Modal = memo(() => {
+ const modalOpen = useAgentMockStore((s) => s.modalOpen);
+ const setModalOpen = useAgentMockStore((s) => s.setModalOpen);
+ const instanceRef = useRef<ModalInstance | null>(null);
+
+ useEffect(() => {
+ if (modalOpen && !instanceRef.current) {
+ instanceRef.current = createModal({
+ content: <DevtoolsLayout />,
+ footer: null,
+ onOpenChange: (open) => {
+ if (!open) setModalOpen(false);
+ },
+ onOpenChangeComplete: (open) => {
+ if (!open) instanceRef.current = null;
+ },
+ styles: { content: { padding: 0 } },
+ title: 'Agent Mock DevTools',
+ width: 'min(1280px, 92vw)',
+ });
+ } else if (!modalOpen && instanceRef.current) {
+ instanceRef.current.close();
+ }
+ }, [modalOpen, setModalOpen]);
+
+ return null;
+});
+
+Modal.displayName = 'AgentMockModal';
diff --git a/src/features/AgentMockDevtools/Popover.tsx b/src/features/AgentMockDevtools/Popover.tsx
new file mode 100644
index 00000000000..15cda267e6d
--- /dev/null
+++ b/src/features/AgentMockDevtools/Popover.tsx
@@ -0,0 +1,473 @@
+import { ActionIcon, Button, Flexbox, toast } from '@lobehub/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/Timeline/EventRow.tsx b/src/features/AgentMockDevtools/Timeline/EventRow.tsx
new file mode 100644
index 00000000000..e7cd9db4f87
--- /dev/null
+++ b/src/features/AgentMockDevtools/Timeline/EventRow.tsx
@@ -0,0 +1,103 @@
+import type { MockEvent } from '@lobechat/agent-mock';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo } from 'react';
+
+type EventTone = 'info' | 'neutral' | 'muted' | 'error';
+
+const TONE_BY_TYPE: Record<string, EventTone> = {
+ error: 'error',
+ step_complete: 'neutral',
+ step_start: 'neutral',
+ stream_chunk: 'neutral',
+ stream_end: 'muted',
+ stream_start: 'muted',
+ tool_end: 'info',
+ tool_execute: 'info',
+ tool_start: 'info',
+};
+
+const toneVar: Record<EventTone, string> = {
+ error: cssVar.colorError,
+ info: cssVar.colorText,
+ muted: cssVar.colorTextQuaternary,
+ neutral: cssVar.colorTextTertiary,
+};
+
+const styles = createStaticStyles(({ css }) => ({
+ active: css`
+ background: ${cssVar.colorFillSecondary};
+ `,
+ dot: css`
+ width: 6px;
+ height: 6px;
+ margin-block-start: 5px;
+ border-radius: 50%;
+ `,
+ preview: css`
+ overflow: hidden;
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ row: css`
+ cursor: pointer;
+
+ display: grid;
+ grid-template-columns: 64px 16px 140px 1fr;
+ gap: 8px;
+
+ padding-block: 4px;
+ padding-inline: 12px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ font-size: 11px;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ type: css`
+ color: ${cssVar.colorTextSecondary};
+ `,
+}));
+
+interface Props {
+ cumulativeMs: number;
+ event: MockEvent;
+ index: number;
+ isActive: boolean;
+ onClick?: () => void;
+}
+
+const previewOf = (event: MockEvent): string => {
+ const data =
+ typeof event.data === 'object' && event.data !== null
+ ? (event.data as Record<string, unknown>)
+ : {};
+ if (event.type === 'stream_chunk') {
+ return String(data.content ?? data.reasoning ?? data.chunkType ?? '').slice(0, 100);
+ }
+ if (event.type === 'tool_start' || event.type === 'tool_end') {
+ return JSON.stringify(data).slice(0, 100);
+ }
+ if (event.type === 'error') return String(data.message ?? '');
+ return JSON.stringify(data).slice(0, 80);
+};
+
+export const EventRow = memo<Props>(({ event, index, cumulativeMs, isActive, onClick }) => {
+ const tone = TONE_BY_TYPE[event.type] ?? 'neutral';
+
+ return (
+ <div className={`${styles.row} ${isActive ? styles.active : ''}`} onClick={onClick}>
+ <span className={styles.type}>+{(cumulativeMs / 1000).toFixed(2)}s</span>
+ <span className={styles.dot} style={{ background: toneVar[tone] }} />
+ <span className={styles.type}>
+ #{index} {event.type}
+ </span>
+ <span className={styles.preview}>{previewOf(event)}</span>
+ </div>
+ );
+});
+
+EventRow.displayName = 'AgentMockEventRow';
diff --git a/src/features/AgentMockDevtools/components/StatsStrip.tsx b/src/features/AgentMockDevtools/components/StatsStrip.tsx
new file mode 100644
index 00000000000..a087feb9102
--- /dev/null
+++ b/src/features/AgentMockDevtools/components/StatsStrip.tsx
@@ -0,0 +1,82 @@
+import { Flexbox } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo } from 'react';
+
+import { useAgentMockStore } from '../store/agentMockStore';
+
+const styles = createStaticStyles(({ css }) => ({
+ card: css`
+ flex: 1;
+
+ padding: 12px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 8px;
+
+ background: ${cssVar.colorBgContainer};
+ `,
+ empty: css`
+ color: ${cssVar.colorTextTertiary};
+ `,
+ label: css`
+ margin-block-end: 4px;
+ font-size: 11px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ sub: css`
+ margin-block-start: 2px;
+ font-size: 11px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ value: css`
+ font-size: 18px;
+ font-feature-settings: 'tnum';
+ font-weight: 600;
+ color: ${cssVar.colorText};
+ `,
+}));
+
+const placeholder = '—';
+
+export const StatsStrip = memo(() => {
+ const playback = useAgentMockStore((s) => s.playback);
+ const speed = useAgentMockStore((s) => s.speed);
+
+ const stepValue = playback
+ ? `${playback.currentStepIndex + 1} / ${playback.totalSteps}`
+ : placeholder;
+ const eventValue = playback
+ ? `${playback.currentEventIndex} / ${playback.totalEvents}`
+ : placeholder;
+ const toolValue = playback ? `${playback.toolsExecuted} / ${playback.totalTools}` : placeholder;
+ const elapsed = playback ? `${(playback.elapsedMs / 1000).toFixed(1)}s` : placeholder;
+ const total = playback ? `${(playback.totalDurationMs / 1000).toFixed(1)}s` : placeholder;
+ const speedLabel = speed === 'instant' ? '∞' : `${speed}×`;
+ const status = playback?.status ?? 'idle';
+
+ return (
+ <Flexbox horizontal gap={12}>
+ <div className={styles.card}>
+ <div className={styles.label}>Step</div>
+ <div className={`${styles.value} ${playback ? '' : styles.empty}`}>{stepValue}</div>
+ <div className={styles.sub}>{status}</div>
+ </div>
+ <div className={styles.card}>
+ <div className={styles.label}>Event</div>
+ <div className={`${styles.value} ${playback ? '' : styles.empty}`}>{eventValue}</div>
+ </div>
+ <div className={styles.card}>
+ <div className={styles.label}>Tools</div>
+ <div className={`${styles.value} ${playback ? '' : styles.empty}`}>{toolValue}</div>
+ </div>
+ <div className={styles.card}>
+ <div className={styles.label}>Elapsed</div>
+ <div className={`${styles.value} ${playback ? '' : styles.empty}`}>{elapsed}</div>
+ <div className={styles.sub}>
+ @ {speedLabel} · total {total}
+ </div>
+ </div>
+ </Flexbox>
+ );
+});
+
+StatsStrip.displayName = 'AgentMockStatsStrip';
diff --git a/src/features/AgentMockDevtools/components/StatusPill.tsx b/src/features/AgentMockDevtools/components/StatusPill.tsx
new file mode 100644
index 00000000000..045c3b7c4f6
--- /dev/null
+++ b/src/features/AgentMockDevtools/components/StatusPill.tsx
@@ -0,0 +1,71 @@
+import type { PlaybackState } from '@lobechat/agent-mock';
+import { Flexbox } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo, useMemo } from 'react';
+
+const styles = createStaticStyles(({ css }) => ({
+ dot: css`
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ `,
+ dotIdle: css`
+ background: ${cssVar.colorTextTertiary};
+ `,
+ dotPlaying: css`
+ background: ${cssVar.colorText};
+ box-shadow: 0 0 0 3px ${cssVar.colorFillTertiary};
+ `,
+ dotError: css`
+ background: ${cssVar.colorError};
+ `,
+ pill: css`
+ display: inline-flex;
+ gap: 8px;
+ align-items: center;
+
+ padding-block: 3px;
+ padding-inline: 10px;
+ border-radius: 999px;
+
+ font-size: 11px;
+ font-feature-settings: 'tnum';
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorFillTertiary};
+ `,
+}));
+
+interface StatusPillProps {
+ playback: PlaybackState | null;
+ speed: PlaybackState['speedMultiplier'];
+}
+
+export const StatusPill = memo<StatusPillProps>(({ playback, speed }) => {
+ const tone = useMemo<'idle' | 'playing' | 'error'>(() => {
+ if (!playback) return 'idle';
+ if (playback.status === 'error') return 'error';
+ if (playback.status === 'running' || playback.status === 'complete') return 'playing';
+ return 'idle';
+ }, [playback]);
+
+ const dotClass =
+ tone === 'error' ? styles.dotError : tone === 'playing' ? styles.dotPlaying : styles.dotIdle;
+
+ const speedLabel = speed === 'instant' ? '∞' : `${speed}×`;
+
+ return (
+ <Flexbox horizontal align="center" className={styles.pill} gap={8}>
+ <span className={`${styles.dot} ${dotClass}`} />
+ {playback ? (
+ <span>
+ {playback.currentEventIndex}/{playback.totalEvents} · {speedLabel}
+ </span>
+ ) : (
+ <span>idle · {speedLabel}</span>
+ )}
+ </Flexbox>
+ );
+});
+
+StatusPill.displayName = 'AgentMockStatusPill';
diff --git a/src/features/AgentMockDevtools/components/TransportBar.tsx b/src/features/AgentMockDevtools/components/TransportBar.tsx
new file mode 100644
index 00000000000..30c4987ce88
--- /dev/null
+++ b/src/features/AgentMockDevtools/components/TransportBar.tsx
@@ -0,0 +1,218 @@
+import type { SpeedMultiplier } from '@lobechat/agent-mock';
+import { ActionIcon, Dropdown, Flexbox, Segmented, toast } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { Pause, Play, Repeat, RotateCcw, SkipForward } from 'lucide-react';
+import { memo, useCallback, useMemo, useRef } from 'react';
+
+import { useAgentMockPlayer } from '../hooks/useAgentMockPlayer';
+import { useAgentMockReplayTarget } from '../hooks/useAgentMockReplayTarget';
+import { useMockCases } from '../hooks/useMockCases';
+import { useAgentMockStore } from '../store/agentMockStore';
+
+const SPEED_OPTIONS: Array<{ label: string; value: SpeedMultiplier }> = [
+ { label: '0.5×', value: 0.5 },
+ { label: '1×', value: 1 },
+ { label: '2×', value: 2 },
+ { label: '5×', value: 5 },
+ { label: '∞', value: 'instant' },
+];
+
+const styles = createStaticStyles(({ css }) => ({
+ bar: css`
+ padding-block: 12px;
+ padding-inline: 16px;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ loopOn: css`
+ color: ${cssVar.colorBgContainer};
+ background: ${cssVar.colorText};
+
+ &:hover {
+ color: ${cssVar.colorBgContainer};
+ background: ${cssVar.colorText};
+ }
+ `,
+ progress: css`
+ cursor: pointer;
+
+ flex: 1;
+
+ height: 6px;
+ border-radius: 3px;
+
+ background: ${cssVar.colorFillSecondary};
+ `,
+ progressFill: css`
+ height: 100%;
+ border-radius: inherit;
+ background: ${cssVar.colorText};
+ transition: width 0.16s linear;
+ `,
+ progressTrack: css`
+ position: relative;
+ overflow: hidden;
+ height: 100%;
+ `,
+ time: css`
+ min-width: 64px;
+
+ font-size: 11px;
+ font-feature-settings: 'tnum';
+ color: ${cssVar.colorTextSecondary};
+ text-align: end;
+ `,
+}));
+
+export const TransportBar = memo(() => {
+ const { all } = useMockCases();
+ const selectedCaseId = useAgentMockStore((s) => s.selectedCaseId);
+ const playback = useAgentMockStore((s) => s.playback);
+ const speed = useAgentMockStore((s) => s.speed);
+ const setSpeedStore = useAgentMockStore((s) => s.setSpeed);
+ const loop = useAgentMockStore((s) => s.loop);
+ const setLoop = useAgentMockStore((s) => s.setLoop);
+
+ const { pause, resume, seekToEventIndex, setSpeed, start, stepEvent, stepStep, stepTool } =
+ useAgentMockPlayer();
+ const resolveReplayTarget = useAgentMockReplayTarget();
+
+ const trackRef = useRef<HTMLDivElement | null>(null);
+
+ const selected = all.find((c) => c.id === selectedCaseId);
+ const disabled = !selected;
+
+ const status = playback?.status;
+ const running = status === 'running';
+ const paused = status === 'paused';
+ const idleOrComplete = !playback || status === 'idle' || status === 'complete';
+
+ 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, paused, pause, resume, running]);
+
+ const handleReplay = useCallback(() => {
+ if (!selected) return;
+ if (playback && status !== 'idle') {
+ seekToEventIndex(0);
+ }
+ launchCase();
+ }, [launchCase, playback, seekToEventIndex, selected, status]);
+
+ const stepMenu = useMemo(
+ () => [
+ { key: 'event', label: 'Next event', onClick: stepEvent },
+ { key: 'step', label: 'Next step', onClick: stepStep },
+ { key: 'tool', label: 'Next tool', onClick: stepTool },
+ ],
+ [stepEvent, stepStep, stepTool],
+ );
+
+ const handleProgressClick = useCallback(
+ (e: React.MouseEvent<HTMLDivElement>) => {
+ if (!playback || playback.totalEvents === 0) return;
+ const el = trackRef.current;
+ if (!el) return;
+ const rect = el.getBoundingClientRect();
+ const ratio = Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width));
+ const idx = Math.round(ratio * playback.totalEvents);
+ seekToEventIndex(idx);
+ },
+ [playback, seekToEventIndex],
+ );
+
+ const pct = playback?.totalEvents
+ ? Math.min(100, (playback.currentEventIndex / playback.totalEvents) * 100)
+ : 0;
+
+ const elapsed = playback ? `${(playback.elapsedMs / 1000).toFixed(1)}s` : '0.0s';
+ const total = playback ? `${(playback.totalDurationMs / 1000).toFixed(1)}s` : '0.0s';
+
+ const playIcon = running ? Pause : Play;
+
+ return (
+ <Flexbox horizontal align="center" className={styles.bar} gap={12}>
+ <ActionIcon
+ disabled={disabled}
+ icon={playIcon}
+ size="small"
+ title={running ? 'Pause' : paused ? 'Resume' : 'Play'}
+ onClick={handlePlay}
+ />
+ <Dropdown
+ disabled={disabled}
+ placement="topLeft"
+ menu={{
+ items: stepMenu.map(({ key, label }) => ({ key, label })),
+ onClick: ({ key }) => stepMenu.find((m) => m.key === key)?.onClick(),
+ }}
+ >
+ <ActionIcon disabled={disabled} icon={SkipForward} size="small" title="Step" />
+ </Dropdown>
+ <ActionIcon
+ disabled={disabled}
+ icon={RotateCcw}
+ size="small"
+ title="Replay from start"
+ onClick={handleReplay}
+ />
+ <ActionIcon
+ active={loop}
+ aria-pressed={loop}
+ className={loop ? styles.loopOn : undefined}
+ icon={Repeat}
+ size="small"
+ title={loop ? 'Loop on' : 'Loop off'}
+ onClick={() => setLoop(!loop)}
+ />
+ <div
+ aria-valuemax={playback?.totalEvents ?? 0}
+ aria-valuemin={0}
+ aria-valuenow={playback?.currentEventIndex ?? 0}
+ className={styles.progress}
+ ref={trackRef}
+ role="slider"
+ tabIndex={0}
+ onClick={handleProgressClick}
+ >
+ <div className={styles.progressTrack}>
+ <div className={styles.progressFill} style={{ width: `${pct}%` }} />
+ </div>
+ </div>
+ <span className={styles.time}>
+ {elapsed} / {total}
+ </span>
+ <Segmented
+ disabled={disabled}
+ options={SPEED_OPTIONS}
+ size="small"
+ value={speed}
+ onChange={(value) => {
+ const next = value as SpeedMultiplier;
+ setSpeedStore(next);
+ setSpeed(next);
+ }}
+ />
+ </Flexbox>
+ );
+});
+
+TransportBar.displayName = 'AgentMockTransportBar';
diff --git a/src/features/AgentMockDevtools/hooks/createMockStoreInjector.test.ts b/src/features/AgentMockDevtools/hooks/createMockStoreInjector.test.ts
new file mode 100644
index 00000000000..5b792229d87
--- /dev/null
+++ b/src/features/AgentMockDevtools/hooks/createMockStoreInjector.test.ts
@@ -0,0 +1,121 @@
+import type { ConversationContext } from '@lobechat/types';
+import { act } from '@testing-library/react';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { useChatStore } from '@/store/chat/store';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+import { createMockStoreInjector } from './createMockStoreInjector';
+
+describe('createMockStoreInjector', () => {
+ beforeEach(() => {
+ useChatStore.setState({
+ activeAgentId: 'agent-1',
+ activeTopicId: undefined,
+ dbMessagesMap: {},
+ messageOperationMap: {},
+ messagesMap: {},
+ operations: {},
+ operationsByContext: {},
+ operationsByMessage: {},
+ operationsByType: {} as any,
+ toolCallingStreamIds: {},
+ });
+ });
+
+ it('writes mock stream chunks into the chat store message maps', () => {
+ const context = {
+ agentId: 'agent-1',
+ scope: 'main',
+ topicId: null,
+ } satisfies ConversationContext;
+
+ const { operationId } = useChatStore.getState().startOperation({
+ context,
+ type: 'execAgentRuntime',
+ });
+ const assistantMessageId = 'mock-msg-1';
+
+ useChatStore.getState().optimisticCreateTmpMessage(
+ {
+ agentId: context.agentId,
+ content: '',
+ role: 'assistant',
+ topicId: undefined,
+ },
+ { operationId, tempMessageId: assistantMessageId },
+ );
+
+ const inject = createMockStoreInjector(() => useChatStore.getState(), {
+ assistantMessageId,
+ context,
+ operationId,
+ });
+
+ act(() => {
+ inject({
+ data: { chunkType: 'text', content: 'hello' },
+ operationId,
+ stepIndex: 0,
+ timestamp: Date.now(),
+ type: 'stream_chunk',
+ });
+ });
+
+ const key = messageMapKey(context);
+ expect(useChatStore.getState().dbMessagesMap[key]).toMatchObject([
+ { content: 'hello', id: assistantMessageId, role: 'assistant' },
+ ]);
+ expect(useChatStore.getState().messagesMap[key]).toMatchObject([
+ { content: 'hello', id: assistantMessageId, role: 'assistant' },
+ ]);
+ });
+
+ it('writes stream chunks into a thread-scoped message bucket', () => {
+ const context = {
+ agentId: 'agent-1',
+ scope: 'thread',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ } satisfies ConversationContext;
+
+ const { operationId } = useChatStore.getState().startOperation({
+ context,
+ type: 'execAgentRuntime',
+ });
+ const assistantMessageId = 'mock-thread-msg-1';
+
+ useChatStore.getState().optimisticCreateTmpMessage(
+ {
+ agentId: context.agentId,
+ content: '',
+ role: 'assistant',
+ threadId: context.threadId,
+ topicId: context.topicId,
+ },
+ { operationId, tempMessageId: assistantMessageId },
+ );
+
+ const inject = createMockStoreInjector(() => useChatStore.getState(), {
+ assistantMessageId,
+ context,
+ operationId,
+ });
+
+ act(() => {
+ inject({
+ data: { chunkType: 'text', content: 'thread hello' },
+ operationId,
+ stepIndex: 0,
+ timestamp: Date.now(),
+ type: 'stream_chunk',
+ });
+ });
+
+ const key = messageMapKey(context);
+ expect(useChatStore.getState().dbMessagesMap[key]).toMatchObject([
+ { content: 'thread hello', id: assistantMessageId, role: 'assistant' },
+ ]);
+ expect(useChatStore.getState().dbMessagesMap['main_agent-1_topic-1']).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentMockDevtools/hooks/createMockStoreInjector.ts b/src/features/AgentMockDevtools/hooks/createMockStoreInjector.ts
new file mode 100644
index 00000000000..8c437bd645b
--- /dev/null
+++ b/src/features/AgentMockDevtools/hooks/createMockStoreInjector.ts
@@ -0,0 +1,273 @@
+import type {
+ AgentStreamEvent,
+ StepCompleteData,
+ StreamChunkData,
+ ToolExecuteData,
+} from '@lobechat/agent-gateway-client';
+import type {
+ ChatMessageError,
+ ChatToolPayload,
+ ChatToolPayloadWithResult,
+ ConversationContext,
+} from '@lobechat/types';
+import { AgentRuntimeErrorType } from '@lobechat/types';
+
+import type { ChatStore } from '@/store/chat/store';
+
+interface MockStoreInjectorParams {
+ assistantMessageId: string;
+ context: ConversationContext;
+ operationId: string;
+}
+
+const toChatMessageError = (data: unknown): ChatMessageError => {
+ if (typeof data === 'object' && data && 'type' in data && typeof data.type === 'string') {
+ const error = data as ChatMessageError;
+ return {
+ ...error,
+ message: error.message || error.body?.message,
+ };
+ }
+
+ const message =
+ typeof data === 'object' && data && 'message' in data && typeof data.message === 'string'
+ ? data.message
+ : typeof data === 'object' && data && 'error' in data && typeof data.error === 'string'
+ ? data.error
+ : 'Unknown error';
+
+ return {
+ body: { message },
+ message,
+ type: AgentRuntimeErrorType.AgentRuntimeError,
+ };
+};
+
+const stringifyResult = (value: unknown): string => {
+ if (typeof value === 'string') return value;
+ if (value == null) return '';
+
+ return JSON.stringify(value, null, 2);
+};
+
+const toToolPayload = (toolCalling: {
+ apiName?: string;
+ arguments?: string;
+ id?: string;
+ identifier?: string;
+}): ChatToolPayload => ({
+ apiName: toolCalling.apiName ?? 'unknown',
+ arguments: toolCalling.arguments ?? '{}',
+ id: toolCalling.id ?? `mock-tc-${Date.now()}`,
+ identifier: toolCalling.identifier ?? 'mock-tool',
+ type: toolCalling.identifier?.startsWith('lobe-') ? 'builtin' : 'default',
+});
+
+export const createMockStoreInjector = (get: () => ChatStore, params: MockStoreInjectorParams) => {
+ const { assistantMessageId, context, operationId } = params;
+ const dispatchContext = { operationId };
+ const toolMessageIds = new Map<string, string>();
+ let terminalState: 'completed' | 'error' | undefined;
+ let accumulatedContent = '';
+ let accumulatedReasoning = '';
+ let tools: ChatToolPayloadWithResult[] = [];
+
+ const updateAssistantTools = () => {
+ get().internal_dispatchMessage(
+ {
+ id: assistantMessageId,
+ type: 'updateMessage',
+ value: { tools },
+ },
+ dispatchContext,
+ );
+ };
+
+ return (event: AgentStreamEvent) => {
+ if (terminalState) return;
+
+ if (event.type === 'agent_runtime_end' || event.type === 'error') {
+ terminalState = event.type === 'error' ? 'error' : 'completed';
+ }
+
+ switch (event.type) {
+ case 'stream_start': {
+ accumulatedContent = '';
+ accumulatedReasoning = '';
+ break;
+ }
+
+ case 'stream_chunk': {
+ const data = event.data as StreamChunkData | undefined;
+ if (!data) break;
+
+ if (data.chunkType === 'text' && data.content) {
+ accumulatedContent += data.content;
+ get().internal_dispatchMessage(
+ {
+ id: assistantMessageId,
+ type: 'updateMessage',
+ value: { content: accumulatedContent },
+ },
+ dispatchContext,
+ );
+ }
+
+ if (data.chunkType === 'reasoning' && data.reasoning) {
+ accumulatedReasoning += data.reasoning;
+ get().internal_dispatchMessage(
+ {
+ id: assistantMessageId,
+ type: 'updateMessage',
+ value: { reasoning: { content: accumulatedReasoning } },
+ },
+ dispatchContext,
+ );
+ }
+
+ if (data.chunkType === 'tools_calling' && data.toolsCalling) {
+ tools = data.toolsCalling.map(toToolPayload);
+ updateAssistantTools();
+ get().internal_toggleToolCallingStreaming(
+ assistantMessageId,
+ data.toolsCalling.map(() => true),
+ );
+ }
+ break;
+ }
+
+ case 'stream_end': {
+ get().internal_toggleToolCallingStreaming(assistantMessageId, undefined);
+ break;
+ }
+
+ case 'tool_start': {
+ const data = event.data as
+ | {
+ toolCalling?: Parameters<typeof toToolPayload>[0];
+ }
+ | undefined;
+ if (!data?.toolCalling) break;
+
+ const payload = toToolPayload(data.toolCalling);
+ const toolMessageId = `mock-tool-msg-${assistantMessageId}-${payload.id}`;
+ toolMessageIds.set(payload.id, toolMessageId);
+
+ tools = tools.some((tool) => tool.id === payload.id)
+ ? tools.map((tool) => (tool.id === payload.id ? { ...tool, ...payload } : tool))
+ : [...tools, payload];
+ updateAssistantTools();
+
+ get().internal_dispatchMessage(
+ {
+ id: toolMessageId,
+ type: 'createMessage',
+ value: {
+ agentId: context.agentId,
+ content: '',
+ parentId: assistantMessageId,
+ plugin: payload,
+ role: 'tool',
+ sessionId: context.sessionId,
+ threadId: context.threadId,
+ tool_call_id: payload.id,
+ topicId: context.topicId ?? undefined,
+ },
+ },
+ dispatchContext,
+ );
+ break;
+ }
+
+ case 'tool_execute': {
+ const data = event.data as ToolExecuteData | undefined;
+ if (!data) break;
+
+ const nextTools = tools.map((tool) =>
+ tool.id === data.toolCallId
+ ? { ...tool, intervention: { status: 'approved' as const } }
+ : tool,
+ );
+ tools = nextTools;
+ updateAssistantTools();
+ break;
+ }
+
+ case 'tool_end': {
+ const data = event.data as
+ | {
+ error?: unknown;
+ isSuccess?: boolean;
+ payload?: { state?: unknown };
+ result?: unknown;
+ toolCallId?: string;
+ }
+ | undefined;
+ if (!data) break;
+
+ const toolId = data.toolCallId ?? tools.at(-1)?.id;
+ if (!toolId) break;
+
+ const resultMessageId = toolMessageIds.get(toolId);
+ const result = {
+ content: stringifyResult(data.result ?? data.payload?.state),
+ error: data.error,
+ id: resultMessageId ?? toolId,
+ state: data.result ?? data.payload?.state,
+ };
+
+ tools = tools.map((tool) =>
+ tool.id === toolId ? { ...tool, result, result_msg_id: resultMessageId } : tool,
+ );
+ updateAssistantTools();
+
+ if (resultMessageId) {
+ get().internal_dispatchMessage(
+ {
+ id: resultMessageId,
+ type: 'updateMessage',
+ value: {
+ content: result.content ?? '',
+ error: data.isSuccess === false ? toChatMessageError(data.error) : undefined,
+ },
+ },
+ dispatchContext,
+ );
+ }
+ break;
+ }
+
+ case 'step_complete': {
+ const data = event.data as StepCompleteData | undefined;
+ if (data?.phase === 'execution_complete') {
+ get().completeOperation(operationId);
+ }
+ break;
+ }
+
+ case 'agent_runtime_end': {
+ get().internal_toggleToolCallingStreaming(assistantMessageId, undefined);
+ get().completeOperation(operationId);
+ break;
+ }
+
+ case 'error': {
+ const messageError = toChatMessageError(event.data);
+ get().internal_toggleToolCallingStreaming(assistantMessageId, undefined);
+ get().failOperation(operationId, {
+ message: messageError.message ?? 'Mock playback failed',
+ type: String(messageError.type),
+ });
+ get().internal_dispatchMessage(
+ {
+ id: assistantMessageId,
+ type: 'updateMessage',
+ value: { error: messageError },
+ },
+ dispatchContext,
+ );
+ break;
+ }
+ }
+ };
+};
diff --git a/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.test.ts b/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.test.ts
new file mode 100644
index 00000000000..20674fc89e6
--- /dev/null
+++ b/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.test.ts
@@ -0,0 +1,513 @@
+import type { MockCase } from '@lobechat/agent-mock';
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useAgentMockStore } from '../store/agentMockStore';
+import { useAgentMockPlayer } from './useAgentMockPlayer';
+
+const { executeMockStream, getChatStoreState, lastDisplayMessageId } = vi.hoisted(() => ({
+ executeMockStream: vi.fn(),
+ getChatStoreState: vi.fn(),
+ lastDisplayMessageId: vi.fn(),
+}));
+
+vi.mock('@lobechat/agent-mock', () => ({
+ executeMockStream,
+}));
+
+vi.mock('@/store/chat/slices/message/selectors', () => ({
+ displayMessageSelectors: {
+ lastDisplayMessageId,
+ },
+}));
+
+vi.mock('@/store/chat/store', () => ({
+ useChatStore: {
+ getState: getChatStoreState,
+ },
+}));
+
+const mockCase: MockCase = {
+ id: 'case-1',
+ name: 'Case 1',
+ source: { events: [], type: 'fixture' },
+};
+
+const createPlaybackState = (overrides: Record<string, unknown> = {}) => ({
+ currentEventIndex: 0,
+ currentStepIndex: 0,
+ elapsedMs: 0,
+ speedMultiplier: 1,
+ status: 'idle',
+ toolsExecuted: 0,
+ totalDurationMs: 0,
+ totalEvents: 8,
+ totalSteps: 0,
+ totalTools: 0,
+ ...overrides,
+});
+
+const createMockHandle = (initialState = createPlaybackState()) => {
+ let state = initialState;
+ const listeners = new Set<(next: typeof state) => void>();
+ const emit = () => {
+ for (const listener of listeners) listener(state);
+ };
+
+ return {
+ player: {
+ getState: vi.fn(() => state),
+ pause: vi.fn(() => {
+ state = { ...state, status: 'paused' };
+ emit();
+ }),
+ resume: vi.fn(() => {
+ state = { ...state, status: 'running' };
+ emit();
+ }),
+ seekToEventIndex: vi.fn((idx: number) => {
+ state = { ...state, currentEventIndex: idx };
+ emit();
+ }),
+ setSpeed: vi.fn(),
+ stepNextEvent: vi.fn(),
+ stepNextStep: vi.fn(),
+ stepNextTool: vi.fn(),
+ subscribe: vi.fn((listener: (next: typeof state) => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ }),
+ },
+ start: vi.fn(() => {
+ state = { ...state, status: 'running' };
+ emit();
+ }),
+ stop: vi.fn(() => {
+ state = { ...state, currentEventIndex: 0, status: 'idle' };
+ emit();
+ }),
+ };
+};
+
+const createChatStoreMock = (overrides: Record<string, unknown> = {}) => ({
+ associateMessageWithOperation: vi.fn(),
+ activeAgentId: 'agent-1',
+ activeGroupId: undefined,
+ cancelOperation: vi.fn(),
+ cancelOperations: vi.fn(),
+ completeOperation: vi.fn(),
+ dbMessagesMap: {},
+ failOperation: vi.fn(),
+ internal_dispatchMessage: vi.fn(),
+ internal_dispatchTopic: vi.fn(),
+ internal_toggleToolCallingStreaming: vi.fn(),
+ internal_updateTopicLoading: vi.fn(),
+ operations: {},
+ operationsByMessage: {},
+ optimisticCreateTmpMessage: vi.fn(),
+ startOperation: vi.fn(),
+ topicDataMap: {},
+ ...overrides,
+});
+
+describe('useAgentMockPlayer', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ useAgentMockStore.setState({
+ activeTab: 'timeline',
+ loop: false,
+ modalOpen: false,
+ playback: null,
+ popoverOpen: false,
+ selectedCaseId: null,
+ speed: 1,
+ });
+ });
+
+ it('creates a frontend operation and injects an assistant message before starting playback', async () => {
+ const handle = createMockHandle();
+ const chatStore = createChatStoreMock();
+
+ executeMockStream.mockReturnValue(handle);
+ getChatStoreState.mockReturnValue(chatStore);
+ lastDisplayMessageId.mockReturnValue('user-1');
+
+ const { result } = renderHook(() => useAgentMockPlayer());
+
+ act(() => {
+ result.current.start({ agentId: 'agent-1', case: mockCase, topicId: 'topic-1' });
+ });
+
+ const operationId = chatStore.startOperation.mock.calls[0][0].operationId as string;
+
+ expect(chatStore.cancelOperations).toHaveBeenCalledWith(
+ {
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ type: ['execAgentRuntime', 'execHeterogeneousAgent', 'execServerAgentRuntime'],
+ },
+ 'Mock playback started',
+ );
+ expect(chatStore.startOperation).toHaveBeenCalledWith({
+ context: {
+ agentId: 'agent-1',
+ messageId: `mock-msg-${operationId}`,
+ scope: 'main',
+ topicId: 'topic-1',
+ },
+ operationId,
+ type: 'execAgentRuntime',
+ });
+ expect(chatStore.optimisticCreateTmpMessage).toHaveBeenCalledWith(
+ {
+ agentId: 'agent-1',
+ content: '',
+ parentId: 'user-1',
+ role: 'assistant',
+ topicId: 'topic-1',
+ },
+ { operationId, tempMessageId: `mock-msg-${operationId}` },
+ );
+ expect(chatStore.associateMessageWithOperation).toHaveBeenCalledWith(
+ `mock-msg-${operationId}`,
+ operationId,
+ );
+ expect(executeMockStream).toHaveBeenCalledWith(
+ expect.objectContaining({
+ case: mockCase,
+ onEvent: expect.any(Function),
+ operationId,
+ }),
+ );
+ expect(handle.start).toHaveBeenCalled();
+ });
+
+ it('targets the active thread message bucket when replay starts from a thread view', async () => {
+ const handle = createMockHandle();
+ const chatStore = createChatStoreMock();
+
+ executeMockStream.mockReturnValue(handle);
+ getChatStoreState.mockReturnValue(chatStore);
+ lastDisplayMessageId.mockReturnValue('thread-user-1');
+
+ const { result } = renderHook(() => useAgentMockPlayer());
+
+ act(() => {
+ result.current.start({
+ agentId: 'agent-1',
+ case: mockCase,
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ });
+ });
+
+ const operationId = chatStore.startOperation.mock.calls[0][0].operationId as string;
+
+ expect(chatStore.cancelOperations).toHaveBeenCalledWith(
+ {
+ agentId: 'agent-1',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ type: ['execAgentRuntime', 'execHeterogeneousAgent', 'execServerAgentRuntime'],
+ },
+ 'Mock playback started',
+ );
+ expect(chatStore.startOperation).toHaveBeenCalledWith({
+ context: {
+ agentId: 'agent-1',
+ messageId: `mock-msg-${operationId}`,
+ scope: 'thread',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ },
+ operationId,
+ type: 'execAgentRuntime',
+ });
+ expect(chatStore.optimisticCreateTmpMessage).toHaveBeenCalledWith(
+ {
+ agentId: 'agent-1',
+ content: '',
+ parentId: 'thread-user-1',
+ role: 'assistant',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ },
+ { operationId, tempMessageId: `mock-msg-${operationId}` },
+ );
+ });
+
+ it('injects stream chunks into the frontend message store', async () => {
+ const handle = createMockHandle();
+ const chatStore = createChatStoreMock({
+ completeOperation: vi.fn(),
+ failOperation: vi.fn(),
+ internal_toggleToolCallingStreaming: vi.fn(),
+ });
+
+ executeMockStream.mockReturnValue(handle);
+ getChatStoreState.mockReturnValue(chatStore);
+ lastDisplayMessageId.mockReturnValue('user-1');
+
+ const { result } = renderHook(() => useAgentMockPlayer());
+
+ act(() => {
+ result.current.start({ agentId: 'agent-1', case: mockCase, topicId: 'topic-1' });
+ });
+
+ const operationId = chatStore.startOperation.mock.calls[0][0].operationId as string;
+ const onEvent = executeMockStream.mock.calls[0][0].onEvent;
+
+ act(() => {
+ onEvent({
+ data: { chunkType: 'text', content: 'hello' },
+ operationId,
+ stepIndex: 0,
+ timestamp: Date.now(),
+ type: 'stream_chunk',
+ });
+ });
+
+ expect(chatStore.internal_dispatchMessage).toHaveBeenCalledWith(
+ {
+ id: `mock-msg-${operationId}`,
+ type: 'updateMessage',
+ value: { content: 'hello' },
+ },
+ { operationId },
+ );
+ });
+
+ it('completes the frontend operation when the mock stream ends', async () => {
+ const handle = createMockHandle();
+ const chatStore = createChatStoreMock({
+ completeOperation: vi.fn(),
+ failOperation: vi.fn(),
+ internal_toggleToolCallingStreaming: vi.fn(),
+ });
+
+ executeMockStream.mockReturnValue(handle);
+ getChatStoreState.mockReturnValue(chatStore);
+ lastDisplayMessageId.mockReturnValue('user-1');
+
+ const { result } = renderHook(() => useAgentMockPlayer());
+
+ act(() => {
+ result.current.start({ agentId: 'agent-1', case: mockCase, topicId: 'topic-1' });
+ });
+
+ const operationId = chatStore.startOperation.mock.calls[0][0].operationId as string;
+ const onEvent = executeMockStream.mock.calls[0][0].onEvent;
+
+ act(() => {
+ onEvent({
+ data: { reason: 'done' },
+ operationId,
+ stepIndex: 0,
+ timestamp: Date.now(),
+ type: 'agent_runtime_end',
+ });
+ });
+
+ expect(chatStore.internal_toggleToolCallingStreaming).toHaveBeenCalledWith(
+ `mock-msg-${operationId}`,
+ undefined,
+ );
+ expect(chatStore.completeOperation).toHaveBeenCalledWith(operationId);
+ });
+
+ it('cancels the frontend operation when playback stops', async () => {
+ const handle = createMockHandle();
+ const chatStore = createChatStoreMock();
+
+ executeMockStream.mockReturnValue(handle);
+ getChatStoreState.mockReturnValue(chatStore);
+ lastDisplayMessageId.mockReturnValue('user-1');
+
+ const { result } = renderHook(() => useAgentMockPlayer());
+
+ act(() => {
+ result.current.start({ agentId: 'agent-1', case: mockCase, topicId: 'topic-1' });
+ });
+
+ const operationId = chatStore.startOperation.mock.calls[0][0].operationId as string;
+
+ act(() => {
+ result.current.stop();
+ });
+
+ expect(handle.stop).toHaveBeenCalled();
+ expect(chatStore.cancelOperation).toHaveBeenCalledWith(operationId, 'Mock playback stopped');
+ });
+
+ it('shares the same playback handle across hook instances', async () => {
+ const handle = createMockHandle();
+ const chatStore = createChatStoreMock();
+
+ executeMockStream.mockReturnValue(handle);
+ getChatStoreState.mockReturnValue(chatStore);
+ lastDisplayMessageId.mockReturnValue('user-1');
+
+ const first = renderHook(() => useAgentMockPlayer());
+ const second = renderHook(() => useAgentMockPlayer());
+
+ act(() => {
+ first.result.current.start({ agentId: 'agent-1', case: mockCase, topicId: 'topic-1' });
+ });
+
+ act(() => {
+ second.result.current.pause();
+ second.result.current.resume();
+ second.result.current.stepStep();
+ });
+
+ expect(handle.player.pause).toHaveBeenCalledTimes(1);
+ expect(handle.player.resume).toHaveBeenCalledTimes(1);
+ expect(handle.player.stepNextStep).toHaveBeenCalledTimes(1);
+ });
+
+ it('reuses the running server assistant message instead of creating a second message', async () => {
+ const handle = createMockHandle();
+ const chatStore = createChatStoreMock({
+ dbMessagesMap: {
+ 'main_agent-1_topic-1': [
+ { content: 'hello', id: 'user-1', role: 'user' },
+ { content: '', id: 'server-assistant-1', parentId: 'user-1', role: 'assistant' },
+ ],
+ },
+ operations: {
+ 'server-op-1': {
+ id: 'server-op-1',
+ status: 'running',
+ type: 'execServerAgentRuntime',
+ },
+ },
+ operationsByMessage: {
+ 'server-assistant-1': ['server-op-1'],
+ },
+ });
+
+ executeMockStream.mockReturnValue(handle);
+ getChatStoreState.mockReturnValue(chatStore);
+ lastDisplayMessageId.mockReturnValue('server-assistant-1');
+
+ const { result } = renderHook(() => useAgentMockPlayer());
+
+ act(() => {
+ result.current.start({ agentId: 'agent-1', case: mockCase, topicId: 'topic-1' });
+ });
+
+ const operationId = chatStore.startOperation.mock.calls[0][0].operationId as string;
+
+ expect(chatStore.cancelOperation).toHaveBeenCalledWith('server-op-1', 'Mock playback started');
+ expect(chatStore.startOperation).toHaveBeenCalledWith({
+ context: {
+ agentId: 'agent-1',
+ messageId: 'server-assistant-1',
+ scope: 'main',
+ topicId: 'topic-1',
+ },
+ operationId,
+ type: 'execAgentRuntime',
+ });
+ expect(chatStore.optimisticCreateTmpMessage).not.toHaveBeenCalled();
+ expect(chatStore.internal_dispatchMessage).toHaveBeenCalledWith(
+ {
+ id: 'server-assistant-1',
+ type: 'updateMessage',
+ value: {
+ content: '',
+ error: null,
+ reasoning: { content: '' },
+ tools: [],
+ },
+ },
+ { operationId },
+ );
+ expect(chatStore.associateMessageWithOperation).toHaveBeenCalledWith(
+ 'server-assistant-1',
+ operationId,
+ );
+ });
+
+ it('rewinds by rebuilding the mock operation and keeps resume on the rewound handle', async () => {
+ const firstHandle = createMockHandle(
+ createPlaybackState({ currentEventIndex: 4, status: 'paused' }),
+ );
+ const secondHandle = createMockHandle();
+ const chatStore = createChatStoreMock();
+
+ executeMockStream.mockReturnValueOnce(firstHandle).mockReturnValueOnce(secondHandle);
+ getChatStoreState.mockReturnValue(chatStore);
+ lastDisplayMessageId.mockReturnValue('user-1');
+
+ const { result } = renderHook(() => useAgentMockPlayer());
+
+ act(() => {
+ result.current.start({ agentId: 'agent-1', case: mockCase, topicId: 'topic-1' });
+ });
+
+ const firstOperationId = chatStore.startOperation.mock.calls[0][0].operationId as string;
+ const assistantMessageId = chatStore.startOperation.mock.calls[0][0].context
+ .messageId as string;
+
+ act(() => {
+ result.current.pause();
+ });
+
+ act(() => {
+ result.current.seekToEventIndex(2);
+ });
+
+ const secondOperationId = chatStore.startOperation.mock.calls[1][0].operationId as string;
+
+ expect(firstHandle.stop).toHaveBeenCalledTimes(1);
+ expect(chatStore.cancelOperation).toHaveBeenCalledWith(
+ firstOperationId,
+ 'Mock playback rewound',
+ );
+ expect(chatStore.startOperation).toHaveBeenCalledTimes(2);
+ expect(chatStore.startOperation.mock.calls[1][0]).toMatchObject({
+ context: {
+ agentId: 'agent-1',
+ messageId: assistantMessageId,
+ scope: 'main',
+ topicId: 'topic-1',
+ },
+ operationId: secondOperationId,
+ type: 'execAgentRuntime',
+ });
+ expect(chatStore.optimisticCreateTmpMessage).toHaveBeenCalledTimes(1);
+ expect(chatStore.internal_dispatchMessage).toHaveBeenCalledWith(
+ {
+ id: assistantMessageId,
+ type: 'deleteMessage',
+ },
+ { operationId: secondOperationId },
+ );
+ expect(chatStore.internal_dispatchMessage).toHaveBeenCalledWith(
+ {
+ id: assistantMessageId,
+ type: 'createMessage',
+ value: {
+ agentId: 'agent-1',
+ content: '',
+ parentId: 'user-1',
+ role: 'assistant',
+ topicId: 'topic-1',
+ },
+ },
+ { operationId: secondOperationId },
+ );
+ expect(secondHandle.player.seekToEventIndex).toHaveBeenCalledWith(2);
+ expect(secondHandle.start).toHaveBeenCalledTimes(1);
+ expect(secondHandle.player.pause).toHaveBeenCalledTimes(1);
+ expect(useAgentMockStore.getState().playback?.status).toBe('paused');
+
+ act(() => {
+ result.current.resume();
+ });
+
+ expect(secondHandle.player.resume).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.ts b/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.ts
new file mode 100644
index 00000000000..4891e01b752
--- /dev/null
+++ b/src/features/AgentMockDevtools/hooks/useAgentMockPlayer.ts
@@ -0,0 +1,419 @@
+import { executeMockStream, type MockCase } from '@lobechat/agent-mock';
+import type { ConversationContext } from '@lobechat/types';
+import { useCallback } from 'react';
+
+import { topicSelectors } from '@/store/chat/selectors';
+import { displayMessageSelectors } from '@/store/chat/slices/message/selectors';
+import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation/types';
+import type { ChatStore } from '@/store/chat/store';
+import { useChatStore } from '@/store/chat/store';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+import { useAgentMockStore } from '../store/agentMockStore';
+import { createMockStoreInjector } from './createMockStoreInjector';
+
+type MockStreamHandle = ReturnType<typeof executeMockStream>;
+
+interface PlaybackSession {
+ args: StartArgs;
+ assistantMessageId: string;
+ parentMessageId: string | null;
+ reuseAssistantMessage: boolean;
+}
+
+const playerController = {
+ handle: null as MockStreamHandle | null,
+ operationId: null as string | null,
+ session: null as PlaybackSession | null,
+ unsubscribe: null as (() => void) | null,
+};
+
+interface StartArgs {
+ /** Required — store dispatches messages keyed by the active conversation target. */
+ agentId: string;
+ case: MockCase;
+ threadId?: string | null;
+ topicId?: string;
+}
+
+const findRunningServerAssistantMessageId = (chatStore: ChatStore, args: StartArgs) => {
+ const contextKey = messageMapKey({
+ agentId: args.agentId,
+ scope: args.threadId ? 'thread' : 'main',
+ threadId: args.threadId ?? null,
+ topicId: args.topicId ?? null,
+ });
+ const messages = chatStore.dbMessagesMap[contextKey] ?? [];
+
+ return [...messages].reverse().find((message) => {
+ if (message.role !== 'assistant') return false;
+
+ return (chatStore.operationsByMessage[message.id] ?? []).some((operationId) => {
+ const operation = chatStore.operations[operationId];
+
+ return operation?.status === 'running' && operation.type === 'execServerAgentRuntime';
+ });
+ })?.id;
+};
+
+const cancelRunningMessageRuntimeOperations = (chatStore: ChatStore, messageId: string) => {
+ for (const operationId of chatStore.operationsByMessage[messageId] ?? []) {
+ const operation = chatStore.operations[operationId];
+ if (!operation || operation.status !== 'running') continue;
+ if (!AI_RUNTIME_OPERATION_TYPES.includes(operation.type)) continue;
+
+ chatStore.cancelOperation(operationId, 'Mock playback started');
+ }
+};
+
+const clearLocalTopicRunningOperation = (chatStore: ChatStore, topicId: string | undefined) => {
+ if (!topicId) return;
+
+ const topic = topicSelectors.getTopicById(topicId)(chatStore);
+ if (!topic?.metadata?.runningOperation) return;
+
+ chatStore.internal_dispatchTopic(
+ {
+ id: topicId,
+ type: 'updateTopic',
+ value: {
+ metadata: {
+ ...topic.metadata,
+ runningOperation: null,
+ },
+ },
+ },
+ 'agentMock/clearRunningOperation',
+ );
+ chatStore.internal_updateTopicLoading(topicId, false);
+};
+
+const getContextKey = (args: StartArgs) =>
+ messageMapKey({
+ agentId: args.agentId,
+ scope: args.threadId ? 'thread' : 'main',
+ threadId: args.threadId ?? null,
+ topicId: args.topicId ?? null,
+ });
+
+const getMockToolMessagePrefix = (assistantMessageId: string) =>
+ `mock-tool-msg-${assistantMessageId}-`;
+
+const clearMockToolMessages = (
+ chatStore: ChatStore,
+ args: StartArgs,
+ assistantMessageId: string,
+ operationId: string,
+) => {
+ const messages = chatStore.dbMessagesMap[getContextKey(args)] ?? [];
+ const prefix = getMockToolMessagePrefix(assistantMessageId);
+ const toolMessageIds = messages
+ .filter(
+ (message) =>
+ message.role === 'tool' &&
+ message.parentId === assistantMessageId &&
+ message.id.startsWith(prefix),
+ )
+ .map((message) => message.id);
+
+ if (toolMessageIds.length === 0) return;
+
+ chatStore.internal_dispatchMessage(
+ {
+ ids: toolMessageIds,
+ type: 'deleteMessages',
+ },
+ { operationId },
+ );
+};
+
+const resetAssistantProjection = (
+ chatStore: ChatStore,
+ session: PlaybackSession,
+ operationId: string,
+) => {
+ clearMockToolMessages(chatStore, session.args, session.assistantMessageId, operationId);
+
+ if (session.reuseAssistantMessage) {
+ chatStore.internal_dispatchMessage(
+ {
+ id: session.assistantMessageId,
+ type: 'updateMessage',
+ value: {
+ content: '',
+ error: null as never,
+ reasoning: { content: '' },
+ tools: [],
+ },
+ },
+ { operationId },
+ );
+ } else {
+ chatStore.internal_dispatchMessage(
+ {
+ id: session.assistantMessageId,
+ type: 'deleteMessage',
+ },
+ { operationId },
+ );
+ chatStore.internal_dispatchMessage(
+ {
+ id: session.assistantMessageId,
+ type: 'createMessage',
+ value: {
+ agentId: session.args.agentId,
+ content: '',
+ parentId: session.parentMessageId ?? undefined,
+ role: 'assistant',
+ threadId: session.args.threadId ?? undefined,
+ topicId: session.args.topicId,
+ },
+ },
+ { operationId },
+ );
+ }
+
+ chatStore.internal_toggleToolCallingStreaming(session.assistantMessageId, undefined);
+};
+
+export function useAgentMockPlayer() {
+ const setPlayback = useAgentMockStore((s) => s.setPlayback);
+ const speed = useAgentMockStore((s) => s.speed);
+
+ const disposeCurrentPlayback = useCallback(
+ (chatStore: ChatStore, reason: string, keepSession: boolean = false) => {
+ playerController.unsubscribe?.();
+ playerController.unsubscribe = null;
+
+ playerController.handle?.stop();
+
+ if (playerController.operationId) {
+ chatStore.cancelOperation(playerController.operationId, reason);
+ playerController.operationId = null;
+ }
+
+ playerController.handle = null;
+ if (!keepSession) {
+ playerController.session = null;
+ }
+ },
+ [],
+ );
+
+ const createPlayback = useCallback(
+ (
+ args: StartArgs,
+ sessionOverride?: Pick<
+ PlaybackSession,
+ 'assistantMessageId' | 'parentMessageId' | 'reuseAssistantMessage'
+ >,
+ ) => {
+ const chatStore = useChatStore.getState();
+
+ playerController.unsubscribe?.();
+ playerController.unsubscribe = null;
+
+ clearLocalTopicRunningOperation(chatStore, args.topicId);
+
+ const now = Date.now();
+ const operationId = `mock-${now}-${Math.random().toString(36).slice(2, 8)}`;
+ const context: ConversationContext = {
+ agentId: args.agentId,
+ scope: args.threadId ? 'thread' : 'main',
+ topicId: args.topicId,
+ ...(args.threadId ? { threadId: args.threadId } : {}),
+ };
+
+ const reusableAssistantMessageId =
+ sessionOverride?.assistantMessageId ?? findRunningServerAssistantMessageId(chatStore, args);
+ const reuseAssistantMessage =
+ sessionOverride?.reuseAssistantMessage ?? reusableAssistantMessageId != null;
+ const assistantMessageId = reusableAssistantMessageId ?? `mock-msg-${operationId}`;
+ const parentMessageId =
+ sessionOverride?.parentMessageId ??
+ (reuseAssistantMessage
+ ? null
+ : displayMessageSelectors.lastDisplayMessageId(useChatStore.getState())) ??
+ null;
+
+ if (!sessionOverride && reuseAssistantMessage) {
+ cancelRunningMessageRuntimeOperations(chatStore, assistantMessageId);
+ }
+
+ chatStore.startOperation({
+ context: { ...context, messageId: assistantMessageId },
+ operationId,
+ type: 'execAgentRuntime',
+ });
+ playerController.operationId = operationId;
+
+ if (sessionOverride) {
+ resetAssistantProjection(
+ chatStore,
+ {
+ args,
+ assistantMessageId,
+ parentMessageId,
+ reuseAssistantMessage,
+ },
+ operationId,
+ );
+ } else if (reuseAssistantMessage) {
+ resetAssistantProjection(
+ chatStore,
+ {
+ args,
+ assistantMessageId,
+ parentMessageId,
+ reuseAssistantMessage: true,
+ },
+ operationId,
+ );
+ }
+
+ if (!reuseAssistantMessage && !sessionOverride) {
+ chatStore.optimisticCreateTmpMessage(
+ {
+ agentId: args.agentId,
+ content: '',
+ parentId: parentMessageId ?? undefined,
+ role: 'assistant',
+ threadId: args.threadId ?? undefined,
+ topicId: args.topicId,
+ },
+ { operationId, tempMessageId: assistantMessageId },
+ );
+ }
+
+ chatStore.associateMessageWithOperation(assistantMessageId, operationId);
+
+ const handler = createMockStoreInjector(() => useChatStore.getState(), {
+ assistantMessageId,
+ context,
+ operationId,
+ });
+
+ const handle = executeMockStream({
+ case: args.case,
+ onEvent: handler,
+ operationId,
+ speedMultiplier: speed,
+ });
+
+ playerController.handle = handle;
+ playerController.session = {
+ args,
+ assistantMessageId,
+ parentMessageId,
+ reuseAssistantMessage,
+ };
+ playerController.unsubscribe = handle.player.subscribe((state) => setPlayback(state));
+ setPlayback(handle.player.getState());
+
+ return handle;
+ },
+ [setPlayback, speed],
+ );
+
+ const start = useCallback(
+ (args: StartArgs) => {
+ const chatStore = useChatStore.getState();
+
+ disposeCurrentPlayback(chatStore, 'Mock playback restarted');
+
+ chatStore.cancelOperations(
+ {
+ agentId: args.agentId,
+ threadId: args.threadId ?? undefined,
+ topicId: args.topicId ?? null,
+ type: AI_RUNTIME_OPERATION_TYPES,
+ },
+ 'Mock playback started',
+ );
+ const handle = createPlayback(args);
+ handle.start();
+ setPlayback(handle.player.getState());
+ },
+ [createPlayback, disposeCurrentPlayback, setPlayback],
+ );
+
+ const pause = useCallback(() => playerController.handle?.player.pause(), []);
+ const resume = useCallback(() => playerController.handle?.player.resume(), []);
+ const stop = useCallback(() => {
+ disposeCurrentPlayback(useChatStore.getState(), 'Mock playback stopped');
+ setPlayback(null);
+ }, [disposeCurrentPlayback, setPlayback]);
+ const stepEvent = useCallback(() => playerController.handle?.player.stepNextEvent(), []);
+ const stepStep = useCallback(() => playerController.handle?.player.stepNextStep(), []);
+ const stepTool = useCallback(() => playerController.handle?.player.stepNextTool(), []);
+ const seekToEventIndex = useCallback(
+ (idx: number) => {
+ const handle = playerController.handle;
+ const session = playerController.session;
+
+ if (!handle || !session) return;
+
+ const currentState = handle.player.getState();
+ if (idx >= currentState.currentEventIndex) {
+ handle.player.seekToEventIndex(idx);
+ setPlayback(handle.player.getState());
+ return;
+ }
+
+ const chatStore = useChatStore.getState();
+ const shouldResumeRunning = currentState.status === 'running';
+ const shouldPauseAtTarget =
+ currentState.status === 'paused' || currentState.status === 'complete';
+
+ disposeCurrentPlayback(chatStore, 'Mock playback rewound', true);
+ chatStore.cancelOperations(
+ {
+ agentId: session.args.agentId,
+ threadId: session.args.threadId ?? undefined,
+ topicId: session.args.topicId ?? null,
+ type: AI_RUNTIME_OPERATION_TYPES,
+ },
+ 'Mock playback rewound',
+ );
+
+ const rebuiltHandle = createPlayback(session.args, {
+ assistantMessageId: session.assistantMessageId,
+ parentMessageId: session.parentMessageId,
+ reuseAssistantMessage: session.reuseAssistantMessage,
+ });
+
+ rebuiltHandle.player.seekToEventIndex(idx);
+ setPlayback(rebuiltHandle.player.getState());
+
+ if (shouldResumeRunning) {
+ rebuiltHandle.start();
+ setPlayback(rebuiltHandle.player.getState());
+ return;
+ }
+
+ if (shouldPauseAtTarget || idx > 0) {
+ rebuiltHandle.start();
+ rebuiltHandle.player.pause();
+ setPlayback(rebuiltHandle.player.getState());
+ }
+ },
+ [createPlayback, disposeCurrentPlayback, setPlayback],
+ );
+ const setSpeed = useCallback(
+ (s: Parameters<MockStreamHandle['player']['setSpeed']>[0]) =>
+ playerController.handle?.player.setSpeed(s),
+ [],
+ );
+
+ return {
+ pause,
+ resume,
+ seekToEventIndex,
+ setSpeed,
+ start,
+ stepEvent,
+ stepStep,
+ stepTool,
+ stop,
+ };
+}
diff --git a/src/features/AgentMockDevtools/hooks/useAgentMockReplayTarget.ts b/src/features/AgentMockDevtools/hooks/useAgentMockReplayTarget.ts
new file mode 100644
index 00000000000..3badce92953
--- /dev/null
+++ b/src/features/AgentMockDevtools/hooks/useAgentMockReplayTarget.ts
@@ -0,0 +1,26 @@
+import { useCallback } from 'react';
+import { useParams, useSearchParams } from 'react-router-dom';
+
+import { useChatStore } from '@/store/chat/store';
+
+export interface AgentMockReplayTarget {
+ agentId?: string;
+ threadId?: string | null;
+ topicId?: string | null;
+}
+
+export const useAgentMockReplayTarget = () => {
+ const params = useParams<{ aid?: string; topicId?: string }>();
+ const [searchParams] = useSearchParams();
+
+ return useCallback((): AgentMockReplayTarget => {
+ const store = useChatStore.getState();
+ const routeThreadId = searchParams.get('thread');
+ const target = {
+ agentId: store.activeAgentId ?? params.aid,
+ threadId: routeThreadId ?? store.activeThreadId ?? null,
+ topicId: params.topicId ?? store.activeTopicId ?? null,
+ };
+ return target;
+ }, [params.aid, params.topicId, searchParams]);
+};
diff --git a/src/features/AgentMockDevtools/hooks/useMockCases.ts b/src/features/AgentMockDevtools/hooks/useMockCases.ts
new file mode 100644
index 00000000000..caff32677d9
--- /dev/null
+++ b/src/features/AgentMockDevtools/hooks/useMockCases.ts
@@ -0,0 +1,45 @@
+import type { MockCase } from '@lobechat/agent-mock';
+import { BUILTIN_CASES, snapshotToMockCase } from '@lobechat/agent-mock';
+import useSWR from 'swr';
+
+interface SnapshotIndex {
+ files: string[];
+}
+
+export function useMockCases() {
+ const { data: snapshots = [] } = useSWR<MockCase[]>(
+ 'agent-mock/snapshots',
+ async () => {
+ const idx: SnapshotIndex = await fetch('/api/dev/agent-tracing').then((r) => r.json());
+ const cases: MockCase[] = [];
+ for (const f of idx.files ?? []) {
+ try {
+ const snap = await fetch(`/api/dev/agent-tracing?file=${encodeURIComponent(f)}`).then(
+ (r) => r.json(),
+ );
+ cases.push(snapshotToMockCase(snap, { id: f, name: f, path: f }));
+ } catch {
+ // skip malformed snapshots
+ }
+ }
+ return cases;
+ },
+ { revalidateOnFocus: false },
+ );
+
+ const generated: MockCase[] = (() => {
+ try {
+ const raw = localStorage.getItem('LOBE_AGENT_MOCK_GENERATED');
+ return raw ? (JSON.parse(raw) as MockCase[]) : [];
+ } catch {
+ return [];
+ }
+ })();
+
+ return {
+ builtins: BUILTIN_CASES,
+ snapshots,
+ generated,
+ all: [...BUILTIN_CASES, ...snapshots, ...generated],
+ };
+}
diff --git a/src/features/AgentMockDevtools/index.tsx b/src/features/AgentMockDevtools/index.tsx
new file mode 100644
index 00000000000..9249172ac77
--- /dev/null
+++ b/src/features/AgentMockDevtools/index.tsx
@@ -0,0 +1,43 @@
+import { memo, useEffect, useState } from 'react';
+
+import { Fab } from './Fab';
+import { Modal } from './Modal';
+import { Popover } from './Popover';
+
+const isDevEnv = process.env.NODE_ENV === 'development';
+const STORAGE_KEY = 'LOBE_AGENT_MOCK_ENABLED';
+
+const useDevtoolsEnabled = (): boolean => {
+ const [enabled, setEnabled] = useState(false);
+ useEffect(() => {
+ if (!isDevEnv) 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 AgentMockDevtools = memo(() => {
+ const enabled = useDevtoolsEnabled();
+ if (!isDevEnv || !enabled) return null;
+ return (
+ <>
+ <Fab />
+ <Popover />
+ <Modal />
+ </>
+ );
+});
+
+AgentMockDevtools.displayName = 'AgentMockDevtools';
+
+export default AgentMockDevtools;
diff --git a/src/features/AgentMockDevtools/store/agentMockStore.ts b/src/features/AgentMockDevtools/store/agentMockStore.ts
new file mode 100644
index 00000000000..4cd5e30ba68
--- /dev/null
+++ b/src/features/AgentMockDevtools/store/agentMockStore.ts
@@ -0,0 +1,53 @@
+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 => {
+ if (typeof localStorage === 'undefined') return false;
+ return localStorage.getItem(LOOP_STORAGE_KEY) === '1';
+};
+
+const writePersistedLoop = (next: boolean) => {
+ if (typeof localStorage === 'undefined') return;
+ localStorage.setItem(LOOP_STORAGE_KEY, next ? '1' : '0');
+};
+
+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/AgentMockDevtools/views/FixtureView.tsx b/src/features/AgentMockDevtools/views/FixtureView.tsx
new file mode 100644
index 00000000000..7397a8e4c9f
--- /dev/null
+++ b/src/features/AgentMockDevtools/views/FixtureView.tsx
@@ -0,0 +1,75 @@
+import { Button, Center, Flexbox, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { Copy } from 'lucide-react';
+import { memo, useMemo } from 'react';
+
+import { useMockCases } from '../hooks/useMockCases';
+import { useAgentMockStore } from '../store/agentMockStore';
+
+const styles = createStaticStyles(({ css }) => ({
+ pre: css`
+ overflow: auto;
+ flex: 1;
+
+ margin: 0;
+ padding: 12px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 8px;
+
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ font-size: 11.5px;
+ line-height: 1.6;
+ color: ${cssVar.colorText};
+
+ background: ${cssVar.colorFillAlter};
+ `,
+ wrap: css`
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ gap: 8px;
+
+ height: 100%;
+ min-height: 0;
+ `,
+}));
+
+export const FixtureView = memo(() => {
+ const { all } = useMockCases();
+ const selectedCaseId = useAgentMockStore((s) => s.selectedCaseId);
+ const c = all.find((x) => x.id === selectedCaseId);
+
+ const json = useMemo(() => (c ? JSON.stringify(c, null, 2) : ''), [c]);
+
+ if (!c) {
+ return (
+ <Center flex={1}>
+ <Text type="secondary">Pick a case to begin.</Text>
+ </Center>
+ );
+ }
+
+ return (
+ <div className={styles.wrap}>
+ <Flexbox horizontal align="center" justify="space-between">
+ <Text style={{ fontSize: 11 }} type="secondary">
+ {c.id}
+ </Text>
+ <Button
+ icon={<Copy size={14} />}
+ size="small"
+ onClick={() =>
+ navigator.clipboard
+ .writeText(json)
+ .catch((err) => console.error('[AgentMock] Copy failed:', err))
+ }
+ >
+ Copy
+ </Button>
+ </Flexbox>
+ <pre className={styles.pre}>{json}</pre>
+ </div>
+ );
+});
+
+FixtureView.displayName = 'AgentMockFixtureView';
diff --git a/src/features/AgentMockDevtools/views/TimelineView.tsx b/src/features/AgentMockDevtools/views/TimelineView.tsx
new file mode 100644
index 00000000000..10e55bca3c7
--- /dev/null
+++ b/src/features/AgentMockDevtools/views/TimelineView.tsx
@@ -0,0 +1,95 @@
+import type { MockEvent } from '@lobechat/agent-mock';
+import { Center, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo, useCallback, useMemo } from 'react';
+import { Virtuoso } from 'react-virtuoso';
+
+import { useAgentMockPlayer } from '../hooks/useAgentMockPlayer';
+import { useMockCases } from '../hooks/useMockCases';
+import { useAgentMockStore } from '../store/agentMockStore';
+import { EventRow } from '../Timeline/EventRow';
+
+const styles = createStaticStyles(({ css }) => ({
+ list: css`
+ overflow: hidden;
+ flex: 1;
+
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 8px;
+
+ background: ${cssVar.colorBgContainer};
+ `,
+ meta: css`
+ margin-block-end: 8px;
+ font-size: 11px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ wrap: css`
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+
+ height: 100%;
+ min-height: 0;
+ `,
+}));
+
+export const TimelineView = memo(() => {
+ const { all } = useMockCases();
+ const selectedCaseId = useAgentMockStore((s) => s.selectedCaseId);
+ const playback = useAgentMockStore((s) => s.playback);
+ const { seekToEventIndex } = useAgentMockPlayer();
+ const c = all.find((x) => x.id === selectedCaseId);
+
+ const events = useMemo<MockEvent[]>(() => {
+ if (!c) return [];
+ if (c.source.type === 'fixture') return c.source.events;
+ if (c.source.type === 'snapshot') return c.source.events ?? [];
+ if (c.source.type === 'generator') return c.source.events ?? [];
+ return [];
+ }, [c]);
+
+ const cumulative = useMemo(() => {
+ const out: number[] = [];
+ let acc = 0;
+ for (const e of events) {
+ acc += e.delay ?? 0;
+ out.push(acc);
+ }
+ return out;
+ }, [events]);
+
+ const renderItem = useCallback(
+ (idx: number, ev: MockEvent) => (
+ <EventRow
+ cumulativeMs={cumulative[idx] ?? 0}
+ event={ev}
+ index={idx}
+ isActive={playback?.currentEventIndex === idx}
+ onClick={() => seekToEventIndex(idx)}
+ />
+ ),
+ [cumulative, playback?.currentEventIndex, seekToEventIndex],
+ );
+
+ if (!c) {
+ return (
+ <Center flex={1}>
+ <Text type="secondary">Pick a case to begin.</Text>
+ </Center>
+ );
+ }
+
+ return (
+ <div className={styles.wrap}>
+ <div className={styles.meta}>
+ {events.length} events · {((cumulative.at(-1) ?? 0) / 1000).toFixed(1)}s total
+ </div>
+ <div className={styles.list}>
+ <Virtuoso data={events} itemContent={renderItem} />
+ </div>
+ </div>
+ );
+});
+
+TimelineView.displayName = 'AgentMockTimelineView';
diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
index 3323555a3fd..9e1e6c4e191 100644
--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx
+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
@@ -71,6 +71,7 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })
isSecondLastMessageFromUser,
virtuaRef,
});
+
const isAutoScrollEnabled = useAutoScrollEnabled();
// Store actions
diff --git a/src/layout/SPAGlobalProvider/index.tsx b/src/layout/SPAGlobalProvider/index.tsx
index 9e73cb5ec48..4f441d9a66b 100644
--- a/src/layout/SPAGlobalProvider/index.tsx
+++ b/src/layout/SPAGlobalProvider/index.tsx
@@ -8,6 +8,7 @@ import { lazy, memo, type PropsWithChildren, Suspense, useLayoutEffect } from 'r
import { LobeAnalyticsProviderWrapper } from '@/components/Analytics/LobeAnalyticsProviderWrapper';
import { DragUploadProvider } from '@/components/DragUploadZone/DragUploadProvider';
import { isDesktop } from '@/const/version';
+import AgentMockDevtools from '@/features/AgentMockDevtools';
import AuthProvider from '@/layout/AuthProvider';
import AppTheme from '@/layout/GlobalProvider/AppTheme';
import DynamicFavicon from '@/layout/GlobalProvider/DynamicFavicon';
@@ -82,6 +83,7 @@ const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {
<Suspense>
<ImportSettings />
{/* DevPanel disabled in SPA: depends on node:fs */}
+ {process.env.NODE_ENV === 'development' && <AgentMockDevtools />}
</Suspense>
</ServerConfigStoreProvider>
</AppTheme>
diff --git a/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts b/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts
index 0e4f7efac2a..752875d46ef 100644
--- a/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts
+++ b/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts
@@ -10,6 +10,10 @@ vi.mock('@/store/user/store', () => ({
getUserStoreState: vi.fn(),
}));
+vi.mock('@/store/chat/store', () => ({
+ getChatStoreState: vi.fn(() => ({})),
+}));
+
describe('emitClientAgentSignalSourceEvent', () => {
beforeEach(() => {
vi.clearAllMocks();