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(memory): a brace in the model's prose threw away the whole answer
purplec1f1c78b54ab
diff --git a/src/lib/__tests__/memory-extraction.test.ts b/src/lib/__tests__/memory-extraction.test.tsindex 0d4326a2..2e98d038 100644--- a/src/lib/__tests__/memory-extraction.test.ts+++ b/src/lib/__tests__/memory-extraction.test.ts@@ -260,3 +260,44 @@ describe('parseResolutionResponse', () => {expect(parseResolutionResponse('{"foo": "bar"}')).toEqual({ action: 'ADD' })})})++// ── JSON extraction from chatty model output (2026-07-28) ────────────+//+// The old greedy /\{[\s\S]*\}/ spanned from the FIRST brace to the LAST one,+// so any brace in the surrounding prose swallowed the real object and the+// parse threw. The two callers then failed in opposite, silent ways:+// extraction saved nothing, resolution added a duplicate instead of merging.+describe('parsers survive prose around the JSON', () => {+ it('extracts the object when prose before it contains braces', () => {+ const res = parseExtractionResponse(+ 'Here is the analysis {see below}:\n{"shouldSave": true, "memories": [' ++ '{"type": "user", "title": "Runs Arch", "content": "The user runs Arch Linux."}]}',+ )+ expect(res.shouldSave).toBe(true)+ expect(res.memories[0].title).toBe('Runs Arch')+ })++ it('extracts the object when prose follows it', () => {+ const res = parseExtractionResponse(+ '{"shouldSave": true, "memories": [{"type": "project", "title": "LU", "content": "Ships 2.6.0 on Friday."}]}\n' ++ 'Let me know if you want {more detail}.',+ )+ expect(res.memories).toHaveLength(1)+ expect(res.memories[0].type).toBe('project')+ })++ it('still resolves UPDATE when the answer is wrapped in prose', () => {+ const decision = parseResolutionResponse(+ 'Thinking {step 1}: this is the same fact.\n' ++ '{"action": "UPDATE", "targetId": "m1", "mergedContent": "merged text"}',+ ['m1'],+ )+ expect(decision.action).toBe('UPDATE')+ expect(decision.targetId).toBe('m1')+ })++ it('keeps returning the fallback when there is no JSON at all', () => {+ expect(parseExtractionResponse('nothing to remember here').shouldSave).toBe(false)+ expect(parseResolutionResponse('no idea {really}').action).toBe('ADD')+ })+})diff --git a/src/lib/memory-extraction.ts b/src/lib/memory-extraction.tsindex c991cceb..a76b991d 100644--- a/src/lib/memory-extraction.ts+++ b/src/lib/memory-extraction.ts@@ -75,6 +75,45 @@ Analyze this exchange. What (if anything) should be remembered?`* Parse the LLM's extraction response. Handles models that wrap JSON in* markdown code blocks or add preamble text.*/+/**+ * First balanced JSON object in `text` that actually parses.+ *+ * The old `/\{[\s\S]*\}/` was greedy: it spanned from the FIRST brace to the+ * LAST one, so a single brace in the model's prose ("Here is the analysis+ * {see below}: {...}") swallowed the real object and JSON.parse threw. Small+ * local models wrap their JSON in prose constantly, and the two callers fail+ * in opposite, silent ways — extraction saves nothing, resolution adds a+ * duplicate instead of merging. Walking the braces (string- and escape-aware)+ * finds the real object regardless of what surrounds it.+ */+function extractJsonObject(text: string): any | null {+ for (let i = 0; i < text.length; i++) {+ if (text[i] !== '{') continue+ let depth = 0+ let inString = false+ let escaped = false+ for (let j = i; j < text.length; j++) {+ const ch = text[j]+ if (escaped) { escaped = false; continue }+ if (ch === '\\') { escaped = inString; continue }+ if (ch === '"') { inString = !inString; continue }+ if (inString) continue+ if (ch === '{') depth+++ else if (ch === '}') {+ depth--+ if (depth === 0) {+ try {+ return JSON.parse(text.slice(i, j + 1))+ } catch {+ break // not the object we want — try the next opening brace+ }+ }+ }+ }+ }+ return null+}+export function parseExtractionResponse(response: string): ExtractionResult {const fallback: ExtractionResult = { shouldSave: false, memories: [] }@@ -89,10 +128,8 @@ export function parseExtractionResponse(response: string): ExtractionResult {}// Try to find JSON object in the response- const jsonMatch = jsonStr.match(/\{[\s\S]*\}/)- if (!jsonMatch) return fallback-- const data = JSON.parse(jsonMatch[0])+ const data = extractJsonObject(jsonStr)+ if (!data || typeof data !== 'object') return fallbackif (typeof data.shouldSave !== 'boolean') return fallbackif (!data.shouldSave) return { shouldSave: false, memories: [] }@@ -212,10 +249,8 @@ export function parseResolutionResponse(const codeBlockMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/)if (codeBlockMatch) jsonStr = codeBlockMatch[1].trim()- const jsonMatch = jsonStr.match(/\{[\s\S]*\}/)- if (!jsonMatch) return fallback-- const data = JSON.parse(jsonMatch[0])+ const data = extractJsonObject(jsonStr)+ if (!data || typeof data !== 'object') return fallbackconst action = typeof data.action === 'string' ? data.action.toUpperCase() : ''if (action === 'NOOP') return { action: 'NOOP' }