fix: 兼容低版本浏览器消息复制

- 为 Chrome 90 增加剪贴板兼容回退

- 统一聊天与智能体试运行的原色对勾反馈
This commit is contained in:
2026-07-22 20:07:34 +08:00
parent 5a3d4788da
commit 9f06c238d3
15 changed files with 423 additions and 83 deletions

View File

@@ -2,7 +2,7 @@
import type { ChatTimeTimelineItem } from '@easyflow/types';
import { Close } from '@element-plus/icons-vue';
import { ElButton, ElEmpty, ElIcon, ElMessage, ElScrollbar } from 'element-plus';
import { ElButton, ElEmpty, ElIcon, ElScrollbar } from 'element-plus';
import ChatTimeMessageContent from '#/components/chat/ChatTimeMessageContent.vue';
import ChatMessageActionBar from '#/components/chat-workspace/ChatMessageActionBar.vue';
@@ -125,18 +125,6 @@ function isFinalAssistantInRound(item: ChatTimeTimelineItem) {
function canCopyMessage(item: ChatTimeTimelineItem) {
return item.role !== 'tool' && Boolean(String(item.content || '').trim());
}
async function handleCopyMessage(item: ChatTimeTimelineItem) {
if (!canCopyMessage(item)) {
return;
}
try {
await navigator.clipboard.writeText(String(item.content || ''));
ElMessage.success('已复制');
} catch {
ElMessage.error('复制失败');
}
}
</script>
<template>
@@ -231,6 +219,7 @@ async function handleCopyMessage(item: ChatTimeTimelineItem) {
<ChatMessageActionBar
:align="item.role === 'user' ? 'end' : 'start'"
:allow-copy="canCopyMessage(item)"
:copy-text="String(item.content || '').trim()"
:show-variant-navigator="shouldShowVariantNavigator(item)"
:disabled-variant-next="!canSwitchVariant(item, 'next')"
:disabled-variant-previous="!canSwitchVariant(item, 'previous')"
@@ -239,7 +228,6 @@ async function handleCopyMessage(item: ChatTimeTimelineItem) {
Number(item.variantIndex || item.selectedVariantIndex || 1)
"
:variant-total="Number(item.variantCount || 1)"
@copy="handleCopyMessage(item)"
@select-next-variant="
emit('selectVariant', { direction: 'next', item })
"

View File

@@ -0,0 +1,66 @@
import { flushPromises, mount } from '@vue/test-utils';
import { copyTextToClipboard } from '@easyflow/utils';
import { ElMessage } from 'element-plus';
import { afterEach, describe, expect, it, vi } from 'vitest';
import ChatMessageActionBar from './ChatMessageActionBar.vue';
vi.mock('@easyflow/utils', () => ({
copyTextToClipboard: vi.fn(),
}));
vi.mock('element-plus', () => ({
ElMessage: {
error: vi.fn(),
},
}));
describe('chat message action bar', () => {
afterEach(() => {
vi.clearAllMocks();
vi.useRealTimers();
});
it('shows a check icon after copying and restores the copy icon', async () => {
vi.useFakeTimers();
vi.mocked(copyTextToClipboard).mockResolvedValue('clipboard-api');
const wrapper = mount(ChatMessageActionBar, {
props: {
allowCopy: true,
copyText: '消息内容',
},
});
await wrapper.get('[aria-label="复制消息"]').trigger('click');
await flushPromises();
expect(copyTextToClipboard).toHaveBeenCalledWith('消息内容');
expect(wrapper.get('button').attributes('aria-label')).toBe('复制成功');
expect(wrapper.get('button').classes()).not.toContain('is-copied');
expect(ElMessage.error).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1600);
expect(wrapper.get('button').attributes('aria-label')).toBe('复制消息');
});
it('keeps the copy icon and shows the existing warning on failure', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined);
vi.mocked(copyTextToClipboard).mockRejectedValue(new Error('copy denied'));
const wrapper = mount(ChatMessageActionBar, {
props: {
allowCopy: true,
copyErrorMessage: '复制失败,请重试',
copyText: '消息内容',
},
});
await wrapper.get('[aria-label="复制消息"]').trigger('click');
await flushPromises();
expect(wrapper.get('button').attributes('aria-label')).toBe('复制消息');
expect(ElMessage.error).toHaveBeenCalledWith('复制失败,请重试');
});
});

View File

@@ -1,8 +1,10 @@
<script setup lang="ts">
import {
CopyDocument,
RefreshRight,
} from '@element-plus/icons-vue';
import { onBeforeUnmount, ref } from 'vue';
import { copyTextToClipboard } from '@easyflow/utils';
import { Check, CopyDocument, RefreshRight } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import ChatAnswerVariantNavigator from './ChatAnswerVariantNavigator.vue';
@@ -11,6 +13,8 @@ const props = withDefaults(
align?: 'end' | 'start';
allowCopy?: boolean;
allowRegenerate?: boolean;
copyErrorMessage?: string;
copyText?: string;
disabledVariantNext?: boolean;
disabledVariantPrevious?: boolean;
regenerateDisabled?: boolean;
@@ -23,6 +27,8 @@ const props = withDefaults(
align: 'start',
allowCopy: false,
allowRegenerate: false,
copyErrorMessage: '复制失败',
copyText: '',
disabledVariantNext: false,
disabledVariantPrevious: false,
regenerateDisabled: false,
@@ -34,14 +40,37 @@ const props = withDefaults(
);
const emit = defineEmits<{
copy: [];
regenerate: [];
selectNextVariant: [];
selectPreviousVariant: [];
}>();
function handleCopy() {
emit('copy');
const copied = ref(false);
const copying = ref(false);
const COPIED_FEEDBACK_DURATION_MS = 1600;
let copiedResetTimer: ReturnType<typeof setTimeout> | undefined;
async function handleCopy() {
if (copying.value || !props.copyText) {
return;
}
copying.value = true;
try {
await copyTextToClipboard(props.copyText);
copied.value = true;
if (copiedResetTimer) {
clearTimeout(copiedResetTimer);
}
copiedResetTimer = setTimeout(() => {
copied.value = false;
copiedResetTimer = undefined;
}, COPIED_FEEDBACK_DURATION_MS);
} catch (error) {
console.error('复制消息失败:', error);
ElMessage.error(props.copyErrorMessage);
} finally {
copying.value = false;
}
}
function handleRegenerate() {
@@ -58,6 +87,12 @@ function handleSelectPreviousVariant() {
function handleSelectNextVariant() {
emit('selectNextVariant');
}
onBeforeUnmount(() => {
if (copiedResetTimer) {
clearTimeout(copiedResetTimer);
}
});
</script>
<template>
@@ -81,11 +116,15 @@ function handleSelectNextVariant() {
v-if="allowCopy"
type="button"
class="message-actions__button"
aria-label="复制消息"
title="复制"
:aria-busy="copying"
:aria-label="copied ? '复制成功' : '复制消息'"
:title="copied ? '复制成功' : '复制'"
@click="handleCopy"
>
<CopyDocument />
<Transition name="message-actions__icon" mode="out-in">
<Check v-if="copied" key="check" />
<CopyDocument v-else key="copy" />
</Transition>
</button>
<button
@@ -150,4 +189,17 @@ function handleSelectNextVariant() {
width: 15px;
height: 15px;
}
.message-actions__icon-enter-active,
.message-actions__icon-leave-active {
transition:
opacity var(--motion-duration-fast) var(--motion-ease-standard),
transform var(--motion-duration-fast) var(--motion-ease-standard);
}
.message-actions__icon-enter-from,
.message-actions__icon-leave-to {
opacity: 0;
transform: scale(0.88);
}
</style>

View File

@@ -387,13 +387,6 @@ const generateMockMessages = (refreshContent: string) => {
return [userMessage];
};
const handleCopy = (content: string) => {
navigator.clipboard
.writeText(content)
.then(() => ElMessage.success($t('message.copySuccess')))
.catch(() => ElMessage.error($t('message.copyFail')));
};
const handleRefresh = () => {
const roundId = String(latestAssistantMessage.value?.roundId || '');
if (!roundId) {
@@ -643,6 +636,8 @@ onBeforeUnmount(() => {
:align="item.role === 'user' ? 'end' : 'start'"
:allow-copy="!!String(item.content || '').trim()"
:allow-regenerate="canRegenerateMessage(item)"
:copy-error-message="$t('message.copyFail')"
:copy-text="String(item.content || '').trim()"
:disabled-variant-next="!canSwitchVariant(item, 'next')"
:disabled-variant-previous="!canSwitchVariant(item, 'previous')"
:regenerate-disabled="sending"
@@ -652,7 +647,6 @@ onBeforeUnmount(() => {
Number(item.variantIndex || item.selectedVariantIndex || 1)
"
:variant-total="Number(item.variantCount || 1)"
@copy="handleCopy(item.content)"
@regenerate="handleRefresh"
@select-next-variant="handleSelectVariant(item, 'next')"
@select-previous-variant="handleSelectVariant(item, 'previous')"

View File

@@ -21,6 +21,7 @@ import {
ChatTimeline,
ChatTimelineBuilder,
} from '@easyflow/common-ui';
import { copyTextToClipboard } from '@easyflow/utils';
import {
Delete,
@@ -872,13 +873,15 @@ function handleStop() {
async function handleCopyMessage(item: ChatTimelineMessageItem) {
const text = copyMessageText(item);
if (!text) {
return;
return false;
}
try {
await navigator.clipboard.writeText(text);
ElMessage.success('已复制');
} catch {
await copyTextToClipboard(text);
return true;
} catch (error) {
console.error('复制消息失败:', error);
ElMessage.error('复制失败');
return false;
}
}
@@ -1133,9 +1136,9 @@ onBeforeUnmount(() => {
:image-loader="loadAgentChatImage"
empty-text="选择智能体后开始对话"
:approval-loading="Boolean(approvalLoadingKey)"
:copy-action="handleCopyMessage"
:copyable="canCopyMessage"
@approve="handleApprove"
@copy-message="handleCopyMessage"
@reject="handleReject"
@select-next-variant="() => undefined"
@select-previous-variant="() => undefined"

View File

@@ -14,6 +14,7 @@ import { computed, onMounted, ref, watch } from 'vue';
import { ChatTimeline } from '@easyflow/common-ui';
import { BrushCleaning } from '@easyflow/icons';
import { copyTextToClipboard } from '@easyflow/utils';
import { ElButton, ElMessage } from 'element-plus';
@@ -148,13 +149,15 @@ function canRegenerateMessage(item: ChatTimelineMessageItem) {
async function handleCopyMessage(item: ChatTimelineMessageItem) {
const text = copyMessageText(item).trim();
if (!text) {
return;
return false;
}
try {
await navigator.clipboard.writeText(text);
ElMessage.success('已复制');
} catch {
await copyTextToClipboard(text);
return true;
} catch (error) {
console.error('复制消息失败:', error);
ElMessage.error('复制失败');
return false;
}
}
@@ -310,11 +313,11 @@ async function handleReject(payload: ChatTimelineToolApprovalPayload) {
:image-loader="loadAgentChatImage"
empty-text="输入问题试运行当前智能体"
:approval-loading="approvalLoading"
:copy-action="handleCopyMessage"
:copyable="canCopyMessage"
:regenerable="canRegenerateMessage"
:regenerate-disabled="true"
@approve="handleApprove"
@copy-message="handleCopyMessage"
@regenerate-message="handleRegenerateMessage"
@reject="handleReject"
@select-next-variant="handleSelectNextVariant"

View File

@@ -951,19 +951,6 @@ function scrollToBottom(force = false) {
});
}
async function copyMessageContent(content?: string) {
const normalized = String(content || '').trim();
if (!normalized) {
return;
}
try {
await navigator.clipboard.writeText(normalized);
ElMessage.success('已复制');
} catch {
ElMessage.error('复制失败');
}
}
function resolveKnowledgeView(knowledgeId: string) {
const view = knowledgeMap.value.get(knowledgeId);
if (view) {
@@ -1369,13 +1356,6 @@ function canRegenerateMessage(item: ChatTimeTimelineItem) {
return !!roundId && !!resolveRoundUserPrompt(roundId);
}
async function handleCopyMessage(item: ChatTimeTimelineItem) {
if (!canCopyMessage(item)) {
return;
}
await copyMessageContent(item.content);
}
async function handleRegenerateMessage() {
if (sending.value || isReadOnly.value) {
return;
@@ -1786,6 +1766,7 @@ async function deleteSession(targetSession?: SessionItem) {
:align="item.role === 'user' ? 'end' : 'start'"
:allow-copy="canCopyMessage(item)"
:allow-regenerate="canRegenerateMessage(item)"
:copy-text="String(item.content || '').trim()"
:disabled-variant-next="!canSwitchVariant(item, 'next')"
:disabled-variant-previous="!canSwitchVariant(item, 'previous')"
:regenerate-disabled="sending || isReadOnly"
@@ -1795,7 +1776,6 @@ async function deleteSession(targetSession?: SessionItem) {
Number(item.variantIndex || item.selectedVariantIndex || 1)
"
:variant-total="Number(item.variantCount || 1)"
@copy="handleCopyMessage(item)"
@regenerate="handleRegenerateMessage"
@select-next-variant="selectVariantForMessage(item, 'next')"
@select-previous-variant="

View File

@@ -1650,18 +1650,6 @@ const isFinalAssistantInRound = (item: BubbleMessage) => {
return true;
};
const handleCopyMessage = async (item: BubbleMessage) => {
if (!canCopyMessage(item)) {
return;
}
try {
await navigator.clipboard.writeText(String(item.content || ''));
ElMessage.success($t('bot.publicChatCopySuccess'));
} catch {
ElMessage.error($t('bot.publicChatCopyFail'));
}
};
const handleRegenerateMessage = async (item: BubbleMessage) => {
if (sending.value || item.role !== 'assistant') {
return;
@@ -1960,6 +1948,8 @@ function prefetchVisibleVariants() {
<ChatMessageActionBar
:align="item.role === 'user' ? 'end' : 'start'"
:allow-copy="canCopyMessage(item)"
:copy-error-message="$t('bot.publicChatCopyFail')"
:copy-text="String(item.content || '').trim()"
:allow-regenerate="
item.role === 'assistant' &&
getLatestAssistantMessage()?.id === item.id &&
@@ -1976,7 +1966,6 @@ function prefetchVisibleVariants() {
Number(item.variantIndex || item.selectedVariantIndex || 1)
"
:variant-total="Number(item.variantCount || 1)"
@copy="handleCopyMessage(item)"
@regenerate="handleRegenerateMessage(item)"
@select-next-variant="handleSelectVariant(item, 'next')"
@select-previous-variant="