feat(ai): add message copy actions

This commit is contained in:
Guoyu Su authored and GitHub committed 2026-08-15 00:28:12 +08:00
1 parent 8737114d28
commit 38a7815b72
12 files changed
+131 -14

No files matched your search

@@ -93,6 +93,7 @@ import { shouldShowReasoningCharCount, reasoningCharCountClass } from "@/lib/ai/
import { saveTextFile } from "@/lib/export/saveTextFile";
import { buildAiAnalysisExport } from "@/lib/export/aiAnalysisExport";
import { buildAiConversationSearchIndex, filterAiConversationSearchIndex } from "@/lib/ai/aiConversationSearch";
import { resolveAiMessageCopyText } from "@/lib/ai/aiMessageCopy";
const { t } = useI18n();
const settings = useSettingsStore();
@@ -1962,14 +1963,14 @@ function tempRunSql(code: string) {
emit("tempRunSql", code);
}
const copiedIndex = ref("");
const copiedContentKey = ref("");
async function copyCode(code: string, key: string) {
async function copyAiContent(content: string, key: string) {
try {
await copyToClipboard(code);
copiedIndex.value = key;
await copyToClipboard(content);
copiedContentKey.value = key;
setTimeout(() => {
if (copiedIndex.value === key) copiedIndex.value = "";
if (copiedContentKey.value === key) copiedContentKey.value = "";
}, 2000);
} catch (e: unknown) {
const message = e instanceof Error ? e.message : String(e);
@@ -1977,6 +1978,28 @@ async function copyCode(code: string, key: string) {
}
}
function isStreamingMessage(msg: ChatMessage): boolean {
return isGenerating.value && msg === messages.value[messages.value.length - 1];
}
function messageCopyText(msg: ChatMessage): string | null {
return resolveAiMessageCopyText(msg, isStreamingMessage(msg));
}
function canCopyMessage(msg: ChatMessage): boolean {
return messageCopyText(msg) !== null;
}
function messageCopyKey(index: number): string {
return `message:${index}`;
}
async function copyMessage(msg: ChatMessage, index: number) {
const text = messageCopyText(msg);
if (text === null) return;
await copyAiContent(text, `message:${index}`);
}
async function exportMessageAsMarkdown(msg: ChatMessage) {
if (!msg.content) return;
@@ -2189,8 +2212,7 @@ const messageRenderer = computed(() => {
* already-finished segments, so a frame only re-parses the growing tail.
*/
function renderMessageSegments(msg: ChatMessage) {
const streaming = isGenerating.value && msg === messages.value[messages.value.length - 1];
return messageRenderer.value.render(msg.content, { streaming });
return messageRenderer.value.render(msg.content, { streaming: isStreamingMessage(msg) });
}
function onMarkdownClick(event: MouseEvent) {
@@ -2337,6 +2359,19 @@ async function openExternalUrl(url: string) {
</div>
<div v-if="msg.content" class="whitespace-pre-wrap">{{ msg.content }}</div>
</div>
<div v-if="canCopyMessage(msg)" class="mt-1 flex justify-end">
<button
data-ai-message-copy="user"
type="button"
class="rounded p-0.5 text-zinc-500 hover:bg-zinc-200 hover:text-zinc-900 dark:text-zinc-400 dark:hover:bg-zinc-700 dark:hover:text-zinc-200"
:title="copiedContentKey === messageCopyKey(i) ? t('ai.copied') : t('ai.copyMessage')"
:aria-label="copiedContentKey === messageCopyKey(i) ? t('ai.copied') : t('ai.copyMessage')"
@click="copyMessage(msg, i)"
>
<Check v-if="copiedContentKey === messageCopyKey(i)" class="h-3.5 w-3.5 text-green-500" />
<Copy v-else class="h-3.5 w-3.5" />
</button>
</div>
</div>
</template>
</div>
@@ -2409,10 +2444,10 @@ async function openExternalUrl(url: string) {
</button>
<button
class="rounded p-0.5 text-zinc-500 hover:bg-zinc-200 hover:text-zinc-900 dark:text-zinc-400 dark:hover:bg-zinc-700 dark:hover:text-zinc-200"
:title="copiedIndex === `${i}-${j}` ? t('ai.copied') : t(seg.isSql ? 'ai.copySql' : 'ai.copyCode')"
@click="copyCode(seg.content, `${i}-${j}`)"
:title="copiedContentKey === `code:${i}:${j}` ? t('ai.copied') : t(seg.isSql ? 'ai.copySql' : 'ai.copyCode')"
@click="copyAiContent(seg.content, `code:${i}:${j}`)"
>
<Check v-if="copiedIndex === `${i}-${j}`" class="h-3.5 w-3.5 text-green-400" />
<Check v-if="copiedContentKey === `code:${i}:${j}`" class="h-3.5 w-3.5 text-green-400" />
<Copy v-else class="h-3.5 w-3.5" />
</button>
</div>
@@ -2431,12 +2466,25 @@ async function openExternalUrl(url: string) {
</Button>
</div>
</div>
<div v-if="msg.content && !isGenerating" class="mt-1 flex items-center justify-between">
<div v-if="canCopyMessage(msg)" class="mt-1 flex items-center justify-between">
<span v-if="msg.tokens" class="text-[10px] text-muted-foreground">&#8593;{{ msg.tokens.input.toLocaleString() }} &#8595;{{ msg.tokens.output.toLocaleString() }} tokens</span>
<span v-else />
<button class="rounded p-0.5 text-zinc-500 hover:bg-zinc-200 hover:text-zinc-900 dark:text-zinc-400 dark:hover:bg-zinc-700 dark:hover:text-zinc-200" :title="t('ai.exportMarkdown')" @click="exportMessageAsMarkdown(msg)">
<FileDown class="h-3.5 w-3.5" />
</button>
<div class="flex items-center gap-1">
<button
data-ai-message-copy="assistant"
type="button"
class="rounded p-0.5 text-zinc-500 hover:bg-zinc-200 hover:text-zinc-900 dark:text-zinc-400 dark:hover:bg-zinc-700 dark:hover:text-zinc-200"
:title="copiedContentKey === messageCopyKey(i) ? t('ai.copied') : t('ai.copyMessage')"
:aria-label="copiedContentKey === messageCopyKey(i) ? t('ai.copied') : t('ai.copyMessage')"
@click="copyMessage(msg, i)"
>
<Check v-if="copiedContentKey === messageCopyKey(i)" class="h-3.5 w-3.5 text-green-500" />
<Copy v-else class="h-3.5 w-3.5" />
</button>
<button class="rounded p-0.5 text-zinc-500 hover:bg-zinc-200 hover:text-zinc-900 dark:text-zinc-400 dark:hover:bg-zinc-700 dark:hover:text-zinc-200" :title="t('ai.exportMarkdown')" @click="exportMessageAsMarkdown(msg)">
<FileDown class="h-3.5 w-3.5" />
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,21 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const source = readFileSync(new URL("../AiAssistant.vue", import.meta.url), "utf8");
describe("AI assistant message copy actions", () => {
it("exposes copy actions below user and assistant messages", () => {
expect(source).toContain('data-ai-message-copy="user"');
expect(source).toContain('data-ai-message-copy="assistant"');
});
it("routes message copies through the body-only copy contract", () => {
expect(source).toContain("resolveAiMessageCopyText(msg, isStreamingMessage(msg))");
expect(source).toContain("copyAiContent(text, `message:${index}`)");
});
it("keeps code-block and message feedback keys separate", () => {
expect(source).toContain("copyAiContent(seg.content, `code:${i}:${j}`)");
expect(source).toContain("messageCopyKey(i)");
});
});
+1
View File
@@ -2319,6 +2319,7 @@ export default {
executeSql: "Execute SQL",
tempRunSql: "Run without modifying editor",
copyAll: "Copy All",
copyMessage: "Copy message",
copied: "Copied",
copyTestResult: "Copy test result",
testErrorAuth: "Authentication or access failed. Check the API key, project permissions, and API availability.",
+1
View File
@@ -2357,6 +2357,7 @@ export default withEnglishFallback({
executeSql: "Ejecutar SQL",
tempRunSql: "Ejecutar sin modificar",
copyAll: "Copiar todo",
copyMessage: "Copiar mensaje",
copied: "Copiado",
copyTestResult: "Copiar resultado de prueba",
testErrorAuth: "Falló la autenticación o el acceso. Comprueba la clave de API, los permisos del proyecto y que la API esté habilitada.",
+1
View File
@@ -2251,6 +2251,7 @@ export default withEnglishFallback({
executeSql: "Esegui SQL",
tempRunSql: "Esegui senza modificare",
copyAll: "Copia Tutto",
copyMessage: "Copia messaggio",
copied: "Copiato",
copyTestResult: "Copia risultato test",
testErrorAuth: "Autenticazione o accesso non riusciti. Controlla la chiave API, i permessi del progetto e che l'API sia abilitata.",
+1
View File
@@ -2391,6 +2391,7 @@ export default withEnglishFallback({
executeSql: "SQLを実行",
tempRunSql: "編集せずに実行",
copyAll: "すべてコピー",
copyMessage: "メッセージをコピー",
copied: "コピーしました",
copyTestResult: "テスト結果をコピー",
testErrorAuth: "認証またはアクセスに失敗しました。API キー、プロジェクト権限、API の有効化状態を確認してください。",
+1
View File
@@ -2177,6 +2177,7 @@ export default withEnglishFallback({
executeSql: "SQL 실행",
tempRunSql: "편집기를 수정하지 않고 실행",
copyAll: "모두 복사",
copyMessage: "메시지 복사",
copied: "복사했습니다",
copyTestResult: "테스트 결과 복사",
testErrorAuth: "인증 또는 접근에 실패했습니다. API 키, 프로젝트 권한 및 API 가용성을 확인하세요.",
+1
View File
@@ -2359,6 +2359,7 @@ export default withEnglishFallback({
executeSql: "Executar SQL",
tempRunSql: "Executar sem modificar",
copyAll: "Copiar Tudo",
copyMessage: "Copiar mensagem",
copied: "Copiado",
copyTestResult: "Copiar resultado do teste",
testErrorAuth: "A autenticação ou o acesso falhou. Verifique a chave de API, as permissões do projeto e se a API está ativada.",
+1
View File
@@ -2243,6 +2243,7 @@ export default withEnglishFallback({
executeSql: "立即执行",
tempRunSql: "临时运行",
copyAll: "复制全部",
copyMessage: "复制消息",
copied: "已复制",
copyTestResult: "复制测试结果",
testErrorAuth: "身份验证或访问失败,请检查 API Key、项目权限和 API 启用状态。",
+1
View File
@@ -2252,6 +2252,7 @@ export default withEnglishFallback({
executeSql: "立即執行",
tempRunSql: "臨時執行",
copyAll: "複製全部",
copyMessage: "複製訊息",
copied: "已複製",
copyTestResult: "複製測試結果",
testErrorAuth: "驗證或存取失敗,請檢查 API Key、專案權限和 API 啟用狀態。",
+26
View File
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { resolveAiMessageCopyText } from "@/lib/ai/aiMessageCopy";
describe("AI message copy payload", () => {
it("preserves user message text exactly", () => {
const content = "Check `orders`\n\n```sql\nSELECT * FROM orders;\n```";
expect(resolveAiMessageCopyText({ role: "user", content }, false)).toBe(content);
});
it("copies only the assistant message body", () => {
const message = {
role: "assistant" as const,
content: "The result is **42**.",
reasoning: "private reasoning",
agentSteps: [{ toolResult: "tool output" }],
};
expect(resolveAiMessageCopyText(message, false)).toBe(message.content);
});
it("does not expose empty or streaming messages", () => {
expect(resolveAiMessageCopyText({ role: "assistant", content: "partial" }, true)).toBeNull();
expect(resolveAiMessageCopyText({ role: "assistant", content: "" }, false)).toBeNull();
});
});
+14
View File
@@ -0,0 +1,14 @@
export interface AiMessageCopyCandidate {
role: "user" | "assistant";
content: string;
}
/**
* Keeps message-level copy payloads scoped to the original message body.
* Reasoning, tool activity, mentions, and rendered HTML live outside this
* contract and must not be appended by the caller.
*/
export function resolveAiMessageCopyText(message: AiMessageCopyCandidate, streaming: boolean): string | null {
if (!message.content || streaming) return null;
return message.content;
}