feat(ai): confirm before resending a chat message
This commit is contained in:
14 files changed
+118
-3
No files matched your search
@@ -178,7 +178,7 @@ import { DBX_TABLE_REFERENCE_DROP_EVENT, clearActiveTableReferencePayload } from
|
||||
import { canSubmitAiPrompt, isAiPromptImeCompositionEvent, shouldSubmitAiPromptOnKeydown } from "@/lib/ai/aiPromptKeyboard";
|
||||
import { isActionableWriteProposalMessage, isActionableWriteSqlProposal, looksLikeActionProposal, looksLikeWriteSqlProposal, shouldGrantWriteSqlOnShortAffirmative } from "@/lib/ai/aiProposalDetect";
|
||||
import { classifyIntentByLlm, routeIntentByRules, type AiIntentRouteInput } from "@/lib/ai/aiIntentRouter";
|
||||
import { visibleToActualIndex } from "@/lib/ai/aiMessageEdit";
|
||||
import { retryableUserMessageIndex, visibleToActualIndex } from "@/lib/ai/aiMessageEdit";
|
||||
import { shouldShowReasoningCharCount, reasoningCharCountClass } from "@/lib/ai/aiReasoningPresentation";
|
||||
import { saveTextFile } from "@/lib/export/saveTextFile";
|
||||
import { buildAiAnalysisExport } from "@/lib/export/aiAnalysisExport";
|
||||
@@ -4285,6 +4285,37 @@ function canCopyMessage(msg: ChatMessage): boolean {
|
||||
return messageCopyText(msg) !== null;
|
||||
}
|
||||
|
||||
/** Returns whether a user message can be submitted again. The helper accepts
|
||||
* the following visible index so the same eligibility rules cover text,
|
||||
* mentions, and attachment-only requests. */
|
||||
function canRetryUserMessage(visibleIndex: number): boolean {
|
||||
return retryableUserMessageIndex(visibleMessages.value, visibleIndex + 1) === visibleIndex;
|
||||
}
|
||||
|
||||
/** Re-runs a user request through the existing edit-and-resend path. This
|
||||
* removes the selected turn and later replies before sending with the current
|
||||
* AI configuration. */
|
||||
function retryUserMessage(visibleIndex: number) {
|
||||
if (isGenerating.value) return;
|
||||
if (!canRetryUserMessage(visibleIndex)) return;
|
||||
startEditMessage(visibleIndex);
|
||||
submitEdit(visibleIndex);
|
||||
}
|
||||
|
||||
const retryConfirmMessageIndex = ref<number | null>(null);
|
||||
|
||||
function cancelRetryUserMessage() {
|
||||
retryConfirmMessageIndex.value = null;
|
||||
}
|
||||
|
||||
function confirmRetryUserMessage() {
|
||||
const visibleIndex = retryConfirmMessageIndex.value;
|
||||
retryConfirmMessageIndex.value = null;
|
||||
if (visibleIndex !== null) retryUserMessage(visibleIndex);
|
||||
}
|
||||
|
||||
watch(conversationId, cancelRetryUserMessage);
|
||||
|
||||
function messageCopyKey(index: number): string {
|
||||
return `message:${index}`;
|
||||
}
|
||||
@@ -5620,8 +5651,26 @@ async function openExternalUrl(url: string) {
|
||||
<span class="truncate">{{ t("ai.routing.chip", { action: actionLabelFor(routedActionOf(msg)) }) }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="canCopyMessage(msg)" class="mt-1 flex justify-end">
|
||||
<div v-if="canCopyMessage(msg) || (!isGenerating && canRetryUserMessage(i))" class="mt-1 flex justify-end gap-1">
|
||||
<Popover v-if="!isGenerating && canRetryUserMessage(i)" :open="retryConfirmMessageIndex === i" @update:open="(open: boolean) => (retryConfirmMessageIndex = open ? i : null)">
|
||||
<PopoverTrigger as-child>
|
||||
<button data-ai-message-retry="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="t('ai.retryMessage')" :aria-label="t('ai.retryMessage')">
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent side="top" align="end" :side-offset="8" class="w-72 max-w-[calc(100vw-2rem)] gap-2 p-3" @click.stop>
|
||||
<p class="flex items-start gap-2 text-xs text-foreground">
|
||||
<AlertTriangle class="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-500" />
|
||||
<span>{{ t("ai.retryConfirmDescription") }}</span>
|
||||
</p>
|
||||
<div class="flex justify-end gap-2">
|
||||
<Button type="button" size="sm" variant="outline" class="h-7 px-2 text-xs" @click="cancelRetryUserMessage">{{ t("common.cancel") }}</Button>
|
||||
<Button type="button" size="sm" variant="destructive" class="h-7 px-2 text-xs" @click="confirmRetryUserMessage">{{ t("common.confirm") }}</Button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<button
|
||||
v-if="canCopyMessage(msg)"
|
||||
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"
|
||||
|
||||
@@ -2933,6 +2933,8 @@ export default withEnglishFallback({
|
||||
tempRunSql: "Redaktoru dəyişdirmədən işlət",
|
||||
copyAll: "Hamısını kopyala",
|
||||
copyMessage: "Mesajı kopyala",
|
||||
retryMessage: "Bu mesajı yenidən göndər",
|
||||
retryConfirmDescription: "Bu mesaj yenidən göndərilsin? Bu tur və sonrakı cavablar əvəz olunacaq.",
|
||||
copied: "Kopyalandı",
|
||||
copyTestResult: "Sınaq nəticəsini kopyala",
|
||||
testErrorAuth: "Şəxsiyyətin təsdiqlənməsi və ya giriş alınmadı. API açarını, layihə icazələrini və API-nin əlçatanlığını yoxlayın.",
|
||||
|
||||
@@ -3293,6 +3293,8 @@ export default {
|
||||
tempRunSql: "Run without modifying editor",
|
||||
copyAll: "Copy All",
|
||||
copyMessage: "Copy message",
|
||||
retryMessage: "Resend this message",
|
||||
retryConfirmDescription: "Resend this message? This turn and later replies will be replaced.",
|
||||
copied: "Copied",
|
||||
copyTestResult: "Copy test result",
|
||||
testErrorAuth: "Authentication or access failed. Check the API key, project permissions, and API availability.",
|
||||
|
||||
@@ -3288,6 +3288,8 @@ export default withEnglishFallback({
|
||||
tempRunSql: "Ejecutar sin modificar",
|
||||
copyAll: "Copiar todo",
|
||||
copyMessage: "Copiar mensaje",
|
||||
retryMessage: "Reenviar este mensaje",
|
||||
retryConfirmDescription: "¿Reenviar este mensaje? Se reemplazarán este turno y las respuestas posteriores.",
|
||||
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.",
|
||||
|
||||
@@ -3107,6 +3107,8 @@ export default withEnglishFallback({
|
||||
tempRunSql: "Esegui senza modificare",
|
||||
copyAll: "Copia Tutto",
|
||||
copyMessage: "Copia messaggio",
|
||||
retryMessage: "Invia di nuovo questo messaggio",
|
||||
retryConfirmDescription: "Inviare di nuovo questo messaggio? Questo turno e le risposte successive verranno sostituiti.",
|
||||
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.",
|
||||
|
||||
@@ -3247,6 +3247,8 @@ export default withEnglishFallback({
|
||||
tempRunSql: "編集せずに実行",
|
||||
copyAll: "すべてコピー",
|
||||
copyMessage: "メッセージをコピー",
|
||||
retryMessage: "このメッセージを再送信",
|
||||
retryConfirmDescription: "このメッセージを再送信しますか?このターンと後続の返信は置き換えられます。",
|
||||
copied: "コピーしました",
|
||||
copyTestResult: "テスト結果をコピー",
|
||||
testErrorAuth: "認証またはアクセスに失敗しました。API キー、プロジェクト権限、API の有効化状態を確認してください。",
|
||||
|
||||
@@ -3011,6 +3011,8 @@ export default withEnglishFallback({
|
||||
tempRunSql: "편집기를 수정하지 않고 실행",
|
||||
copyAll: "모두 복사",
|
||||
copyMessage: "메시지 복사",
|
||||
retryMessage: "이 메시지 다시 보내기",
|
||||
retryConfirmDescription: "이 메시지를 다시 보낼까요? 이 턴과 이후 답변이 대체됩니다.",
|
||||
copied: "복사했습니다",
|
||||
copyTestResult: "테스트 결과 복사",
|
||||
testErrorAuth: "인증 또는 접근에 실패했습니다. API 키, 프로젝트 권한 및 API 가용성을 확인하세요.",
|
||||
|
||||
@@ -3214,6 +3214,8 @@ export default withEnglishFallback({
|
||||
tempRunSql: "Executar sem modificar",
|
||||
copyAll: "Copiar Tudo",
|
||||
copyMessage: "Copiar mensagem",
|
||||
retryMessage: "Reenviar esta mensagem",
|
||||
retryConfirmDescription: "Reenviar esta mensagem? Esta rodada e as respostas posteriores serão substituídas.",
|
||||
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.",
|
||||
|
||||
@@ -3156,6 +3156,8 @@ export default withEnglishFallback({
|
||||
tempRunSql: "Выполнить без изменения редактора",
|
||||
copyAll: "Копировать всё",
|
||||
copyMessage: "Копировать сообщение",
|
||||
retryMessage: "Повторно отправить это сообщение",
|
||||
retryConfirmDescription: "Повторно отправить это сообщение? Этот раунд и последующие ответы будут заменены.",
|
||||
copied: "Скопировано",
|
||||
copyTestResult: "Копировать результат проверки",
|
||||
testErrorAuth: "Не удалось пройти аутентификацию или получить доступ. Проверьте ключ API, права на проект и доступность API.",
|
||||
|
||||
@@ -2909,6 +2909,8 @@ export default withEnglishFallback({
|
||||
tempRunSql: "Düzenleyiciyi değiştirmeden çalıştır",
|
||||
copyAll: "Tümünü Kopyala",
|
||||
copyMessage: "Mesajı kopyala",
|
||||
retryMessage: "Bu mesajı yeniden gönder",
|
||||
retryConfirmDescription: "Bu mesaj yeniden gönderilsin mi? Bu tur ve sonraki yanıtlar değiştirilecek.",
|
||||
copied: "Kopyalandı",
|
||||
copyTestResult: "Test sonucunu kopyala",
|
||||
testErrorAuth: "Kimlik doğrulama veya erişim başarısız oldu. API anahtarını, proje yetkilerini ve API erişilebilirliğini denetleyin.",
|
||||
|
||||
@@ -3205,6 +3205,8 @@ export default withEnglishFallback({
|
||||
tempRunSql: "临时运行",
|
||||
copyAll: "复制全部",
|
||||
copyMessage: "复制消息",
|
||||
retryMessage: "重新发送这条消息",
|
||||
retryConfirmDescription: "重新发送这条消息?当前轮次及后续回复将被替换。",
|
||||
copied: "已复制",
|
||||
copyTestResult: "复制测试结果",
|
||||
testErrorAuth: "身份验证或访问失败,请检查 API Key、项目权限和 API 启用状态。",
|
||||
|
||||
@@ -3105,6 +3105,8 @@ export default withEnglishFallback({
|
||||
tempRunSql: "臨時執行",
|
||||
copyAll: "複製全部",
|
||||
copyMessage: "複製訊息",
|
||||
retryMessage: "重新傳送這則訊息",
|
||||
retryConfirmDescription: "重新傳送這則訊息?目前輪次及後續回覆將被取代。",
|
||||
copied: "已複製",
|
||||
copyTestResult: "複製測試結果",
|
||||
testErrorAuth: "驗證或存取失敗,請檢查 API Key、專案權限和 API 啟用狀態。",
|
||||
|
||||
+25
-1
@@ -1,5 +1,29 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { visibleToActualIndex } from "@/lib/ai/aiMessageEdit";
|
||||
import { retryableUserMessageIndex, visibleToActualIndex } from "@/lib/ai/aiMessageEdit";
|
||||
|
||||
describe("retryableUserMessageIndex", () => {
|
||||
it("finds the closest preceding user turn", () => {
|
||||
const messages = [
|
||||
{ role: "user" as const, content: "first" },
|
||||
{ role: "assistant" as const, content: "reply" },
|
||||
{ role: "user" as const, content: "latest" },
|
||||
{ role: "assistant" as const, content: "latest reply" },
|
||||
];
|
||||
expect(retryableUserMessageIndex(messages, 3)).toBe(2);
|
||||
});
|
||||
|
||||
it("keeps attachment-only requests retryable", () => {
|
||||
const messages = [
|
||||
{ role: "user" as const, content: "", imageAttachments: [{}] },
|
||||
{ role: "assistant" as const, content: "reply" },
|
||||
];
|
||||
expect(retryableUserMessageIndex(messages, 1)).toBe(0);
|
||||
});
|
||||
|
||||
it("returns -1 when no preceding user request exists", () => {
|
||||
expect(retryableUserMessageIndex([{ role: "assistant", content: "reply" }], 0)).toBe(-1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("visibleToActualIndex", () => {
|
||||
it("maps visible index 0 to first non-summary message", () => {
|
||||
|
||||
@@ -2,6 +2,26 @@ export interface MessageWithKind {
|
||||
kind?: string;
|
||||
}
|
||||
|
||||
export interface RetryableMessage {
|
||||
role: "user" | "assistant";
|
||||
content: string;
|
||||
mentions?: unknown[];
|
||||
csvAttachments?: unknown[];
|
||||
imageAttachments?: unknown[];
|
||||
}
|
||||
|
||||
/** Finds the closest preceding user turn that can be submitted again for an
|
||||
* assistant reply in the visible transcript. */
|
||||
export function retryableUserMessageIndex(messages: RetryableMessage[], assistantVisibleIndex: number): number {
|
||||
for (let i = assistantVisibleIndex - 1; i >= 0; i--) {
|
||||
const message = messages[i];
|
||||
if (message.role !== "user") continue;
|
||||
if (message.content.trim() || message.mentions?.length || message.csvAttachments?.length || message.imageAttachments?.length) return i;
|
||||
return -1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a visible message index (contextSummary messages excluded) to the
|
||||
* actual index in the full messages array.
|
||||
|
||||
Reference in new issue
Block a user