Skip to content

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

✨ feat(chat): add copy operation id action to assistant message menus (#17710)

YuTengjingba0bc6ccfee1
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index ba3fb91776e..009b7d0b920 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -579,6 +579,7 @@
"mention.title": "Mention Members",
"messageAction.collapse": "Collapse Message",
"messageAction.continueGeneration": "Continue Generating",
+ "messageAction.copyOperationId": "Copy Operation ID",
"messageAction.delAndRegenerate": "Delete and Regenerate",
"messageAction.deleteDisabledByThreads": "This message has a subtopic and can’t be deleted",
"messageAction.expand": "Expand Message",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index ddfe17ac696..b484084b441 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -579,6 +579,7 @@
"mention.title": "ζεŠζˆε‘˜",
"messageAction.collapse": "ζ”Άθ΅·ζΆˆζ―",
"messageAction.continueGeneration": "η»§η»­η”Ÿζˆ",
+ "messageAction.copyOperationId": "倍刢 Operation ID",
"messageAction.delAndRegenerate": "εˆ ι™€εΉΆι‡ζ–°η”Ÿζˆ",
"messageAction.deleteDisabledByThreads": "θ―₯ζΆˆζ―ζœ‰ε­θ―ι’˜οΌŒζ— ζ³•εˆ ι™€",
"messageAction.expand": "ε±•εΌ€ζΆˆζ―",
diff --git a/packages/agent-runtime/src/executors/callLlm.test.ts b/packages/agent-runtime/src/executors/callLlm.test.ts
index 0a1dd554bd1..20ecf07c6c0 100644
--- a/packages/agent-runtime/src/executors/callLlm.test.ts
+++ b/packages/agent-runtime/src/executors/callLlm.test.ts
@@ -191,6 +191,9 @@ describe('callLlm executor', () => {
expect.objectContaining({
agentId: 'agent-1',
content: '',
+ // Creation provenance stamp β€” must reference the running operation so
+ // the id stays resolvable after client reloads.
+ metadata: { operationId: 'op-1' },
model: 'gpt-4',
parentId: 'parent-1',
provider: 'openai',
@@ -264,6 +267,11 @@ describe('callLlm executor', () => {
newState: { messages: [expect.objectContaining({ id: 'assistant-existing' })] },
});
expect(messages.createAssistantMessage).not.toHaveBeenCalled();
+ // Pre-created placeholders exist before the operation does β€” the executor
+ // must merge the provenance stamp onto them.
+ expect(messages.update).toHaveBeenCalledWith('assistant-existing', {
+ metadata: { operationId: 'op-1' },
+ });
expect(transport.createTrace).toHaveBeenCalledWith(
expect.objectContaining({
assistantMessageId: 'assistant-existing',
@@ -271,6 +279,26 @@ describe('callLlm executor', () => {
);
});
+ it('keeps the run alive when the provenance stamp write fails', async () => {
+ const state = createState();
+ const transport = createCallTransport();
+ const messages = createMessageTransport();
+ vi.mocked(messages.update).mockRejectedValueOnce(new Error('db down'));
+ const host = createHost(transport.llm, messages);
+ const reuseInstruction: AgentInstructionCallLlm = {
+ payload: {
+ ...instruction.payload,
+ assistantMessageId: 'assistant-existing',
+ },
+ type: 'call_llm',
+ };
+
+ // The stamp is a tracing aid β€” its failure must not become an LLM error.
+ await expect(callLlm(host)(reuseInstruction, state)).resolves.toMatchObject({
+ newState: { messages: [expect.objectContaining({ id: 'assistant-existing' })] },
+ });
+ });
+
it('throws when the LLM transport does not provide runAttempt', async () => {
const host = createHost({
retryPolicy: createRetryPolicy(),
diff --git a/packages/agent-runtime/src/executors/callLlm.ts b/packages/agent-runtime/src/executors/callLlm.ts
index df61272bd2e..138d0b8cb53 100644
--- a/packages/agent-runtime/src/executors/callLlm.ts
+++ b/packages/agent-runtime/src/executors/callLlm.ts
@@ -305,6 +305,20 @@ export const callLlm =
}
const existingAssistantMessageId = llmPayload.assistantMessageId;
+ // Pre-created placeholders (e.g. sendMessage creates the assistant row
+ // before the operation exists) miss the creation-time provenance stamp β€”
+ // merge it here so reused messages carry metadata.operationId too.
+ // Best-effort: the stamp is only a tracing aid and must never turn a
+ // normal send/resume into an LLM error before streaming starts.
+ if (existingAssistantMessageId) {
+ try {
+ await transports.messages.update(existingAssistantMessageId, {
+ metadata: { operationId: operation.operationId },
+ });
+ } catch (error) {
+ console.warn('[call_llm] Failed to stamp operation id provenance:', error);
+ }
+ }
const assistantMessage = existingAssistantMessageId
? { id: existingAssistantMessageId }
: await transports.messages.createAssistantMessage(
@@ -312,6 +326,9 @@ export const callLlm =
agentId: state.metadata!.agentId!,
content: '',
groupId: state.metadata?.groupId ?? undefined,
+ // Creation provenance (metadata.operationId): ties the row to the
+ // operation that produced it so the id survives client reloads.
+ metadata: { operationId: operation.operationId },
model,
parentId,
provider,
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 0b305ebee79..06a0b30bcdd 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -588,6 +588,7 @@ export default {
'mention.title': 'Mention Members',
'messageAction.collapse': 'Collapse Message',
'messageAction.continueGeneration': 'Continue Generating',
+ 'messageAction.copyOperationId': 'Copy Operation ID',
'messageAction.delAndRegenerate': 'Delete and Regenerate',
'messageAction.interrupted': 'Interrupted',
'messageAction.interruptedHint': 'What should I do instead?',
diff --git a/packages/types/src/message/common/metadata.test.ts b/packages/types/src/message/common/metadata.test.ts
index bc32d18da71..b40411156aa 100644
--- a/packages/types/src/message/common/metadata.test.ts
+++ b/packages/types/src/message/common/metadata.test.ts
@@ -23,6 +23,15 @@ describe('MessageMetadataSchema', () => {
expect(parsed).toEqual({ heteroMessageId: 'cc-1', heteroSessionId: 'sess-A' });
});
+ it('preserves the operation id provenance stamp so it is not stripped on writes', () => {
+ const parsed = MessageMetadataSchema.parse({
+ operationId: 'op-1',
+ unknown: 'stripped',
+ });
+
+ expect(parsed).toEqual({ operationId: 'op-1' });
+ });
+
it('preserves the durable heterogeneous tool-state watermark', () => {
const parsed = MessageMetadataSchema.parse({
heterogeneousToolStateOperationId: 'op-1',
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index f4628e000e1..8629c0047f3 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -201,6 +201,10 @@ export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSche
isMultimodal: z.boolean().optional(),
isSupervisor: z.boolean().optional(),
localSystemToolSnapshots: z.array(LocalSystemToolSnapshotSchema).optional(),
+ // Creation provenance (agent operation that produced this message). Listed
+ // here so zod does NOT strip the runtime's stamp from writes going through
+ // CreateMessageParamsSchema / UpdateMessageParamsSchema.
+ operationId: z.string().min(1).optional(),
orchestrationRole: z.enum(['supervisor', 'member']).optional(),
pageSelections: z.array(PageSelectionSchema).optional(),
// Canonical nested shape β€” flat fields above are deprecated. Must be listed
@@ -368,6 +372,16 @@ export interface MessageMetadata {
* and so the standard message `role` stays `'assistant'` (training-friendly).
* Supersedes the boolean {@link isSupervisor}, which is kept for back-compat.
*/
+ /**
+ * Creation provenance: id of the agent operation that produced this message
+ * (`agent_operations.id`), stamped when the runtime creates the assistant
+ * row. Always the message's OWN operation β€” for sub-agent (callAgent) turns
+ * this is the sub-operation, not the root; climb `parent_operation_id` for
+ * the root. Do not confuse with `work.rootOperationId` (Work display anchor,
+ * root op, only on Work-producing rounds) or `verifyOperationId` (the run a
+ * verify card verifies).
+ */
+ operationId?: string;
orchestrationRole?: 'supervisor' | 'member';
/** @deprecated use the top-level message `usage` field instead */
outputAudioTokens?: number;
diff --git a/src/features/Conversation/Messages/Assistant/Actions/index.tsx b/src/features/Conversation/Messages/Assistant/Actions/index.tsx
index 07eb80dcbfb..9070a8c8713 100644
--- a/src/features/Conversation/Messages/Assistant/Actions/index.tsx
+++ b/src/features/Conversation/Messages/Assistant/Actions/index.tsx
@@ -15,6 +15,7 @@ const DEFAULT_BAR: MessageActionSlot[] = ['edit', 'copy'];
const DEFAULT_MENU: MessageActionSlot[] = [
'edit',
'copy',
+ 'copyOperationId',
'comments',
'branching',
'collapse',
@@ -30,7 +31,15 @@ const DEFAULT_MENU: MessageActionSlot[] = [
'del',
];
const ERROR_BAR: MessageActionSlot[] = ['regenerate', 'del'];
-const ERROR_MENU: MessageActionSlot[] = ['edit', 'copy', 'comments', 'divider', 'del'];
+const EMPTY_ERROR_MENU: MessageActionSlot[] = ['copyOperationId'];
+const ERROR_MENU: MessageActionSlot[] = [
+ 'edit',
+ 'copy',
+ 'copyOperationId',
+ 'comments',
+ 'divider',
+ 'del',
+];
interface AssistantActionsBarProps {
actionsConfig?: MessageActionsConfig;
@@ -44,12 +53,18 @@ export const AssistantActionsBar = memo<AssistantActionsBarProps>(({ actionsConf
const { content, error, tools } = data;
// Empty error messages render only an interception card β€” nothing to edit
- // or copy, so no overflow menu. When the turn streamed content before
- // erroring, keep edit/copy so the partial reply stays salvageable.
+ // or copy, so only the dev-mode operation-id action remains menu-worthy
+ // (failed runs are exactly what it traces; the menu collapses away when the
+ // action opts out). When the turn streamed content before erroring, keep
+ // edit/copy so the partial reply stays salvageable.
if (error) {
const hasContent = !!content && content !== LOADING_FLAT && String(content).trim() !== '';
return (
- <MessageActionBar bar={ERROR_BAR} ctx={ctx} menu={hasContent ? ERROR_MENU : undefined} />
+ <MessageActionBar
+ bar={ERROR_BAR}
+ ctx={ctx}
+ menu={hasContent ? ERROR_MENU : EMPTY_ERROR_MENU}
+ />
);
}
diff --git a/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsx
index 455dae9e731..8c06ba8d32d 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsx
@@ -15,6 +15,7 @@ const DEFAULT_BAR: MessageActionSlot[] = ['edit', 'copy'];
const DEFAULT_MENU: MessageActionSlot[] = [
'edit',
'copy',
+ 'copyOperationId',
'comments',
'branching',
'collapse',
@@ -32,7 +33,15 @@ const IN_PROGRESS_BAR: MessageActionSlot[] = ['del'];
// shared and multi-selected/forwarded as one aggregated assistant reply. The
// forward serializer keeps child text while excluding child tool payloads.
const NO_TEXT_BLOCK_BAR: MessageActionSlot[] = ['delAndRegenerate'];
-const NO_TEXT_BLOCK_MENU: MessageActionSlot[] = ['comments', 'share', 'select', 'divider', 'del'];
+const NO_TEXT_BLOCK_MENU: MessageActionSlot[] = [
+ 'comments',
+ 'share',
+ 'select',
+ 'divider',
+ 'del',
+ 'divider',
+ 'copyOperationId',
+];
interface GroupActionsProps {
actionsConfig?: MessageActionsConfig;
diff --git a/src/features/Conversation/Messages/Task/Actions/index.tsx b/src/features/Conversation/Messages/Task/Actions/index.tsx
index 6b8e65546d0..ba4ad715a66 100644
--- a/src/features/Conversation/Messages/Task/Actions/index.tsx
+++ b/src/features/Conversation/Messages/Task/Actions/index.tsx
@@ -14,6 +14,7 @@ const DEFAULT_BAR: MessageActionSlot[] = ['edit', 'copy'];
const DEFAULT_MENU: MessageActionSlot[] = [
'edit',
'copy',
+ 'copyOperationId',
'comments',
'collapse',
'divider',
@@ -23,7 +24,15 @@ const DEFAULT_MENU: MessageActionSlot[] = [
'del',
];
const ERROR_BAR: MessageActionSlot[] = ['regenerate', 'del'];
-const ERROR_MENU: MessageActionSlot[] = ['edit', 'copy', 'comments', 'divider', 'del'];
+const EMPTY_ERROR_MENU: MessageActionSlot[] = ['copyOperationId'];
+const ERROR_MENU: MessageActionSlot[] = [
+ 'edit',
+ 'copy',
+ 'copyOperationId',
+ 'comments',
+ 'divider',
+ 'del',
+];
interface AssistantActionsBarProps {
actionsConfig?: MessageActionsConfig;
@@ -42,12 +51,18 @@ export const AssistantActionsBar = memo<AssistantActionsBarProps>(({ actionsConf
const { content, error, tools } = data;
// Empty error messages render only an interception card β€” nothing to edit
- // or copy, so no overflow menu. When the turn streamed content before
- // erroring, keep edit/copy so the partial reply stays salvageable.
+ // or copy, so only the dev-mode operation-id action remains menu-worthy
+ // (failed runs are exactly what it traces; the menu collapses away when the
+ // action opts out). When the turn streamed content before erroring, keep
+ // edit/copy so the partial reply stays salvageable.
if (error) {
const hasContent = !!content && content !== LOADING_FLAT && String(content).trim() !== '';
return (
- <MessageActionBar bar={ERROR_BAR} ctx={ctx} menu={hasContent ? ERROR_MENU : undefined} />
+ <MessageActionBar
+ bar={ERROR_BAR}
+ ctx={ctx}
+ menu={hasContent ? ERROR_MENU : EMPTY_ERROR_MENU}
+ />
);
}
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/copyOperationId.test.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/copyOperationId.test.ts
new file mode 100644
index 00000000000..b6a4741053a
--- /dev/null
+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/copyOperationId.test.ts
@@ -0,0 +1,190 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import type { AssistantContentBlock, UIChatMessage } from '@lobechat/types';
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { MessageActionContext } from '../types';
+import { copyOperationIdAction } from './copyOperationId';
+
+interface MockOperation {
+ id: string;
+ isRuntimeRoot?: boolean;
+ metadata: { serverOperationId?: string };
+ parentOperationId?: string;
+}
+
+const mocks = vi.hoisted(() => ({
+ copyToClipboard: vi.fn(),
+ isDevMode: true,
+ messageOperationMap: {} as Record<string, string>,
+ messageSuccess: vi.fn(),
+ operations: {} as Record<string, MockOperation>,
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ copyToClipboard: mocks.copyToClipboard,
+}));
+
+vi.mock('antd', () => ({
+ App: { useApp: () => ({ message: { success: mocks.messageSuccess } }) },
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: unknown) => unknown) =>
+ selector({
+ messageOperationMap: mocks.messageOperationMap,
+ operations: mocks.operations,
+ }),
+}));
+
+vi.mock('@/store/chat/selectors', () => ({
+ operationSelectors: {
+ // Test double for the parent-chain walk: climbs `parentOperationId` until
+ // an op flagged `isRuntimeRoot` (stand-in for AI_RUNTIME_OPERATION_TYPES).
+ findRootRuntimeOperation:
+ (operationId: string) => (s: { operations: Record<string, MockOperation> }) => {
+ let op: MockOperation | undefined = s.operations[operationId];
+ while (op && !op.isRuntimeRoot) {
+ op = op.parentOperationId ? s.operations[op.parentOperationId] : undefined;
+ }
+ return op;
+ },
+ },
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ userGeneralSettingsSelectors: {
+ config: () => ({ isDevMode: mocks.isDevMode }),
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+const build = (
+ data: Partial<UIChatMessage> = {},
+ role: MessageActionContext['role'] = 'assistant',
+ contentBlock?: Partial<AssistantContentBlock>,
+) =>
+ renderHook(() =>
+ copyOperationIdAction.useBuild({
+ contentBlock: contentBlock as AssistantContentBlock,
+ data: { content: 'Hello', role: 'assistant', ...data } as UIChatMessage,
+ id: 'message-1',
+ role,
+ }),
+ ).result.current;
+
+describe('copyOperationIdAction', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.isDevMode = true;
+ mocks.messageOperationMap = {};
+ mocks.operations = {};
+ });
+
+ it('is absent when Advanced Tools (dev mode) is off', () => {
+ mocks.isDevMode = false;
+
+ expect(build({ metadata: { operationId: 'op-server' } })).toBeNull();
+ });
+
+ it('is absent when no operation id is resolvable', () => {
+ expect(build()).toBeNull();
+ });
+
+ it('copies the provenance stamp persisted on the message', async () => {
+ const action = build({ metadata: { operationId: 'op-durable' } });
+
+ await act(async () => action?.handleClick?.());
+
+ expect(mocks.copyToClipboard).toHaveBeenCalledWith('op-durable');
+ expect(mocks.messageSuccess).toHaveBeenCalled();
+ });
+
+ it('prefers the durable stamp over the live runtime operation', async () => {
+ mocks.messageOperationMap = { 'message-1': 'op-local' };
+ mocks.operations = {
+ 'op-local': { id: 'op-local', isRuntimeRoot: true, metadata: {} },
+ };
+
+ const action = build({ metadata: { operationId: 'op-durable' } });
+
+ await act(async () => action?.handleClick?.());
+
+ expect(mocks.copyToClipboard).toHaveBeenCalledWith('op-durable');
+ });
+
+ it('prefers the block-level stamp for group messages', async () => {
+ const action = build({ metadata: { operationId: 'op-message' } }, 'group', {
+ id: 'block-1',
+ metadata: { operationId: 'op-block' },
+ });
+
+ await act(async () => action?.handleClick?.());
+
+ expect(mocks.copyToClipboard).toHaveBeenCalledWith('op-block');
+ });
+
+ it('walks the runtime chain to the root and prefers its server operation id', async () => {
+ mocks.messageOperationMap = { 'message-1': 'op-child' };
+ mocks.operations = {
+ 'op-child': { id: 'op-child', metadata: {}, parentOperationId: 'op-root' },
+ 'op-root': {
+ id: 'op-root',
+ isRuntimeRoot: true,
+ metadata: { serverOperationId: 'op-server' },
+ },
+ };
+
+ const action = build();
+
+ await act(async () => action?.handleClick?.());
+
+ expect(mocks.copyToClipboard).toHaveBeenCalledWith('op-server');
+ });
+
+ it('falls back to the local runtime operation id without a server id', async () => {
+ mocks.messageOperationMap = { 'message-1': 'op-local' };
+ mocks.operations = {
+ 'op-local': { id: 'op-local', isRuntimeRoot: true, metadata: {} },
+ };
+
+ const action = build();
+
+ await act(async () => action?.handleClick?.());
+
+ expect(mocks.copyToClipboard).toHaveBeenCalledWith('op-local');
+ });
+
+ it('is absent when the mapped operation has no AI-runtime ancestor', () => {
+ // messageOperationMap is last-write-wins: a later translate/tts operation
+ // can own the slot. Its id must not surface as the message's operation id.
+ mocks.messageOperationMap = { 'message-1': 'op-translate' };
+ mocks.operations = {
+ 'op-translate': { id: 'op-translate', metadata: {} },
+ };
+
+ expect(build()).toBeNull();
+ });
+
+ it('resolves the runtime operation through the content block id for groups', async () => {
+ mocks.messageOperationMap = { 'block-1': 'op-block-local' };
+ mocks.operations = {
+ 'op-block-local': { id: 'op-block-local', isRuntimeRoot: true, metadata: {} },
+ };
+
+ const action = build({}, 'group', { id: 'block-1' });
+
+ await act(async () => action?.handleClick?.());
+
+ expect(mocks.copyToClipboard).toHaveBeenCalledWith('op-block-local');
+ });
+});
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/copyOperationId.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/copyOperationId.ts
new file mode 100644
index 00000000000..ae086911618
--- /dev/null
+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/copyOperationId.ts
@@ -0,0 +1,65 @@
+import { copyToClipboard } from '@lobehub/ui';
+import { App } from 'antd';
+import { Hash } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+import { operationSelectors } from '@/store/chat/selectors';
+import { useUserStore } from '@/store/user';
+import { userGeneralSettingsSelectors } from '@/store/user/selectors';
+
+import { defineAction } from '../defineAction';
+
+/**
+ * Dev-tool action (visible only with Advanced Tools enabled): copies the id of
+ * the operation that produced this message, for tracing/debugging.
+ *
+ * Resolution order: the creation-provenance stamp persisted on the
+ * block/message (`metadata.operationId`, survives reloads) β†’ the live runtime
+ * operation chain, preferring the gateway's server operation id over the local
+ * client-generated one. Absent when neither source knows the message.
+ */
+const getStampedOperationId = (metadata?: { operationId?: unknown } | null) =>
+ typeof metadata?.operationId === 'string' ? metadata.operationId : undefined;
+
+export const copyOperationIdAction = defineAction({
+ key: 'copyOperationId',
+ useBuild: (ctx) => {
+ const { t } = useTranslation('chat');
+ const { message } = App.useApp();
+ const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);
+
+ // For group messages the operation is associated with the underlying
+ // assistant message (the content block), not the aggregate group id.
+ const runtimeOperationId = useChatStore((s) => {
+ const localOpId =
+ (ctx.contentBlock && s.messageOperationMap[ctx.contentBlock.id]) ||
+ s.messageOperationMap[ctx.id];
+ if (!localOpId) return;
+ // Only accept an AI-runtime ancestor: messageOperationMap is
+ // last-write-wins, so per-message utility operations (translate, tts, …)
+ // can own the slot β€” their ids are not what this action traces.
+ const rootOp = operationSelectors.findRootRuntimeOperation(localOpId)(s);
+ if (!rootOp) return;
+ return rootOp.metadata.serverOperationId ?? rootOp.id;
+ });
+
+ const durableOperationId =
+ getStampedOperationId(ctx.contentBlock?.metadata) ?? getStampedOperationId(ctx.data.metadata);
+ const operationId = durableOperationId ?? runtimeOperationId;
+
+ return useMemo(() => {
+ if (!isDevMode || !operationId) return null;
+ return {
+ handleClick: async () => {
+ await copyToClipboard(operationId);
+ message.success(t('copySuccess', { ns: 'common' }));
+ },
+ icon: Hash,
+ key: 'copyOperationId',
+ label: t('messageAction.copyOperationId'),
+ };
+ }, [t, message, isDevMode, operationId]);
+ },
+});
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/index.test.tsx b/src/features/Conversation/Messages/components/MessageActionBar/index.test.tsx
index 08aa4bf01d7..2b171442af2 100644
--- a/src/features/Conversation/Messages/components/MessageActionBar/index.test.tsx
+++ b/src/features/Conversation/Messages/components/MessageActionBar/index.test.tsx
@@ -27,6 +27,7 @@ vi.mock('@lobehub/ui', () => ({
variant?: string;
}) => (
<div
+ data-has-menu={String(!!menu)}
data-items={items.map((item) => item.key).join(',')}
data-menu={menu?.map((item) => item.key || item.type).join(',') ?? ''}
data-testid="action-group"
@@ -143,4 +144,48 @@ describe('MessageActionBar', () => {
expect(group).toHaveAttribute('data-items', 'copy');
expect(group).toHaveAttribute('data-menu', '');
});
+
+ it('collapses a menu whose every action opted out instead of passing []', () => {
+ actionMocks.commentsAvailable = true;
+ permissionMock.canEdit = true;
+
+ // 'tts' is not in the mocked registry β€” the slot resolves to nothing, like
+ // copyOperationId with dev mode off. ActionIconGroup would render an empty
+ // overflow trigger for [], so the bar must pass undefined instead.
+ render(
+ <MessageActionBar
+ bar={['copy']}
+ menu={['tts']}
+ ctx={{
+ data: { content: 'hello', role: 'assistant' } as UIChatMessage,
+ id: 'message-1',
+ role: 'assistant',
+ }}
+ />,
+ );
+
+ expect(screen.getByTestId('action-group')).toHaveAttribute('data-has-menu', 'false');
+ });
+
+ it('drops dangling dividers when the group behind one opted out', () => {
+ actionMocks.commentsAvailable = true;
+ permissionMock.canEdit = true;
+
+ // 'tts' resolves to nothing (not in the mocked registry), so the trailing
+ // "divider + hidden group" must collapse away, and the double boundary
+ // around the missing middle group must merge into one divider.
+ render(
+ <MessageActionBar
+ bar={['copy']}
+ menu={['edit', 'divider', 'tts', 'divider', 'del', 'divider', 'restoreToInput']}
+ ctx={{
+ data: { content: 'hello', role: 'assistant' } as UIChatMessage,
+ id: 'message-1',
+ role: 'assistant',
+ }}
+ />,
+ );
+
+ expect(screen.getByTestId('action-group')).toHaveAttribute('data-menu', 'edit,divider,del');
+ });
});
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/index.tsx b/src/features/Conversation/Messages/components/MessageActionBar/index.tsx
index 29b54fe99d1..88860d74cf2 100644
--- a/src/features/Conversation/Messages/components/MessageActionBar/index.tsx
+++ b/src/features/Conversation/Messages/components/MessageActionBar/index.tsx
@@ -47,6 +47,14 @@ const buildActionsMap = (items: MessageActionItemOrDivider[]): Map<string, Messa
return map;
};
+const isDivider = (item: MessageActionItemOrDivider) => 'type' in item && item.type === 'divider';
+
+/**
+ * Resolves slot keys against the built actions. Dividers are declarative
+ * group boundaries, not literal items: when the actions around one opt out
+ * (return null), leading/trailing/consecutive dividers are dropped so a
+ * conditionally hidden group never leaves a dangling separator.
+ */
const resolveSlots = (
slots: MessageActionSlot[],
built: Record<string, MessageActionItem | null>,
@@ -54,12 +62,13 @@ const resolveSlots = (
const out: MessageActionItemOrDivider[] = [];
for (const slot of slots) {
if (slot === DIVIDER_KEY) {
- out.push(DIVIDER);
+ if (out.length > 0 && !isDivider(out.at(-1)!)) out.push(DIVIDER);
continue;
}
const item = built[slot];
if (item) out.push(item);
}
+ while (out.length > 0 && isDivider(out.at(-1)!)) out.pop();
return out;
};
@@ -106,7 +115,12 @@ export const MessageActionBar = memo<MessageActionBarProps>(({ ctx, bar, leading
() => barItems.filter((item) => !('disabled' in item && item.disabled)).map(stripHandleClick),
[barItems],
);
- const menuStripped = useMemo(() => menuItems?.map(stripHandleClick), [menuItems]);
+ // An all-null menu (every slot's action opted out) must collapse to no menu β€”
+ // ActionIconGroup renders the overflow trigger for any truthy array, even [].
+ const menuStripped = useMemo(
+ () => (menuItems?.length ? menuItems.map(stripHandleClick) : undefined),
+ [menuItems],
+ );
const allActions = useMemo(
() => buildActionsMap([...barItems, ...(menuItems ?? [])]),
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/useBuildActions.ts b/src/features/Conversation/Messages/components/MessageActionBar/useBuildActions.ts
index 95f75d33b86..453dac29ab6 100644
--- a/src/features/Conversation/Messages/components/MessageActionBar/useBuildActions.ts
+++ b/src/features/Conversation/Messages/components/MessageActionBar/useBuildActions.ts
@@ -5,6 +5,7 @@ import { collapseAction } from './actions/collapse';
import { commentsAction } from './actions/comments';
import { continueGenerationAction } from './actions/continueGeneration';
import { copyAction } from './actions/copy';
+import { copyOperationIdAction } from './actions/copyOperationId';
import { delAction } from './actions/del';
import { delAndRegenerateAction } from './actions/delAndRegenerate';
import { editAction } from './actions/edit';
@@ -39,6 +40,7 @@ export const useBuildActions = (
comments: commentsAction.useBuild(ctx),
continueGeneration: continueGenerationAction.useBuild(ctx),
copy: copyAction.useBuild(ctx),
+ copyOperationId: copyOperationIdAction.useBuild(ctx),
del: delAction.useBuild(ctx),
delAndRegenerate: delAndRegenerateAction.useBuild(ctx),
edit: editAction.useBuild(ctx),
diff --git a/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-llm.test.ts b/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-llm.test.ts
index ce84be26285..5299b3a7d78 100644
--- a/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-llm.test.ts
+++ b/src/store/chat/agents/__tests__/clientRuntimeExecutors/call-llm.test.ts
@@ -276,8 +276,17 @@ describe('createClientRuntimeExecutors call_llm', () => {
createState([userMessage]),
);
- expect(messageService.batchMutate).toHaveBeenCalledTimes(1);
- expect(messageService.batchMutate).toHaveBeenCalledWith([
+ // Reuse stamps operation provenance first, then persists the streamed
+ // content β€” both target the seeded message; neither creates a duplicate.
+ expect(messageService.batchMutate).toHaveBeenCalledTimes(2);
+ expect(messageService.batchMutate).toHaveBeenNthCalledWith(1, [
+ expect.objectContaining({
+ id: assistantMessage.id,
+ type: 'updateMessage',
+ value: expect.objectContaining({ metadata: { operationId } }),
+ }),
+ ]);
+ expect(messageService.batchMutate).toHaveBeenNthCalledWith(2, [
expect.objectContaining({ id: assistantMessage.id, type: 'updateMessage' }),
]);
});
diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.ts
index 30b4555ad26..8bd15815384 100644
--- a/src/store/chat/slices/operation/types.ts
+++ b/src/store/chat/slices/operation/types.ts
@@ -151,6 +151,13 @@ export interface OperationMetadata {
// Runtime hooks (collected during execution, executed after completion)
runtimeHooks?: RuntimeHooks;
+ /**
+ * Server-side operation id reported by the agent gateway for this local
+ * runtime operation. Preferred over the local nanoid when surfacing an
+ * operation id for tracing (e.g. the message "Copy Operation ID" action).
+ */
+ serverOperationId?: string;
+
// Performance information
startTime: number;