Skip to content

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.

fix(agent): an invented link is caught by the app, not believed by the user

purple1d767400741a
diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsx
index eafbdfb1..ad77165c 100644
--- a/src/components/chat/MessageBubble.tsx
+++ b/src/components/chat/MessageBubble.tsx
@@ -1,5 +1,5 @@
import { motion } from 'framer-motion'
-import { User, Copy, Check, Pencil, RefreshCw, X, Wrench, Trash2, Scissors } from 'lucide-react'
+import { User, Copy, Check, Pencil, RefreshCw, X, Wrench, Trash2, Scissors, Unlink } from 'lucide-react'
import { useState, useRef, useEffect, useMemo, memo } from 'react'
import { MarkdownRenderer } from './MarkdownRenderer'
import { ThinkingBlock } from './ThinkingBlock'
@@ -12,6 +12,7 @@ import { ChatArtifactCard } from './ChatArtifactCard'
import type { Message } from '../../types/chat'
import { stripModelNoise } from '../../lib/strip-model-noise'
import { truncationNotice } from '../../lib/answer-notes'
+import { unbackedLinksNotice } from '../../lib/unbacked-links'
import { useAgentModeStore } from '../../stores/agentModeStore'
import { useChatStore } from '../../stores/chatStore'
import { useModelStore } from '../../stores/modelStore'
@@ -381,6 +382,16 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o
<span>{truncationNotice(message.finishReason)}</span>
</div>
)}
+ {/* Z36 finding 3: the model cited links no tool returned and
+ ignored the corrective steer. The answer stays untouched,
+ it is the model's text (G14-2); this labelled app notice
+ names the links that came from nowhere. */}
+ {unbackedLinksNotice(message.unbackedLinks) && (
+ <div className="mt-1 flex items-start gap-1 text-[0.6rem] text-amber-600/80 dark:text-amber-300/70">
+ <Unlink size={9} className="mt-0.5 shrink-0" />
+ <span>{unbackedLinksNotice(message.unbackedLinks)}</span>
+ </div>
+ )}
{/* A reasoning-only reply used to print a stand-in sentence
here ("The model only produced internal reasoning and no
answer"). That is our text in the model's mouth (G14-3,
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index a3f84f58..ce8d3d94 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -69,6 +69,7 @@ import { finalStripThinkingTags, splitOrphanCloser, splitUnclosedThink } from '.
import { openPlanGap, planReconcileSteer, PLAN_RECONCILE_BUDGET } from '../lib/plan-reconcile'
import { PlanStaleness, planStalenessSteer } from '../lib/plan-staleness'
import { reasoningOnlyRound, REASONING_CONTINUE_BUDGET, REASONING_CONTINUE_STEER } from '../lib/reasoning-round'
+import { findUnbackedLinks, unbackedLinksSteer } from '../lib/unbacked-links'
import { useTodoStore } from '../stores/todoStore'
import { platformPromptLine } from '../lib/host-platform'
import { httpStatusOf, isTerminalModelError, retryDelayMs } from '../lib/http-status'
@@ -637,6 +638,14 @@ export function useAgentChat() {
let mediaSynthesized = false
let forceNoThink = false
let dudRetried = false
+ // Z36 finding 3: one corrective steer for a final answer citing links no
+ // tool returned. A second offence keeps the model's text (G14-2) and
+ // flags the message instead, never a retry loop.
+ let linksSteered = false
+ // Arms the fabrication guard, exactly the Z36 trigger: it fired only once
+ // a REAL success sat in the history. Counts completed and cached calls
+ // after the D#81 media reclassification, so a failed render never arms it.
+ let anyToolSucceeded = false
// G16, parity with useCodex: a final turn that leaves the model's own todo
// list unfinished gets a bounded contradiction instead of ending the run.
let planReconcilesRemaining = PLAN_RECONCILE_BUDGET
@@ -1294,6 +1303,46 @@ export function useAgentChat() {
agentMessages.push({ role: 'user', content: REASONING_CONTINUE_STEER })
continue
}
+ // Z36 finding 3: with one real success in the history the model
+ // starts fabricating the next ones, confident links no tool ever
+ // returned. The G14 guards cover text the APP invents; this one
+ // catches the MODEL inventing, deterministically: a URL absent from
+ // everything the model was shown cannot have come from a tool. One
+ // steer to really search or retract; if it insists, the text stands
+ // (it is the model's answer, G14-2) and the bubble gets a labelled
+ // notice via unbackedLinks instead.
+ if (anyToolSucceeded && turnContent.trim()) {
+ const shownToModel = agentMessages
+ .map((m) => {
+ const c = (m as { content?: unknown }).content
+ if (typeof c === 'string') return c
+ if (Array.isArray(c)) {
+ return c
+ .map((p) => (p && typeof p === 'object' && 'text' in p ? String((p as { text?: unknown }).text ?? '') : ''))
+ .join('\n')
+ }
+ return ''
+ })
+ .join('\n')
+ const invented = findUnbackedLinks(turnContent, shownToModel)
+ if (invented.length > 0) {
+ if (!linksSteered) {
+ linksSteered = true
+ log.info('agent.unbacked_links_steer', { count: invented.length, links: invented })
+ agentMessages.push({ role: 'assistant', content: turnContent })
+ addBlock(convId!, assistantMessage.id, {
+ id: uuid(),
+ phase: 'reflection',
+ content: turnContent,
+ timestamp: Date.now(),
+ })
+ agentMessages.push({ role: 'user', content: unbackedLinksSteer(invented) })
+ continue
+ }
+ log.info('agent.unbacked_links_flagged', { count: invented.length, links: invented })
+ useChatStore.getState().updateMessageUnbackedLinks(convId!, assistantMessage.id, invented)
+ }
+ }
contentRef.current = turnContent
// G21-2: after tool activity the closing thought belongs in the
// block sequence too, in position before the final answer, not in
@@ -1534,6 +1583,7 @@ export function useAgentChat() {
const mediaOk = mediaCallSucceeded(entry.ac.toolName, entry.ac.result)
if (!mediaOk) entry.ac.status = 'failed'
if ((result.status === 'completed' || result.status === 'cached') && mediaOk) {
+ anyToolSucceeded = true
if (entry.ac.toolName === 'image_generate') imageGenDone++
else if (entry.ac.toolName === 'video_generate') videoGenDone++
}
diff --git a/src/lib/__tests__/unbacked-links.test.ts b/src/lib/__tests__/unbacked-links.test.ts
new file mode 100644
index 00000000..e2f23957
--- /dev/null
+++ b/src/lib/__tests__/unbacked-links.test.ts
@@ -0,0 +1,158 @@
+/**
+ * Z36 finding 3 (W3 run 2026-08-16): with one real tool success in the
+ * history the model fabricated the next ones, confident links no tool ever
+ * returned, and the G14 guards could not see it because the MODEL was the
+ * author, not the app. These tests lock the deterministic detector (a URL
+ * absent from everything the model was shown cannot come from a tool), the
+ * one-steer-then-flag contract in useAgentChat, and the labelled notice in
+ * the bubble. The negative controls pin the under-flagging bias: anything
+ * the model was actually shown is never called invented.
+ */
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { describe, it, expect } from 'vitest'
+import {
+ extractUrls,
+ normalizeUrl,
+ findUnbackedLinks,
+ unbackedLinksSteer,
+ unbackedLinksNotice,
+} from '../unbacked-links'
+
+describe('extractUrls', () => {
+ it('finds bare and markdown-wrapped http(s) URLs', () => {
+ const text =
+ 'See https://example.com/a and [docs](https://docs.example.org/guide) plus http://plain.io.'
+ expect(extractUrls(text)).toEqual([
+ 'https://example.com/a',
+ 'https://docs.example.org/guide',
+ 'http://plain.io',
+ ])
+ })
+
+ it('trims trailing sentence punctuation but keeps the path', () => {
+ expect(extractUrls('Read https://a.io/x/y?z=1, then stop.')).toEqual(['https://a.io/x/y?z=1'])
+ })
+
+ it('returns nothing for prose without URLs (negative control)', () => {
+ expect(extractUrls('no links here, just example.com mentioned barely')).toEqual([])
+ expect(extractUrls('')).toEqual([])
+ })
+})
+
+describe('normalizeUrl', () => {
+ it('drops protocol, www, fragment, one trailing slash, and lowercases', () => {
+ expect(normalizeUrl('HTTPS://WWW.Example.COM/Path/')).toBe('example.com/path')
+ expect(normalizeUrl('http://example.com/page#section')).toBe('example.com/page')
+ })
+
+ it('keeps the query string, a different query is a different resource', () => {
+ expect(normalizeUrl('https://a.io/s?q=1')).toBe('a.io/s?q=1')
+ })
+})
+
+describe('findUnbackedLinks', () => {
+ const toolResult = 'Search results:\n1. https://real-source.com/article (fetched)\nsome text'
+
+ it('flags a link that appears nowhere in the shown corpus', () => {
+ const answer = 'According to https://invented-news.com/story this is true.'
+ expect(findUnbackedLinks(answer, toolResult)).toEqual(['https://invented-news.com/story'])
+ })
+
+ it('NEGATIVE CONTROL: a link the tool really returned is never flagged', () => {
+ const answer = 'Source: https://real-source.com/article'
+ expect(findUnbackedLinks(answer, toolResult)).toEqual([])
+ })
+
+ it('NEGATIVE CONTROL: protocol, www, case and trailing-slash variants still count as backed', () => {
+ const answer = 'Source: http://WWW.Real-Source.com/Article/'
+ expect(findUnbackedLinks(answer, toolResult.toLowerCase())).toEqual([])
+ })
+
+ it('NEGATIVE CONTROL: a bare-domain mention in the corpus backs the https link in the answer', () => {
+ const answer = 'Docs: https://example.com/docs/setup'
+ const corpus = 'the readme says to open example.com/docs/setup in a browser'
+ expect(findUnbackedLinks(answer, corpus)).toEqual([])
+ })
+
+ it('deduplicates by normalized form and keeps the model spelling', () => {
+ const answer = 'See https://Fake.io/x and https://fake.io/x/ twice.'
+ expect(findUnbackedLinks(answer, 'nothing')).toEqual(['https://Fake.io/x'])
+ })
+
+ it('an answer without URLs never flags, whatever the corpus (negative control)', () => {
+ expect(findUnbackedLinks('all prose, no links', '')).toEqual([])
+ })
+
+ it('mixed answer: only the invented link is flagged, the backed one passes', () => {
+ const answer = 'Real: https://real-source.com/article, fake: https://made-up.net/page'
+ expect(findUnbackedLinks(answer, toolResult)).toEqual(['https://made-up.net/page'])
+ })
+})
+
+describe('unbackedLinksSteer', () => {
+ it('names every invented link and both honest ways out', () => {
+ const steer = unbackedLinksSteer(['https://a.io/1', 'https://b.io/2'])
+ expect(steer).toContain('https://a.io/1')
+ expect(steer).toContain('https://b.io/2')
+ expect(steer).toContain('call a tool')
+ expect(steer).toContain('rewrite your final answer')
+ })
+
+ it('singular wording for one link', () => {
+ expect(unbackedLinksSteer(['https://a.io/1'])).toContain('a link that no tool returned')
+ })
+})
+
+describe('unbackedLinksNotice', () => {
+ it('null when there is nothing to flag, so the bubble renders nothing (negative control)', () => {
+ expect(unbackedLinksNotice(undefined)).toBeNull()
+ expect(unbackedLinksNotice([])).toBeNull()
+ })
+
+ it('one link: singular sentence naming it without protocol', () => {
+ expect(unbackedLinksNotice(['https://fake.io/x'])).toBe(
+ 'This link came from the model, not from any tool result: fake.io/x'
+ )
+ })
+
+ it('many links: counts them, shows three, sums the rest', () => {
+ const notice = unbackedLinksNotice([
+ 'https://a.io/1',
+ 'https://b.io/2',
+ 'https://c.io/3',
+ 'https://d.io/4',
+ 'https://e.io/5',
+ ])
+ expect(notice).toContain('5 links came from the model')
+ expect(notice).toContain('a.io/1, b.io/2, c.io/3')
+ expect(notice).toContain('and 2 more')
+ expect(notice).not.toContain('d.io/4')
+ })
+})
+
+describe('wiring (source guards)', () => {
+ const agentSrc = readFileSync(join(__dirname, '../../hooks/useAgentChat.ts'), 'utf8')
+ const bubbleSrc = readFileSync(join(__dirname, '../../components/chat/MessageBubble.tsx'), 'utf8')
+ const storeSrc = readFileSync(join(__dirname, '../../stores/chatStore.ts'), 'utf8')
+
+ it('the agent loop runs the detector on the final turn and steers with it', () => {
+ expect(agentSrc).toContain('findUnbackedLinks(turnContent, shownToModel)')
+ expect(agentSrc).toContain('unbackedLinksSteer(invented)')
+ })
+
+ it('the guard only arms after a real success, the Z36 trigger', () => {
+ expect(agentSrc).toContain('anyToolSucceeded = true')
+ expect(agentSrc).toContain('if (anyToolSucceeded && turnContent.trim())')
+ })
+
+ it('the steer fires once, then the message is flagged instead of looped', () => {
+ expect(agentSrc).toContain('linksSteered = true')
+ expect(agentSrc).toContain('updateMessageUnbackedLinks(convId!, assistantMessage.id, invented)')
+ })
+
+ it('the store persists the flag and the bubble renders the labelled notice', () => {
+ expect(storeSrc).toContain('updateMessageUnbackedLinks: (conversationId, messageId, unbackedLinks) =>')
+ expect(bubbleSrc).toContain('unbackedLinksNotice(message.unbackedLinks)')
+ })
+})
diff --git a/src/lib/unbacked-links.ts b/src/lib/unbacked-links.ts
new file mode 100644
index 00000000..298caa0e
--- /dev/null
+++ b/src/lib/unbacked-links.ts
@@ -0,0 +1,97 @@
+/**
+ * Z36 finding 3 (W3 run 2026-08-16): once one real tool success sits in the
+ * run history, the model starts fabricating the next ones. It wrote confident
+ * final answers citing links no tool ever returned, without emitting a tool
+ * call. The G14 family guards text the APP invents; here the MODEL is the
+ * author, so the app has to notice it deterministically: a URL in the final
+ * answer that appears nowhere in what the model was shown (system prompt,
+ * history, tool results) cannot have come from a tool.
+ *
+ * Contract with useAgentChat: one corrective steer gives the model the chance
+ * to really search or to retract. If it insists, the answer stands untouched
+ * (it is the model's text, G14-2) and the bubble carries a labelled app
+ * notice naming the unverified links.
+ *
+ * Matching is biased towards under-flagging on purpose: a link only counts
+ * as invented when its normalized form (no protocol, no www, no fragment, no
+ * trailing slash, lowercased) is absent from the ENTIRE shown corpus as a
+ * substring. A tool result that mentions the bare domain path without a
+ * protocol therefore still backs the pretty https link in the answer.
+ */
+
+const URL_RE = /https?:\/\/[^\s<>"'`()[\]{}|\\^]+/gi
+
+/** Trailing sentence punctuation is prose, not part of the URL. */
+function trimTrailingPunctuation(url: string): string {
+ return url.replace(/[.,;:!?]+$/, '')
+}
+
+/** Every http(s) URL in the text, in order, trailing punctuation trimmed. */
+export function extractUrls(text: string): string[] {
+ if (!text) return []
+ const found = text.match(URL_RE) ?? []
+ return found.map(trimTrailingPunctuation).filter((u) => u.length > 0)
+}
+
+/** Comparison form: lowercased, protocol, leading www, fragment and one
+ * trailing slash removed. The query string stays, a different query is a
+ * different resource. */
+export function normalizeUrl(raw: string): string {
+ let u = trimTrailingPunctuation(raw.trim())
+ u = u.replace(/^https?:\/\//i, '')
+ u = u.replace(/^www\./i, '')
+ u = u.replace(/#.*$/, '')
+ if (u.endsWith('/')) u = u.slice(0, -1)
+ return u.toLowerCase()
+}
+
+/**
+ * URLs in `answer` that appear nowhere in `shownToModel` (the concatenated
+ * text of everything the model was shown this run). Returned in the exact
+ * spelling the model used, deduplicated by normalized form. Empty when the
+ * answer carries no URLs at all.
+ */
+export function findUnbackedLinks(answer: string, shownToModel: string): string[] {
+ const urls = extractUrls(answer)
+ if (urls.length === 0) return []
+ const corpus = (shownToModel ?? '').toLowerCase()
+ const seen = new Set<string>()
+ const out: string[] = []
+ for (const url of urls) {
+ const norm = normalizeUrl(url)
+ if (!norm || seen.has(norm)) continue
+ if (corpus.includes(norm)) continue
+ seen.add(norm)
+ out.push(url)
+ }
+ return out
+}
+
+/** The one corrective user turn. Direct, names every invented link, offers
+ * the two honest ways out (really search, or retract). */
+export function unbackedLinksSteer(links: string[]): string {
+ const list = links.join(', ')
+ const noun = links.length === 1 ? 'a link that no tool returned' : `${links.length} links that no tool returned`
+ const these = links.length === 1 ? 'this link' : 'these links'
+ return (
+ `Stop: your answer presents ${noun} in this run: ${list}. ` +
+ `You must not invent URLs or cite sources you did not actually open. ` +
+ `Either call a tool now to really find the source, or rewrite your final answer ` +
+ `without ${these} and say plainly which part is unverified.`
+ )
+}
+
+/** Badge label under the bubble once the steer was ignored. null when there
+ * is nothing to flag, so the caller renders nothing. */
+export function unbackedLinksNotice(links?: string[]): string | null {
+ if (!links || links.length === 0) return null
+ const shorten = (u: string) => {
+ const s = u.replace(/^https?:\/\//i, '')
+ return s.length > 60 ? s.slice(0, 57) + '...' : s
+ }
+ const shown = links.slice(0, 3).map(shorten).join(', ')
+ const more = links.length > 3 ? ` and ${links.length - 3} more` : ''
+ return links.length === 1
+ ? `This link came from the model, not from any tool result: ${shown}`
+ : `${links.length} links came from the model, not from any tool result: ${shown}${more}`
+}
diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.ts
index 92a0b806..53f3fb4e 100644
--- a/src/stores/chatStore.ts
+++ b/src/stores/chatStore.ts
@@ -50,6 +50,8 @@ interface ChatState {
updateMessageThinking: (conversationId: string, messageId: string, thinking: string) => void
updateMessageUsage: (conversationId: string, messageId: string, usage: { promptTokens: number; completionTokens: number; totalTokens: number; estimated?: boolean }) => void
updateMessageFinishReason: (conversationId: string, messageId: string, finishReason: string) => void
+ /** Z36 finding 3: links in the agent answer no tool returned. */
+ updateMessageUnbackedLinks: (conversationId: string, messageId: string, unbackedLinks: string[]) => void
updateMessageAgentBlocks: (conversationId: string, messageId: string, blocks: AgentBlock[]) => void
updateMessageArtifacts: (conversationId: string, messageId: string, artifacts: ChatArtifact[]) => void
deleteMessagesAfter: (conversationId: string, messageId: string) => void
@@ -284,6 +286,19 @@ export const useChatStore = create<ChatState>()(
),
})),
+ updateMessageUnbackedLinks: (conversationId, messageId, unbackedLinks) =>
+ set((state) => ({
+ conversations: state.conversations.map((c) =>
+ c.id === conversationId
+ ? {
+ ...c,
+ messages: c.messages.map((m) => (m.id === messageId ? { ...m, unbackedLinks } : m)),
+ updatedAt: Date.now(),
+ }
+ : c
+ ),
+ })),
+
updateMessageAgentBlocks: (conversationId, messageId, agentBlocks) =>
set((state) => ({
conversations: state.conversations.map((c) =>
diff --git a/src/types/chat.ts b/src/types/chat.ts
index 1b7059f7..0792c44d 100644
--- a/src/types/chat.ts
+++ b/src/types/chat.ts
@@ -84,6 +84,12 @@ export interface Message {
* a truncated answer is not shown as if it were complete (parity with the
* benchmark screen). Absent or 'stop' on a clean finish. */
finishReason?: string
+ /** Z36 finding 3: URLs in this agent answer that appear nowhere in what the
+ * model was shown this run (system prompt, history, tool results), so no
+ * tool returned them. Set only after the one corrective steer was ignored.
+ * Drives a labelled notice under the bubble instead of rewriting the
+ * model's text (G14-2). Absent when every link was backed. */
+ unbackedLinks?: string[]
}
export interface Conversation {