Skip to content

AI-native design editor. Open-source Figma alternative.

fix(chat): retry a request that failed before any reply (#1018)

Danila Poyarkova22a4cadef8f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c5899a8a9..35c84f170 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -73,7 +73,7 @@
- Choose how much an AI model thinks for each message from the chat composer, from Off to Extra high or the provider default. Anthropic, Google, DeepSeek, OpenAI, OpenRouter, and compatible models apply it, where reasoning effort previously reached only OpenAI and OpenRouter models. A model profile's thinking level, which replaces its free-text reasoning effort, sets the starting choice, and finished reasoning shows how long the model thought.
- Read AI tool calls at a glance: each call shows a one-line summary and buttons that bring the layers it touched into view, even on another page. Expanded, it shows highlighted JSX, scripts, and JSON input and output, and exported images inline. A render call's JSX streams in as the model writes it, and a long run folds its earlier steps into one row that lists them by name and counts failures.
- Review what each AI edit changed from its tool call in the chat: a before and after image split by a draggable divider, or the changed pixels highlighted, and a diff of the layers' JSX. Both are saved with the conversation. Settings → Chat → Change previews sets the image size (240, 480, or 960 px) or turns images off to keep only the JSX diff. The chat AI can check its own work the same way with `diff_changes`, which compares the page or a layer with its state before the run edited it as a patch that `diff_apply` can replay.
-- Revert an AI reply's edits from the chat while nothing has been edited since, regenerate the last reply, or edit the last message and send it again; regenerating and resending undo the replaced reply's edits first when they can. A reverted reply stays in the chat, dimmed and marked *Changes reverted*, also after reopening the conversation, and your next message tells the AI that those edits are gone, so it does not build on them; **Restore changes** on the reply, or Edit → Redo, brings the edits back and removes the mark while nothing has been edited since.
+- Revert an AI reply's edits from the chat while nothing has been edited since, regenerate the last reply, retry a message that failed before any reply from the message or its error notice, or edit the last message and send it again; regenerating and resending undo the replaced reply's edits first when they can. A reverted reply stays in the chat, dimmed and marked *Changes reverted*, also after reopening the conversation, and your next message tells the AI that those edits are gone, so it does not build on them; **Restore changes** on the reply, or Edit → Redo, brings the edits back and removes the mark while nothing has been edited since.
- Preview designs progressively on the canvas as direct AI providers stream JSX, without saving partial designs or adding intermediate undo steps. A preview stays with its page: it hides while you view another page and returns when you come back.
- Write design trees as TSX with `@open-pencil/design-jsx` as the JSX import source, and render them with `renderTree`.
- Swap the component behind an instance with `instance.swapComponent(component)` in the plugin API, as in Figma.
@@ -139,6 +139,7 @@
### Fixed
+- Use an API key saved in Settings for the open AI chat right away, including when asking again after a failed request, instead of only after reloading; the failure's notice closes once the request is sent again.
- Renaming a section title on the canvas keeps the title's size, weight, and place. Section titles draw in Inter SemiBold rather than an emboldened regular weight, and labels that are not rotated sit on whole pixels, so they stay crisp.
- Reject an argument an AI, MCP, CLI, or WebMCP tool does not take, such as `properties: { y: 500 }` for `update_node` or `font: { family }` for `set_font`, and name it, instead of reporting success without changing anything (#977).
- Choose an instance's variant by its variant property in design JSX, such as `<Instance component="Button" State="Pressed" />`, without a warning that the property is unsupported.
diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.json
index bbea6a013..d67184db0 100644
--- a/packages/vue/src/i18n/locales/de/ai.json
+++ b/packages/vue/src/i18n/locales/de/ai.json
@@ -38,6 +38,7 @@
"restoreTurn": "Änderungen wiederherstellen",
"regenerate": "Neu generieren",
"revertAndRegenerate": "Zurücknehmen und neu generieren",
+ "retryRequest": "Erneut versuchen",
"editMessage": "Nachricht bearbeiten",
"cancelEdit": "Abbrechen",
"resendMessage": "Erneut senden",
diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.json
index 33f92c162..d3fec86aa 100644
--- a/packages/vue/src/i18n/locales/es/ai.json
+++ b/packages/vue/src/i18n/locales/es/ai.json
@@ -38,6 +38,7 @@
"restoreTurn": "Restaurar cambios",
"regenerate": "Regenerar",
"revertAndRegenerate": "Revertir y regenerar",
+ "retryRequest": "Reintentar",
"editMessage": "Editar mensaje",
"cancelEdit": "Cancelar",
"resendMessage": "Enviar de nuevo",
diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.json
index f49ea9367..2adf3bd05 100644
--- a/packages/vue/src/i18n/locales/fr/ai.json
+++ b/packages/vue/src/i18n/locales/fr/ai.json
@@ -38,6 +38,7 @@
"restoreTurn": "Rétablir les modifications",
"regenerate": "Régénérer",
"revertAndRegenerate": "Annuler et régénérer",
+ "retryRequest": "Réessayer",
"editMessage": "Modifier le message",
"cancelEdit": "Annuler",
"resendMessage": "Renvoyer",
diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.json
index 5ad8bcb12..545393de3 100644
--- a/packages/vue/src/i18n/locales/it/ai.json
+++ b/packages/vue/src/i18n/locales/it/ai.json
@@ -38,6 +38,7 @@
"restoreTurn": "Ripristina modifiche",
"regenerate": "Rigenera",
"revertAndRegenerate": "Annulla e rigenera",
+ "retryRequest": "Riprova",
"editMessage": "Modifica messaggio",
"cancelEdit": "Annulla",
"resendMessage": "Invia di nuovo",
diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.json
index 934995474..75a55a3e1 100644
--- a/packages/vue/src/i18n/locales/ja/ai.json
+++ b/packages/vue/src/i18n/locales/ja/ai.json
@@ -38,6 +38,7 @@
"restoreTurn": "変更を元に戻す",
"regenerate": "再生成",
"revertAndRegenerate": "元に戻して再生成",
+ "retryRequest": "再試行",
"editMessage": "メッセージを編集",
"cancelEdit": "キャンセル",
"resendMessage": "再送信",
diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.json
index b7555ee3f..d73421428 100644
--- a/packages/vue/src/i18n/locales/pl/ai.json
+++ b/packages/vue/src/i18n/locales/pl/ai.json
@@ -38,6 +38,7 @@
"restoreTurn": "Przywróć zmiany",
"regenerate": "Wygeneruj ponownie",
"revertAndRegenerate": "Cofnij i wygeneruj ponownie",
+ "retryRequest": "Ponów",
"editMessage": "Edytuj wiadomość",
"cancelEdit": "Anuluj",
"resendMessage": "Wyślij ponownie",
diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.json
index dab278279..cdc42b288 100644
--- a/packages/vue/src/i18n/locales/ru/ai.json
+++ b/packages/vue/src/i18n/locales/ru/ai.json
@@ -38,6 +38,7 @@
"restoreTurn": "Вернуть изменения",
"regenerate": "Сгенерировать заново",
"revertAndRegenerate": "Отменить и сгенерировать заново",
+ "retryRequest": "Повторить",
"editMessage": "Изменить сообщение",
"cancelEdit": "Отмена",
"resendMessage": "Отправить снова",
diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.json
index abefe1092..14495e7c6 100644
--- a/packages/vue/src/i18n/locales/zh-cn/ai.json
+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json
@@ -38,6 +38,7 @@
"restoreTurn": "恢复更改",
"regenerate": "重新生成",
"revertAndRegenerate": "撤销并重新生成",
+ "retryRequest": "重试",
"editMessage": "编辑消息",
"cancelEdit": "取消",
"resendMessage": "重新发送",
diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.ts
index 267ddf527..6144522a9 100644
--- a/packages/vue/src/i18n/messages/ai.ts
+++ b/packages/vue/src/i18n/messages/ai.ts
@@ -85,6 +85,7 @@ export const aiMessageDefaults = {
restoreTurn: 'Restore changes',
regenerate: 'Regenerate',
revertAndRegenerate: 'Revert and regenerate',
+ retryRequest: 'Retry',
editMessage: 'Edit message',
cancelEdit: 'Cancel',
resendMessage: 'Send again',
diff --git a/src/app/ai/chat/storage.ts b/src/app/ai/chat/storage.ts
index 08e5cadf9..f328e3d8a 100644
--- a/src/app/ai/chat/storage.ts
+++ b/src/app/ai/chat/storage.ts
@@ -1,3 +1,4 @@
+import { isEqual } from 'es-toolkit'
import { computed, ref, watch } from 'vue'
import { IS_TAURI } from '@open-pencil/core/constants'
@@ -11,7 +12,8 @@ import {
designModelID,
designProviderDefinition,
designProviderID,
- modelConnectionCredentialRef
+ modelConnectionCredentialRef,
+ modelCredentialRevision
} from '@/app/ai/models'
import { appCredentialServices, browserCredentialsRemembered } from '@/app/settings/credentials/app'
import {
@@ -65,7 +67,9 @@ function designCredentialReference(): CredentialRef | null {
export async function refreshAIProviderStatus(): Promise<void> {
const reference = designCredentialReference()
- apiKeyStatus.value = reference ? await refreshStatus(reference) : 'missing'
+ const status = reference ? await refreshStatus(reference) : 'missing'
+ // A connection chosen while the lookup ran owns the status now.
+ if (isEqual(designCredentialReference(), reference)) apiKeyStatus.value = status
}
// Startup checks metadata only. Secret migration/resolution belongs to explicit provider use.
@@ -113,4 +117,9 @@ export function registerAIChatEffects(markTransportDirty: () => void) {
markTransportDirty()
})
watch(credentialRevision, markTransportDirty)
+ // A key saved in Settings; the chat reads it when it builds its transport.
+ watch(modelCredentialRevision, () => {
+ void refreshAIProviderStatus()
+ markTransportDirty()
+ })
}
diff --git a/src/app/ai/chat/submission/resend.ts b/src/app/ai/chat/submission/resend.ts
new file mode 100644
index 000000000..caf4316b9
--- /dev/null
+++ b/src/app/ai/chat/submission/resend.ts
@@ -0,0 +1,30 @@
+import { markRaw, type Ref } from 'vue'
+
+import { reportSubmissionError, type SubmissionErrorOptions } from '@/app/ai/chat/submission/errors'
+import type { ChatInstance } from '@/app/ai/chat/submission/types'
+
+interface ResendOptions extends SubmissionErrorOptions {
+ chat: Ref<ChatInstance | null>
+ ensureChat: () => Promise<ChatInstance | null>
+}
+
+/**
+ * The chat to ask again with. A key or model changed since the chat was made, such as after a
+ * failure that sent the user to Settings, makes `ensureChat` rebuild it with the same messages.
+ */
+export async function chatToResend(
+ options: ResendOptions,
+ ready: ChatInstance | null
+): Promise<ChatInstance | null> {
+ if (!ready) return null
+ try {
+ const current = await options.ensureChat()
+ // Another tab or a new message took the chat over while it was being made.
+ if (options.chat.value !== ready) return null
+ if (current && current !== ready) options.chat.value = markRaw(current)
+ return current
+ } catch (error) {
+ reportSubmissionError(options, error)
+ return null
+ }
+}
diff --git a/src/app/ai/chat/submission/use.ts b/src/app/ai/chat/submission/use.ts
index d329bc0e2..f88624089 100644
--- a/src/app/ai/chat/submission/use.ts
+++ b/src/app/ai/chat/submission/use.ts
@@ -14,6 +14,7 @@ import {
import { setVisibleMessageText } from '@/app/ai/chat/presentation'
import { reportSubmissionError, type SubmissionErrorOptions } from '@/app/ai/chat/submission/errors'
import { prepareSubmittedImages } from '@/app/ai/chat/submission/images'
+import { chatToResend } from '@/app/ai/chat/submission/resend'
import { useRevertRecords } from '@/app/ai/chat/submission/reverts'
import type { ChatInstance, ChatSubmission } from '@/app/ai/chat/submission/types'
import { recordTurn, restoreTurn, revertTurn } from '@/app/ai/chat/turns'
@@ -200,16 +201,16 @@ export function useChatSubmission(options: SubmissionOptions) {
return currentChat.status === 'ready' || currentChat.status === 'error' ? currentChat : null
}
- /** Asks again for the last reply, undoing its edits first while nothing has been edited since. */
+ /** Asks again for the last reply, undoing its edits when it can, or for an unanswered request. */
async function regenerate(): Promise<void> {
- const currentChat = readyChat()
- const reply = currentChat ? lastAssistantId(currentChat) : undefined
- if (!currentChat || !reply) return
+ const currentChat = await chatToResend(options, readyChat())
+ const last = currentChat?.messages.at(-1)
+ if (!currentChat || !last) return
options.clearFailure()
- revertTurn(reply)
+ if (last.role === 'assistant') revertTurn(last.id)
try {
await withTurn(currentChat, () =>
- currentChat.regenerate({ messageId: reply }).catch(() => undefined)
+ currentChat.regenerate({ messageId: last.id }).catch(() => undefined)
)
} finally {
await options.flush?.().catch(() => undefined)
@@ -218,7 +219,7 @@ export function useChatSubmission(options: SubmissionOptions) {
/** Replaces the last user message and asks again, undoing the old reply's edits when it can. */
async function resend(messageId: string, text: string): Promise<void> {
- const currentChat = readyChat()
+ const currentChat = await chatToResend(options, readyChat())
const trimmed = text.trim()
if (!currentChat || !trimmed) return
const index = currentChat.messages.findIndex((message) => message.id === messageId)
diff --git a/src/app/shell/ui.ts b/src/app/shell/ui.ts
index 75853eb27..d69ea8e0c 100644
--- a/src/app/shell/ui.ts
+++ b/src/app/shell/ui.ts
@@ -52,7 +52,8 @@ const toasts = ref<Toast[]>([])
let nextId = 0
let errorHandlersInitialized = false
-function push(message: string, variant: ToastVariant, action?: ToastAction) {
+/** Returns the toast's ID, which `remove` takes, also when it merged into a visible one. */
+function push(message: string, variant: ToastVariant, action?: ToastAction): number {
// Dedupe: if the same message+variant is already visible, increment
// its repeat count instead of stacking a duplicate. Prevents the
// cascade-on-every-frame failure mode where a single unhealthy
@@ -64,10 +65,12 @@ function push(message: string, variant: ToastVariant, action?: ToastAction) {
if (existing) {
existing.count += 1
existing.action = action
- return
+ return existing.id
}
- toasts.value.push({ id: ++nextId, message, variant, count: 1, action })
+ const id = ++nextId
+ toasts.value.push({ id, message, variant, count: 1, action })
trim()
+ return id
}
function trim() {
@@ -120,8 +123,8 @@ function warning(message: string) {
push(message, 'warning')
}
-function error(message: string, action?: ToastAction) {
- push(message, 'error', action)
+function error(message: string, action?: ToastAction): number {
+ return push(message, 'error', action)
}
function remove(id: number) {
diff --git a/src/components/ChatPanel.vue b/src/components/ChatPanel.vue
index 5e14ede32..de7a7b1da 100644
--- a/src/components/ChatPanel.vue
+++ b/src/components/ChatPanel.vue
@@ -147,18 +147,27 @@ const showContinue = computed(() => {
return last.role === 'assistant' && didHitStepLimit()
})
+// Asking again clears the failure, and its notice goes with it.
+let failureToast: number | null = null
+/** The notice outlives a switch to another tab, whose chat its Retry must not touch. */
+function retryFailed(messageId: string | undefined): void {
+ if (messageId && chat.value?.messages.at(-1)?.id === messageId) void submission.regenerate()
+}
watch(
() => chatFailure.value?.reason,
(reason) => {
+ if (failureToast !== null) toast.remove(failureToast)
+ failureToast = null
if (!reason) return
- toast.error(
+ const failedId = chat.value?.messages.at(-1)?.id
+ failureToast = toast.error(
failureMessage.value ?? ai.value.chatRequestFailed,
failureHasSettingsAction.value
? {
label: ai.value.openProviderSettingsAction,
run: () => openSettingsDialog('ai')
}
- : undefined
+ : { label: ai.value.retryRequest, run: () => retryFailed(failedId) }
)
}
)
@@ -231,7 +240,7 @@ function handleStop() {
:status="status"
:show-continue="showContinue"
:nodes-live="!history.readOnly.value"
- :interactive="chat !== null"
+ :interactive="chat !== null && !submission.busy.value"
@regenerate="submission.regenerate()"
@revert="(messageId) => submission.revert(messageId)"
@restore="(messageId) => submission.restore(messageId)"
diff --git a/src/components/chat/ChatMessage.vue b/src/components/chat/ChatMessage.vue
index 6799f3fc2..8f6fcd564 100644
--- a/src/components/chat/ChatMessage.vue
+++ b/src/components/chat/ChatMessage.vue
@@ -18,6 +18,7 @@ import ReasoningBlock from '@/components/chat/ReasoningBlock.vue'
import ToolCallGroup from '@/components/chat/tool/ToolCallGroup.vue'
import ChatMessageEditor from '@/components/chat/turn/ChatMessageEditor.vue'
import ChatTurnActions from '@/components/chat/turn/ChatTurnActions.vue'
+import AppButton from '@/components/ui/button/AppButton.vue'
import IconButton from '@/components/ui/button/IconButton.vue'
const {
@@ -25,6 +26,7 @@ const {
streaming = false,
presentation,
canRegenerate = false,
+ canRetry = false,
canEdit = false
} = defineProps<{
message: UIMessage
@@ -32,6 +34,8 @@ const {
presentation?: { text?: string; attachments?: AttachmentPresentation[] }
/** The last reply, when the chat is idle. */
canRegenerate?: boolean
+ /** The last message, a request that got no reply, when the chat is idle. */
+ canRetry?: boolean
/** The last user message without attachments, when the chat is idle. */
canEdit?: boolean
}>()
@@ -79,6 +83,8 @@ async function copyResponse(): Promise<void> {
// The AI SDK updates parts in place and replaces only the message, so copy each part for
// the cards' computed state to see the new values.
const reverted = computed(() => revertOf(message) !== null)
+// A request that failed once its reply had started leaves the reply without content.
+const empty = computed(() => message.parts.every((part) => part.type === 'step-start'))
const groups = computed(() => groupMessageParts(message.parts.map((part) => ({ ...part }))))
function groupKey(group: MessagePartGroup): string {
@@ -147,6 +153,7 @@ function groupKey(group: MessagePartGroup): string {
v-if="!streaming"
:message-id="message.id"
:can-regenerate="canRegenerate"
+ :empty="empty"
:reverted="reverted"
@regenerate="emit('regenerate')"
@revert="emit('revert')"
@@ -181,6 +188,17 @@ function groupKey(group: MessagePartGroup): string {
<icon-lucide-pencil class="size-3" />
</IconButton>
</div>
+ <div v-if="canRetry && !editing" class="flex justify-end">
+ <AppButton
+ size="xs"
+ variant="ghost"
+ data-test-id="chat-retry"
+ @click="emit('regenerate')"
+ >
+ <template #leading><icon-lucide-refresh-cw aria-hidden="true" /></template>
+ {{ ai.retryRequest }}
+ </AppButton>
+ </div>
</template>
</div>
</div>
diff --git a/src/components/chat/ChatPlayground.stories.ts b/src/components/chat/ChatPlayground.stories.ts
index 4489d5311..baa410e26 100644
--- a/src/components/chat/ChatPlayground.stories.ts
+++ b/src/components/chat/ChatPlayground.stories.ts
@@ -125,5 +125,17 @@ export const Empty: Story = { args: { initialChat: 'empty' } }
export const Streaming: Story = { args: { initialChat: 'streaming' } }
export const ToolError: Story = { args: { initialChat: 'error' } }
export const RevertedReply: Story = { args: { initialChat: 'reverted' } }
+export const FailedRequest: Story = {
+ args: { initialChat: 'failed-request' },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ // Only the unanswered request offers to go again; the earlier reply does not regenerate.
+ await expect(canvas.queryByRole('button', { name: 'Regenerate' })).toBeNull()
+ await userEvent.click(canvas.getByRole('button', { name: 'Retry' }))
+ // The new reply is now the last message, so it offers to regenerate instead.
+ await expect(await canvas.findByRole('button', { name: 'Regenerate' })).toBeVisible()
+ await expect(canvas.queryByRole('button', { name: 'Retry' })).toBeNull()
+ }
+}
export const Narrow: Story = { args: { narrow: true } }
export const LongTitle: Story = { args: { initialChat: 'long-title', narrow: true } }
diff --git a/src/components/chat/ChatTranscript.vue b/src/components/chat/ChatTranscript.vue
index 895b285ec..3b5b0a879 100644
--- a/src/components/chat/ChatTranscript.vue
+++ b/src/components/chat/ChatTranscript.vue
@@ -27,7 +27,7 @@ const {
status: ChatStatus
showContinue?: boolean
presentations?: Record<string, { text?: string; attachments?: AttachmentPresentation[] }>
- /** Offers regenerating the last reply and editing the last request. */
+ /** Offers regenerating the last reply, retrying an unanswered request, and editing the last request. */
interactive?: boolean
/** False for a conversation from another document: its layer IDs are not this document's. */
nodesLive?: boolean
@@ -56,7 +56,8 @@ const isThinking = computed(() => {
return status === 'submitted'
})
const idle = computed(() => interactive && (status === 'ready' || status === 'error'))
-const lastReplyId = computed(() => messages.findLast((m) => m.role === 'assistant')?.id)
+// A request that failed before any reply is the last message; it is retried, not an older reply.
+const lastMessage = computed(() => messages.at(-1))
const lastRequest = computed(() => messages.findLast((m) => m.role === 'user'))
/** Messages with attachments carry context a plain text edit would drop. */
const editableRequestId = computed(() => {
@@ -96,7 +97,8 @@ const { arrivedState, resumeFollowing } = useScrollFollowing(
:message="msg"
:presentation="presentations?.[msg.id]"
:streaming="running && msg.role === 'assistant' && index === messages.length - 1"
- :can-regenerate="idle && msg.id === lastReplyId"
+ :can-regenerate="idle && msg.id === lastMessage?.id && msg.role === 'assistant'"
+ :can-retry="idle && msg.id === lastMessage?.id && msg.role === 'user'"
:can-edit="idle && msg.id === editableRequestId"
@regenerate="emit('regenerate')"
@revert="emit('revert', msg.id)"
diff --git a/src/components/chat/stories/fixtures.ts b/src/components/chat/stories/fixtures.ts
index da3867522..65248f03f 100644
--- a/src/components/chat/stories/fixtures.ts
+++ b/src/components/chat/stories/fixtures.ts
@@ -103,6 +103,29 @@ export function conversations(): Conversation[] {
}
]
},
+ {
+ id: 'failed-request',
+ title: 'Card spacing',
+ status: 'error',
+ messages: [
+ {
+ id: 'failed-first-request',
+ role: 'user',
+ parts: [{ type: 'text', text: 'Add a card.' }]
+ },
+ {
+ id: 'failed-first-response',
+ role: 'assistant',
+ parts: [{ type: 'text', text: 'Added a card to the page.' }]
+ },
+ {
+ id: 'failed-request-unanswered',
+ role: 'user',
+ // The request failed before any reply, so the chat ends with it.
+ parts: [{ type: 'text', text: 'Give it more padding.' }]
+ }
+ ]
+ },
{
id: 'reverted',
title: 'Blue header',
diff --git a/src/components/chat/stories/useConversations.ts b/src/components/chat/stories/useConversations.ts
index 6f26b01e5..acd30dd47 100644
--- a/src/components/chat/stories/useConversations.ts
+++ b/src/components/chat/stories/useConversations.ts
@@ -69,9 +69,20 @@ export function useConversations(initialChat: string) {
chat.status = 'ready'
}
function regenerate() {
- const reply = selected.value?.messages.findLast((message) => message.role === 'assistant')
- if (!reply) return
- reply.parts = [{ type: 'text', text: `${PREVIEW_REPLY} (regenerated)` }]
+ const chat = selected.value
+ const last = chat?.messages.at(-1)
+ if (!chat || !last) return
+ chat.status = 'ready'
+ if (last.role === 'assistant') {
+ last.parts = [{ type: 'text', text: `${PREVIEW_REPLY} (regenerated)` }]
+ return
+ }
+ // A request that got no reply is sent again.
+ chat.messages.push({
+ id: crypto.randomUUID(),
+ role: 'assistant',
+ parts: [{ type: 'text', text: PREVIEW_REPLY }]
+ })
}
function resend(messageId: string, text: string) {
const chat = selected.value
diff --git a/src/components/chat/turn/ChatTurnActions.vue b/src/components/chat/turn/ChatTurnActions.vue
index 18c2a8a4d..ec863a57b 100644
--- a/src/components/chat/turn/ChatTurnActions.vue
+++ b/src/components/chat/turn/ChatTurnActions.vue
@@ -9,10 +9,13 @@ import AppButton from '@/components/ui/button/AppButton.vue'
const {
messageId,
canRegenerate = false,
+ empty = false,
reverted = false
} = defineProps<{
messageId: string
canRegenerate?: boolean
+ /** The reply failed before any content, so asking again is a retry. */
+ empty?: boolean
/** The reply's edits were reverted; it stays in the chat, marked. */
reverted?: boolean
}>()
@@ -67,7 +70,7 @@ const restorable = computed(() => edits.value?.restorable === true)
@click="emit('regenerate')"
>
<template #leading><icon-lucide-refresh-cw aria-hidden="true" /></template>
- {{ revertable ? ai.revertAndRegenerate : ai.regenerate }}
+ {{ empty ? ai.retryRequest : revertable ? ai.revertAndRegenerate : ai.regenerate }}
</AppButton>
</div>
</template>
diff --git a/src/components/ui/feedback/AppToast.stories.ts b/src/components/ui/feedback/AppToast.stories.ts
index 41d38fed2..1a4d213fc 100644
--- a/src/components/ui/feedback/AppToast.stories.ts
+++ b/src/components/ui/feedback/AppToast.stories.ts
@@ -66,6 +66,18 @@ export const WithAction: Story = {
args: { message: 'Design file moved to Trash.', actionLabel: 'Undo' }
}
+export const ErrorWithAction: Story = {
+ args: {
+ message: 'Your provider API key is invalid or expired. Replace it in Settings.',
+ variant: 'error',
+ actionLabel: 'Open settings',
+ copyable: true,
+ copyLabel: 'Copy message',
+ copiedLabel: 'Copied',
+ closeLabel: 'Close'
+ }
+}
+
export const RepeatedMessage: Story = {
args: {
message: 'Lost connection to the collaboration room',
diff --git a/src/theme/feedback/toast.ts b/src/theme/feedback/toast.ts
index 69425f730..b0a63dcf5 100644
--- a/src/theme/feedback/toast.ts
+++ b/src/theme/feedback/toast.ts
@@ -8,17 +8,19 @@ const toastTheme = {
message: 'select-text',
count: 'ml-1.5',
progress: 'mt-1.5',
+ // A filled button that darkens the toast, so its text keeps the toast's contrast.
action:
- 'shrink-0 cursor-pointer rounded px-1.5 py-0.5 text-[10px] font-medium underline-offset-2 hover:underline',
+ 'shrink-0 cursor-pointer rounded px-2 py-0.5 text-[11px] leading-4 font-medium transition-colors focus-visible:outline-1 focus-visible:outline-current',
control: 'mt-0.5 shrink-0 cursor-pointer rounded p-0.5 opacity-70 hover:opacity-100'
},
variants: {
tone: {
- default: { root: 'bg-accent text-white' },
+ default: { root: 'bg-accent text-white', action: 'bg-black/20 hover:bg-black/30' },
warning: {
- root: 'border border-[var(--color-warning-border)] bg-[var(--color-warning-bg)] text-[var(--color-warning-text)]'
+ root: 'border border-[var(--color-warning-border)] bg-[var(--color-warning-bg)] text-[var(--color-warning-text)]',
+ action: 'bg-current/10 hover:bg-current/15'
},
- error: { root: 'bg-red-600 text-white' }
+ error: { root: 'bg-red-600 text-white', action: 'bg-black/20 hover:bg-black/30' }
},
// Work in progress spins the icon; AppProgress draws the bar.
progress: {
diff --git a/tests/app/ai/chat/turns.test.ts b/tests/app/ai/chat/turns.test.ts
index a8d05a7f9..23bc6ebcd 100644
--- a/tests/app/ai/chat/turns.test.ts
+++ b/tests/app/ai/chat/turns.test.ts
@@ -58,6 +58,8 @@ function fakeChat(nodeId: string, finish?: (tools: Tools) => Promise<unknown>) {
let replies = 0
const messages = ref<UIMessage[]>([])
const chat = {
+ /** Fails the next request before any reply, as a provider or network error does. */
+ failNext: false,
status: 'ready' as const,
get messages(): UIMessage[] {
return messages.value
@@ -66,6 +68,10 @@ function fakeChat(nodeId: string, finish?: (tools: Tools) => Promise<unknown>) {
messages.value = value
},
async reply() {
+ if (chat.failNext) {
+ chat.failNext = false
+ throw new Error('Request failed')
+ }
startRun(store, 10)
const width = widths[replies] ?? 500
replies++
@@ -89,8 +95,12 @@ function fakeChat(nodeId: string, finish?: (tools: Tools) => Promise<unknown>) {
chat.messages = [...kept, request]
await chat.reply()
},
- async regenerate() {
- chat.messages = chat.messages.slice(0, -1)
+ // Like Chat's: a reply is replaced, and a request is kept and sent again.
+ async regenerate({ messageId }: { messageId?: string } = {}) {
+ const index = chat.messages.findIndex((candidate) => candidate.id === messageId)
+ const target = chat.messages[index]
+ if (!target) throw new Error(`message ${messageId} not found`)
+ chat.messages = chat.messages.slice(0, target.role === 'assistant' ? index : index + 1)
await chat.reply()
},
stop: async () => undefined
@@ -98,10 +108,14 @@ function fakeChat(nodeId: string, finish?: (tools: Tools) => Promise<unknown>) {
return chat
}
-function submission(chat: ReturnType<typeof fakeChat>) {
+function submission(
+ chat: ReturnType<typeof fakeChat>,
+ ensureChat: () => Promise<ChatInstance | null> = async () => chat,
+ current = shallowRef<ChatInstance | null>(chat)
+) {
return useChatSubmission({
- chat: shallowRef<ChatInstance | null>(chat),
- ensureChat: async () => chat,
+ chat: current,
+ ensureChat,
clearFailure: () => undefined,
getEditor: () => store,
messages: shallowRef({
@@ -186,6 +200,76 @@ test('regenerating undoes the last reply before asking again', async () => {
expect(chat.messages.map((message) => message.id)).toEqual(['request-0', 'reply-2'])
})
+test('retrying a request that got no reply sends it again and keeps the earlier turn', async () => {
+ const { card, chat, actions } = setup()
+ await actions.submit({ modelText: 'Wider', displayText: 'Wider', images: [], nodes: [] })
+ chat.failNext = true
+ await actions.submit({
+ modelText: 'Wider still',
+ displayText: 'Wider still',
+ images: [],
+ nodes: []
+ })
+ expect(chat.messages.map((message) => message.role)).toEqual(['user', 'assistant', 'user'])
+
+ await actions.regenerate()
+
+ // The first reply's 200 stays, and the retried request's reply resizes on top of it.
+ expect(width(card.id)).toBe(300)
+ expect(chat.messages.map((message) => message.id)).toEqual([
+ 'request-0',
+ 'reply-1',
+ 'request-1',
+ 'reply-2'
+ ])
+ store.undoAction()
+ expect(width(card.id)).toBe(200)
+})
+
+test('retrying after the key changed asks through the rebuilt chat', async () => {
+ const { card, chat } = setup()
+ // Like the session's: a changed key or model rebuilds the chat with the same messages.
+ const rebuilt = fakeChat(card.id)
+ let active = chat
+ const current = shallowRef<ChatInstance | null>(chat)
+ const actions = submission(chat, async () => active, current)
+ chat.failNext = true
+ await actions.submit({ modelText: 'Wider', displayText: 'Wider', images: [], nodes: [] })
+ rebuilt.messages = chat.messages
+ active = rebuilt
+
+ await actions.regenerate()
+
+ expect(current.value).toBe(rebuilt)
+ expect(rebuilt.messages.map((message) => message.role)).toEqual(['user', 'assistant'])
+ expect(width(card.id)).toBe(200)
+})
+
+test('a retry backs off when another chat takes over while it is being made', async () => {
+ const { card, chat } = setup()
+ const other = fakeChat(card.id)
+ const current = shallowRef<ChatInstance | null>(chat)
+ // Like switching tabs while the session rebuilds the chat with a new key.
+ const actions = submission(
+ chat,
+ async () => {
+ current.value = other
+ return chat
+ },
+ current
+ )
+ chat.failNext = true
+ await actions.submit({ modelText: 'Wider', displayText: 'Wider', images: [], nodes: [] })
+ current.value = chat
+
+ await actions.regenerate()
+
+ expect(current.value).toBe(other)
+ expect(chat.messages.map((message) => message.role)).toEqual(['user'])
+ expect(other.messages).toEqual([])
+ expect(width(card.id)).toBe(100)
+})
+
test('resending an edited request replaces it and undoes the old reply first', async () => {
const { card, chat, actions } = setup()
await actions.submit({ modelText: 'Wider', displayText: 'Wider', images: [], nodes: [] })
diff --git a/tests/e2e/chat/profiles.spec.ts b/tests/e2e/chat/profiles.spec.ts
index d18388cf3..5e1f4b976 100644
--- a/tests/e2e/chat/profiles.spec.ts
+++ b/tests/e2e/chat/profiles.spec.ts
@@ -1,5 +1,9 @@
-import { CATALOG_ONLY_MODEL } from '#tests/helpers/chat/catalog'
+import type { Page } from '@playwright/test'
+
+import { CanvasHelper } from '#tests/helpers/canvas'
+import { CATALOG_ONLY_MODEL, routeModelCatalog } from '#tests/helpers/chat/catalog'
import { expect, test } from '#tests/helpers/chat/fixture'
+import { ChatHarness } from '#tests/helpers/chat/harness'
test('Design profile selector exposes provider and capabilities', async ({
configuredChat: chat
@@ -37,3 +41,58 @@ test('Get API key links to the provider key page', async ({ configuredChat: chat
'https://openrouter.ai/keys'
)
})
+
+/** OpenRouter refusing every key but `validKey`, and answering that one with a streamed reply. */
+async function routeOpenRouterKey(page: Page, validKey: string): Promise<string[]> {
+ const keys: string[] = []
+ await page.route('https://openrouter.ai/api/v1/chat/completions', (route) => {
+ const key = route.request().headers().authorization?.replace('Bearer ', '') ?? ''
+ keys.push(key)
+ if (key !== validKey) {
+ return route.fulfill({
+ status: 401,
+ contentType: 'application/json',
+ body: JSON.stringify({ error: { message: 'User not found.', code: 401 } })
+ })
+ }
+ const chunk = (delta: object, finish: string | null) =>
+ `data: ${JSON.stringify({
+ id: 'key-test',
+ object: 'chat.completion.chunk',
+ created: 0,
+ model: 'test/model',
+ choices: [{ index: 0, delta, finish_reason: finish }]
+ })}\n\n`
+ return route.fulfill({
+ contentType: 'text/event-stream',
+ body:
+ chunk({ role: 'assistant', content: 'Hello again' }, null) +
+ chunk({}, 'stop') +
+ 'data: [DONE]\n\n'
+ })
+ })
+ return keys
+}
+
+test('a key replaced in Settings is used when asking again', async ({ page }) => {
+ await routeModelCatalog(page)
+ const keys = await routeOpenRouterKey(page, 'sk-or-valid')
+ const chat = new ChatHarness(page)
+ await chat.open()
+ await new CanvasHelper(page).waitForInit()
+ await chat.configureOpenRouter('sk-or-expired')
+
+ await chat.submit('Say hello')
+ const toast = page.locator('[data-slot="toast"]')
+ await toast.getByRole('button', { name: 'Open settings' }).click()
+ await page.locator('[data-model-id]').first().click()
+ await chat.apiKeyInput.fill('sk-or-valid')
+ await page.getByRole('button', { name: 'Save model' }).click()
+ await page.getByTestId('app-settings-done').click()
+
+ await chat.assistantMessage().getByTestId('chat-regenerate').click()
+ await expect(chat.assistantMessage()).toContainText('Hello again')
+ expect(keys).toEqual(['sk-or-expired', 'sk-or-valid'])
+ // The failure's notice goes once the request is asked again.
+ await expect(toast).toHaveCount(0)
+})
diff --git a/tests/e2e/chat/responses.spec.ts b/tests/e2e/chat/responses.spec.ts
index 472c18253..dd2b72bfb 100644
--- a/tests/e2e/chat/responses.spec.ts
+++ b/tests/e2e/chat/responses.spec.ts
@@ -78,3 +78,23 @@ test('transport errors show a safe localized toast', async ({ configuredChat: ch
})
).toBeVisible()
})
+
+test('a request that failed before any reply can be retried', async ({ configuredChat: chat }) => {
+ await chat.submit('Hello there')
+ await expect(chat.assistantMessage()).toContainText('mock response')
+ await chat.submit('Flaky request')
+
+ const toast = chat.page.locator('[data-slot="toast"]')
+ await expect(toast.getByRole('button', { name: 'Retry' })).toBeVisible()
+ // The failed request offers the retry; the earlier reply does not offer to regenerate itself.
+ await expect(chat.userMessage().getByTestId('chat-retry')).toBeVisible()
+ await expect(chat.page.getByTestId('chat-regenerate')).toHaveCount(0)
+
+ await chat.userMessage().getByTestId('chat-retry').click()
+ await expect(chat.assistantMessage()).toContainText('Flaky request')
+ await expect(chat.page.getByTestId('chat-message-user')).toHaveCount(2)
+ await expect(chat.page.getByTestId('chat-message-assistant')).toHaveCount(2)
+ await expect(chat.page.getByTestId('chat-message-assistant').first()).toContainText('Hello there')
+ await expect(chat.page.getByTestId('chat-retry')).toHaveCount(0)
+ await expect(chat.assistantMessage().getByTestId('chat-regenerate')).toBeVisible()
+})
diff --git a/tests/helpers/chat/transport.ts b/tests/helpers/chat/transport.ts
index 2445b4d2d..8b269de22 100644
--- a/tests/helpers/chat/transport.ts
+++ b/tests/helpers/chat/transport.ts
@@ -5,6 +5,7 @@ export async function injectMockChatTransport(page: Page): Promise<void> {
const setChatTransport = window.openPencil?.setChatTransport
if (!setChatTransport) throw new Error('Transport override not available')
let messageCounter = 0
+ let flakyFailed = false
setChatTransport(() => ({
async sendMessages({
@@ -35,6 +36,11 @@ export async function injectMockChatTransport(page: Page): Promise<void> {
if (normalized.includes('missing agent')) {
throw new Error('Mock agent unavailable')
}
+ // Fails the first time only, before any reply, as a dropped connection does.
+ if (normalized.includes('flaky request') && !flakyFailed) {
+ flakyFailed = true
+ throw new Error('Mock connection dropped')
+ }
return new ReadableStream({
start(controller) {