diff --git a/frontend/src/components/AgentEmbedChannelPanel.vue b/frontend/src/components/AgentEmbedChannelPanel.vue index 674efd90..a3e1ab01 100644 --- a/frontend/src/components/AgentEmbedChannelPanel.vue +++ b/frontend/src/components/AgentEmbedChannelPanel.vue @@ -397,6 +397,7 @@ import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue' import { useI18n } from 'vue-i18n' import { MessagePlugin } from 'tdesign-vue-next' +import { copyWithToast } from '@/utils/clipboard' import { useAuthStore } from '@/stores/auth' import SettingDrawer from '@/components/settings/SettingDrawer.vue' import EmbedChannelPreview from '@/components/EmbedChannelPreview.vue' @@ -749,8 +750,7 @@ const copyToken = async (ch: EmbedChannel) => { MessagePlugin.warning(t('embedPublish.tokenHint')) return } - await navigator.clipboard.writeText(token) - MessagePlugin.success(t('embedPublish.tokenCopied')) + await copyWithToast(token, 'embedPublish.tokenCopied') } const iframeSnippet = (ch: EmbedChannel) => { @@ -1035,15 +1035,11 @@ async function openPreviewForChannel( } const copySecureServerExample = async () => { - if (!secureServerExample.value) return - await navigator.clipboard.writeText(secureServerExample.value) - MessagePlugin.success(t('embedPublish.copied')) + await copyWithToast(secureServerExample.value, 'embedPublish.copied') } const copyDrawerSnippet = async () => { - if (!drawerSnippet.value) return - await navigator.clipboard.writeText(drawerSnippet.value) - MessagePlugin.success(t('embedPublish.copied')) + await copyWithToast(drawerSnippet.value, 'embedPublish.copied') } const performRotate = async (id: string) => { diff --git a/frontend/src/components/ChatHeader.vue b/frontend/src/components/ChatHeader.vue index 79aec898..04425147 100644 --- a/frontend/src/components/ChatHeader.vue +++ b/frontend/src/components/ChatHeader.vue @@ -117,6 +117,7 @@ import { computed, nextTick, ref } from 'vue' import { useI18n } from 'vue-i18n' import { MessagePlugin } from 'tdesign-vue-next' +import { copyToClipboard } from '@/utils/clipboard' import { getMessageList } from '@/api/chat' import { clearSession, @@ -179,26 +180,8 @@ function onMenuAction(value: string): void { } async function copyText(text: string): Promise { - if (navigator.clipboard?.writeText) { - try { - await navigator.clipboard.writeText(text) - return - } catch { - // Some browsers expose Clipboard API outside a permitted context. - // Fall through to the legacy copy path before reporting a failure. - } - } - - const textarea = document.createElement('textarea') - textarea.value = text - textarea.setAttribute('readonly', '') - textarea.style.position = 'fixed' - textarea.style.opacity = '0' - document.body.appendChild(textarea) - textarea.select() - const copied = document.execCommand('copy') - textarea.remove() - if (!copied) throw new Error('clipboard unavailable') + const ok = await copyToClipboard(text) + if (!ok) throw new Error('clipboard unavailable') } function currentSessionLink(): string { diff --git a/frontend/src/components/ChatRequestInfoButton.vue b/frontend/src/components/ChatRequestInfoButton.vue index 2919cfc6..ea9e5e43 100644 --- a/frontend/src/components/ChatRequestInfoButton.vue +++ b/frontend/src/components/ChatRequestInfoButton.vue @@ -48,12 +48,11 @@ diff --git a/frontend/src/components/IMChannelPanel.vue b/frontend/src/components/IMChannelPanel.vue index 7c94ff3b..f4ac1475 100644 --- a/frontend/src/components/IMChannelPanel.vue +++ b/frontend/src/components/IMChannelPanel.vue @@ -579,6 +579,7 @@ import { ref, onMounted, watch, onUnmounted, computed } from 'vue'; import { useI18n } from 'vue-i18n'; import { MessagePlugin } from 'tdesign-vue-next'; +import { copyWithToast } from '@/utils/clipboard'; import { listIMChannels, createIMChannel, updateIMChannel, deleteIMChannel, toggleIMChannel, getWeChatQRCode, pollWeChatQRCodeStatus, listAllIMChannels, listAgents, @@ -936,25 +937,7 @@ function getCallbackUrl(channel: IMChannel): string { } async function copyUrl(channel: IMChannel) { - const text = getCallbackUrl(channel); - try { - await navigator.clipboard.writeText(text); - MessagePlugin.success(t('common.copySuccess')); - } catch { - const el = document.createElement('textarea'); - el.value = text; - el.style.cssText = 'position:fixed;top:-9999px;left:-9999px;opacity:0'; - document.body.appendChild(el); - el.focus(); - el.select(); - const ok = document.execCommand('copy'); - document.body.removeChild(el); - if (ok) { - MessagePlugin.success(t('common.copySuccess')); - } else { - MessagePlugin.error(t('common.copyFailed')); - } - } + await copyWithToast(getCallbackUrl(channel), 'common.copySuccess'); } function openCreate() { diff --git a/frontend/src/components/ModelDebugDrawer.vue b/frontend/src/components/ModelDebugDrawer.vue index 9a4e8055..00fd0c6d 100644 --- a/frontend/src/components/ModelDebugDrawer.vue +++ b/frontend/src/components/ModelDebugDrawer.vue @@ -195,6 +195,7 @@ import { computed, ref, watch, onBeforeUnmount } from 'vue' import { MessagePlugin } from 'tdesign-vue-next' import { useI18n } from 'vue-i18n' +import { copyWithToast } from '@/utils/clipboard' import SettingDrawer from '@/components/settings/SettingDrawer.vue' import { debugModel, type ModelConfig, type ModelDebugResult } from '@/api/model' import { fileSizeVerification } from '@/utils' @@ -448,12 +449,7 @@ const runDebug = async () => { const copyResult = async () => { if (!result.value) return - try { - await navigator.clipboard.writeText(JSON.stringify(result.value, null, 2)) - MessagePlugin.success(t('common.copied')) - } catch { - MessagePlugin.error(t('common.copyFailed')) - } + await copyWithToast(JSON.stringify(result.value, null, 2), 'common.copied') } onBeforeUnmount(() => { diff --git a/frontend/src/components/knowledge-processing-timeline.vue b/frontend/src/components/knowledge-processing-timeline.vue index 2cf82b64..8776bc0e 100644 --- a/frontend/src/components/knowledge-processing-timeline.vue +++ b/frontend/src/components/knowledge-processing-timeline.vue @@ -2,6 +2,7 @@ import { ref, reactive, onMounted, onBeforeUnmount, watch, computed, nextTick } from 'vue' import { MessagePlugin } from 'tdesign-vue-next' import { useI18n } from 'vue-i18n' +import { copyWithToast } from '@/utils/clipboard' import { getKnowledgeSpans, reparseKnowledge, cancelKnowledgeParse, getKnowledgeDetails } from '@/api/knowledge-base/index' import { groupPostprocessGraphSpans, @@ -446,13 +447,8 @@ function localizedErrorSuggestion(code?: string): string { } async function copyValue(value: any) { - try { - const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2) - await navigator.clipboard.writeText(text) - MessagePlugin.success(t('knowledgeStages.copied')) - } catch { - MessagePlugin.error(t('knowledgeStages.copyDetails')) - } + const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2) + await copyWithToast(text, 'knowledgeStages.copied', 'knowledgeStages.copyDetails') } async function copySpan(node: SpanNode) { diff --git a/frontend/src/utils/chatMessageShared.ts b/frontend/src/utils/chatMessageShared.ts index f4aad38e..c09e82cd 100644 --- a/frontend/src/utils/chatMessageShared.ts +++ b/frontend/src/utils/chatMessageShared.ts @@ -100,19 +100,3 @@ export const buildManualMarkdown = (_question: string, answer: string): string = const safeAnswer = answer?.trim() || i18n.global.t('chat.noAnswerContent'); return `${safeAnswer}`; }; - -export const copyTextToClipboard = async (content: string): Promise => { - if (navigator.clipboard && navigator.clipboard.writeText) { - await navigator.clipboard.writeText(content); - return; - } - - const textArea = document.createElement('textarea'); - textArea.value = content; - textArea.style.position = 'fixed'; - textArea.style.opacity = '0'; - document.body.appendChild(textArea); - textArea.select(); - document.execCommand('copy'); - document.body.removeChild(textArea); -}; diff --git a/frontend/src/utils/clipboard.ts b/frontend/src/utils/clipboard.ts new file mode 100644 index 00000000..82972f86 --- /dev/null +++ b/frontend/src/utils/clipboard.ts @@ -0,0 +1,67 @@ +import { MessagePlugin } from 'tdesign-vue-next' +import i18n from '@/i18n' + +/** + * Copy text to the clipboard, falling back to a hidden textarea + + * document.execCommand('copy') when the async Clipboard API is unavailable + * (e.g. on non-secure HTTP origins) or rejects (e.g. permission denied). + * + * Returns true on success, false otherwise. This helper is UI-agnostic — + * callers own any feedback. Use copyWithToast for the common "copy + toast" + * case; call this directly when you need custom feedback (e.g. inline DOM + * state) or none at all. + */ +export async function copyToClipboard(text: string): Promise { + if (!text) return false + + // Prefer the async Clipboard API where available (HTTPS / localhost). + if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') { + try { + await navigator.clipboard.writeText(text) + return true + } catch { + // Fall through to the legacy path (e.g. permission denied). + } + } + + // Legacy fallback that also works on non-secure (HTTP) origins. + try { + const textArea = document.createElement('textarea') + textArea.value = text + textArea.style.position = 'fixed' + textArea.style.top = '0' + textArea.style.left = '0' + textArea.style.opacity = '0' + document.body.appendChild(textArea) + textArea.focus() + textArea.select() + const ok = document.execCommand('copy') + document.body.removeChild(textArea) + return ok + } catch { + return false + } +} + +/** + * Copy text and surface the result via a toast. Returns the underlying + * copyToClipboard result so callers can run extra side effects on success + * (e.g. closing a dialog). Empty / null / undefined text is a silent no-op + * (no toast), so callers can pass optional values (e.g. obj.value?.id) + * without a separate guard. successKey is required; failureKey defaults to + * the common message. + */ +export async function copyWithToast( + text: string | null | undefined, + successKey: string, + failureKey: string = 'common.copyFailed', +): Promise { + if (!text) return false + const ok = await copyToClipboard(text) + if (ok) { + MessagePlugin.success(i18n.global.t(successKey)) + } else { + MessagePlugin.error(i18n.global.t(failureKey)) + } + return ok +} diff --git a/frontend/src/utils/markdownEnhancements.ts b/frontend/src/utils/markdownEnhancements.ts index 72a0c91f..4b5e866d 100644 --- a/frontend/src/utils/markdownEnhancements.ts +++ b/frontend/src/utils/markdownEnhancements.ts @@ -1,6 +1,7 @@ import i18n from '@/i18n'; import hljs from 'highlight.js'; import { openMermaidFullscreen } from '@/utils/mermaidViewer'; +import { copyToClipboard } from '@/utils/clipboard'; const ENHANCE_FLAG = 'data-markdown-enhancements'; const boundMarkdownRoots = new WeakSet(); @@ -134,26 +135,15 @@ async function handleCodeCopy(btn: HTMLButtonElement): Promise { const copiedLabel = i18n.global.t('common.copied'); const defaultLabel = i18n.global.t('embedPublish.copyCode'); - try { - if (navigator.clipboard?.writeText) { - await navigator.clipboard.writeText(code); - } else { - const textArea = document.createElement('textarea'); - textArea.value = code; - textArea.style.position = 'fixed'; - textArea.style.opacity = '0'; - document.body.appendChild(textArea); - textArea.select(); - document.execCommand('copy'); - document.body.removeChild(textArea); - } + const ok = await copyToClipboard(code); + if (ok) { btn.classList.add('is-copied'); if (textEl) textEl.textContent = copiedLabel; window.setTimeout(() => { btn.classList.remove('is-copied'); if (textEl) textEl.textContent = defaultLabel; }, 1600); - } catch { + } else { btn.classList.add('is-error'); window.setTimeout(() => btn.classList.remove('is-error'), 1600); } diff --git a/frontend/src/views/agent/AgentEditorModal.vue b/frontend/src/views/agent/AgentEditorModal.vue index 517b8076..ef9528b4 100644 --- a/frontend/src/views/agent/AgentEditorModal.vue +++ b/frontend/src/views/agent/AgentEditorModal.vue @@ -1689,6 +1689,7 @@ import { } from '@/config/contextualGuides'; import { useI18n } from 'vue-i18n'; import { selectInitialModelId } from '@/utils/modelDefaults'; +import { copyWithToast } from '@/utils/clipboard'; import { MessagePlugin } from 'tdesign-vue-next'; import { createAgent, @@ -1778,27 +1779,7 @@ const saveButtonLabel = computed(() => ); const copyAgentId = async () => { - const id = editorAgent.value?.id; - if (!id) return; - - try { - if (navigator.clipboard?.writeText) { - await navigator.clipboard.writeText(id); - } else { - const textarea = document.createElement('textarea'); - textarea.value = id; - textarea.setAttribute('readonly', ''); - textarea.style.position = 'fixed'; - textarea.style.opacity = '0'; - document.body.appendChild(textarea); - textarea.select(); - document.execCommand('copy'); - document.body.removeChild(textarea); - } - MessagePlugin.success(t('common.copied')); - } catch { - MessagePlugin.error(t('common.copyFailed')); - } + await copyWithToast(editorAgent.value?.id, 'common.copied'); }; const currentSection = ref(props.initialSection || 'basic'); diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue index 7372a441..92397ed3 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -539,13 +539,13 @@ import { getQueryText, getWikiPageText } from '@/utils/agent-tool-display'; import { parseWikiToolReferences } from '@/utils/wikiToolReferences'; import { buildManualMarkdown, - copyTextToClipboard, formatManualTitle, replaceIncompleteMermaidWithPlaceholder, prepareStreamingMermaidMarkdown, extractFirstMermaidCode, injectCachedMermaidSvg, } from '@/utils/chatMessageShared'; +import { copyWithToast } from '@/utils/clipboard'; import { configureMarkedForChatMarkdown, renderChatMarkdown, @@ -2766,13 +2766,7 @@ const handleCopyAnswer = async (answerEvent: any) => { return; } - try { - await copyTextToClipboard(content); - MessagePlugin.success(t('agentStream.copy.success')); - } catch (err) { - console.error('Copy failed:', err); - MessagePlugin.error(t('agentStream.copy.failed')); - } + await copyWithToast(content, 'agentStream.copy.success', 'agentStream.copy.failed'); }; const handleAddToKnowledge = (answerEvent: any) => { diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vue index 38fa5899..40c96e7f 100644 --- a/frontend/src/views/chat/components/botmsg.vue +++ b/frontend/src/views/chat/components/botmsg.vue @@ -112,9 +112,9 @@ import { MessagePlugin } from 'tdesign-vue-next'; import { useUIStore } from '@/stores/ui'; import { buildManualMarkdown, - copyTextToClipboard, formatManualTitle, } from '@/utils/chatMessageShared'; +import { copyWithToast } from '@/utils/clipboard'; import { createChatMarkdownRenderer, renderChatMarkdown, @@ -306,13 +306,7 @@ const handleCopyAnswer = async () => { return; } - try { - await copyTextToClipboard(content); - MessagePlugin.success(t('chat.copySuccess')); - } catch (err) { - console.error('复制失败:', err); - MessagePlugin.error(t('chat.copyFailed')); - } + await copyWithToast(content, 'chat.copySuccess', 'chat.copyFailed'); }; // 添加到知识库 diff --git a/frontend/src/views/chat/components/tool-results/ChunkDetail.vue b/frontend/src/views/chat/components/tool-results/ChunkDetail.vue index 73ab49b3..f7ea7536 100644 --- a/frontend/src/views/chat/components/tool-results/ChunkDetail.vue +++ b/frontend/src/views/chat/components/tool-results/ChunkDetail.vue @@ -37,6 +37,7 @@