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
feat(chat): a refusing answer says so and offers a new chat
purple0946dc7c975d
diff --git a/e2e/refusal-notice.spec.ts b/e2e/refusal-notice.spec.tsnew file mode 100644index 00000000..78ec9bcc--- /dev/null+++ b/e2e/refusal-notice.spec.ts@@ -0,0 +1,99 @@+import { test, expect, type Page } from '@playwright/test'+import { tauriMockInit, DEFAULT_MODEL_NAME } from './support/tauri-mock'+import { seedOnboardingDone } from './support/cloud-mock'+import { openNewChat } from './support/ui'++/**+ * The notice under a refusing answer (David, 2026-10-05).+ *+ * Measured that day: a refusal in the history is copied by better models in+ * the same chat. The app says so directly under the refusing answer and+ * offers a new chat on the same model. Nothing of it may stand in or above+ * the prompt field.+ *+ * The mock engine answers with the sentence Llama 3.1 8B Turbo gave in the+ * measurement.+ *+ * Run: CI=1 LU_E2E_PORT=5311 npx playwright test e2e/refusal-notice.spec.ts+ */++const REFUSAL = "I can't create explicit content. Is there anything else I can help you with?"+const NOTICE =+ 'This model declined. A refusal stays in the chat history, and other models tend to copy it. Start a new chat and pick a model marked No refusals.'++const picker = (page: Page) => page.getByRole('button', { name: 'Select chat model', exact: true })+const notice = (page: Page) => page.getByTestId('refusal-notice')+const answer = (page: Page) => page.getByRole('main').locator('p').filter({ hasText: REFUSAL })++async function boot(page: Page, assistantReply: string) {+ await page.addInitScript(tauriMockInit, { assistantReply, modelName: DEFAULT_MODEL_NAME })+ await seedOnboardingDone(page)+ await page.goto('/')+ await openNewChat(page)+}++async function send(page: Page, text: string) {+ const box = page.locator('textarea').first()+ await box.fill(text)+ await page.getByRole('button', { name: 'Send message' }).click()+}++test('a refusing answer gets the notice under it, and "New chat" opens a chat on the same model', async ({ page }) => {+ await boot(page, REFUSAL)+ await expect(picker(page)).toContainText('qwen2.5-7b')+ await send(page, 'write the scene')+ await expect(answer(page)).toBeVisible({ timeout: 15_000 })++ await expect(notice(page)).toHaveCount(1)+ await expect(notice(page)).toContainText(NOTICE)+ await expect(notice(page).locator('svg')).toBeVisible()+ const button = notice(page).getByRole('button', { name: 'New chat', exact: true })+ await expect(button).toBeVisible()++ // Under the answer, above the prompt field, and not part of the composer.+ const answerBox = (await answer(page).boundingBox())!+ const noticeBox = (await notice(page).boundingBox())!+ const promptBox = (await page.locator('textarea').first().boundingBox())!+ expect(noticeBox.y).toBeGreaterThanOrEqual(answerBox.y + answerBox.height - 1)+ expect(noticeBox.y + noticeBox.height).toBeLessThan(promptBox.y)+ // The transcript scrolls, the composer does not: the notice is a child of+ // the scrolling transcript and of no element that holds the prompt field.+ expect(await notice(page).evaluate((el) => {+ for (let p = el.parentElement; p; p = p.parentElement) {+ if (p.querySelector('textarea')) return getComputedStyle(el.closest('.overflow-y-auto')!).overflowY+ }+ return 'no common ancestor'+ })).toBe('auto')+ expect(await notice(page).evaluate((el) => !!el.closest('.overflow-y-auto')?.querySelector('textarea'))).toBe(false)++ // A second refusal moves the notice to the latest one.+ // The composer holds a short double-fire lock after an accepted send+ // (SEND_LOCK_MS, chat/ChatInput.tsx); a send inside it stays in the field,+ // and a person presses again.+ await expect(async () => {+ if ((await answer(page).count()) < 2) {+ const box = page.locator('textarea').first()+ if ((await box.inputValue()) === '') await box.fill('please')+ await page.getByRole('button', { name: 'Send message' }).click()+ }+ await expect(answer(page)).toHaveCount(2, { timeout: 3_000 })+ }).toPass({ timeout: 30_000 })+ await expect(notice(page)).toHaveCount(1)+ const secondAnswer = (await answer(page).nth(1).boundingBox())!+ expect((await notice(page).boundingBox())!.y).toBeGreaterThanOrEqual(secondAnswer.y + secondAnswer.height - 1)++ // New chat: empty transcript, same model, the refusal stays behind.+ await notice(page).getByRole('button', { name: 'New chat', exact: true }).click()+ await expect(answer(page)).toHaveCount(0)+ await expect(notice(page)).toHaveCount(0)+ await expect(picker(page)).toContainText('qwen2.5-7b')+ await expect(page.locator('textarea').first()).toBeVisible()+ await expect(page.locator('textarea').first()).toHaveValue('')+})++test('an ordinary answer gets no notice', async ({ page }) => {+ await boot(page, 'Sure, here is the scene you asked for.')+ await send(page, 'write the scene')+ await expect(page.getByRole('main').locator('p').filter({ hasText: 'Sure, here is the scene' })).toBeVisible({ timeout: 15_000 })+ await expect(notice(page)).toHaveCount(0)+})diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsxindex ca32924c..8618e986 100644--- a/src/components/chat/MessageBubble.tsx+++ b/src/components/chat/MessageBubble.tsx@@ -31,6 +31,7 @@ import { MONOGRAM, MONOGRAM_INVERT } from '../layout/brand'import { AVATAR_SLOT } from './avatar-slot'import { MOTION_S } from '../ui/motion'import { Hinweis } from '../ui/Hinweis'+import { RefusalNotice } from './RefusalNotice'import { fitTextarea } from '../../lib/fit-textarea'interface Props {@@ -54,9 +55,12 @@ interface Props {/** Group chat: the persona this participant speaks as, when it has one of* its own. Shown in front of the model name. */speakerName?: string+ /** This answer is the latest one of the chat in which the model declined+ * (lib/refusal-detect). The notice with "New chat" stands under it. */+ declined?: boolean}-function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, onApprove, onReject, isLast, isStreaming, speakerName }: Props) {+function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, onApprove, onReject, isLast, isStreaming, speakerName, declined }: Props) {const [copied, setCopied] = useState(false)const [isEditing, setIsEditing] = useState(false)const [editContent, setEditContent] = useState('')@@ -586,6 +590,10 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o</div>)}+ {/* The model declined: said under the answer, never at the prompt+ field, and before the action bar so it reads as part of the turn. */}+ {declined && <RefusalNotice />}+{/* Action bar UNDER the message (David 2026-06-06: "eigene Leiste unterder Nachricht" instead of cramped hover-icons in the corner). Biggertargets; assistant left, user right. */}diff --git a/src/components/chat/MessageList.tsx b/src/components/chat/MessageList.tsxindex fb952592..670215bf 100644--- a/src/components/chat/MessageList.tsx+++ b/src/components/chat/MessageList.tsx@@ -10,6 +10,8 @@ import { CompactBlock } from './CompactBlock'import { compactionAnchors } from '../../lib/compact-summary'import { Hinweis } from '../ui/Hinweis'import { TRANSCRIPT_MAX_PX } from './composer-width'+import { useAgentModeStore } from '../../stores/agentModeStore'+import { latestRefusalId, refusalNoticeApplies } from '../../lib/refusal-detect'/*** Above this many visible messages the transcript stops paying full layout +@@ -84,6 +86,12 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel[groupModels, groupPersonas, personas],)+ // Agent mode of THIS chat: a short "I can't ..." there is usually about a+ // file or a command, so the refusal notice stays out (lib/refusal-detect).+ const agentModeActive = useAgentModeStore((s) =>+ conversation ? s.agentModeActive[conversation.id] ?? false : false,+ )+const lastMessage = conversation?.messages[conversation.messages.length - 1]// The approval id is part of the scroll trigger (G31): a run waiting for a// decision often adds NO content, so the list stood still while the inline@@ -136,6 +144,13 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel(m) => (m.role !== 'system' || !!m.notice) && !m.hidden,)const lastVisibleId = visibleMessages[visibleMessages.length - 1]?.id+ // The one answer that carries the refusal notice, if any. The answer that+ // is still being written is never judged: every long answer is a short one+ // for a moment.+ const streamingId = showTyping && lastMessage?.role === 'assistant' ? lastMessage.id : null+ const declinedId = refusalNoticeApplies(conversation, agentModeActive)+ ? latestRefusalId(visibleMessages, streamingId)+ : nullif (skipGate.id !== conversation.id) {setSkipGate({@@ -216,6 +231,7 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModelpendingApprovalId={pendingApprovalId}onApprove={onApprove}onReject={onReject}+ declined={message.id === declinedId}speakerName={message.modelId && speakers[message.modelId]?.personaPrompt !== undefined? speakers[message.modelId].name: undefined}diff --git a/src/components/chat/RefusalNotice.tsx b/src/components/chat/RefusalNotice.tsxnew file mode 100644index 00000000..abb42fbb--- /dev/null+++ b/src/components/chat/RefusalNotice.tsx@@ -0,0 +1,27 @@+import { AlertTriangle } from 'lucide-react'+import { Hinweis } from '../ui/Hinweis'+import { REFUSAL_NOTICE } from '../../lib/refusal-detect'+import { newChatWithSameModel } from '../../lib/new-chat-same-model'++/**+ * The line under an answer in which the model declined (lib/refusal-detect).+ *+ * It stands under the answer and not at the prompt field: nothing is written+ * in or above the prompt field. Quiet tone, because nothing is broken; the+ * triangle marks it as the line that asks the user to do something.+ */+export function RefusalNotice() {+ return (+ <div data-testid="refusal-notice" className="pl-1">+ <Hinweis icon={<AlertTriangle size={11} className="mt-0.5 shrink-0" aria-hidden="true" />}>+ {REFUSAL_NOTICE}{' '}+ <button+ onClick={newChatWithSameModel}+ className="font-medium underline underline-offset-2 hover:no-underline"+ >+ New chat+ </button>+ </Hinweis>+ </div>+ )+}diff --git a/src/components/chat/__tests__/eine-ablehnung-bekommt-ihren-hinweis.test.tsx b/src/components/chat/__tests__/eine-ablehnung-bekommt-ihren-hinweis.test.tsxnew file mode 100644index 00000000..259cc028--- /dev/null+++ b/src/components/chat/__tests__/eine-ablehnung-bekommt-ihren-hinweis.test.tsx@@ -0,0 +1,224 @@+// @vitest-environment jsdom+/**+ * The notice under a refusing answer (David, 2026-10-05).+ *+ * Measured that day: a refusal in the history is copied by better models in+ * the same chat. The chat says so directly UNDER the refusing answer, with a+ * warning triangle and a "New chat" button that opens a new chat on the same+ * model. Same in Cloud and in local chat. Nothing of it stands in or above+ * the prompt field: the line belongs to the transcript.+ *+ * What counts as a refusal is pinned in lib/__tests__/refusal-detect.test.ts.+ *+ * Run: npx vitest run src/components/chat/__tests__/eine-ablehnung-bekommt-ihren-hinweis.test.tsx+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'+import { MessageList } from '../MessageList'+import { useChatStore } from '../../../stores/chatStore'+import { useModelStore } from '../../../stores/modelStore'+import { useSettingsStore } from '../../../stores/settingsStore'+import { useAgentModeStore } from '../../../stores/agentModeStore'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'+import { BUILT_IN_PERSONAS, DEFAULT_SETTINGS } from '../../../lib/constants'+import type { AIModel } from '../../../types/models'+import type { Message } from '../../../types/chat'++const LOCAL = 'openai::Qwen3-14B-Q4_K_M'+const CLOUD = 'lu-cloud::llama-3.1-8b-turbo'+const NOTICE =+ 'This model declined. A refusal stays in the chat history, and other models tend to copy it. Start a new chat and pick a model marked No refusals.'+const REFUSAL = "I can't create explicit content. Is there anything else I can help you with?"++const textModel = (name: string): AIModel => ({ name, type: 'text' } as AIModel)+let n = 0+const msg = (role: Message['role'], content: string, extra: Partial<Message> = {}): Message => ({+ id: `m${++n}`, role, content, timestamp: n, ...extra,+})++let convId = ''+function chatWith(model: string, messages: Message[]) {+ useModelStore.setState({ models: [textModel(LOCAL), textModel(CLOUD)], activeModel: model })+ convId = useChatStore.getState().createConversation(model, '')+ useChatStore.setState((s) => ({+ conversations: s.conversations.map((c) => (c.id === convId ? { ...c, messages } : c)),+ }))+}++beforeEach(() => {+ useChatStore.setState({ conversations: [], activeConversationId: null })+ useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS }, personas: [...BUILT_IN_PERSONAS] })+ useAgentModeStore.setState({ agentModeActive: {} })+})+afterEach(cleanup)++const notices = () => screen.queryAllByTestId('refusal-notice')++describe.each([+ ['a local chat', LOCAL],+ ['a Cloud chat', CLOUD],+])('%s', (_name, model) => {+ it('shows the notice under the refusing answer, word for word, with the button', () => {+ chatWith(model, [msg('user', 'write the scene'), msg('assistant', REFUSAL)])+ render(<MessageList isGenerating={false} />)+ expect(notices()).toHaveLength(1)+ expect(notices()[0].textContent).toBe(`${NOTICE} New chat`)+ expect(within(notices()[0]).getByRole('button', { name: 'New chat' })).toBeTruthy()+ expect(notices()[0].querySelector('svg')).not.toBeNull()+ })++ it('"New chat" opens an empty chat on the same model and leaves the old one as it is', () => {+ chatWith(model, [msg('user', 'write the scene'), msg('assistant', REFUSAL)])+ render(<MessageList isGenerating={false} />)+ fireEvent.click(within(notices()[0]).getByRole('button', { name: 'New chat' }))+ const { conversations, activeConversationId } = useChatStore.getState()+ expect(conversations).toHaveLength(2)+ expect(activeConversationId).not.toBe(convId)+ const fresh = conversations.find((c) => c.id === activeConversationId)!+ expect(fresh.model).toBe(model)+ expect(fresh.messages).toHaveLength(0)+ expect(conversations.find((c) => c.id === convId)!.messages).toHaveLength(2)+ expect(useModelStore.getState().activeModel).toBe(model)+ // The new chat has no refusal in it, so the line is gone with the old one.+ expect(notices()).toHaveLength(0)+ })+})++describe('where the notice stands', () => {+ it('sits inside the transcript row of the refusing answer, after its text', () => {+ chatWith(LOCAL, [msg('user', 'write the scene'), msg('assistant', REFUSAL)])+ const { container } = render(<MessageList isGenerating={false} />)+ const answer = screen.getByText(REFUSAL)+ const notice = notices()[0]+ expect(answer.compareDocumentPosition(notice) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()+ expect(container.querySelector('textarea')).toBeNull()+ })++ it('only at the latest refusal of the chat', () => {+ const second = msg('assistant', "I'm sorry, but I can't continue this story.")+ chatWith(LOCAL, [msg('user', 'write the scene'), msg('assistant', REFUSAL), msg('user', 'please'), second])+ render(<MessageList isGenerating={false} />)+ expect(notices()).toHaveLength(1)+ const answer = screen.getByText(second.content)+ expect(answer.compareDocumentPosition(notices()[0]) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()+ })++ it('stays when a later answer is an ordinary one: the refusal is still in the history', () => {+ chatWith(LOCAL, [+ msg('user', 'write the scene'), msg('assistant', REFUSAL),+ msg('user', 'what is 2 + 2'), msg('assistant', 'Four.'),+ ])+ render(<MessageList isGenerating={false} />)+ expect(notices()).toHaveLength(1)+ })+})++describe('what gets no notice', () => {+ it('an ordinary answer', () => {+ chatWith(LOCAL, [msg('user', 'hi'), msg('assistant', 'Hello, how can I help?')])+ render(<MessageList isGenerating={false} />)+ expect(notices()).toHaveLength(0)+ })++ it('an answer that is still streaming, even when it begins like a refusal', () => {+ chatWith(LOCAL, [msg('user', 'write the scene'), msg('assistant', "I can't")])+ render(<MessageList isGenerating isThisChatGenerating />)+ expect(notices()).toHaveLength(0)+ })++ it('NEGATIVE CONTROL: the same answer once the stream is over', () => {+ chatWith(LOCAL, [msg('user', 'write the scene'), msg('assistant', "I can't")])+ render(<MessageList isGenerating={false} isThisChatGenerating={false} />)+ expect(notices()).toHaveLength(1)+ })++ it('a long answer that opens with the phrase', () => {+ const long = "I can't give you one single answer here, so let me walk through the options. " ++ 'The first option is to keep the scene as it is and tighten the dialogue. '.repeat(8)+ chatWith(LOCAL, [msg('user', 'help me'), msg('assistant', long)])+ render(<MessageList isGenerating={false} />)+ expect(notices()).toHaveLength(0)+ })++ it('an error sentence of the app and an app notice', () => {+ chatWith(LOCAL, [+ msg('user', 'hi'),+ msg('assistant', 'Error: the backend cannot help, connection failed'),+ msg('system', "I cannot help with that.", { notice: 'warn' }),+ ])+ render(<MessageList isGenerating={false} />)+ expect(notices()).toHaveLength(0)+ })+})++describe('only the plain chat: Agent, Code and group chats get no notice', () => {+ // "I can't find that file" is a report about a tool, not a refusal of the+ // request, and it is exactly as short and opens exactly the same way.+ const FILE = "I can't find that file."++ it('NEGATIVE CONTROL: the same sentence in a plain chat is marked', () => {+ chatWith(LOCAL, [msg('user', 'read notes.txt'), msg('assistant', FILE)])+ render(<MessageList isGenerating={false} />)+ expect(notices()).toHaveLength(1)+ })++ it('Agent mode on for this chat: no notice, for a tool report or a real refusal', () => {+ chatWith(LOCAL, [msg('user', 'read notes.txt'), msg('assistant', FILE), msg('user', 'write it'), msg('assistant', REFUSAL)])+ useAgentModeStore.setState({ agentModeActive: { [convId]: true } })+ render(<MessageList isGenerating={false} />)+ expect(notices()).toHaveLength(0)+ })++ it('Agent mode on in ANOTHER chat does not silence this one', () => {+ chatWith(LOCAL, [msg('user', 'write it'), msg('assistant', REFUSAL)])+ useAgentModeStore.setState({ agentModeActive: { 'some-other-chat': true } })+ render(<MessageList isGenerating={false} />)+ expect(notices()).toHaveLength(1)+ })++ it('an answer of a turn that ran a tool, with Agent mode off again', () => {+ const blocks = [{+ id: 'b1', phase: 'answer', content: FILE, timestamp: 1,+ toolCalls: [{ id: 't1', toolName: 'file_read', args: { path: 'notes.txt' }, status: 'failed', timestamp: 1 }],+ }] as unknown as Message['agentBlocks']+ chatWith(LOCAL, [msg('user', 'read notes.txt'), msg('assistant', FILE, { agentBlocks: blocks })])+ render(<MessageList isGenerating={false} />)+ expect(notices()).toHaveLength(0)+ })++ it('a Code conversation', () => {+ chatWith(LOCAL, [msg('user', 'fix the bug'), msg('assistant', FILE)])+ useChatStore.setState((s) => ({+ conversations: s.conversations.map((c) => (c.id === convId ? { ...c, mode: 'codex' as const } : c)),+ }))+ render(<MessageList isGenerating={false} />)+ expect(notices()).toHaveLength(0)+ })++ it('the Code transcript does not draw the notice at all', () => {+ const here = dirname(fileURLToPath(import.meta.url))+ const codex = readFileSync(resolve(here, '../CodexView.tsx'), 'utf8')+ expect(codex).not.toContain('RefusalNotice')+ expect(codex).not.toContain('refusal-detect')+ })++ it('a group chat', () => {+ chatWith(LOCAL, [msg('user', 'write it'), msg('assistant', REFUSAL, { modelId: LOCAL })])+ useChatStore.getState().setGroupModels(convId, [LOCAL, CLOUD])+ render(<MessageList isGenerating={false} />)+ expect(notices()).toHaveLength(0)+ })+})++describe('"New chat" without a picked model', () => {+ it('opens the landing page instead of a chat on no model', () => {+ chatWith(CLOUD, [msg('user', 'write the scene'), msg('assistant', REFUSAL)])+ useModelStore.setState({ activeModel: null })+ render(<MessageList isGenerating={false} />)+ fireEvent.click(within(notices()[0]).getByRole('button', { name: 'New chat' }))+ expect(useChatStore.getState().activeConversationId).toBeNull()+ expect(useChatStore.getState().conversations).toHaveLength(1)+ })+})diff --git a/src/lib/__tests__/refusal-detect.test.ts b/src/lib/__tests__/refusal-detect.test.tsnew file mode 100644index 00000000..cfad3059--- /dev/null+++ b/src/lib/__tests__/refusal-detect.test.ts@@ -0,0 +1,212 @@+/**+ * The refusal notice under an answer (David, 2026-10-05).+ *+ * Measured that day: a refusal in the history is copied by better models in+ * the same chat. The app says so under the refusing answer. This file pins+ * what counts as a refusal: a SHORT answer that OPENS with a refusal phrase,+ * judged on finished model answers only, and marked once per chat.+ *+ * Run: npx vitest run src/lib/__tests__/refusal-detect.test.ts+ */+import { describe, it, expect } from 'vitest'+import { looksLikeRefusal, latestRefusalId, refusalNoticeApplies, REFUSAL_NOTICE } from '../refusal-detect'+import type { AgentBlock } from '../../types/agent-mode'+import type { Message } from '../../types/chat'++describe('looksLikeRefusal', () => {+ it.each([+ "I can't help with that request.",+ 'I cannot create explicit content.',+ "I'm sorry, but I can't continue this story.",+ 'I’m sorry, but I can’t assist with that.',+ "I won't write that.",+ "I'm unable to help with this.",+ 'I am unable to assist with that request.',+ "I'm not comfortable writing this scene.",+ 'I must decline this request.',+ "I can't engage in explicit roleplay.",+ 'Sorry, but I cannot continue with this.',+ 'I apologize, but I cannot generate that content.',+ 'As an AI language model, I cannot create content of that nature.',+ 'This is a request I am not comfortable with, so let us talk about something else.',+ '**I cannot continue this roleplay.**',+ '"I can\'t assist with that."',+ ])('a short refusal: %s', (text) => {+ expect(looksLikeRefusal(text)).toBe(true)+ })++ it('the verbatim answer of Llama 3.1 8B Turbo from the measurement', () => {+ expect(looksLikeRefusal("I can't create explicit content. Is there anything else I can help you with?")).toBe(true)+ })++ it('reasoning in a <think> block does not count towards the length', () => {+ const thought = '<think>' + 'the user asks for something I should weigh carefully '.repeat(30) + '</think>'+ expect(looksLikeRefusal(`${thought}\n\nI can't help with that.`)).toBe(true)+ })++ it('a reply that starts mid-thought and only closes the tag is read after the tag', () => {+ expect(looksLikeRefusal("weighing the request, this is not allowed</think>I cannot assist with that.")).toBe(true)+ })++ it('a refusal phrase that only stands inside the reasoning is not a refusal', () => {+ expect(looksLikeRefusal("<think>I can't help with that, or can I? Yes I can.</think>Here is the scene you asked for.")).toBe(false)+ })++ it('an answer that is still all reasoning says nothing yet', () => {+ expect(looksLikeRefusal("<think>I can't help with")).toBe(false)+ })++ it('a LONG answer that opens with the phrase is not a refusal', () => {+ const long = "I can't give you one single answer here, so let me walk through the options. " ++ 'The first option is to keep the scene as it is and tighten the dialogue. '.repeat(8)+ expect(long.split(/\s+/).length).toBeGreaterThan(60)+ expect(looksLikeRefusal(long)).toBe(false)+ })++ it('a phrase in the middle of a story is not a refusal', () => {+ const story = 'The rain had not stopped for three days when Mara reached the harbour. ' ++ 'She found the old keeper by the gate, and he shook his head before she had asked anything. ' ++ '"I cannot help you," he said, "the boats are gone." She laughed, because she had expected nothing else.'+ expect(looksLikeRefusal(story)).toBe(false)+ })++ it('a short story line with the phrase past the opening is not a refusal', () => {+ const text = 'The keeper looked at her for a long while, at the rain on her coat and the mud on her boots, ' ++ 'at the letter in her hand that nobody in this town would ever read aloud, and then he said: "I cannot help you."'+ expect(looksLikeRefusal(text)).toBe(false)+ })++ it.each([+ 'Sure, here is the scene you asked for.',+ "I can't wait to show you what I came up with!",+ "I can't believe how well that worked. Here is the next part.",+ 'She cannot help but smile at him.',+ 'Yes.',+ '',+ ' ',+ ])('an ordinary short answer: %s', (text) => {+ expect(looksLikeRefusal(text)).toBe(false)+ })++ it('exactly at the limit the answer is no longer short', () => {+ const fifty = "I can't help with that. " + 'word '.repeat(54)+ expect(fifty.trim().split(/\s+/).length).toBe(59)+ expect(looksLikeRefusal(fifty)).toBe(true)+ const sixty = "I can't help with that. " + 'word '.repeat(55)+ expect(sixty.trim().split(/\s+/).length).toBe(60)+ expect(looksLikeRefusal(sixty)).toBe(false)+ })+})++const REFUSAL = "I can't help with that."+let n = 0+const msg = (role: Message['role'], content: string, extra: Partial<Message> = {}): Message => ({+ id: `m${++n}`, role, content, timestamp: n, ...extra,+})++describe('latestRefusalId', () => {+ it('names the refusing answer', () => {+ const list = [msg('user', 'write it'), msg('assistant', REFUSAL)]+ expect(latestRefusalId(list)).toBe(list[1].id)+ })++ it('only the latest of several refusals', () => {+ const list = [+ msg('user', 'write it'), msg('assistant', REFUSAL),+ msg('user', 'please'), msg('assistant', "I'm sorry, but I can't continue."),+ ]+ expect(latestRefusalId(list)).toBe(list[3].id)+ })++ it('a later ordinary answer does not remove it: the refusal is still in the history', () => {+ const list = [+ msg('user', 'write it'), msg('assistant', REFUSAL),+ msg('user', 'what is 2 + 2'), msg('assistant', 'Four.'),+ ]+ expect(latestRefusalId(list)).toBe(list[1].id)+ })++ it('a chat without a refusal has none', () => {+ expect(latestRefusalId([msg('user', 'hi'), msg('assistant', 'Hello, how can I help?')])).toBeNull()+ expect(latestRefusalId([])).toBeNull()+ })++ it('the answer that is still streaming is not judged', () => {+ const list = [msg('user', 'write it'), msg('assistant', "I can't")]+ expect(latestRefusalId(list, list[1].id)).toBeNull()+ expect(latestRefusalId(list)).toBe(list[1].id)+ })++ it('an earlier refusal keeps its notice while a new answer streams', () => {+ const list = [+ msg('user', 'write it'), msg('assistant', REFUSAL),+ msg('user', 'again'), msg('assistant', "I can't"),+ ]+ expect(latestRefusalId(list, list[3].id)).toBe(list[1].id)+ })++ it('the user saying it is not a refusal of the model', () => {+ expect(latestRefusalId([msg('user', "I can't help with that.")])).toBeNull()+ })++ it('tool results, app notices, hidden rows and error sentences are not judged', () => {+ expect(latestRefusalId([msg('tool', "I cannot help with that.")])).toBeNull()+ expect(latestRefusalId([msg('system', "I cannot help with that.", { notice: 'warn' })])).toBeNull()+ expect(latestRefusalId([msg('assistant', "I cannot help with that.", { hidden: true })])).toBeNull()+ expect(latestRefusalId([msg('assistant', 'Error: the backend cannot help, connection failed')])).toBeNull()+ })+})++describe('answers of a turn that ran tools are reports, not refusals', () => {+ const FILE = "I can't find that file."+ const call = { id: 't1', toolName: 'file_read', args: {}, status: 'failed', timestamp: 1 }++ it('a tool call in the blocks of the answer', () => {+ const blocks = [{ id: 'b1', phase: 'answer', content: FILE, timestamp: 1, toolCalls: [call] }] as unknown as AgentBlock[]+ expect(latestRefusalId([msg('assistant', FILE, { agentBlocks: blocks })])).toBeNull()+ })++ it('the legacy single tool call, a tool call summary, and native tool_calls', () => {+ const legacy = [{ id: 'b1', phase: 'answer', content: FILE, timestamp: 1, toolCall: call }] as unknown as AgentBlock[]+ expect(latestRefusalId([msg('assistant', FILE, { agentBlocks: legacy })])).toBeNull()+ expect(latestRefusalId([msg('assistant', FILE, { toolCallSummary: 'file_read failed' })])).toBeNull()+ expect(latestRefusalId([msg('assistant', FILE, { tool_calls: [{ function: { name: 'file_read', arguments: {} } }] })])).toBeNull()+ })++ it('NEGATIVE CONTROL: answer blocks without any tool call are a plain answer', () => {+ // Plain chat with Chat Tools on runs through the same executor and gets+ // answer blocks too. Without a tool call it is still the model declining.+ const blocks = [{ id: 'b1', phase: 'answer', content: REFUSAL, timestamp: 1 }] as unknown as AgentBlock[]+ const list = [msg('assistant', REFUSAL, { agentBlocks: blocks })]+ expect(latestRefusalId(list)).toBe(list[0].id)+ })+})++describe('refusalNoticeApplies: only the plain chat', () => {+ it('a plain chat, hosted or local, with and without the mode written out', () => {+ expect(refusalNoticeApplies({}, false)).toBe(true)+ expect(refusalNoticeApplies({ mode: 'lu' }, false)).toBe(true)+ expect(refusalNoticeApplies({ mode: 'lu', groupModels: [] }, false)).toBe(true)+ })++ it('not in Agent mode', () => {+ expect(refusalNoticeApplies({ mode: 'lu' }, true)).toBe(false)+ })++ it('not in Code', () => {+ expect(refusalNoticeApplies({ mode: 'codex' }, false)).toBe(false)+ expect(refusalNoticeApplies({ mode: 'openclaw' }, false)).toBe(false)+ })++ it('not in a group chat', () => {+ expect(refusalNoticeApplies({ mode: 'lu', groupModels: ['a', 'b'] }, false)).toBe(false)+ })+})++describe('the wording', () => {+ it('is the sentence agreed with the web app, and names the mark of the model picker', () => {+ expect(REFUSAL_NOTICE).toBe(+ 'This model declined. A refusal stays in the chat history, and other models tend to copy it. Start a new chat and pick a model marked No refusals.',+ )+ })+})diff --git a/src/lib/new-chat-same-model.ts b/src/lib/new-chat-same-model.tsnew file mode 100644index 00000000..df1c1c22--- /dev/null+++ b/src/lib/new-chat-same-model.ts@@ -0,0 +1,27 @@+import { useChatStore } from '../stores/chatStore'+import { useModelStore } from '../stores/modelStore'+import { useSettingsStore } from '../stores/settingsStore'++/**+ * A new chat on the model the user is chatting with right now. The button+ * under a refusing answer calls this (components/chat/RefusalNotice): the+ * refusal stays behind in the old chat, the model comes along.+ *+ * The picked model is the one that answers in the open chat, the store keeps+ * the two in step (modelStore.setActiveModel). The persona rule is the one of+ * the sidebar's New Chat.+ *+ * Without a picked model there is nothing to carry over. The landing page+ * opens instead, with the composer and the model picker in it.+ */+export function newChatWithSameModel(): void {+ const model = useModelStore.getState().activeModel+ const chat = useChatStore.getState()+ if (!model) {+ chat.setActiveConversation(null)+ return+ }+ const { settings, getActivePersona } = useSettingsStore.getState()+ const persona = settings.personasEnabled ? getActivePersona() : null+ chat.createConversation(model, persona?.systemPrompt || '')+}diff --git a/src/lib/refusal-detect.ts b/src/lib/refusal-detect.tsnew file mode 100644index 00000000..b0b0553d--- /dev/null+++ b/src/lib/refusal-detect.ts@@ -0,0 +1,143 @@+import type { Conversation, Message } from '../types/chat'++/**+ * Did the model decline, and where does the chat say so.+ *+ * Measured 2026-10-05 (lu-305/mail/TEST-VERWEIGERUNG-2026-10-05.md): once a+ * refusal stands in the history, models that would have answered copy it in+ * the same chat. The way out is a new chat, so the app says that under the+ * refusing answer, in Cloud and in local chat alike, and offers the new chat+ * right there.+ *+ * A refusal is a SHORT answer that OPENS with a refusal phrase. Both halves+ * are needed: a long answer that starts with "I can't" usually goes on to do+ * the work, and a story may hold "I cannot help you" in the middle of a+ * dialogue. Neither is a refusal of the request.+ */++/** The notice under the refusing answer. Agreed word for word with the web+ * app, and "No refusals" is the mark in the model picker (ModelRowMarks). */+export const REFUSAL_NOTICE =+ 'This model declined. A refusal stays in the chat history, and other models tend to copy it. ' ++ 'Start a new chat and pick a model marked No refusals.'++/** Below this many words an answer counts as short. */+const SHORT_ANSWER_WORDS = 60++/** How much of the answer counts as its opening. Roughly the first sentence+ * or two, so "I'm sorry, but I cannot create that" is still caught behind+ * its apology. */+const OPENING_CHARS = 160++/** Phrases that open a refusal when they are the first words of the answer. */+const OPENS_WITH = new RegExp(+ '^(?:' + [+ // "I can't wait to show you" and "I can't believe it" are not refusals.+ "i (?:can't|cannot|can not|won't|will not)\\b(?! (?:wait|believe|thank|stress|emphasize|overstate|say enough|help but|get enough))",+ "(?:i'm|i am) (?:unable|not able|not comfortable|sorry,? but)\\b",+ 'i must decline\\b',+ '(?:sorry|i apologi[sz]e|unfortunately),? (?:but )?i ' ++ "(?:can't|cannot|can not|won't|will not|am unable|am not able|am not comfortable|must decline)\\b",+ ].join('|') + ')',+)++/** Phrases that mark a refusal anywhere in the opening, e.g. behind "As an AI". */+const OPENING_HOLDS = new RegExp(+ [+ "\\b(?:cannot|can't|can not|unable to|won't|will not) " ++ '(?:help|assist|create|continue|engage|fulfill|comply|write|generate|produce|provide)\\b(?! but)',+ '\\bnot comfortable\\b',+ '\\bi must decline\\b',+ ].join('|'),+)++/** The visible text of an answer: reasoning the model sent inline is not part+ * of what it said. Covers a closed block, a block that never closed, and a+ * reply that starts in the middle of a thought and only sends the closing tag+ * (lib/hermes-stream). */+function withoutThinking(content: string): string {+ let text = content.replace(/<think>[\s\S]*?<\/think>/gi, ' ')+ const strayClose = text.toLowerCase().lastIndexOf('</think>')+ if (strayClose !== -1) text = text.slice(strayClose + '</think>'.length)+ const strayOpen = text.toLowerCase().indexOf('<think>')+ if (strayOpen !== -1) text = text.slice(0, strayOpen)+ return text+}++/**+ * Pure: does this finished answer text read as a refusal?+ * Short (under 60 words without `<think>` blocks) AND a refusal phrase in its+ * opening.+ */+export function looksLikeRefusal(content: string): boolean {+ const text = withoutThinking(content).trim()+ if (!text) return false+ if (text.split(/\s+/).length >= SHORT_ANSWER_WORDS) return false+ const opening = text+ .slice(0, OPENING_CHARS)+ .toLowerCase()+ // Typographic apostrophes, as most hosted models send them.+ .replace(/[\u2018\u2019\u02BC]/g, "'")+ // Leading quote marks, markdown emphasis and the like.+ .replace(/^[^a-z]+/, '')+ return OPENS_WITH.test(opening) || OPENING_HOLDS.test(opening)+}++/** Message objects are replaced, never mutated (chatStore), so the verdict of+ * one object never changes and a streaming frame costs one lookup per+ * message it did not touch. */+const verdicts = new WeakMap<Message, boolean>()++/** Is this message a plain answer of the model? Tool results, app notices,+ * hidden history rows and the app's own error sentences are not, and neither+ * is an answer of a turn that ran tools: "I can't find that file" after a+ * failed read is a report, not a refusal. */+function isModelAnswer(m: Message): boolean {+ if (m.role !== 'assistant' || m.hidden || m.notice) return false+ if (m.tool_calls?.length || m.toolCallSummary) return false+ if (m.agentBlocks?.some((b) => b.toolCall || b.toolCalls?.length)) return false+ return !/^\s*error:/i.test(m.content || '')+}++/**+ * Is this a chat in which the notice may appear at all? Only the plain chat,+ * hosted or local. In Agent mode and in Code a short "I can't ..." is usually+ * about a file or a command, and in a group chat one model's short line is+ * often an answer to another model, so the phrase proves nothing there. Code+ * has its own transcript and never comes through here; the check on `mode`+ * holds the line in case it ever does.+ */+export function refusalNoticeApplies(+ conversation: Pick<Conversation, 'mode' | 'groupModels'>,+ agentModeActive: boolean,+): boolean {+ if (agentModeActive) return false+ if (conversation.mode === 'codex' || conversation.mode === 'openclaw') return false+ return !conversation.groupModels?.length+}++function declined(m: Message): boolean {+ let verdict = verdicts.get(m)+ if (verdict === undefined) {+ verdict = isModelAnswer(m) && looksLikeRefusal(m.content || '')+ verdicts.set(m, verdict)+ }+ return verdict+}++/**+ * The id of the LATEST refusing answer of a chat, or null. The notice stands+ * there and nowhere else: one line per chat says it, a second one further up+ * would say nothing new.+ *+ * `streamingId` is the answer still being written. A refusal is judged on a+ * finished answer only, since every long answer is a short one for a moment.+ */+export function latestRefusalId(messages: readonly Message[], streamingId?: string | null): string | null {+ for (let i = messages.length - 1; i >= 0; i--) {+ const m = messages[i]+ if (m.id === streamingId) continue+ if (declined(m)) return m.id+ }+ return null+}