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.

🐛 fix(codex): scope repeated tool results (#15659)

Arvin Xu981c57d6f94a
diff --git a/packages/conversation-flow/src/__tests__/parse.test.ts b/packages/conversation-flow/src/__tests__/parse.test.ts
index fedd7cd506a..c340e2fa4b8 100644
--- a/packages/conversation-flow/src/__tests__/parse.test.ts
+++ b/packages/conversation-flow/src/__tests__/parse.test.ts
@@ -39,6 +39,128 @@ describe('parse', () => {
expect(serializeParseResult(result)).toEqual(outputs.assistantChainWithFollowup);
});
+
+ it('should keep assistant tool results scoped when tool call IDs repeat', () => {
+ const result = parse([
+ {
+ content: 'Current request',
+ createdAt: 0,
+ id: 'user-current',
+ role: 'user',
+ updatedAt: 0,
+ },
+ {
+ agentId: 'agent-1',
+ content: 'First step',
+ createdAt: 1,
+ id: 'assistant-current-1',
+ parentId: 'user-current',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'command_execution',
+ arguments: '{}',
+ id: 'item_1',
+ identifier: 'codex',
+ result_msg_id: 'tool-current-1',
+ type: 'default',
+ },
+ ],
+ updatedAt: 1,
+ },
+ {
+ content: 'Current tool result',
+ createdAt: 2,
+ id: 'tool-current-1',
+ parentId: 'assistant-current-1',
+ role: 'tool',
+ tool_call_id: 'item_1',
+ updatedAt: 2,
+ },
+ {
+ agentId: 'agent-1',
+ content: 'Second step',
+ createdAt: 3,
+ id: 'assistant-current-2',
+ parentId: 'tool-current-1',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'command_execution',
+ arguments: '{}',
+ id: 'item_2',
+ identifier: 'codex',
+ result_msg_id: 'tool-current-2',
+ type: 'default',
+ },
+ ],
+ updatedAt: 3,
+ },
+ {
+ content: 'Second tool result',
+ createdAt: 4,
+ id: 'tool-current-2',
+ parentId: 'assistant-current-2',
+ role: 'tool',
+ tool_call_id: 'item_2',
+ updatedAt: 4,
+ },
+ {
+ agentId: 'agent-1',
+ content: 'Final summary',
+ createdAt: 5,
+ id: 'assistant-current-final',
+ parentId: 'tool-current-2',
+ role: 'assistant',
+ updatedAt: 5,
+ },
+ {
+ content: 'Later request',
+ createdAt: 6,
+ id: 'user-later',
+ role: 'user',
+ updatedAt: 6,
+ },
+ {
+ agentId: 'agent-1',
+ content: 'Another turn reuses Codex item ids',
+ createdAt: 7,
+ id: 'assistant-later',
+ parentId: 'user-later',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'command_execution',
+ arguments: '{}',
+ id: 'item_1',
+ identifier: 'codex',
+ result_msg_id: 'tool-later-1',
+ type: 'default',
+ },
+ ],
+ updatedAt: 7,
+ },
+ {
+ content: 'Later tool result',
+ createdAt: 8,
+ id: 'tool-later-1',
+ parentId: 'assistant-later',
+ role: 'tool',
+ tool_call_id: 'item_1',
+ updatedAt: 8,
+ },
+ ]);
+
+ const currentGroup = result.flatList.find((message) => message.id === 'assistant-current-1');
+
+ expect(currentGroup?.role).toBe('assistantGroup');
+ expect((currentGroup as any).children.map((child: any) => child.id)).toEqual([
+ 'assistant-current-1',
+ 'assistant-current-2',
+ 'assistant-current-final',
+ ]);
+ expect((currentGroup as any).children[0].tools[0].result_msg_id).toBe('tool-current-1');
+ });
});
describe('Branching', () => {
diff --git a/packages/conversation-flow/src/transformation/MessageCollector.ts b/packages/conversation-flow/src/transformation/MessageCollector.ts
index 951a5c0df67..79a3e3cc3a9 100644
--- a/packages/conversation-flow/src/transformation/MessageCollector.ts
+++ b/packages/conversation-flow/src/transformation/MessageCollector.ts
@@ -68,10 +68,40 @@ export class MessageCollector {
* Collect tool messages related to an assistant message
*/
collectToolMessages(assistant: Message, messages: Message[]): Message[] {
- const toolCallIds = new Set(assistant.tools?.map((t) => t.id) || []);
- return messages.filter(
- (m) => m.role === 'tool' && m.tool_call_id && toolCallIds.has(m.tool_call_id),
+ const tools = assistant.tools || [];
+ if (tools.length === 0) return [];
+
+ const toolMessagesById = new Map(
+ messages.filter((m) => m.role === 'tool').map((m) => [m.id, m]),
);
+ const collected: Message[] = [];
+ const collectedIds = new Set<string>();
+
+ for (const tool of tools) {
+ const explicitResultId = tool.result_msg_id;
+ const explicitToolMessage = explicitResultId
+ ? toolMessagesById.get(explicitResultId)
+ : undefined;
+
+ if (explicitToolMessage) {
+ if (!collectedIds.has(explicitToolMessage.id)) {
+ collected.push(explicitToolMessage);
+ collectedIds.add(explicitToolMessage.id);
+ }
+ continue;
+ }
+
+ const fallbackToolMessage = messages.find(
+ (m) => m.role === 'tool' && m.parentId === assistant.id && m.tool_call_id === tool.id,
+ );
+
+ if (fallbackToolMessage && !collectedIds.has(fallbackToolMessage.id)) {
+ collected.push(fallbackToolMessage);
+ collectedIds.add(fallbackToolMessage.id);
+ }
+ }
+
+ return collected;
}
/**
diff --git a/packages/conversation-flow/src/transformation/__tests__/MessageCollector.test.ts b/packages/conversation-flow/src/transformation/__tests__/MessageCollector.test.ts
index 0bb49398364..ce6b1355368 100644
--- a/packages/conversation-flow/src/transformation/__tests__/MessageCollector.test.ts
+++ b/packages/conversation-flow/src/transformation/__tests__/MessageCollector.test.ts
@@ -97,6 +97,103 @@ describe('MessageCollector', () => {
expect(result).toHaveLength(2);
expect(result.map((m) => m.id)).toEqual(['msg-2', 'msg-3']);
});
+
+ it('should prefer result_msg_id when tool call IDs repeat in the same topic', () => {
+ const messageMap = new Map<string, Message>();
+ const childrenMap = new Map<string | null, string[]>();
+ const collector = new MessageCollector(messageMap, childrenMap);
+
+ const assistant: Message = {
+ content: 'current turn',
+ createdAt: 0,
+ id: 'assistant-current',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'command_execution',
+ arguments: '{}',
+ id: 'item_1',
+ identifier: 'codex',
+ result_msg_id: 'tool-current',
+ type: 'default',
+ },
+ ],
+ updatedAt: 0,
+ };
+
+ const messages: Message[] = [
+ {
+ content: 'older result with the same Codex item id',
+ createdAt: 0,
+ id: 'tool-old',
+ parentId: 'assistant-old',
+ role: 'tool',
+ tool_call_id: 'item_1',
+ updatedAt: 0,
+ },
+ {
+ content: 'current result',
+ createdAt: 0,
+ id: 'tool-current',
+ parentId: 'assistant-current',
+ role: 'tool',
+ tool_call_id: 'item_1',
+ updatedAt: 0,
+ },
+ ];
+
+ const result = collector.collectToolMessages(assistant, messages);
+
+ expect(result.map((m) => m.id)).toEqual(['tool-current']);
+ });
+
+ it('should fall back to parent-scoped tool_call_id matching for older tool payloads', () => {
+ const messageMap = new Map<string, Message>();
+ const childrenMap = new Map<string | null, string[]>();
+ const collector = new MessageCollector(messageMap, childrenMap);
+
+ const assistant: Message = {
+ content: 'current turn',
+ createdAt: 0,
+ id: 'assistant-current',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'command_execution',
+ arguments: '{}',
+ id: 'item_1',
+ identifier: 'codex',
+ type: 'default',
+ },
+ ],
+ updatedAt: 0,
+ };
+
+ const messages: Message[] = [
+ {
+ content: 'older result with the same Codex item id',
+ createdAt: 0,
+ id: 'tool-old',
+ parentId: 'assistant-old',
+ role: 'tool',
+ tool_call_id: 'item_1',
+ updatedAt: 0,
+ },
+ {
+ content: 'current result',
+ createdAt: 0,
+ id: 'tool-current',
+ parentId: 'assistant-current',
+ role: 'tool',
+ tool_call_id: 'item_1',
+ updatedAt: 0,
+ },
+ ];
+
+ const result = collector.collectToolMessages(assistant, messages);
+
+ expect(result.map((m) => m.id)).toEqual(['tool-current']);
+ });
});
describe('findLastNodeInAssistantGroup', () => {
diff --git a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx
index f5f2186780f..ae157d6f606 100644
--- a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx
+++ b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx
@@ -2,6 +2,7 @@
* @vitest-environment happy-dom
*/
import { fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { useChatStore } from '@/store/chat';
@@ -37,6 +38,30 @@ vi.mock('@/components/FileIcon', () => ({
),
}));
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...((await importOriginal()) as Record<string, unknown>),
+ Tooltip: ({
+ children,
+ mouseEnterDelay,
+ placement,
+ title,
+ }: {
+ children: ReactNode;
+ mouseEnterDelay?: number;
+ placement?: string;
+ title?: ReactNode;
+ }) => (
+ <span
+ data-mouse-enter-delay={String(mouseEnterDelay)}
+ data-placement={placement}
+ data-testid="local-file-tooltip"
+ data-title={typeof title === 'string' ? title : undefined}
+ >
+ {children}
+ </span>
+ ),
+}));
+
describe('LocalFileLink Render', () => {
afterEach(() => {
useChatStore.setState(useChatStore.getInitialState());
@@ -68,7 +93,19 @@ describe('LocalFileLink Render', () => {
/>,
);
- fireEvent.click(screen.getByRole('link', { name: 'Group.tsx' }));
+ const link = screen.getByRole('link', { name: 'Group.tsx' });
+
+ expect(screen.getByTestId('local-file-tooltip')).toHaveAttribute(
+ 'data-title',
+ '/Users/me/project/src/Group.tsx (line 265)',
+ );
+ expect(screen.getByTestId('local-file-tooltip')).toHaveAttribute(
+ 'data-mouse-enter-delay',
+ '0.1',
+ );
+ expect(screen.getByTestId('local-file-tooltip')).toHaveAttribute('data-placement', 'topLeft');
+
+ fireEvent.click(link);
expect(screen.getByTestId('file-icon')).toHaveAttribute('data-file-name', 'Group.tsx');
expect(screen.getByTestId('file-icon')).toHaveAttribute('data-size', '16');
diff --git a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx
index 21218af0c34..a9acdb9aa96 100644
--- a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx
+++ b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx
@@ -1,15 +1,17 @@
'use client';
import { isDesktop } from '@lobechat/const';
-import { A } from '@lobehub/ui';
+import { A, Tooltip } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
-import { memo, type MouseEvent, useCallback } from 'react';
+import type { MouseEvent } from 'react';
+import { memo, useCallback } from 'react';
import FileIcon from '@/components/FileIcon';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
-import { type MarkdownElementProps } from '../type';
+import type { MarkdownElementProps } from '../type';
+import type { ParsedLocalFileHref } from './parse';
import { parseLocalFileHref } from './parse';
interface LocalFileLinkProperties {
@@ -17,22 +19,60 @@ interface LocalFileLinkProperties {
linkLabel?: string;
}
-const styles = createStaticStyles(({ css }) => ({
+const styles = createStaticStyles(({ css, cssVar }) => ({
icon: css`
display: inline-flex;
flex-shrink: 0;
align-items: center;
`,
link: css`
+ cursor: pointer;
+
display: inline-flex;
gap: 4px;
align-items: center;
+
+ margin-inline: -2px;
+ padding-inline: 2px;
+ border-radius: ${cssVar.borderRadiusSM};
+
+ text-decoration: none;
vertical-align: -0.16em;
+
+ transition:
+ color 0.2s ${cssVar.motionEaseOut},
+ background 0.2s ${cssVar.motionEaseOut},
+ box-shadow 0.2s ${cssVar.motionEaseOut};
+
+ &:hover {
+ color: ${cssVar.colorLinkHover};
+ text-decoration: underline;
+ text-underline-offset: 2px;
+
+ background: ${cssVar.colorFillSecondary};
+ box-shadow: inset 0 0 0 1px ${cssVar.colorPrimaryBorder};
+ }
+
+ &:active {
+ color: ${cssVar.colorLinkActive};
+ background: ${cssVar.colorFill};
+ }
+
+ &:focus-visible {
+ outline: 2px solid ${cssVar.colorPrimaryBorder};
+ outline-offset: 2px;
+ }
`,
}));
const getFileName = (filePath: string) => filePath.split(/[\\/]/).at(-1) || filePath;
+const formatLocalFileTitle = ({ column, filePath, line }: ParsedLocalFileHref) => {
+ if (!line) return filePath;
+
+ return column ? `${filePath} (line ${line}, column ${column})` : `${filePath} (line ${line})`;
+};
+
const Render = memo<MarkdownElementProps<LocalFileLinkProperties>>(({ node }) => {
const { linkHref, linkLabel } = node?.properties || {};
const openLocalFile = useChatStore((s) => s.openLocalFile);
@@ -40,6 +80,7 @@ const Render = memo<MarkdownElementProps<LocalFileLinkProperties>>(({ node }) =>
const parsed = isDesktop ? parseLocalFileHref(linkHref, { workingDirectory }) : null;
const label = linkLabel || parsed?.filePath || linkHref || '';
const iconFileName = parsed ? getFileName(parsed.filePath) : label;
+ const title = parsed ? formatLocalFileTitle(parsed) : linkHref;
const handleClick = useCallback(
(event: MouseEvent<HTMLAnchorElement>) => {
@@ -58,12 +99,14 @@ const Render = memo<MarkdownElementProps<LocalFileLinkProperties>>(({ node }) =>
);
return (
- <A className={styles.link} href={linkHref} onClick={handleClick}>
- <span aria-hidden className={styles.icon}>
- <FileIcon fileName={iconFileName} size={16} variant={'raw'} />
- </span>
- <span>{label}</span>
- </A>
+ <Tooltip mouseEnterDelay={0.1} placement={'topLeft'} title={title}>
+ <A className={styles.link} href={linkHref} onClick={handleClick}>
+ <span aria-hidden className={styles.icon}>
+ <FileIcon fileName={iconFileName} size={16} variant={'raw'} />
+ </span>
+ <span>{label}</span>
+ </A>
+ </Tooltip>
);
});