π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(codex): improve rich tool rendering and add devtools preview (#14100)
Arvin Xuf7ed6df35be6
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.tsindex 25b46bc21ca..96364f7d02c 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts@@ -16,6 +16,7 @@ import {import { app as electronApp, BrowserWindow } from 'electron';import { getHeterogeneousAgentDriver } from '@/modules/heterogeneousAgent';+import { CodexFileChangeTracker } from '@/modules/heterogeneousAgent/codexFileChangeTracker';import type {HeterogeneousAgentImageAttachment,HeterogeneousAgentParsedOutput,@@ -587,18 +588,31 @@ export default class HeterogeneousAgentCtr extends ControllerModule {session.process = proc;const streamProcessor = driver.createStreamProcessor();+ const codexFileChangeTracker =+ session.agentType === 'codex' ? new CodexFileChangeTracker() : undefined;+ let stdoutBroadcastQueue: Promise<void> = Promise.resolve();const broadcastParsedOutputs = (parsedOutputs: HeterogeneousAgentParsedOutput[]) => {- for (const parsedOutput of parsedOutputs) {- if (parsedOutput.agentSessionId) {- session.agentSessionId = parsedOutput.agentSessionId;- }-- this.broadcast('heteroAgentRawLine', {- line: parsedOutput.payload,- sessionId: session.sessionId,+ stdoutBroadcastQueue = stdoutBroadcastQueue+ .then(async () => {+ for (const parsedOutput of parsedOutputs) {+ if (parsedOutput.agentSessionId) {+ session.agentSessionId = parsedOutput.agentSessionId;+ }++ const line = codexFileChangeTracker+ ? await codexFileChangeTracker.track(parsedOutput.payload)+ : parsedOutput.payload;++ this.broadcast('heteroAgentRawLine', {+ line,+ sessionId: session.sessionId,+ });+ }+ })+ .catch((error) => {+ logger.error('Failed to broadcast parsed agent output:', error);});- }};// Stream stdout events as raw provider payloads to Renderer.@@ -628,33 +642,37 @@ export default class HeterogeneousAgentCtr extends ControllerModule {});proc.on('exit', (code, signal) => {- logger.info('Agent process exited:', { code, sessionId: session.sessionId, signal });- session.process = undefined;-- // If *we* killed it (cancel / stop / before-quit), treat the non-zero- // exit as a clean shutdown β surfacing it as an error would make a- // user-initiated cancel look like an agent failure, and an Electron- // shutdown affecting OTHER running CC sessions would pollute their- // topics with a misleading "Agent exited with code 143" message.- if (session.cancelledByUs) {- this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });- resolve();- return;- }+ void stdoutBroadcastQueue.finally(() => {+ logger.info('Agent process exited:', { code, sessionId: session.sessionId, signal });+ session.process = undefined;++ // If *we* killed it (cancel / stop / before-quit), treat the non-zero+ // exit as a clean shutdown β surfacing it as an error would make a+ // user-initiated cancel look like an agent failure, and an Electron+ // shutdown affecting OTHER running CC sessions would pollute their+ // topics with a misleading "Agent exited with code 143" message.+ if (session.cancelledByUs) {+ this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });+ resolve();+ return;+ }- if (code === 0) {- this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });- resolve();- } else {- const stderrOutput = stderrChunks.join('').trim();- const errorMsg = stderrOutput || `Agent exited with code ${code}`;- const sessionError = this.getSessionErrorPayload(errorMsg, session);- this.broadcast('heteroAgentSessionError', {- error: sessionError,- sessionId: session.sessionId,- });- reject(new Error(typeof sessionError === 'string' ? sessionError : sessionError.message));- }+ if (code === 0) {+ this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });+ resolve();+ } else {+ const stderrOutput = stderrChunks.join('').trim();+ const errorMsg = stderrOutput || `Agent exited with code ${code}`;+ const sessionError = this.getSessionErrorPayload(errorMsg, session);+ this.broadcast('heteroAgentSessionError', {+ error: sessionError,+ sessionId: session.sessionId,+ });+ reject(+ new Error(typeof sessionError === 'string' ? sessionError : sessionError.message),+ );+ }+ });});});}diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/codexFileChangeTracker.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/codexFileChangeTracker.test.tsnew file mode 100644index 00000000000..ca8c45ca0cd--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/codexFileChangeTracker.test.ts@@ -0,0 +1,146 @@+import { mkdtemp, rename, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it } from 'vitest';++import { CodexFileChangeTracker } from './codexFileChangeTracker';++describe('CodexFileChangeTracker', () => {+ const tempDirs: string[] = [];++ afterEach(async () => {+ await Promise.all(tempDirs.map((dir) => rm(dir, { force: true, recursive: true })));+ tempDirs.length = 0;+ });++ it('enriches completed file_change payloads with per-file and total line stats', async () => {+ const dir = await mkdtemp(path.join(tmpdir(), 'codex-file-change-tracker-'));+ tempDirs.push(dir);++ const updatePath = path.join(dir, 'a.txt');+ const addPath = path.join(dir, 'b.txt');++ await writeFile(updatePath, 'hello\n', 'utf8');++ const tracker = new CodexFileChangeTracker();++ await tracker.track({+ item: {+ changes: [+ { kind: 'update', path: updatePath },+ { kind: 'add', path: addPath },+ ],+ id: 'item_1',+ type: 'file_change',+ },+ type: 'item.started',+ });++ await writeFile(updatePath, 'hello\nappended line\n', 'utf8');+ await writeFile(addPath, 'line one\nline two\n', 'utf8');++ const enriched = await tracker.track({+ item: {+ changes: [+ { kind: 'update', path: updatePath },+ { kind: 'add', path: addPath },+ ],+ id: 'item_1',+ type: 'file_change',+ },+ type: 'item.completed',+ });++ expect(enriched.item).toMatchObject({+ changes: [+ {+ kind: 'update',+ linesAdded: 1,+ linesDeleted: 0,+ path: updatePath,+ },+ {+ kind: 'add',+ linesAdded: 2,+ linesDeleted: 0,+ path: addPath,+ },+ ],+ linesAdded: 3,+ linesDeleted: 0,+ });+ });++ it('treats rename changes as metadata-only and keeps line stats at zero', async () => {+ const dir = await mkdtemp(path.join(tmpdir(), 'codex-file-change-tracker-'));+ tempDirs.push(dir);++ const beforePath = path.join(dir, 'before.txt');+ const afterPath = path.join(dir, 'after.txt');++ await writeFile(beforePath, 'content\n', 'utf8');++ const tracker = new CodexFileChangeTracker();++ await tracker.track({+ item: {+ changes: [{ kind: 'rename', path: afterPath }],+ id: 'item_rename',+ type: 'file_change',+ },+ type: 'item.started',+ });++ await rename(beforePath, afterPath);++ const enriched = await tracker.track({+ item: {+ changes: [{ kind: 'rename', path: afterPath }],+ id: 'item_rename',+ type: 'file_change',+ },+ type: 'item.completed',+ });++ expect(enriched.item).toMatchObject({+ changes: [{ kind: 'rename', linesAdded: 0, linesDeleted: 0, path: afterPath }],+ linesAdded: 0,+ linesDeleted: 0,+ });+ });++ it('counts added lines even when file content begins with repeated plus markers', async () => {+ const dir = await mkdtemp(path.join(tmpdir(), 'codex-file-change-tracker-'));+ tempDirs.push(dir);++ const addPath = path.join(dir, 'plus-prefixed.txt');+ const tracker = new CodexFileChangeTracker();++ await tracker.track({+ item: {+ changes: [{ kind: 'add', path: addPath }],+ id: 'item_plus_prefix',+ type: 'file_change',+ },+ type: 'item.started',+ });++ await writeFile(addPath, '++leading content\n+++header lookalike\n', 'utf8');++ const enriched = await tracker.track({+ item: {+ changes: [{ kind: 'add', path: addPath }],+ id: 'item_plus_prefix',+ type: 'file_change',+ },+ type: 'item.completed',+ });++ expect(enriched.item).toMatchObject({+ changes: [{ kind: 'add', linesAdded: 2, linesDeleted: 0, path: addPath }],+ linesAdded: 2,+ linesDeleted: 0,+ });+ });+});diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/codexFileChangeTracker.ts b/apps/desktop/src/main/modules/heterogeneousAgent/codexFileChangeTracker.tsnew file mode 100644index 00000000000..1340fa7ff5e--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/codexFileChangeTracker.ts@@ -0,0 +1,181 @@+import { access, readFile } from 'node:fs/promises';++import { createPatch } from 'diff';++interface CodexFileChangeEntry {+ kind?: string;+ path?: string;+}++interface CodexFileChangeSnapshot {+ content?: string;+ exists: boolean;+}++interface CodexFileChangeItem {+ changes?: CodexFileChangeEntry[];+ id?: string;+ type?: string;+}++interface CodexFileChangePayload {+ item?: CodexFileChangeItem;+ type?: string;+}++interface CodexFileChangeLineStats {+ linesAdded: number;+ linesDeleted: number;+}++interface CodexTrackedFileChangeEntry extends CodexFileChangeEntry, CodexFileChangeLineStats {}++interface CodexTrackedFileChangeItem extends CodexFileChangeItem, CodexFileChangeLineStats {+ changes?: CodexTrackedFileChangeEntry[];+}++const isCodexFileChangePayload = (+ payload: CodexFileChangePayload,+): payload is Required<CodexFileChangePayload> =>+ payload?.item?.type === 'file_change' && !!payload.item.id;++const readTextFileSnapshot = async (filePath: string): Promise<CodexFileChangeSnapshot> => {+ try {+ await access(filePath);+ } catch {+ return { exists: false };+ }++ try {+ return {+ content: await readFile(filePath, 'utf8'),+ exists: true,+ };+ } catch {+ return { exists: true };+ }+};++const countPatchLines = (+ previousContent: string,+ nextContent: string,+): CodexFileChangeLineStats => {+ if (previousContent === nextContent) return { linesAdded: 0, linesDeleted: 0 };++ const patch = createPatch('codex-file-change', previousContent, nextContent, '', '');+ let insideHunk = false;+ let linesAdded = 0;+ let linesDeleted = 0;++ for (const line of patch.split('\n')) {+ if (line.startsWith('@@')) {+ insideHunk = true;+ continue;+ }++ if (!insideHunk) continue;++ if (line.startsWith('+')) {+ linesAdded += 1;+ continue;+ }++ if (line.startsWith('-')) {+ linesDeleted += 1;+ }+ }++ return { linesAdded, linesDeleted };+};++const computeLineStats = async (+ change: CodexFileChangeEntry,+ snapshot?: CodexFileChangeSnapshot,+): Promise<CodexFileChangeLineStats> => {+ const filePath = change.path;+ if (!filePath) return { linesAdded: 0, linesDeleted: 0 };++ const kind = change.kind ?? 'update';+ if (kind === 'rename') return { linesAdded: 0, linesDeleted: 0 };++ const previousContent = snapshot?.content ?? '';+ const current = await readTextFileSnapshot(filePath);+ const nextContent = current.content ?? '';++ if (kind === 'add') {+ if (!current.exists) return { linesAdded: 0, linesDeleted: 0 };+ return countPatchLines('', nextContent);+ }++ if (kind === 'delete' || kind === 'remove') {+ if (!snapshot?.exists) return { linesAdded: 0, linesDeleted: 0 };+ return countPatchLines(previousContent, '');+ }++ if (!snapshot?.exists && !current.exists) return { linesAdded: 0, linesDeleted: 0 };++ return countPatchLines(previousContent, nextContent);+};++export class CodexFileChangeTracker {+ private snapshots = new Map<string, Map<string, CodexFileChangeSnapshot>>();++ async track<T extends CodexFileChangePayload>(payload: T): Promise<T> {+ if (!isCodexFileChangePayload(payload)) return payload;++ const itemId = payload.item.id;+ const changes = payload.item.changes ?? [];++ if (payload.type === 'item.started') {+ const snapshots = new Map<string, CodexFileChangeSnapshot>();++ await Promise.all(+ changes.map(async (change) => {+ if (!change.path || snapshots.has(change.path)) return;+ snapshots.set(change.path, await readTextFileSnapshot(change.path));+ }),+ );++ this.snapshots.set(itemId, snapshots);+ return payload;+ }++ if (payload.type !== 'item.completed') return payload;++ const snapshots = this.snapshots.get(itemId);+ this.snapshots.delete(itemId);++ if (!snapshots) return payload;++ const trackedChanges = await Promise.all(+ changes.map(async (change) => {+ const stats = await computeLineStats(+ change,+ change.path ? snapshots.get(change.path) : undefined,+ );++ return {+ ...change,+ ...stats,+ } satisfies CodexTrackedFileChangeEntry;+ }),+ );++ const totals = trackedChanges.reduce<CodexFileChangeLineStats>(+ (acc, change) => ({+ linesAdded: acc.linesAdded + change.linesAdded,+ linesDeleted: acc.linesDeleted + change.linesDeleted,+ }),+ { linesAdded: 0, linesDeleted: 0 },+ );++ return {+ ...payload,+ item: {+ ...payload.item,+ ...totals,+ changes: trackedChanges,+ } satisfies CodexTrackedFileChangeItem,+ };+ }+}diff --git a/packages/builtin-tools/src/codex/FileChangeInspector.tsx b/packages/builtin-tools/src/codex/FileChangeInspector.tsxnew file mode 100644index 00000000000..61b593bc5f7--- /dev/null+++ b/packages/builtin-tools/src/codex/FileChangeInspector.tsx@@ -0,0 +1,83 @@+'use client';++import { FilePathDisplay } from '@lobechat/shared-tool-ui/components';+import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';+import type { BuiltinInspectorProps } from '@lobechat/types';+import { createStaticStyles, cx } from 'antd-style';+import { memo } from 'react';++import { type CodexFileChangeArgs, type CodexFileChangeState, getFileChangeStats } from './utils';++const styles = createStaticStyles(({ css, cssVar }) => ({+ chip: css`+ overflow: hidden;+ display: inline-flex;+ flex-shrink: 1;+ align-items: center;++ min-width: 0;+ margin-inline-start: 6px;+ padding-block: 2px;+ padding-inline: 10px;+ border-radius: 999px;++ background: ${cssVar.colorFillTertiary};+ `,+ count: css`+ margin-inline-start: 4px;+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ lineAdded: css`+ margin-inline-start: 6px;+ font-size: 12px;+ font-weight: 600;+ color: ${cssVar.colorSuccess};+ `,+ lineDeleted: css`+ margin-inline-start: 4px;+ font-size: 12px;+ font-weight: 600;+ color: ${cssVar.colorError};+ `,+}));++const FileChangeInspector = memo<BuiltinInspectorProps<CodexFileChangeArgs, CodexFileChangeState>>(+ ({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {+ const stats = getFileChangeStats(args || partialArgs, pluginState);+ const hasLineStats = stats.linesAdded > 0 || stats.linesDeleted > 0;++ if (isArgumentsStreaming && !stats.firstPath) {+ return (+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>File changes</div>+ );+ }++ return (+ <div+ className={cx(+ inspectorTextStyles.root,+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,+ )}+ >+ <span>File changes:</span>+ {stats.firstPath && (+ <span className={styles.chip}>+ <FilePathDisplay filePath={stats.firstPath} />+ </span>+ )}+ {stats.total > 1 && <span className={styles.count}>+{stats.total - 1}</span>}+ {hasLineStats && (+ <>+ <span className={styles.lineAdded}>+{stats.linesAdded}</span>+ <span className={styles.lineDeleted}>-{stats.linesDeleted}</span>+ </>+ )}+ </div>+ );+ },+);++FileChangeInspector.displayName = 'CodexFileChangeInspector';++export default FileChangeInspector;diff --git a/packages/builtin-tools/src/codex/FileChangeRender.tsx b/packages/builtin-tools/src/codex/FileChangeRender.tsxnew file mode 100644index 00000000000..1c1040bcc69--- /dev/null+++ b/packages/builtin-tools/src/codex/FileChangeRender.tsx@@ -0,0 +1,253 @@+'use client';++import { FilePathDisplay, ToolResultCard } from '@lobechat/shared-tool-ui/components';+import type { BuiltinRenderProps } from '@lobechat/types';+import { Flexbox, Icon, Text } from '@lobehub/ui';+import { createStaticStyles, cx } from 'antd-style';+import { Files, FileText } from 'lucide-react';+import { memo } from 'react';++import {+ type CodexFileChangeArgs,+ type CodexFileChangeKind,+ type CodexFileChangeState,+ getFileChangeData,+ getFileChangeKind,+ getFileChangeStats,+} from './utils';++const styles = createStaticStyles(({ css, cssVar }) => ({+ emptyState: css`+ padding: 4px;+ font-size: 13px;+ color: ${cssVar.colorTextTertiary};+ `,+ header: css`+ flex-wrap: wrap;+ gap: 6px;+ align-items: center;+ min-width: 0;+ `,+ headerChip: css`+ overflow: hidden;+ display: inline-flex;+ flex: 0 1 auto;+ align-items: center;++ min-width: 0;+ max-width: 100%;+ padding-block: 4px;+ padding-inline: 10px;+ border-radius: 999px;++ background: ${cssVar.colorFillTertiary};+ `,+ headerCount: css`+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ headerLabel: css`+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ `,+ kindAdded: css`+ background: ${cssVar.colorSuccess};+ `,+ kindDeleted: css`+ background: ${cssVar.colorError};+ `,+ kindDot: css`+ flex-shrink: 0;+ width: 8px;+ height: 8px;+ border-radius: 999px;+ `,+ kindModified: css`+ background: ${cssVar.colorInfo};+ `,+ kindRenamed: css`+ background: ${cssVar.colorWarning};+ `,+ lineAdded: css`+ font-weight: 600;+ color: ${cssVar.colorSuccess};+ `,+ lineDeleted: css`+ font-weight: 600;+ color: ${cssVar.colorError};+ `,+ lineStats: css`+ display: inline-flex;+ flex-shrink: 0;+ gap: 6px;+ align-items: center;++ font-size: 12px;+ `,+ list: css`+ gap: 0;+ `,+ panel: css`+ overflow: hidden;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 12px;+ background: ${cssVar.colorFillQuaternary};+ `,+ panelHeader: css`+ flex-wrap: wrap;+ gap: 8px;+ align-items: center;++ padding: 12px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ background: ${cssVar.colorBgContainer};+ `,+ panelMeta: css`+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ panelTitle: css`+ display: flex;+ gap: 8px;+ align-items: center;+ min-width: 0;+ `,+ rowMain: css`+ display: flex;+ flex: 1;+ gap: 10px;+ align-items: center;++ min-width: 0;+ `,+ path: css`+ overflow: hidden;+ display: flex;+ align-items: center;+ min-width: 0;+ `,+ row: css`+ gap: 10px;+ align-items: center;+ padding: 12px;++ & + & {+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ }+ `,+ unknownPath: css`+ font-size: 13px;+ color: ${cssVar.colorTextTertiary};+ `,+}));++const getKindClassName = (kind: CodexFileChangeKind) => {+ switch (kind) {+ case 'added': {+ return styles.kindAdded;+ }+ case 'deleted': {+ return styles.kindDeleted;+ }+ case 'renamed': {+ return styles.kindRenamed;+ }+ default: {+ return styles.kindModified;+ }+ }+};++const LineStats = memo<{ className?: string; linesAdded?: number; linesDeleted?: number }>(+ ({ className, linesAdded = 0, linesDeleted = 0 }) => {+ if (linesAdded === 0 && linesDeleted === 0) return null;++ return (+ <span className={cx(styles.lineStats, className)}>+ <span className={styles.lineAdded}>+{linesAdded}</span>+ <span className={styles.lineDeleted}>-{linesDeleted}</span>+ </span>+ );+ },+);+LineStats.displayName = 'CodexFileChangeLineStats';++const FileChangeRender = memo<BuiltinRenderProps<CodexFileChangeArgs, CodexFileChangeState>>(+ ({ args, pluginState }) => {+ const stats = getFileChangeStats(args, pluginState);+ const data = getFileChangeData(args, pluginState);+ const summary = stats.total === 1 ? '1 file change' : `${stats.total} file changes`;+ const detail = [+ stats.byKind.added > 0 ? `${stats.byKind.added} added` : null,+ stats.byKind.modified > 0 ? `${stats.byKind.modified} modified` : null,+ stats.byKind.deleted > 0 ? `${stats.byKind.deleted} deleted` : null,+ stats.byKind.renamed > 0 ? `${stats.byKind.renamed} renamed` : null,+ ]+ .filter(Boolean)+ .join(', ');++ return (+ <ToolResultCard+ wrapHeader+ icon={FileText}+ header={+ <Flexbox horizontal align={'center'} className={styles.header} wrap={'wrap'}>+ <Text className={styles.headerLabel}>File changes:</Text>+ {stats.firstPath && (+ <span className={styles.headerChip}>+ <FilePathDisplay filePath={stats.firstPath} />+ </span>+ )}+ {stats.total > 1 && <Text className={styles.headerCount}>+{stats.total - 1}</Text>}+ <LineStats linesAdded={stats.linesAdded} linesDeleted={stats.linesDeleted} />+ </Flexbox>+ }+ >+ {stats.total > 0 ? (+ <div className={styles.panel}>+ <Flexbox horizontal align={'center'} className={styles.panelHeader} wrap={'wrap'}>+ <div className={styles.panelTitle}>+ <Icon icon={Files} size={16} />+ <Text strong>{summary}</Text>+ </div>+ {detail && <Text className={styles.panelMeta}>{detail}</Text>}+ <LineStats linesAdded={stats.linesAdded} linesDeleted={stats.linesDeleted} />+ </Flexbox>+ <Flexbox className={styles.list}>+ {data.changes.map((change, index) => {+ const kind = getFileChangeKind(change.kind);+ const path = change.path || '';++ return (+ <Flexbox horizontal className={styles.row} key={`${path}-${index}`}>+ <span className={cx(styles.kindDot, getKindClassName(kind))} />+ <div className={styles.rowMain}>+ <div className={styles.path}>+ {path ? (+ <FilePathDisplay filePath={path} />+ ) : (+ <Text className={styles.unknownPath}>Unknown file</Text>+ )}+ </div>+ <LineStats+ linesAdded={change.linesAdded}+ linesDeleted={change.linesDeleted}+ />+ </div>+ </Flexbox>+ );+ })}+ </Flexbox>+ </div>+ ) : (+ <Text className={styles.emptyState}>No file changes</Text>+ )}+ </ToolResultCard>+ );+ },+);++FileChangeRender.displayName = 'CodexFileChangeRender';++export default FileChangeRender;diff --git a/packages/builtin-tools/src/codex/TodoListInspector.tsx b/packages/builtin-tools/src/codex/TodoListInspector.tsxnew file mode 100644index 00000000000..a29ab72f510--- /dev/null+++ b/packages/builtin-tools/src/codex/TodoListInspector.tsx@@ -0,0 +1,29 @@+'use client';++import type { TodoWriteArgs } from '@lobechat/builtin-tool-claude-code';+import { ClaudeCodeApiName } from '@lobechat/builtin-tool-claude-code';+import { ClaudeCodeInspectors } from '@lobechat/builtin-tool-claude-code/client';+import type { BuiltinInspectorProps } from '@lobechat/types';+import { type ComponentType, memo } from 'react';++import { type CodexTodoListArgs, toTodoWriteArgs } from './utils';++const TodoListInspector = memo<BuiltinInspectorProps<CodexTodoListArgs>>(+ ({ args, partialArgs, ...rest }) => {+ const TodoWriteInspector = ClaudeCodeInspectors[ClaudeCodeApiName.TodoWrite] as ComponentType<+ BuiltinInspectorProps<TodoWriteArgs>+ >;++ return (+ <TodoWriteInspector+ {...rest}+ args={toTodoWriteArgs(args)}+ partialArgs={toTodoWriteArgs(partialArgs)}+ />+ );+ },+);++TodoListInspector.displayName = 'CodexTodoListInspector';++export default TodoListInspector;diff --git a/packages/builtin-tools/src/codex/TodoListRender.tsx b/packages/builtin-tools/src/codex/TodoListRender.tsxnew file mode 100644index 00000000000..4f34931f4ea--- /dev/null+++ b/packages/builtin-tools/src/codex/TodoListRender.tsx@@ -0,0 +1,21 @@+'use client';++import type { TodoWriteArgs } from '@lobechat/builtin-tool-claude-code';+import { ClaudeCodeApiName } from '@lobechat/builtin-tool-claude-code';+import { ClaudeCodeRenders } from '@lobechat/builtin-tool-claude-code/client';+import type { BuiltinRenderProps } from '@lobechat/types';+import { type ComponentType, memo } from 'react';++import { type CodexTodoListArgs, toTodoWriteArgs } from './utils';++const TodoListRender = memo<BuiltinRenderProps<CodexTodoListArgs>>(({ args, ...rest }) => {+ const TodoWriteRender = ClaudeCodeRenders[ClaudeCodeApiName.TodoWrite] as ComponentType<+ BuiltinRenderProps<TodoWriteArgs>+ >;++ return <TodoWriteRender {...rest} args={toTodoWriteArgs(args)} />;+});++TodoListRender.displayName = 'CodexTodoListRender';++export default TodoListRender;diff --git a/packages/builtin-tools/src/codex/index.ts b/packages/builtin-tools/src/codex/index.tsnew file mode 100644index 00000000000..32cd0355b9e--- /dev/null+++ b/packages/builtin-tools/src/codex/index.ts@@ -0,0 +1,25 @@+import {+ type BuiltinInspector,+ type BuiltinRender,+ type RenderDisplayControl,+} from '@lobechat/types';++import FileChangeInspector from './FileChangeInspector';+import FileChangeRender from './FileChangeRender';+import TodoListInspector from './TodoListInspector';+import TodoListRender from './TodoListRender';++export const CodexInspectors: Record<string, BuiltinInspector> = {+ file_change: FileChangeInspector as BuiltinInspector,+ todo_list: TodoListInspector as BuiltinInspector,+};++export const CodexRenders: Record<string, BuiltinRender> = {+ file_change: FileChangeRender as BuiltinRender,+ todo_list: TodoListRender as BuiltinRender,+};++export const CodexRenderDisplayControls: Record<string, RenderDisplayControl> = {+ file_change: 'expand',+ todo_list: 'expand',+};diff --git a/packages/builtin-tools/src/codex/utils.ts b/packages/builtin-tools/src/codex/utils.tsnew file mode 100644index 00000000000..c0f5ca6595c--- /dev/null+++ b/packages/builtin-tools/src/codex/utils.ts@@ -0,0 +1,157 @@+'use client';++import type { ClaudeCodeTodoItem, TodoWriteArgs } from '@lobechat/builtin-tool-claude-code';++export interface CodexTodoListEntry {+ completed?: boolean;+ text?: string;+}++export interface CodexTodoListArgs {+ items?: CodexTodoListEntry[];+}++export type CodexFileChangeKind = 'added' | 'deleted' | 'modified' | 'renamed';++export interface CodexFileChangeEntry {+ kind?: string;+ linesAdded?: number;+ linesDeleted?: number;+ path?: string;+}++export interface CodexFileChangeArgs {+ changes?: CodexFileChangeEntry[];+}++export interface CodexFileChangeState {+ changes?: CodexFileChangeEntry[];+ linesAdded?: number;+ linesDeleted?: number;+}++export interface CodexFileChangeStats {+ byKind: Record<CodexFileChangeKind, number>;+ firstPath?: string;+ linesAdded: number;+ linesDeleted: number;+ total: number;+}++const normalizeTodoEntries = (args?: CodexTodoListArgs) =>+ (args?.items || [])+ .map((item) => ({+ completed: !!item.completed,+ text: typeof item.text === 'string' ? item.text.trim() : '',+ }))+ .filter((item) => item.text.length > 0);++export const toTodoWriteArgs = (args?: CodexTodoListArgs): TodoWriteArgs => {+ let assignedProcessing = false;++ const todos = normalizeTodoEntries(args).map((item): ClaudeCodeTodoItem => {+ if (item.completed) {+ return {+ activeForm: item.text,+ content: item.text,+ status: 'completed',+ };+ }++ if (!assignedProcessing) {+ assignedProcessing = true;+ return {+ activeForm: item.text,+ content: item.text,+ status: 'in_progress',+ };+ }++ return {+ activeForm: item.text,+ content: item.text,+ status: 'pending',+ };+ });++ return { todos };+};++export const getFileChangeKind = (kind?: string): CodexFileChangeKind => {+ switch (kind) {+ case 'add': {+ return 'added';+ }+ case 'delete':+ case 'remove': {+ return 'deleted';+ }+ case 'rename': {+ return 'renamed';+ }+ default: {+ return 'modified';+ }+ }+};++export const getFileChangeKindLabel = (kind: CodexFileChangeKind) => {+ switch (kind) {+ case 'added': {+ return 'Add';+ }+ case 'deleted': {+ return 'Delete';+ }+ case 'renamed': {+ return 'Rename';+ }+ default: {+ return 'Modify';+ }+ }+};++export const formatFileChangeLineStats = (linesAdded = 0, linesDeleted = 0) => {+ if (linesAdded === 0 && linesDeleted === 0) return '';+ return `+${linesAdded} -${linesDeleted}`;+};++export const getFileChangeData = (+ args?: CodexFileChangeArgs,+ pluginState?: CodexFileChangeState,+) => ({+ changes: pluginState?.changes?.length ? pluginState.changes : (args?.changes ?? []),+ linesAdded: pluginState?.linesAdded ?? 0,+ linesDeleted: pluginState?.linesDeleted ?? 0,+});++export const getFileChangeStats = (+ args?: CodexFileChangeArgs,+ pluginState?: CodexFileChangeState,+): CodexFileChangeStats => {+ const byKind = {+ added: 0,+ deleted: 0,+ modified: 0,+ renamed: 0,+ } satisfies Record<CodexFileChangeKind, number>;++ const data = getFileChangeData(args, pluginState);+ let firstPath: string | undefined;+ let total = 0;++ for (const change of data.changes) {+ if (!firstPath && change.path) firstPath = change.path;+ byKind[getFileChangeKind(change.kind)] += 1;+ total += 1;+ }++ return {+ byKind,+ firstPath,+ linesAdded: data.linesAdded,+ linesDeleted: data.linesDeleted,+ total,+ };+};diff --git a/packages/builtin-tools/src/displayControls.ts b/packages/builtin-tools/src/displayControls.tsindex 01593dd8fcb..1c7330de602 100644--- a/packages/builtin-tools/src/displayControls.ts+++ b/packages/builtin-tools/src/displayControls.ts@@ -4,11 +4,19 @@ import {} from '@lobechat/builtin-tool-claude-code/client';import { type RenderDisplayControl } from '@lobechat/types';+import { CodexRenderDisplayControls } from './codex';+// Kept separate from `./renders` so consumers that only need display-control// fallbacks (e.g. the tool store selector) don't pull in every builtin tool's// render registry β that graph cycles back through `@/store/tool/selectors`.-const BuiltinRenderDisplayControls: Record<string, Record<string, RenderDisplayControl>> = {- [ClaudeCodeIdentifier]: ClaudeCodeRenderDisplayControls,+const getBuiltinRenderDisplayControls = (): Record<+ string,+ Record<string, RenderDisplayControl>+> => {+ return {+ [ClaudeCodeIdentifier]: ClaudeCodeRenderDisplayControls,+ codex: CodexRenderDisplayControls,+ };};export const getBuiltinRenderDisplayControl = (@@ -16,5 +24,5 @@ export const getBuiltinRenderDisplayControl = (apiName?: string,): RenderDisplayControl | undefined => {if (!identifier || !apiName) return undefined;- return BuiltinRenderDisplayControls[identifier]?.[apiName];+ return getBuiltinRenderDisplayControls()[identifier]?.[apiName];};diff --git a/packages/builtin-tools/src/inspectors.ts b/packages/builtin-tools/src/inspectors.tsindex 5db4f790aa4..8c5f1f7ae90 100644--- a/packages/builtin-tools/src/inspectors.ts+++ b/packages/builtin-tools/src/inspectors.ts@@ -51,6 +51,8 @@ import {import { createRunCommandInspector } from '@lobechat/shared-tool-ui/inspectors';import { type BuiltinInspector } from '@lobechat/types';+import { CodexInspectors } from './codex';+/*** Builtin tools inspector registry* Organized by toolset (identifier) -> API name@@ -88,6 +90,7 @@ const BuiltinToolInspectors: Record<string, Record<string, BuiltinInspector>> =[SkillsManifest.identifier]: SkillsInspectors as Record<string, BuiltinInspector>,[WebBrowsingManifest.identifier]: WebBrowsingInspectors as Record<string, BuiltinInspector>,codex: {+ ...CodexInspectors,command_execution: createRunCommandInspector('Run') as BuiltinInspector,},};diff --git a/packages/builtin-tools/src/renders.ts b/packages/builtin-tools/src/renders.tsindex 6da8c7eecf4..90ef1e4714e 100644--- a/packages/builtin-tools/src/renders.ts+++ b/packages/builtin-tools/src/renders.ts@@ -36,6 +36,14 @@ import {import { RunCommandRender } from '@lobechat/shared-tool-ui/renders';import { type BuiltinRender } from '@lobechat/types';+import { CodexRenders } from './codex';++export interface BuiltinRenderRegistryEntry {+ apiName: string;+ identifier: string;+ render: BuiltinRender;+}+/*** Builtin tools renders registry* Organized by toolset (identifier) -> API name@@ -61,10 +69,22 @@ const BuiltinToolsRenders: Record<string, Record<string, BuiltinRender>> = {['lobe-tools']: LobeActivatorRenders as Record<string, BuiltinRender>,[WebBrowsingManifest.identifier]: WebBrowsingRenders as Record<string, BuiltinRender>,codex: {+ ...CodexRenders,command_execution: RunCommandRender as BuiltinRender,},};+export const listBuiltinRenderEntries = (): BuiltinRenderRegistryEntry[] =>+ Object.entries(BuiltinToolsRenders).flatMap(([identifier, toolset]) =>+ Object.entries(toolset)+ .filter((entry): entry is [string, BuiltinRender] => !!entry[1])+ .map(([apiName, render]) => ({+ apiName,+ identifier,+ render,+ })),+ );+/*** Get builtin render component for a specific API* @param identifier - Tool identifier (e.g., 'lobe-local-system')diff --git a/packages/heterogeneous-agents/src/adapters/__fixtures__/codex/collab_tool_call.spawn_wait.jsonl b/packages/heterogeneous-agents/src/adapters/__fixtures__/codex/collab_tool_call.spawn_wait.jsonlnew file mode 100644index 00000000000..7617aa0ce4f--- /dev/null+++ b/packages/heterogeneous-agents/src/adapters/__fixtures__/codex/collab_tool_call.spawn_wait.jsonl@@ -0,0 +1,11 @@+{"type":"thread.started","thread_id":"019dba1e-eec2-7a22-bdfb-ac6175e03081"}+{"type":"turn.started"}+{"type":"item.completed","item":{"id":"item_0","type":"agent_message","text":"Delegating a minimal side task to a subagent now, then Iβll wait for its result and return a two-point summary only."}}+{"type":"item.started","item":{"id":"item_1","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"019dba1e-eec2-7a22-bdfb-ac6175e03081","receiver_thread_ids":[],"prompt":"Return a single short line stating what 2 + 2 equals. Do not add anything else.","agents_states":{},"status":"in_progress"}}+{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"The first delegation call was rejected because of incompatible spawn settings. Retrying with a minimal subagent configuration."}}+{"type":"item.started","item":{"id":"item_3","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"019dba1e-eec2-7a22-bdfb-ac6175e03081","receiver_thread_ids":[],"prompt":"Return a single short line stating what 2 + 2 equals. Do not add anything else.","agents_states":{},"status":"in_progress"}}+{"type":"item.completed","item":{"id":"item_3","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"019dba1e-eec2-7a22-bdfb-ac6175e03081","receiver_thread_ids":["019dba1f-171e-7ae0-8d0d-2c659c15a4f0"],"prompt":"Return a single short line stating what 2 + 2 equals. Do not add anything else.","agents_states":{"019dba1f-171e-7ae0-8d0d-2c659c15a4f0":{"status":"pending_init","message":null}},"status":"completed"}}+{"type":"item.started","item":{"id":"item_4","type":"collab_tool_call","tool":"wait","sender_thread_id":"019dba1e-eec2-7a22-bdfb-ac6175e03081","receiver_thread_ids":["019dba1f-171e-7ae0-8d0d-2c659c15a4f0"],"prompt":null,"agents_states":{},"status":"in_progress"}}+{"type":"item.completed","item":{"id":"item_4","type":"collab_tool_call","tool":"wait","sender_thread_id":"019dba1e-eec2-7a22-bdfb-ac6175e03081","receiver_thread_ids":["019dba1f-171e-7ae0-8d0d-2c659c15a4f0"],"prompt":null,"agents_states":{"019dba1f-171e-7ae0-8d0d-2c659c15a4f0":{"status":"completed","message":"2 + 2 = 4"}},"status":"completed"}}+{"type":"item.completed","item":{"id":"item_5","type":"agent_message","text":"- Spawned one subagent to handle the side task of answering `2 + 2`.\n- Waited for completion, and the subagent returned: `2 + 2 = 4`."}}+{"type":"turn.completed","usage":{"input_tokens":52937,"cached_input_tokens":43008,"output_tokens":416}}diff --git a/packages/heterogeneous-agents/src/adapters/codex.test.ts b/packages/heterogeneous-agents/src/adapters/codex.test.tsindex 445edd8b151..a032ecddeba 100644--- a/packages/heterogeneous-agents/src/adapters/codex.test.ts+++ b/packages/heterogeneous-agents/src/adapters/codex.test.ts@@ -1,7 +1,17 @@+import { readFile } from 'node:fs/promises';+import { describe, expect, it } from 'vitest';import { CodexAdapter } from './codex';+const loadFixture = async (name: string) => {+ const raw = await readFile(new URL(`./__fixtures__/codex/${name}`, import.meta.url), 'utf8');+ return raw+ .trim()+ .split('\n')+ .map((line) => JSON.parse(line));+};+describe('CodexAdapter', () => {it('captures the session id from thread.started', () => {const adapter = new CodexAdapter();@@ -188,6 +198,273 @@ describe('CodexAdapter', () => {});});+ it('maps todo_list items into shared todo plugin state', () => {+ const adapter = new CodexAdapter();++ const todoItem = {+ id: 'item_0',+ items: [+ { completed: true, text: 'Create the three-item todo list' },+ { completed: false, text: 'Keep the second item incomplete' },+ { completed: false, text: 'Keep the third item incomplete' },+ ],+ type: 'todo_list',+ };++ const started = adapter.adapt({+ item: todoItem,+ type: 'item.started',+ });+ const completed = adapter.adapt({+ item: todoItem,+ type: 'item.completed',+ });++ expect(started[0]).toMatchObject({+ data: {+ chunkType: 'tools_calling',+ toolsCalling: [+ {+ apiName: 'todo_list',+ id: 'item_0',+ identifier: 'codex',+ },+ ],+ },+ type: 'stream_chunk',+ });+ expect(completed[0]).toMatchObject({+ data: {+ content: 'Todo list updated (1/3 completed).',+ pluginState: {+ todos: {+ items: [+ { status: 'completed', text: 'Create the three-item todo list' },+ { status: 'processing', text: 'Keep the second item incomplete' },+ { status: 'todo', text: 'Keep the third item incomplete' },+ ],+ },+ },+ toolCallId: 'item_0',+ },+ type: 'tool_result',+ });+ expect(completed[1]).toMatchObject({+ data: { isSuccess: true, toolCallId: 'item_0' },+ type: 'tool_end',+ });+ });++ it('maps file_change items into readable tool results', () => {+ const adapter = new CodexAdapter();++ const started = adapter.adapt({+ item: {+ changes: [{ kind: 'add', path: '/private/tmp/codex-file-change-sample.txt' }],+ id: 'item_1',+ status: 'in_progress',+ type: 'file_change',+ },+ type: 'item.started',+ });+ const completed = adapter.adapt({+ item: {+ changes: [+ {+ kind: 'add',+ linesAdded: 3,+ linesDeleted: 0,+ path: '/private/tmp/codex-file-change-sample.txt',+ },+ ],+ id: 'item_1',+ linesAdded: 3,+ linesDeleted: 0,+ status: 'completed',+ type: 'file_change',+ },+ type: 'item.completed',+ });++ expect(started[0]).toMatchObject({+ data: {+ chunkType: 'tools_calling',+ toolsCalling: [+ {+ apiName: 'file_change',+ id: 'item_1',+ identifier: 'codex',+ },+ ],+ },+ type: 'stream_chunk',+ });+ expect(completed[0]).toMatchObject({+ data: {+ content: 'File changes applied (1 added, +3 -0).',+ isError: false,+ pluginState: {+ changes: [+ {+ kind: 'add',+ linesAdded: 3,+ linesDeleted: 0,+ path: '/private/tmp/codex-file-change-sample.txt',+ },+ ],+ linesAdded: 3,+ linesDeleted: 0,+ },+ toolCallId: 'item_1',+ },+ type: 'tool_result',+ });+ expect(completed[1]).toMatchObject({+ data: { isSuccess: true, toolCallId: 'item_1' },+ type: 'tool_end',+ });+ });++ it('uses failure copy for unsuccessful non-command tool completions', () => {+ const adapter = new CodexAdapter();++ adapter.adapt({+ item: {+ id: 'todo_failed',+ items: [{ completed: false, text: 'Keep this pending' }],+ status: 'failed',+ type: 'todo_list',+ },+ type: 'item.started',+ });+ const failedTodo = adapter.adapt({+ item: {+ id: 'todo_failed',+ items: [{ completed: false, text: 'Keep this pending' }],+ status: 'failed',+ type: 'todo_list',+ },+ type: 'item.completed',+ });++ expect(failedTodo[0]).toMatchObject({+ data: {+ content: 'Todo list update failed.',+ isError: true,+ toolCallId: 'todo_failed',+ },+ type: 'tool_result',+ });+ expect(failedTodo[0].data).not.toHaveProperty('pluginState');+ expect(failedTodo[1]).toMatchObject({+ data: { isSuccess: false, toolCallId: 'todo_failed' },+ type: 'tool_end',+ });++ adapter.adapt({+ item: {+ changes: [{ kind: 'add', path: '/private/tmp/cancelled-change.ts' }],+ id: 'file_cancelled',+ status: 'cancelled',+ type: 'file_change',+ },+ type: 'item.started',+ });+ const cancelledFileChange = adapter.adapt({+ item: {+ changes: [{ kind: 'add', path: '/private/tmp/cancelled-change.ts' }],+ id: 'file_cancelled',+ status: 'cancelled',+ type: 'file_change',+ },+ type: 'item.completed',+ });++ expect(cancelledFileChange[0]).toMatchObject({+ data: {+ content: 'File changes cancelled.',+ isError: true,+ toolCallId: 'file_cancelled',+ },+ type: 'tool_result',+ });+ expect(cancelledFileChange[0].data).not.toHaveProperty('pluginState');+ expect(cancelledFileChange[1]).toMatchObject({+ data: { isSuccess: false, toolCallId: 'file_cancelled' },+ type: 'tool_end',+ });++ adapter.adapt({+ item: {+ id: 'wait_failed',+ status: 'error',+ tool: 'wait',+ type: 'collab_tool_call',+ },+ type: 'item.started',+ });+ const failedWait = adapter.adapt({+ item: {+ id: 'wait_failed',+ status: 'error',+ tool: 'wait',+ type: 'collab_tool_call',+ },+ type: 'item.completed',+ });++ expect(failedWait[0]).toMatchObject({+ data: {+ content: 'wait failed.',+ isError: true,+ toolCallId: 'wait_failed',+ },+ type: 'tool_result',+ });+ expect(failedWait[1]).toMatchObject({+ data: { isSuccess: false, toolCallId: 'wait_failed' },+ type: 'tool_end',+ });+ });++ it('keeps a real collab_tool_call stream fixture readable and flushes unfinished attempts', async () => {+ const adapter = new CodexAdapter();+ const rawEvents = await loadFixture('collab_tool_call.spawn_wait.jsonl');++ const adapted = rawEvents.flatMap((event) => adapter.adapt(event));+ const flushed = adapter.flush();++ const toolStarts = adapted+ .filter((event) => event.type === 'tool_start')+ .map((event) => event.data.toolCallId);+ const toolResults = adapted+ .filter((event) => event.type === 'tool_result')+ .map((event) => event.data);++ expect(toolStarts).toEqual(['item_1', 'item_3', 'item_4']);+ expect(toolResults).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ content: 'Spawned 1 subagent.',+ toolCallId: 'item_3',+ }),+ expect.objectContaining({+ content: 'Wait completed: 2 + 2 = 4',+ toolCallId: 'item_4',+ }),+ ]),+ );+ expect(flushed).toEqual([+ expect.objectContaining({+ data: {+ isSuccess: false,+ toolCallId: 'item_1',+ },+ type: 'tool_end',+ }),+ ]);+ });+it('emits cumulative tools_calling within the same Codex step', () => {const adapter = new CodexAdapter();diff --git a/packages/heterogeneous-agents/src/adapters/codex.ts b/packages/heterogeneous-agents/src/adapters/codex.tsindex e1bf1636f40..4e37be0fa0c 100644--- a/packages/heterogeneous-agents/src/adapters/codex.ts+++ b/packages/heterogeneous-agents/src/adapters/codex.ts@@ -9,17 +9,77 @@ import type {} from '../types';const CODEX_IDENTIFIER = 'codex';+const CODEX_COLLAB_TOOL_CALL_API = 'collab_tool_call';const CODEX_COMMAND_API = 'command_execution';+const CODEX_FILE_CHANGE_API = 'file_change';+const CODEX_TODO_LIST_API = 'todo_list';-interface CodexCommandExecutionItem {+interface CodexBaseItem {+ id: string;+ status?: string;+ type: string;+}++interface CodexCommandExecutionItem extends CodexBaseItem {aggregated_output?: string;command?: string;exit_code?: number | null;- id: string;+}++interface CodexTodoListEntry {+ completed?: boolean;+ text?: string;+}++interface CodexTodoListItem extends CodexBaseItem {+ items?: CodexTodoListEntry[];+}++interface CodexFileChangeEntry {+ kind?: string;+ linesAdded?: number;+ linesDeleted?: number;+ path?: string;+}++interface CodexFileChangeItem extends CodexBaseItem {+ changes?: CodexFileChangeEntry[];+ linesAdded?: number;+ linesDeleted?: number;+}++interface CodexCollabAgentState {+ message?: string | null;status?: string;- type: string;}+interface CodexCollabToolCallItem extends CodexBaseItem {+ agents_states?: Record<string, CodexCollabAgentState>;+ prompt?: string | null;+ receiver_thread_ids?: string[];+ sender_thread_id?: string;+ tool?: string;+}++type CodexToolItem =+ | CodexBaseItem+ | CodexCollabToolCallItem+ | CodexCommandExecutionItem+ | CodexFileChangeItem+ | CodexTodoListItem;++const isCommandExecutionItem = (item: CodexToolItem): item is CodexCommandExecutionItem =>+ item.type === CODEX_COMMAND_API;++const isCollabToolCallItem = (item: CodexToolItem): item is CodexCollabToolCallItem =>+ item.type === CODEX_COLLAB_TOOL_CALL_API;++const isFileChangeItem = (item: CodexToolItem): item is CodexFileChangeItem =>+ item.type === CODEX_FILE_CHANGE_API;++const isTodoListItem = (item: CodexToolItem): item is CodexTodoListItem =>+ item.type === CODEX_TODO_LIST_API;+const toUsageData = (raw:| {@@ -48,37 +108,212 @@ const toUsageData = (};};-const toToolPayload = (item: CodexCommandExecutionItem): ToolCallPayload => ({+const normalizeTodoListItems = (item: CodexTodoListItem) =>+ (item.items || [])+ .map((todo) => ({+ completed: !!todo.completed,+ text: typeof todo.text === 'string' ? todo.text.trim() : '',+ }))+ .filter((todo) => todo.text.length > 0);++/**+ * Codex's `todo_list` only exposes a boolean completed flag. To light up the+ * shared todo progress UI, treat the first incomplete item as the active one+ * and the remaining incomplete items as pending.+ */+const synthesizeTodoListPluginState = (item: CodexTodoListItem) => {+ const todos = normalizeTodoListItems(item);+ if (todos.length === 0) return;++ let assignedProcessing = false;+ const items = todos.map((todo) => {+ if (todo.completed) return { status: 'completed', text: todo.text } as const;+ if (!assignedProcessing) {+ assignedProcessing = true;+ return { status: 'processing', text: todo.text } as const;+ }+ return { status: 'todo', text: todo.text } as const;+ });++ return {+ todos: {+ items,+ updatedAt: new Date().toISOString(),+ },+ };+};++const synthesizeFileChangePluginState = (item: CodexFileChangeItem) => {+ const changes = (item.changes || []).map((change) => ({+ kind: change.kind,+ linesAdded: change.linesAdded ?? 0,+ linesDeleted: change.linesDeleted ?? 0,+ path: change.path,+ }));++ if (changes.length === 0 && item.linesAdded === undefined && item.linesDeleted === undefined) {+ return;+ }++ return {+ changes,+ linesAdded: item.linesAdded ?? 0,+ linesDeleted: item.linesDeleted ?? 0,+ };+};++const pluralize = (count: number, singular: string, plural = `${singular}s`) =>+ count === 1 ? singular : plural;++const toToolPayload = (item: CodexToolItem): ToolCallPayload => ({apiName: item.type || CODEX_COMMAND_API,- arguments: JSON.stringify(- item.type === CODEX_COMMAND_API ? { command: item.command || '' } : item,- ),+ arguments: JSON.stringify(isCommandExecutionItem(item) ? { command: item.command || '' } : item),id: item.id,identifier: CODEX_IDENTIFIER,type: 'default',});-const getToolContent = (item: CodexCommandExecutionItem): string => {- if (typeof item.aggregated_output === 'string') return item.aggregated_output;- return '';+const getFileChangeKind = (kind?: string) => {+ switch (kind) {+ case 'add': {+ return 'added';+ }+ case 'delete':+ case 'remove': {+ return 'deleted';+ }+ case 'rename': {+ return 'renamed';+ }+ default: {+ return 'modified';+ }+ }+};++const summarizeTodoList = (item: CodexTodoListItem): string => {+ const todos = normalizeTodoListItems(item);+ if (todos.length === 0) return 'Todo list updated.';++ const completed = todos.filter((todo) => todo.completed).length;+ return `Todo list updated (${completed}/${todos.length} completed).`;};-const getToolResultData = (item: CodexCommandExecutionItem): ToolResultData => {- const exitCode = item.exit_code ?? undefined;- const output = getToolContent(item);- const isSuccess = item.status === 'completed' && (exitCode === undefined || exitCode === 0);+const summarizeFileChange = (item: CodexFileChangeItem): string => {+ const counts = new Map<string, number>();++ for (const change of item.changes || []) {+ const kind = getFileChangeKind(change.kind);+ counts.set(kind, (counts.get(kind) || 0) + 1);+ }++ const totalChanges = [...counts.values()].reduce((sum, count) => sum + count, 0);+ if (totalChanges === 0) return 'File changes applied.';++ const parts = [...counts.entries()].map(([kind, count]) => `${count} ${kind}`);+ const statsSuffix =+ item.linesAdded || item.linesDeleted+ ? `, +${item.linesAdded || 0} -${item.linesDeleted || 0}`+ : '';++ return `File changes applied (${parts.join(', ')}${statsSuffix}).`;+};++const summarizeCollabToolCall = (item: CodexCollabToolCallItem): string => {+ const toolName = item.tool || 'collaboration';+ const agentStates = Object.values(item.agents_states || {});+ const agentCount = item.receiver_thread_ids?.length || agentStates.length;+ const completedMessage = agentStates.find(+ (state) => state.status === 'completed' && typeof state.message === 'string' && state.message,+ )?.message;++ if (toolName === 'spawn_agent') {+ return agentCount > 0+ ? `Spawned ${agentCount} ${pluralize(agentCount, 'subagent')}.`+ : 'Spawned subagent.';+ }++ if (toolName === 'wait') {+ if (completedMessage) return `Wait completed: ${completedMessage}`;+ return agentCount > 0+ ? `Wait completed for ${agentCount} ${pluralize(agentCount, 'subagent')}.`+ : 'Wait completed.';+ }++ return `${toolName} completed.`;+};++const summarizeFallbackTool = (item: CodexToolItem): string => {+ return `Completed ${item.type}.`;+};++const getFailureVerb = (item: CodexToolItem): 'cancelled' | 'failed' =>+ item.status === 'cancelled' ? 'cancelled' : 'failed';++const getToolFailureContent = (item: CodexToolItem): string => {+ if (isTodoListItem(item)) return `Todo list update ${getFailureVerb(item)}.`;+ if (isFileChangeItem(item)) return `File changes ${getFailureVerb(item)}.`;+ if (isCollabToolCallItem(item)) return `${item.tool || 'Collaboration'} ${getFailureVerb(item)}.`;++ return `${item.type} ${getFailureVerb(item)}.`;+};++const getToolContent = (item: CodexToolItem, isSuccess: boolean): string => {+ if (isCommandExecutionItem(item)) {+ return typeof item.aggregated_output === 'string' ? item.aggregated_output : '';+ }++ if (!isSuccess) return getToolFailureContent(item);++ if (isTodoListItem(item)) return summarizeTodoList(item);+ if (isFileChangeItem(item)) return summarizeFileChange(item);+ if (isCollabToolCallItem(item)) return summarizeCollabToolCall(item);++ return summarizeFallbackTool(item);+};++const isSuccessfulToolCompletion = (item: CodexToolItem): boolean => {+ if (isCommandExecutionItem(item)) {+ const exitCode = item.exit_code ?? undefined;+ return item.status === 'completed' && (exitCode === undefined || exitCode === 0);+ }++ return item.status !== 'cancelled' && item.status !== 'error' && item.status !== 'failed';+};++const getToolResultData = (item: CodexToolItem): ToolResultData => {+ const isSuccess = isSuccessfulToolCompletion(item);+ const output = getToolContent(item, isSuccess);++ if (isCommandExecutionItem(item)) {+ const exitCode = item.exit_code ?? undefined;++ return {+ content: output,+ isError: !isSuccess,+ pluginState: {+ ...(exitCode !== undefined ? { exitCode } : {}),+ ...(isSuccess ? {} : { error: output || `Command failed (${exitCode ?? 'unknown'})` }),+ isBackground: false,+ output,+ stdout: output,+ success: isSuccess,+ },+ toolCallId: item.id,+ };+ }++ const pluginState =+ isSuccess && isTodoListItem(item)+ ? synthesizeTodoListPluginState(item)+ : isSuccess && isFileChangeItem(item)+ ? synthesizeFileChangePluginState(item)+ : undefined;return {content: output,isError: !isSuccess,- pluginState: {- ...(exitCode !== undefined ? { exitCode } : {}),- ...(isSuccess ? {} : { error: output || `Command failed (${exitCode ?? 'unknown'})` }),- isBackground: false,- output,- stdout: output,- success: isSuccess,- },+ ...(pluginState ? { pluginState } : {}),toolCallId: item.id,};};@@ -248,12 +483,10 @@ export class CodexAdapter implements AgentEventAdapter {this.pendingToolCalls.delete(item.id);this.hasStepActivity = true;- events.push(this.makeEvent('tool_result', getToolResultData(item)));+ events.push(this.makeEvent('tool_result', getToolResultData(item as CodexToolItem)));events.push(this.makeEvent('tool_end', {- isSuccess:- item.status === 'completed' &&- (item.exit_code === null || item.exit_code === undefined || item.exit_code === 0),+ isSuccess: isSuccessfulToolCompletion(item as CodexToolItem),toolCallId: item.id,}),);diff --git a/src/features/DevPanel/RenderGallery/index.tsx b/src/features/DevPanel/RenderGallery/index.tsxnew file mode 100644index 00000000000..fafeca54331--- /dev/null+++ b/src/features/DevPanel/RenderGallery/index.tsx@@ -0,0 +1,285 @@+'use client';++import { listBuiltinRenderEntries } from '@lobechat/builtin-tools/renders';+import type { BuiltinRender } from '@lobechat/types';+import { Block, Flexbox, Tag, Text } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { Component, type ReactNode, useEffect, useMemo } from 'react';++import { useAgentGroupStore } from '@/store/agentGroup';++import {+ DEVTOOLS_GROUP_DETAIL,+ DEVTOOLS_GROUP_ID,+ getToolRenderFixture,+ getToolRenderMeta,+} from './toolRenderFixtures';++const styles = createStaticStyles(({ css, cssVar }) => ({+ body: css`+ gap: 24px;+ max-width: 1400px;+ padding: 28px;+ `,+ card: css`+ overflow: hidden;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 20px;+ background: ${cssVar.colorBgContainer};+ box-shadow: ${cssVar.boxShadowSecondary};+ `,+ cardBody: css`+ padding: 16px;+ `,+ cardHeader: css`+ gap: 10px;+ padding: 16px;+ border-bottom: 1px solid ${cssVar.colorBorderSecondary};+ background:+ linear-gradient(180deg, ${cssVar.colorFillQuaternary} 0%, ${cssVar.colorBgContainer} 100%);+ `,+ code: css`+ overflow: auto;+ max-height: 280px;+ margin: 0;+ padding: 12px;+ border-radius: 12px;+ font-size: 12px;+ line-height: 1.55;+ color: ${cssVar.colorTextSecondary};+ background: ${cssVar.colorFillQuaternary};+ `,+ fixtureSummary: css`+ cursor: pointer;+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ user-select: none;+ `,+ group: css`+ gap: 16px;+ `,+ groupHeader: css`+ gap: 8px;+ padding-block-end: 4px;+ `,+ page: css`+ overflow: auto;+ width: 100%;+ height: 100%;+ background:+ radial-gradient(circle at top, ${cssVar.colorFillTertiary} 0%, transparent 35%),+ ${cssVar.colorBgLayout};+ `,+ previewShell: css`+ padding: 16px;+ border-radius: 16px;+ background: ${cssVar.colorFillQuaternary};+ `,+ subtitle: css`+ max-width: 900px;+ font-size: 14px;+ line-height: 1.6;+ color: ${cssVar.colorTextSecondary};+ `,+ title: css`+ font-size: 36px;+ font-weight: 700;+ line-height: 1.1;+ color: ${cssVar.colorText};+ `,+}));++class RenderBoundary extends Component<+ { children: ReactNode },+ { error?: Error | undefined }+> {+ constructor(props: { children: ReactNode }) {+ super(props);+ this.state = { error: undefined };+ }++ static getDerivedStateFromError(error: Error) {+ return { error };+ }++ override render() {+ if (!this.state.error) return this.props.children;++ return (+ <Block padding={16} variant={'outlined'}>+ <Flexbox gap={8}>+ <Text fontSize={14} type={'danger'} weight={500}>+ Render crashed+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {this.state.error.message}+ </Text>+ </Flexbox>+ </Block>+ );+ }+}++const DevtoolsPage = () => {+ useEffect(() => {+ const previousGroupState = useAgentGroupStore.getState();++ useAgentGroupStore.setState({+ activeGroupId: DEVTOOLS_GROUP_ID,+ groupMap: {+ ...previousGroupState.groupMap,+ [DEVTOOLS_GROUP_ID]: DEVTOOLS_GROUP_DETAIL as any,+ },+ });++ return () => {+ useAgentGroupStore.setState({+ activeGroupId: previousGroupState.activeGroupId,+ groupMap: previousGroupState.groupMap,+ });+ };+ }, []);++ const groupedEntries = useMemo(() => {+ const sections = new Map<+ string,+ {+ description?: string;+ entries: Array<{+ apiName: string;+ description?: string;+ fixture: ReturnType<typeof getToolRenderFixture>;+ identifier: string;+ render: BuiltinRender;+ toolsetName: string;+ }>;+ toolsetName: string;+ }+ >();++ const entries = listBuiltinRenderEntries().sort((left, right) => {+ const identifierCompare = left.identifier.localeCompare(right.identifier);+ if (identifierCompare !== 0) return identifierCompare;+ return left.apiName.localeCompare(right.apiName);+ });++ for (const entry of entries) {+ const meta = getToolRenderMeta(entry.identifier, entry.apiName);+ const fixture = getToolRenderFixture(entry.identifier, entry.apiName, meta.api);+ const group = sections.get(entry.identifier);++ const normalizedEntry = {+ apiName: entry.apiName,+ description: meta.description,+ fixture,+ identifier: entry.identifier,+ render: entry.render,+ toolsetName: meta.toolsetName,+ };++ if (group) {+ group.entries.push(normalizedEntry);+ } else {+ sections.set(entry.identifier, {+ description: meta.toolsetDescription,+ entries: [normalizedEntry],+ toolsetName: meta.toolsetName,+ });+ }+ }++ return [...sections.values()];+ }, []);++ return (+ <div className={styles.page}>+ <Flexbox className={styles.body}>+ <Flexbox gap={12}>+ <div className={styles.title}>Devtools Render Gallery</div>+ <div className={styles.subtitle}>+ Development-only preview page for every registered builtin tool render. Each card is+ driven by a stable local fixture so we can visually smoke test new tool UIs without+ reproducing a full conversation flow first.+ </div>+ </Flexbox>++ {groupedEntries.map((group) => (+ <Flexbox className={styles.group} key={group.toolsetName}>+ <Flexbox className={styles.groupHeader}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Text fontSize={20} weight={600}>+ {group.toolsetName}+ </Text>+ <Tag>{group.entries.length} renders</Tag>+ </Flexbox>+ {group.description && (+ <Text fontSize={13} type={'secondary'}>+ {group.description}+ </Text>+ )}+ </Flexbox>++ {group.entries.map((entry) => {+ const Render = entry.render as BuiltinRender;+ const fixture = entry.fixture;+ const messageId = `devtools-${entry.identifier}-${entry.apiName}`;++ return (+ <Flexbox className={styles.card} key={`${entry.identifier}-${entry.apiName}`}>+ <Flexbox className={styles.cardHeader}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Text fontSize={16} weight={600}>+ {entry.apiName}+ </Text>+ <Tag>{entry.identifier}</Tag>+ </Flexbox>+ {entry.description && (+ <Text fontSize={13} type={'secondary'}>+ {entry.description}+ </Text>+ )}+ </Flexbox>++ <Flexbox className={styles.cardBody} gap={12}>+ <div className={styles.previewShell}>+ <RenderBoundary>+ <Render+ apiName={entry.apiName}+ args={fixture.args}+ content={fixture.content}+ identifier={entry.identifier}+ messageId={messageId}+ pluginError={fixture.pluginError}+ pluginState={fixture.pluginState}+ toolCallId={`${messageId}-tool`}+ />+ </RenderBoundary>+ </div>++ <details>+ <summary className={styles.fixtureSummary}>Fixture payload</summary>+ <pre className={styles.code}>+ {JSON.stringify(+ {+ args: fixture.args,+ content: fixture.content,+ pluginError: fixture.pluginError,+ pluginState: fixture.pluginState,+ },+ null,+ 2,+ )}+ </pre>+ </details>+ </Flexbox>+ </Flexbox>+ );+ })}+ </Flexbox>+ ))}+ </Flexbox>+ </div>+ );+};++export default DevtoolsPage;diff --git a/src/features/DevPanel/RenderGallery/toolRenderFixtures.ts b/src/features/DevPanel/RenderGallery/toolRenderFixtures.tsnew file mode 100644index 00000000000..17846472bcf--- /dev/null+++ b/src/features/DevPanel/RenderGallery/toolRenderFixtures.ts@@ -0,0 +1,1083 @@+'use client';++import { ClaudeCodeIdentifier } from '@lobechat/builtin-tool-claude-code/client';+import { builtinTools } from '@lobechat/builtin-tools';+import type { BuiltinRenderProps, BuiltinToolManifest, LobeChatPluginApi } from '@lobechat/types';++export interface ToolRenderFixture extends Partial<+ Pick<BuiltinRenderProps, 'args' | 'content' | 'pluginError' | 'pluginState'>+> {}++export interface ToolRenderMeta {+ api?: LobeChatPluginApi;+ apiName: string;+ description?: string;+ identifier: string;+ toolsetDescription?: string;+ toolsetName: string;+}++export const DEVTOOLS_GROUP_ID = 'devtools-preview-group';++export const DEVTOOLS_GROUP_DETAIL = {+ agents: [+ {+ avatar: 'π§',+ backgroundColor: '#E8F3FF',+ id: 'researcher-agent',+ title: 'Researcher',+ },+ {+ avatar: 'π ',+ backgroundColor: '#FFF3E8',+ id: 'builder-agent',+ title: 'Builder',+ },+ ],+ avatar: 'π₯',+ backgroundColor: '#EEF2FF',+ description: 'Fixture group used by /devtools to preview grouped task renders.',+ id: DEVTOOLS_GROUP_ID,+ title: 'Devtools Preview Group',+};++const customToolsets: Record<+ string,+ {+ api: Array<Pick<LobeChatPluginApi, 'description' | 'name'>>;+ meta: { description?: string; title: string };+ }+> = {+ [ClaudeCodeIdentifier]: {+ api: [+ { description: 'Spawn and summarize a sub-agent task.', name: 'Agent' },+ { description: 'Run a shell command.', name: 'Bash' },+ { description: 'Patch file contents.', name: 'Edit' },+ { description: 'Find files by glob pattern.', name: 'Glob' },+ { description: 'Search file contents.', name: 'Grep' },+ { description: 'Read file content.', name: 'Read' },+ { description: 'Run a Claude Code skill.', name: 'Skill' },+ { description: 'Track todo progress.', name: 'TodoWrite' },+ { description: 'Write a new file.', name: 'Write' },+ ],+ meta: {+ description: 'Anthropic Claude Code render previews.',+ title: 'Claude Code',+ },+ },+ codex: {+ api: [+ { description: 'Run a shell command in Codex.', name: 'command_execution' },+ { description: 'Preview Codex file change summaries.', name: 'file_change' },+ { description: 'Preview Codex todo list rendering.', name: 'todo_list' },+ ],+ meta: {+ description: 'Codex-specific render previews and shared command cards.',+ title: 'Codex',+ },+ },+};++const manifestByIdentifier = new Map<string, BuiltinToolManifest>(+ builtinTools.map((tool) => [tool.identifier, tool.manifest]),+);++const humanize = (value: string) =>+ value+ .replaceAll('_', ' ')+ .replaceAll(/([a-z0-9])([A-Z])/g, '$1 $2')+ .replaceAll(/\s+/g, ' ')+ .trim()+ .replace(/^./, (char) => char.toUpperCase());++const buildStringSample = (key: string, schema: any) => {+ if (schema?.format === 'uri' || key.toLowerCase().includes('url')) return 'https://example.com';+ if (key.toLowerCase().includes('path'))+ return `/workspace/${key.replace(/Path$/i, '').toLowerCase() || 'file'}.ts`;+ if (key.toLowerCase().includes('id')) return `${key}-sample`;+ if (key.toLowerCase().includes('query')) return 'tool render preview';+ if (key.toLowerCase().includes('title')) return 'Preview title';+ if (key.toLowerCase().includes('description')) return 'Preview description';+ if (key.toLowerCase().includes('content') || key.toLowerCase().includes('prompt')) {+ return `Sample ${humanize(key).toLowerCase()} for the devtools preview.`;+ }++ return `${humanize(key)} sample`;+};++const buildSchemaSample = (schema: any, key = 'value'): any => {+ if (!schema) return undefined;+ if (schema.default !== undefined) return schema.default;+ if (schema.example !== undefined) return schema.example;+ if (Array.isArray(schema.examples) && schema.examples.length > 0) return schema.examples[0];+ if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum[0];++ switch (schema.type) {+ case 'array': {+ const item = buildSchemaSample(+ schema.items,+ key.endsWith('s') ? key.slice(0, -1) : `${key}Item`,+ );+ return item === undefined ? [] : [item];+ }+ case 'boolean': {+ return true;+ }+ case 'integer':+ case 'number': {+ return 1;+ }+ case 'object': {+ const properties = schema.properties || {};+ return Object.fromEntries(+ Object.entries(properties)+ .map(([propertyKey, propertySchema]) => [+ propertyKey,+ buildSchemaSample(propertySchema, propertyKey),+ ])+ .filter(([, value]) => value !== undefined),+ );+ }+ case 'string':+ default: {+ return buildStringSample(key, schema);+ }+ }+};++const keyOf = (identifier: string, apiName: string) => `${identifier}:${apiName}`;++const toolRenderFixtures: Record<string, ToolRenderFixture> = {+ [keyOf('codex', 'command_execution')]: {+ args: { command: 'bun run type-check' },+ content: 'Checked 1247 files in 2.3s\nNo type errors found.',+ pluginState: {+ exitCode: 0,+ isBackground: false,+ output: 'Checked 1247 files in 2.3s\nNo type errors found.',+ stdout: 'Checked 1247 files in 2.3s\nNo type errors found.',+ success: true,+ },+ },+ [keyOf('codex', 'file_change')]: {+ args: {+ changes: [+ {+ kind: 'add',+ linesAdded: 62,+ linesDeleted: 0,+ path: 'src/routes/(main)/devtools/index.tsx',+ },+ {+ kind: 'modify',+ linesAdded: 23,+ linesDeleted: 0,+ path: 'packages/builtin-tools/src/renders.ts',+ },+ {+ kind: 'rename',+ linesAdded: 28,+ linesDeleted: 0,+ path: 'tmp/devtools-preview-old.tsx',+ },+ ],+ },+ content: 'File changes applied (1 added, 1 modified, 1 renamed).',+ pluginState: {+ changes: [+ {+ kind: 'add',+ linesAdded: 62,+ linesDeleted: 0,+ path: 'src/routes/(main)/devtools/index.tsx',+ },+ {+ kind: 'modify',+ linesAdded: 23,+ linesDeleted: 0,+ path: 'packages/builtin-tools/src/renders.ts',+ },+ {+ kind: 'rename',+ linesAdded: 28,+ linesDeleted: 0,+ path: 'tmp/devtools-preview-old.tsx',+ },+ ],+ linesAdded: 113,+ linesDeleted: 0,+ },+ },+ [keyOf('codex', 'todo_list')]: {+ args: {+ items: [+ { completed: true, text: 'Wire up the render registry export' },+ { completed: false, text: 'Build a devtools preview page' },+ { completed: false, text: 'Verify every tool render fixture' },+ ],+ },+ content: 'Todo list updated (1/3 completed).',+ },++ [keyOf(ClaudeCodeIdentifier, 'Agent')]: {+ args: {+ prompt:+ 'Inspect the generated preview fixtures and reply with a short note about the riskiest missing case.',+ },+ content:+ '- Search-driven renders still need richer empty-state fixtures.\n- The grouped execute-tasks preview depends on seeded agent-group state.',+ },+ [keyOf(ClaudeCodeIdentifier, 'Bash')]: {+ args: { command: 'rg -n "TodoListRender" packages src' },+ content:+ 'packages/builtin-tools/src/codex/TodoListRender.tsx:11:const TodoListRender = memo<...>',+ pluginState: {+ exitCode: 0,+ isBackground: false,+ output:+ 'packages/builtin-tools/src/codex/TodoListRender.tsx:11:const TodoListRender = memo<...>',+ stdout:+ 'packages/builtin-tools/src/codex/TodoListRender.tsx:11:const TodoListRender = memo<...>',+ success: true,+ },+ },+ [keyOf(ClaudeCodeIdentifier, 'Edit')]: {+ args: {+ file_path: 'src/spa/router/desktopRouter.config.desktop.tsx',+ new_string: "path: 'tasks',",+ old_string: "path: 'tasks',",+ },+ },+ [keyOf(ClaudeCodeIdentifier, 'Glob')]: {+ args: { path: 'src/routes', pattern: '**/index.tsx' },+ content: 'src/routes/(main)/agent/index.tsx\nsrc/routes/(main)/devtools/index.tsx',+ },+ [keyOf(ClaudeCodeIdentifier, 'Grep')]: {+ args: { path: 'packages', pattern: 'BuiltinRenderProps', type: 'ts' },+ content:+ 'packages/types/src/tool/builtin.ts:244:export interface BuiltinRenderProps<Arguments = any, State = any, Content = any> {',+ },+ [keyOf(ClaudeCodeIdentifier, 'Read')]: {+ args: { file_path: 'packages/builtin-tools/src/renders.ts' },+ content:+ "1 import { RunCommandRender } from '@lobechat/shared-tool-ui/renders';\n2 export interface BuiltinRenderRegistryEntry { ... }",+ },+ [keyOf(ClaudeCodeIdentifier, 'Skill')]: {+ args: { skill: 'codebase-search' },+ content: 'Use ripgrep first, then open only the relevant files to keep context sharp.',+ },+ [keyOf(ClaudeCodeIdentifier, 'TodoWrite')]: {+ args: {+ todos: [+ {+ activeForm: 'Capture current registry coverage',+ content: 'Capture current registry coverage',+ status: 'completed',+ },+ {+ activeForm: 'Build /devtools page',+ content: 'Build /devtools page',+ status: 'in_progress',+ },+ {+ activeForm: 'Audit missing fixtures',+ content: 'Audit missing fixtures',+ status: 'pending',+ },+ ],+ },+ },+ [keyOf(ClaudeCodeIdentifier, 'Write')]: {+ args: {+ content: "export const previewEnabled = process.env.NODE_ENV === 'development';\n",+ file_path: 'src/routes/(main)/devtools/featureFlag.ts',+ },+ },++ [keyOf('lobe-activator', 'activateSkill')]: {+ content:+ 'This skill focuses on shipping UI previews fast while keeping the registry easy to extend.',+ pluginState: {+ description: 'A lightweight workflow for building internal preview harnesses.',+ name: 'Preview Builder',+ },+ },++ [keyOf('lobe-agent-builder', 'getAvailableModels')]: {+ pluginState: {+ providers: [+ {+ id: 'openai',+ models: [+ { abilities: { functionCall: true, reasoning: true, vision: true }, id: 'gpt-5.4' },+ { abilities: { functionCall: true }, id: 'gpt-5.4-mini' },+ ],+ name: 'OpenAI',+ },+ {+ id: 'anthropic',+ models: [{ abilities: { functionCall: true, vision: true }, id: 'claude-sonnet-4' }],+ name: 'Anthropic',+ },+ ],+ },+ },+ [keyOf('lobe-agent-builder', 'installPlugin')]: {+ pluginState: {+ awaitingApproval: false,+ installed: true,+ pluginId: 'lobe-web-browsing',+ pluginName: 'Web Browsing',+ serverStatus: 'active',+ },+ },+ [keyOf('lobe-agent-builder', 'searchMarketTools')]: {+ pluginState: {+ query: 'browser',+ tools: [+ {+ author: 'LobeHub',+ description: 'Search and crawl web pages with configurable engines.',+ icon: 'π',+ identifier: 'lobe-web-browsing',+ installed: true,+ name: 'Web Browsing',+ tags: ['search', 'crawl'],+ },+ {+ author: 'LobeHub',+ description: 'Run code and inspect local files inside a sandbox.',+ icon: 'π§ͺ',+ identifier: 'lobe-cloud-sandbox',+ installed: false,+ name: 'Cloud Sandbox',+ tags: ['files', 'code'],+ },+ ],+ totalCount: 2,+ },+ },+ [keyOf('lobe-agent-builder', 'updateAgentConfig')]: {+ pluginState: {+ config: {+ newValues: { model: 'gpt-5.4', temperature: 0.4 },+ previousValues: { model: 'gpt-5.4-mini', temperature: 0.7 },+ updatedFields: ['model', 'temperature'],+ },+ meta: {+ newValues: {+ description: 'Pairs on internal developer workflows.',+ title: 'Devtools Copilot',+ },+ previousValues: { description: 'General helper.', title: 'Workspace Helper' },+ updatedFields: ['title', 'description'],+ },+ togglePlugin: {+ enabled: true,+ pluginId: 'lobe-web-browsing',+ },+ },+ },+ [keyOf('lobe-agent-builder', 'updatePrompt')]: {+ pluginState: {+ newPrompt:+ 'Be concise, keep teammates unblocked, and prefer reusable preview infrastructure over one-off screenshots.',+ },+ },++ [keyOf('lobe-agent-documents', 'createDocument')]: {+ args: {+ content:+ '# Devtools Preview Plan\n\n- Enumerate every render.\n- Provide a stable sample fixture.\n- Keep the page development-only.',+ title: 'Devtools Preview Plan',+ },+ pluginState: {+ documentId: 'doc_devtools_preview_plan',+ },+ },++ [keyOf('lobe-agent-management', 'callAgent')]: {+ args: {+ instruction:+ 'Review the `/devtools` route and list any preview cards that still need richer fixtures.',+ },+ },+ [keyOf('lobe-agent-management', 'createAgent')]: {+ args: {+ description: 'Internal helper for preview and QA workflows.',+ model: 'gpt-5.4',+ plugins: ['lobe-web-browsing', 'lobe-local-system'],+ provider: 'openai',+ systemRole: 'You help engineers verify UI changes quickly and carefully.',+ title: 'Preview QA Agent',+ },+ },+ [keyOf('lobe-agent-management', 'duplicateAgent')]: {+ pluginState: {+ newAgentId: 'agent_preview_clone',+ sourceAgentId: 'agent_workspace_helper',+ success: true,+ },+ },+ [keyOf('lobe-agent-management', 'getAgentDetail')]: {+ pluginState: {+ config: {+ model: 'gpt-5.4',+ plugins: ['lobe-web-browsing', 'lobe-cloud-sandbox'],+ provider: 'openai',+ systemRole: 'Focus on frontend verification and fast local feedback loops.',+ },+ meta: {+ avatar: 'π§ͺ',+ backgroundColor: '#EEF6FF',+ description: 'Specialized in preview harnesses and UI regression checks.',+ tags: ['preview', 'qa'],+ title: 'Preview Specialist',+ },+ },+ },+ [keyOf('lobe-agent-management', 'installPlugin')]: {+ pluginState: {+ installed: true,+ pluginId: 'lobe-cloud-sandbox',+ pluginName: 'Cloud Sandbox',+ },+ },+ [keyOf('lobe-agent-management', 'searchAgent')]: {+ pluginState: {+ agents: [+ {+ avatar: 'π§ͺ',+ backgroundColor: '#EEF6FF',+ description: 'Preview route and fixture maintainer.',+ id: 'agent_preview_specialist',+ isMarket: false,+ title: 'Preview Specialist',+ },+ {+ avatar: 'π',+ backgroundColor: '#FFF7E8',+ description: 'Keeps internal docs and issue writeups tidy.',+ id: 'agent_doc_partner',+ isMarket: true,+ title: 'Documentation Partner',+ },+ ],+ },+ },+ [keyOf('lobe-agent-management', 'updateAgent')]: {+ args: {+ config: JSON.stringify({+ model: 'gpt-5.4',+ systemRole: 'Prioritize maintainable developer tooling and preview coverage.',+ }),+ meta: JSON.stringify({+ description: 'Expanded to cover internal tooling previews.',+ title: 'Workspace Preview Partner',+ }),+ },+ },+ [keyOf('lobe-agent-management', 'updatePrompt')]: {+ args: {+ prompt:+ 'When asked for a visual check, prefer building a reusable preview harness before taking a screenshot.',+ },+ },++ [keyOf('lobe-cloud-sandbox', 'editLocalFile')]: {+ args: { path: '/sandbox/src/routes/devtools.tsx' },+ pluginState: {+ diffText: '@@ -1,2 +1,3 @@\n export const devtools = true;\n+export const previews = true;\n',+ linesAdded: 1,+ linesDeleted: 0,+ replacements: 1,+ },+ },+ [keyOf('lobe-cloud-sandbox', 'executeCode')]: {+ args: {+ code: 'const tools = ["todo", "file_change", "command_execution"]; console.log(tools.length);',+ language: 'typescript',+ },+ pluginState: {+ output: '3',+ stderr: '',+ },+ },+ [keyOf('lobe-cloud-sandbox', 'exportFile')]: {+ args: { path: '/sandbox/reports/devtools-preview.html' },+ pluginState: {+ downloadUrl: 'https://example.com/devtools-preview.html',+ filename: 'devtools-preview.html',+ success: true,+ },+ },+ [keyOf('lobe-cloud-sandbox', 'listLocalFiles')]: {+ args: { directoryPath: '/sandbox/src/routes' },+ pluginState: {+ files: [+ { isDirectory: true, name: 'agent' },+ { isDirectory: false, name: 'index.tsx', size: 2048 },+ { isDirectory: false, name: 'devtools.tsx', size: 4096 },+ ],+ },+ },+ [keyOf('lobe-cloud-sandbox', 'moveLocalFiles')]: {+ pluginState: {+ results: [+ {+ destination: '/sandbox/archive/devtools-preview.tsx',+ source: '/sandbox/tmp/devtools-preview.tsx',+ success: true,+ },+ ],+ successCount: 1,+ totalCount: 1,+ },+ },+ [keyOf('lobe-cloud-sandbox', 'readLocalFile')]: {+ args: { path: '/sandbox/src/routes/devtools.tsx' },+ pluginState: {+ content: 'export default function Devtools() {\n return <div>Preview</div>;\n}\n',+ endLine: 3,+ startLine: 1,+ totalLines: 3,+ },+ },+ [keyOf('lobe-cloud-sandbox', 'runCommand')]: {+ args: { command: 'bunx vitest run src/spa/router/desktopRouter.sync.test.tsx' },+ content: '1 passed',+ pluginState: {+ exitCode: 0,+ isBackground: false,+ output: '1 passed',+ stdout: '1 passed',+ success: true,+ },+ },+ [keyOf('lobe-cloud-sandbox', 'searchLocalFiles')]: {+ args: { directory: '/sandbox/src', keyword: 'devtools' },+ pluginState: {+ results: [+ { isDirectory: false, name: 'devtools.tsx', path: '/sandbox/src/routes/devtools.tsx' },+ {+ isDirectory: false,+ name: 'desktopRouter.config.tsx',+ path: '/sandbox/src/spa/router/desktopRouter.config.tsx',+ },+ ],+ totalCount: 2,+ },+ },+ [keyOf('lobe-cloud-sandbox', 'writeLocalFile')]: {+ args: {+ content: 'export const isDevtoolsEnabled = true;\n',+ path: '/sandbox/src/routes/devtools/flags.ts',+ },+ },++ [keyOf('lobe-group-agent-builder', 'batchCreateAgents')]: {+ args: {+ agents: [+ {+ avatar: 'π§ͺ',+ description: 'Checks render output and local screenshots.',+ title: 'Preview QA',+ tools: ['lobe-web-browsing', 'lobe-cloud-sandbox'],+ },+ {+ avatar: 'π',+ description: 'Writes issue notes and rollout summaries.',+ title: 'Docs Writer',+ tools: ['lobe-notebook'],+ },+ ],+ },+ pluginState: {+ agents: [+ { agentId: 'agent_preview_qa', success: true, title: 'Preview QA' },+ { agentId: 'agent_docs_writer', success: true, title: 'Docs Writer' },+ ],+ },+ },+ [keyOf('lobe-group-agent-builder', 'updateAgentPrompt')]: {+ pluginState: {+ newPrompt: 'Focus on validating preview fixtures and reporting only concrete UI issues.',+ },+ },+ [keyOf('lobe-group-agent-builder', 'updateGroupPrompt')]: {+ pluginState: {+ newPrompt: 'Coordinate fixture coverage across agents and avoid overlapping work.',+ },+ },++ [keyOf('lobe-group-management', 'broadcast')]: {+ args: {+ instruction:+ 'Everyone review one tool render section and flag any empty states that look broken.',+ },+ },+ [keyOf('lobe-group-management', 'executeAgentTask')]: {+ args: {+ instruction: 'Verify the `/devtools` route works in desktop development mode.',+ timeout: 1_800_000,+ title: 'Desktop smoke check',+ },+ },+ [keyOf('lobe-group-management', 'executeAgentTasks')]: {+ args: {+ tasks: [+ {+ agentId: 'researcher-agent',+ instruction: 'Check which render entries still fall back to empty-state samples.',+ title: 'Fixture audit',+ },+ {+ agentId: 'builder-agent',+ instruction:+ 'Verify router gating and ensure production builds cannot navigate to /devtools.',+ title: 'Route audit',+ },+ ],+ },+ },+ [keyOf('lobe-group-management', 'speak')]: {+ args: {+ instruction:+ 'Summarize the preview harness approach in two short sentences for the issue update.',+ },+ },++ [keyOf('lobe-gtd', 'clearTodos')]: {+ pluginState: {+ todos: {+ items: [+ { status: 'completed', text: 'Capture real stream data' },+ { status: 'processing', text: 'Build /devtools route' },+ ],+ },+ },+ },+ [keyOf('lobe-gtd', 'createPlan')]: {+ pluginState: {+ plan: {+ context:+ 'We want a reusable development-only page that renders every registered builtin tool card with a stable sample fixture.',+ description: 'Create a maintainable preview harness for builtin tool renders.',+ goal: 'Build /devtools render preview',+ id: 'plan_devtools_preview',+ },+ },+ },+ [keyOf('lobe-gtd', 'createTodos')]: {+ pluginState: {+ todos: {+ items: [+ { status: 'completed', text: 'Enumerate all render entries' },+ { status: 'processing', text: 'Create preview fixtures' },+ { status: 'todo', text: 'Smoke test the route locally' },+ ],+ },+ },+ },+ [keyOf('lobe-gtd', 'execTask')]: {+ pluginState: {+ task: {+ description: 'Smoke test the desktop router config',+ instruction:+ 'Run the desktop router sync test and confirm /devtools only appears in development.',+ },+ },+ },+ [keyOf('lobe-gtd', 'execTasks')]: {+ pluginState: {+ tasks: [+ {+ description: 'Audit builtin render coverage',+ instruction: 'Find any registered render without a usable sample fixture.',+ },+ {+ description: 'Check route gating',+ instruction: 'Make sure production builds do not expose /devtools.',+ },+ ],+ },+ },+ [keyOf('lobe-gtd', 'updatePlan')]: {+ pluginState: {+ plan: {+ context:+ 'The route is now in place; expand the preview harness by keeping fixture data next to the page.',+ description: 'Track the follow-up work for richer render fixtures.',+ goal: 'Expand /devtools coverage',+ id: 'plan_devtools_preview',+ },+ },+ },+ [keyOf('lobe-gtd', 'updateTodos')]: {+ pluginState: {+ todos: {+ items: [+ { status: 'completed', text: 'Export render registry entries' },+ { status: 'processing', text: 'Hydrate grouped task fixtures' },+ { status: 'todo', text: 'Add richer missing-state cases' },+ ],+ },+ },+ },++ [keyOf('lobe-knowledge-base', 'readKnowledge')]: {+ pluginState: {+ files: [+ {+ fileId: 'kb_devtools_guide',+ filename: 'devtools-preview-guide.md',+ preview:+ 'Use the /devtools route to visually verify builtin tool renders during development.',+ totalCharCount: 1420,+ totalLineCount: 42,+ },+ ],+ },+ },+ [keyOf('lobe-knowledge-base', 'searchKnowledgeBase')]: {+ pluginState: {+ fileResults: [+ {+ fileId: 'kb_router_preview',+ fileName: 'router-preview-checklist.md',+ relevanceScore: 0.93,+ },+ {+ fileId: 'kb_tool_fixtures',+ fileName: 'tool-render-fixtures.md',+ relevanceScore: 0.88,+ },+ ],+ },+ },++ [keyOf('lobe-local-system', 'editLocalFile')]: {+ args: { path: '/workspace/src/spa/router/desktopRouter.config.tsx' },+ pluginState: {+ diffText:+ "@@ -1,3 +1,7 @@\n export const desktopRoutes = [\n+ {\n+ path: 'devtools',\n+ },\n ];\n",+ },+ },+ [keyOf('lobe-local-system', 'listLocalFiles')]: {+ pluginState: {+ files: [+ { isDirectory: true, name: 'src' },+ { isDirectory: false, name: 'package.json', size: 1320 },+ { isDirectory: false, name: 'README.md', size: 4096 },+ ],+ },+ },+ [keyOf('lobe-local-system', 'moveLocalFiles')]: {+ args: {+ items: [+ {+ newPath: '/workspace/src/routes/(main)/devtools/index.tsx',+ oldPath: '/workspace/tmp/devtools-preview.tsx',+ },+ ],+ },+ },+ [keyOf('lobe-local-system', 'readLocalFile')]: {+ args: { path: '/workspace/src/routes/(main)/devtools/index.tsx' },+ pluginState: {+ content: 'export default function DevtoolsPage() {\n return <div>Render preview</div>;\n}\n',+ endLine: 3,+ fullPath: '/workspace/src/routes/(main)/devtools/index.tsx',+ path: 'src/routes/(main)/devtools/index.tsx',+ startLine: 1,+ totalLines: 3,+ },+ },+ [keyOf('lobe-local-system', 'runCommand')]: {+ args: { command: 'bun run type-check' },+ content: 'Checked 1247 files in 2.3s\nNo type errors found.',+ pluginState: {+ exitCode: 0,+ isBackground: false,+ output: 'Checked 1247 files in 2.3s\nNo type errors found.',+ stdout: 'Checked 1247 files in 2.3s\nNo type errors found.',+ success: true,+ },+ },+ [keyOf('lobe-local-system', 'searchLocalFiles')]: {+ args: { directory: '/workspace/src', keyword: 'devtools' },+ pluginState: {+ results: [+ {+ isDirectory: false,+ name: 'index.tsx',+ path: '/workspace/src/routes/(main)/devtools/index.tsx',+ },+ {+ isDirectory: false,+ name: 'desktopRouter.config.tsx',+ path: '/workspace/src/spa/router/desktopRouter.config.tsx',+ },+ ],+ },+ },+ [keyOf('lobe-local-system', 'writeLocalFile')]: {+ args: {+ content: 'export const devtoolsEnabled = process.env.NODE_ENV === "development";\n',+ path: '/workspace/src/routes/(main)/devtools/flags.ts',+ },+ },++ [keyOf('lobe-user-memory', 'addExperienceMemory')]: {+ args: {+ details: 'A reusable preview harness saved time compared with manual screenshot stitching.',+ summary: 'Building /devtools made visual QA faster and repeatable.',+ tags: ['devtools', 'preview', 'qa'],+ title: 'Preview harness rollout',+ withExperience: {+ action: 'Built a development-only route backed by stable sample fixtures.',+ keyLearning: 'Reusable preview pages reduce repeated manual validation work.',+ possibleOutcome: 'Future render additions can be checked in one place.',+ reasoning: 'A route-based harness is easier to maintain than ad hoc screenshot scripts.',+ situation: 'We needed to verify many builtin tool cards quickly.',+ },+ },+ },+ [keyOf('lobe-user-memory', 'addPreferenceMemory')]: {+ args: {+ details: 'Prefer route-based previews for UI verification over isolated screenshots.',+ summary: 'Use reusable local preview routes for internal QA.',+ tags: ['workflow', 'frontend'],+ title: 'Preview workflow preference',+ withPreference: {+ appContext: {+ app: 'LobeHub Desktop',+ feature: 'Builtin tool rendering',+ surface: '/devtools',+ },+ conclusionDirectives:+ 'Keep fixtures close to the route and update them when new renders land.',+ originContext: {+ actor: 'Frontend engineer',+ applicableWhen: 'Adding or refactoring tool renders',+ scenario: 'Need to verify many cards at once',+ trigger: 'A screenshot or local QA request comes in',+ },+ suggestions: ['Add a preview fixture before shipping a new render.'],+ type: 'workflow',+ },+ },+ },+ [keyOf('lobe-user-memory', 'searchUserMemory')]: {+ pluginState: {+ activities: [+ {+ feedback: 'The page made local validation much easier.',+ id: 'activity_devtools',+ narrative: 'Implemented a dev-only /devtools route for builtin render previews.',+ notes: 'Devtools preview route',+ tags: ['preview', 'devtools'],+ type: 'engineering',+ },+ ],+ experiences: [+ {+ action: 'Adopted a route-based preview harness.',+ id: 'experience_devtools',+ keyLearning: 'Stable fixtures are cheaper than repeating manual screenshots.',+ situation: 'Needed to verify many render components in one place.',+ tags: ['render', 'qa'],+ },+ ],+ preferences: [+ {+ conclusionDirectives: 'Prefer reusable preview infrastructure for repeated UI checks.',+ id: 'preference_devtools',+ tags: ['workflow'],+ title: 'Preview harness preference',+ },+ ],+ },+ },++ [keyOf('lobe-notebook', 'createDocument')]: {+ pluginState: {+ document: {+ content:+ '# Devtools route\n\nThis page renders every registered builtin tool card with sample fixtures so local QA stays fast.',+ id: 'notebook_devtools_route',+ title: 'Devtools Route Notes',+ },+ },+ },++ [keyOf('lobe-skill-store', 'importFromMarket')]: {+ content: 'preview-builder',+ pluginState: {+ name: 'preview-builder',+ status: 'created',+ success: true,+ },+ },+ [keyOf('lobe-skill-store', 'importSkill')]: {+ content: 'preview-builder',+ pluginState: {+ name: 'preview-builder',+ status: 'updated',+ success: true,+ },+ },+ [keyOf('lobe-skill-store', 'searchSkill')]: {+ pluginState: {+ items: [+ {+ category: 'Engineering',+ description: 'Scaffold and maintain internal preview routes for UI checks.',+ identifier: 'preview-builder',+ installCount: 128,+ name: 'Preview Builder',+ repository: 'https://github.com/lobehub/preview-builder',+ summary: 'Reusable preview harness workflows.',+ version: '0.3.1',+ },+ ],+ },+ },++ [keyOf('lobe-skills', 'activateSkill')]: {+ content: 'Use a fixture-backed route to preview all builtin tool cards locally.',+ pluginState: {+ description: 'Reusable workflow for internal preview harnesses.',+ name: 'Preview Builder',+ },+ },+ [keyOf('lobe-skills', 'execScript')]: {+ args: { command: 'pnpm lint src/routes/(main)/devtools' },+ content: 'No lint issues found.',+ pluginState: {+ command: 'pnpm lint src/routes/(main)/devtools',+ },+ },+ [keyOf('lobe-skills', 'readReference')]: {+ content:+ 'export const listBuiltinRenderEntries = () => [{ identifier: "codex", apiName: "todo_list" }];\n',+ pluginState: {+ encoding: 'utf-8',+ fullPath: '/workspace/packages/builtin-tools/src/renders.ts',+ path: 'packages/builtin-tools/src/renders.ts',+ size: 2048,+ },+ },+ [keyOf('lobe-skills', 'runCommand')]: {+ args: { command: 'bunx vitest run src/spa/router/desktopRouter.sync.test.tsx' },+ content: '1 passed',+ pluginState: {+ exitCode: 0,+ isBackground: false,+ output: '1 passed',+ stdout: '1 passed',+ success: true,+ },+ },++ [keyOf('lobe-web-browsing', 'crawlMultiPages')]: {+ args: {+ urls: ['https://lobehub.com', 'https://docs.lobehub.com'],+ },+ pluginState: {+ results: [+ {+ crawler: 'firecrawl',+ data: {+ content: 'LobeHub ships desktop and web experiences for AI collaboration.',+ description: 'Product homepage',+ title: 'LobeHub',+ url: 'https://lobehub.com',+ },+ originalUrl: 'https://lobehub.com',+ },+ {+ crawler: 'firecrawl',+ data: {+ content: 'Developer documentation for routing, tooling, and local testing.',+ description: 'Docs homepage',+ title: 'LobeHub Docs',+ url: 'https://docs.lobehub.com',+ },+ originalUrl: 'https://docs.lobehub.com',+ },+ ],+ },+ },+ [keyOf('lobe-web-browsing', 'crawlSinglePage')]: {+ args: { url: 'https://lobehub.com/blog' },+ pluginState: {+ results: [+ {+ crawler: 'firecrawl',+ data: {+ content: 'Recent product updates and engineering notes.',+ description: 'Blog landing page',+ title: 'LobeHub Blog',+ url: 'https://lobehub.com/blog',+ },+ originalUrl: 'https://lobehub.com/blog',+ },+ ],+ },+ },+ [keyOf('lobe-web-browsing', 'search')]: {+ args: {+ query: 'LobeHub devtools preview route',+ searchEngines: ['google', 'bing'],+ },+ pluginState: {+ query: 'LobeHub devtools preview route',+ results: [+ {+ content: 'Documentation and implementation notes about local preview tooling.',+ engines: ['google'],+ title: 'Preview tooling guide',+ url: 'https://docs.example.com/preview-tooling',+ },+ {+ content: 'Issue thread describing the /devtools route rollout.',+ engines: ['bing'],+ title: 'Builtin render devtools issue',+ url: 'https://linear.example.com/issue/LOBE-8114',+ },+ ],+ },+ },+};++export const getToolRenderFixture = (+ identifier: string,+ apiName: string,+ api?: LobeChatPluginApi,+): ToolRenderFixture => {+ const fixture = toolRenderFixtures[keyOf(identifier, apiName)];+ if (fixture) return fixture;++ return {+ args: buildSchemaSample(api?.parameters, apiName) || {},+ content: '',+ pluginState: undefined,+ };+};++export const getToolRenderMeta = (identifier: string, apiName: string): ToolRenderMeta => {+ const manifest = manifestByIdentifier.get(identifier);+ const api = manifest?.api.find((item) => item.name === apiName);+ const customToolset = customToolsets[identifier];+ const customApi = customToolset?.api.find((item) => item.name === apiName);++ return {+ api,+ apiName,+ description: api?.description || customApi?.description,+ identifier,+ toolsetDescription: manifest?.meta.description || customToolset?.meta.description,+ toolsetName: manifest?.meta.title || customToolset?.meta.title || humanize(identifier),+ };+};diff --git a/src/routes/(main)/devtools/index.tsx b/src/routes/(main)/devtools/index.tsxnew file mode 100644index 00000000000..a7d19f41b2b--- /dev/null+++ b/src/routes/(main)/devtools/index.tsx@@ -0,0 +1,3 @@+'use client';++export { default } from '@/features/DevPanel/RenderGallery';diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsxindex 88f9933f7cb..bbed7de7195 100644--- a/src/spa/router/desktopRouter.config.desktop.tsx+++ b/src/spa/router/desktopRouter.config.desktop.tsx@@ -42,6 +42,7 @@ import CommunityListModelLayout from '@/routes/(main)/community/(list)/model/_laimport CommunityListProviderPage from '@/routes/(main)/community/(list)/provider';import CommunityListSkillPage from '@/routes/(main)/community/(list)/skill';import CommunityListSkillLayout from '@/routes/(main)/community/(list)/skill/_layout';+import DevtoolsPage from '@/routes/(main)/devtools';import EvalOverviewPage from '@/routes/(main)/eval';import EvalLayout from '@/routes/(main)/eval/_layout';import EvalHomeLayout from '@/routes/(main)/eval/(home)/_layout';@@ -78,6 +79,8 @@ import ShareTopicPage from '@/routes/share/t/[id]';import ShareTopicLayout from '@/routes/share/t/[id]/_layout';import { ErrorBoundary, redirectElement } from '@/utils/router';+const isDev = process.env.NODE_ENV === 'development';+// Desktop router configuration β all sync imports for Electron local buildexport const desktopRoutes: RouteObject[] = [{@@ -458,6 +461,15 @@ export const desktopRoutes: RouteObject[] = [path: 'page',},+ ...(isDev+ ? [+ {+ element: <DevtoolsPage />,+ path: 'devtools',+ },+ ]+ : []),+// Default route - home page (handled by persistent layout){index: true,diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsxindex 0e4497e0c67..2286e81767a 100644--- a/src/spa/router/desktopRouter.config.tsx+++ b/src/spa/router/desktopRouter.config.tsx@@ -8,6 +8,8 @@ import {} from '@/business/client/BusinessDesktopRoutes';import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';+const isDev = process.env.NODE_ENV === 'development';+// Desktop router configuration (declarative mode)export const desktopRoutes: RouteObject[] = [{@@ -576,6 +578,18 @@ export const desktopRoutes: RouteObject[] = [path: 'page',},+ ...(isDev+ ? [+ {+ element: dynamicElement(+ () => import('@/routes/(main)/devtools'),+ 'Desktop > Devtools',+ ),+ path: 'devtools',+ },+ ]+ : []),+// Default route - home page (handled by persistent layout){index: true,