The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(chat): regenerate asked the same question again instead of replacing it
purplebb42c942fba8
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex 2bc17b2e..ad528cda 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -14,6 +14,7 @@ import { requestGenerationCancel } from "../api/vram-handoff"import { effectiveContextWindow } from "../lib/context-window"import { useAgentChat } from "./useAgentChat"import { parseAgentCommand, parseLoopSpec } from '../lib/agent-commands'+import { planResend } from '../lib/resend-plan'import { applyGoalCommand } from '../lib/goal-command'import { useMemory } from "./useMemory"import { useAgentModeStore } from "../stores/agentModeStore"@@ -611,38 +612,31 @@ export function useChat() {requestGenerationCancel()}, [])- const regenerateMessage = useCallback((conversationId: string, assistantMessageId: string) => {+ /**+ * Regenerate and Edit both replace the turn: the question leaves the thread+ * together with everything after it and goes back in through sendMessage,+ * attachments included. Deleting only the ANSWER left the question in place+ * for sendMessage to add a second time — the thread grew one more copy of it+ * per click and the model was asked it twice.+ */+ const resend = useCallback((conversationId: string, targetId: string, override?: string) => {+ // sendMessage bails without a model; deleting first would eat the question.+ if (!useModelStore.getState().activeModel) returnconst conv = useChatStore.getState().conversations.find(c => c.id === conversationId)if (!conv) return-- // Find the assistant message and the preceding user message- const msgIndex = conv.messages.findIndex(m => m.id === assistantMessageId)- if (msgIndex < 1) return-- const userMsg = conv.messages[msgIndex - 1]- if (userMsg.role !== 'user') return-- // Delete from the assistant message onward, then resend- useChatStore.getState().deleteMessagesAfter(conversationId, assistantMessageId)- sendMessage(userMsg.content)+ const plan = planResend(conv.messages, targetId, override)+ if (!plan) return+ useChatStore.getState().deleteMessagesAfter(conversationId, plan.deleteFromId)+ sendMessage(plan.content, plan.images)}, [sendMessage])- const editAndResend = useCallback((conversationId: string, messageId: string, newContent: string) => {- const conv = useChatStore.getState().conversations.find(c => c.id === conversationId)- if (!conv) return-- const msgIndex = conv.messages.findIndex(m => m.id === messageId)- if (msgIndex < 0) return+ const regenerateMessage = useCallback((conversationId: string, assistantMessageId: string) => {+ resend(conversationId, assistantMessageId)+ }, [resend])- // Update content and delete everything after this message- useChatStore.getState().updateMessageContent(conversationId, messageId, newContent)- // Find next message to delete from- const nextMsg = conv.messages[msgIndex + 1]- if (nextMsg) {- useChatStore.getState().deleteMessagesAfter(conversationId, nextMsg.id)- }- sendMessage(newContent)- }, [sendMessage])+ const editAndResend = useCallback((conversationId: string, messageId: string, newContent: string) => {+ resend(conversationId, messageId, newContent)+ }, [resend])return {sendMessage,diff --git a/src/lib/__tests__/resend-plan.test.ts b/src/lib/__tests__/resend-plan.test.tsnew file mode 100644index 00000000..b285c70e--- /dev/null+++ b/src/lib/__tests__/resend-plan.test.ts@@ -0,0 +1,169 @@+/**+ * planResend — the surgery behind the Regenerate and Edit buttons.+ *+ * Measured against the version before this round, which passed the ASSISTANT+ * message to deleteMessagesAfter and then re-sent the question: the store kept+ * the original user message, sendMessage appended a second one, and the thread+ * grew a duplicate question per click. Images never made the trip at all.+ */+import { describe, it, expect } from 'vitest'+import { planResend } from '../resend-plan'+import { useChatStore } from '../../stores/chatStore'++const img = [{ data: 'AAAA', mimeType: 'image/png', name: 'shot.png' }]++const plain = [+ { id: 'u1', role: 'user' as const, content: 'first' },+ { id: 'a1', role: 'assistant' as const, content: 'answer one' },+ { id: 'u2', role: 'user' as const, content: 'second' },+ { id: 'a2', role: 'assistant' as const, content: 'answer two' },+]++describe('regenerate deletes the question too, so it is not asked twice', () => {+ it('anchors on the user message, not on the answer', () => {+ // The old code deleted from 'a2', which left 'u2' behind for sendMessage to+ // duplicate. Deleting from 'u2' is what makes the resend replace the turn.+ expect(planResend(plain, 'a2')).toEqual({ deleteFromId: 'u2', content: 'second' })+ })++ it('regenerating an earlier answer drops everything after that question', () => {+ expect(planResend(plain, 'a1')).toEqual({ deleteFromId: 'u1', content: 'first' })+ })++ it('carries the attachments of the question back into the resend', () => {+ const withImage = [+ { id: 'u1', role: 'user' as const, content: 'what is this?', images: img },+ { id: 'a1', role: 'assistant' as const, content: 'a cat' },+ ]+ // Without this the vision model was re-asked "what is this?" with no image+ // and answered about nothing.+ expect(planResend(withImage, 'a1')).toEqual({+ deleteFromId: 'u1',+ content: 'what is this?',+ images: img,+ })+ })++ it('walks back past the tool results of an agent turn', () => {+ // In agent mode the message before the answer is a tool result, so the old+ // `messages[idx - 1].role !== 'user'` check returned early and the+ // Regenerate button did nothing.+ const agent = [+ { id: 'u1', role: 'user' as const, content: 'read the file' },+ { id: 'a1', role: 'assistant' as const, content: '' },+ { id: 't1', role: 'tool' as const, content: '{"ok":true}' },+ { id: 'a2', role: 'assistant' as const, content: 'it says hello' },+ ]+ expect(planResend(agent, 'a2')?.deleteFromId).toBe('u1')+ })+})++describe('a slash command goes back in as the command, not as its expansion', () => {+ it('resends the "/review" the user typed', () => {+ const slash = [+ { id: 'u1', role: 'user' as const, content: 'Review the changes …long expansion…', displayContent: '/review' },+ { id: 'a1', role: 'assistant' as const, content: 'looks fine' },+ ]+ // sendMessage expands it again; passing the expansion instead would strip+ // the read-only tool gating the command carries.+ expect(planResend(slash, 'a1')?.content).toBe('/review')+ })++ it('ignores a displayContent that is a label rather than input', () => {+ // The /loop driver writes "pass 3 of 5" over the instruction it ran.+ const loop = [+ { id: 'u1', role: 'user' as const, content: 'recheck the build', displayContent: 'pass 3 of 5' },+ { id: 'a1', role: 'assistant' as const, content: 'still green' },+ ]+ expect(planResend(loop, 'a1')?.content).toBe('recheck the build')+ })+})++describe('edit replaces the question in place', () => {+ it('deletes from the edited message and resends the new text', () => {+ expect(planResend(plain, 'u2', 'second, rephrased')).toEqual({+ deleteFromId: 'u2',+ content: 'second, rephrased',+ })+ })++ it('keeps the attachments of the message being edited', () => {+ const withImage = [{ id: 'u1', role: 'user' as const, content: 'what is this?', images: img }]+ expect(planResend(withImage, 'u1', 'describe this')).toEqual({+ deleteFromId: 'u1',+ content: 'describe this',+ images: img,+ })+ })++ it('refuses to edit anything that is not a question', () => {+ expect(planResend(plain, 'a2', 'nope')).toBeNull()+ })+})++describe('against the real store, the thread does not grow a copy per click', () => {+ // What useChat does with the plan: drop from the anchor, then let sendMessage+ // add the question back. The old path passed the ASSISTANT id here.+ function clickRegenerate(convId: string, assistantId: string, old = false) {+ const store = useChatStore.getState()+ const conv = store.conversations.find((c) => c.id === convId)!+ if (old) {+ const idx = conv.messages.findIndex((m) => m.id === assistantId)+ const userMsg = conv.messages[idx - 1]+ store.deleteMessagesAfter(convId, assistantId)+ store.addMessage(convId, { id: `u-${Date.now()}-${Math.random()}`, role: 'user', content: userMsg.content, timestamp: Date.now() })+ } else {+ const plan = planResend(conv.messages, assistantId)!+ store.deleteMessagesAfter(convId, plan.deleteFromId)+ store.addMessage(convId, { id: `u-${Date.now()}-${Math.random()}`, role: 'user', content: plan.content, timestamp: Date.now() })+ }+ useChatStore.getState().addMessage(convId, { id: `a-${Date.now()}-${Math.random()}`, role: 'assistant', content: 'answer', timestamp: Date.now() })+ }++ function seed() {+ useChatStore.setState({ conversations: [], activeConversationId: null })+ const convId = useChatStore.getState().createConversation('m', '')+ useChatStore.getState().addMessage(convId, { id: 'u1', role: 'user', content: 'why?', timestamp: 1 })+ useChatStore.getState().addMessage(convId, { id: 'a1', role: 'assistant', content: 'because', timestamp: 2 })+ return convId+ }++ it('three regenerates leave one question, not four', () => {+ const convId = seed()+ let lastAssistant = 'a1'+ for (let i = 0; i < 3; i++) {+ clickRegenerate(convId, lastAssistant)+ const msgs = useChatStore.getState().conversations.find((c) => c.id === convId)!.messages+ lastAssistant = msgs[msgs.length - 1].id+ }+ const msgs = useChatStore.getState().conversations.find((c) => c.id === convId)!.messages+ expect(msgs.filter((m) => m.role === 'user')).toHaveLength(1)+ expect(msgs).toHaveLength(2)+ })++ it('counter-proof: the old surgery grew one copy per click', () => {+ const convId = seed()+ let lastAssistant = 'a1'+ for (let i = 0; i < 3; i++) {+ clickRegenerate(convId, lastAssistant, true)+ const msgs = useChatStore.getState().conversations.find((c) => c.id === convId)!.messages+ lastAssistant = msgs[msgs.length - 1].id+ }+ const msgs = useChatStore.getState().conversations.find((c) => c.id === convId)!.messages+ expect(msgs.filter((m) => m.role === 'user')).toHaveLength(4)+ })+})++describe('nothing to resend', () => {+ it('unknown id', () => {+ expect(planResend(plain, 'nope')).toBeNull()+ })++ it('an answer with no question before it', () => {+ expect(planResend([{ id: 'a1', role: 'assistant' as const, content: 'orphan' }], 'a1')).toBeNull()+ })++ it('an empty thread', () => {+ expect(planResend([], 'a1')).toBeNull()+ })+})diff --git a/src/lib/resend-plan.ts b/src/lib/resend-plan.tsnew file mode 100644index 00000000..a3b90b6a--- /dev/null+++ b/src/lib/resend-plan.ts@@ -0,0 +1,54 @@+import type { ImageAttachment, Message } from '../types/chat'++/**+ * What has to leave the thread before a turn is sent again — Regenerate and+ * Edit-and-resend share this, because they are the same operation with a+ * different starting point.+ *+ * Both used to leave the original user message in place and then let+ * sendMessage add a SECOND copy of it: the question showed up twice, once more+ * with every further click, and the model was asked it twice. Attachments were+ * dropped on the way, so regenerating a vision turn re-asked the question+ * without the image. And in an agent thread the message before the answer is a+ * tool result, not the question, so Regenerate did nothing at all.+ */+export interface ResendPlan {+ /** First message to drop — deleteMessagesAfter removes it and everything after it. */+ deleteFromId: string+ /** Exactly what sendMessage receives as the user's input. */+ content: string+ images?: ImageAttachment[]+}++type ThreadMessage = Pick<Message, 'id' | 'role' | 'content' | 'displayContent' | 'images'>++export function planResend(+ messages: ThreadMessage[],+ targetId: string,+ /** Edit-and-resend: the rewritten text. Undefined for a plain regenerate. */+ override?: string,+): ResendPlan | null {+ const idx = messages.findIndex((m) => m.id === targetId)+ if (idx < 0) return null+ // An edit rewrites the question itself, so its target has to BE one.+ if (override !== undefined && messages[idx].role !== 'user') return null++ // Regenerate targets the answer; walk back to the question that produced it,+ // past the tool results an agent turn leaves in between.+ let anchorIdx = messages[idx].role === 'user' ? idx : idx - 1+ while (anchorIdx >= 0 && messages[anchorIdx].role !== 'user') anchorIdx--+ if (anchorIdx < 0) return null+ const anchor = messages[anchorIdx]++ // A slash command's displayContent is literally what the user typed+ // ("/review"), so that is what goes back in — sendMessage expands it again.+ // Any other displayContent is a label, not input: the /loop driver writes+ // "pass 3 of 5" there over the instruction the model actually ran.+ const typed = anchor.displayContent?.startsWith('/') ? anchor.displayContent : anchor.content++ return {+ deleteFromId: anchor.id,+ content: override ?? typed,+ ...(anchor.images?.length ? { images: anchor.images } : {}),+ }+}