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
tech(M-any): `src/lib` und `src/stores` typisieren (178 `any` raus, 4 echte Fehler)
David1ea409cda025
diff --git a/src/lib/__tests__/app-identity.test.ts b/src/lib/__tests__/app-identity.test.tsindex 92fe4c90..d011fe43 100644--- a/src/lib/__tests__/app-identity.test.ts+++ b/src/lib/__tests__/app-identity.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest'-import { readFileSync } from 'node:fs'+import { readdirSync, readFileSync } from 'node:fs'import { resolve } from 'node:path'import {AGENT_WORKSPACE_DIR,diff --git a/src/lib/__tests__/benchmark-run.test.ts b/src/lib/__tests__/benchmark-run.test.tsindex 7c8e47c7..cc21d776 100644--- a/src/lib/__tests__/benchmark-run.test.ts+++ b/src/lib/__tests__/benchmark-run.test.ts@@ -117,7 +117,7 @@ describe('measureRun', () => {// stream produces no tokens.describe('the wall clock reaches a stream that has stopped sending', () => {/** A stream that yields one chunk and then never resolves again. */- function stalling(): AsyncIterable<any> {+ function stalling(): AsyncIterable<ChatStreamChunk> {let served = falsereturn {[Symbol.asyncIterator]() {@@ -125,7 +125,7 @@ describe('the wall clock reaches a stream that has stopped sending', () => {next() {if (!served) {served = true- return Promise.resolve({ done: false, value: { content: 'hi' } })+ return Promise.resolve({ done: false, value: { content: 'hi', done: false } })}return new Promise<never>(() => { /* the stall */ })},@@ -150,7 +150,7 @@ describe('the wall clock reaches a stream that has stopped sending', () => {it('closes the generator so the model is not left generating', async () => {let closed = false- const stream: AsyncIterable<any> = {+ const stream: AsyncIterable<ChatStreamChunk> = {[Symbol.asyncIterator]() {return {next() { return new Promise<never>(() => {}) },diff --git a/src/lib/__tests__/chatbot-export.test.ts b/src/lib/__tests__/chatbot-export.test.tsindex d24bf5cc..cf25c9c6 100644--- a/src/lib/__tests__/chatbot-export.test.ts+++ b/src/lib/__tests__/chatbot-export.test.ts@@ -190,6 +190,48 @@ describe('parseJsonText — Gemini', () => {expect(c.markdown).toContain('**You**')expect(c.markdown).toContain('**Assistant**')})++ // Fehler 1: Gemini-Takeout-Turns, deren Text in `content` als Blockarray+ // liegt, wurden mit String(...) zu "[object Object]" verkocht und genau so+ // importiert — der echte Gesprächstext war weg, im RAG-Index stand pro Zug+ // eine Zeile "[object Object]".+ it('reads Gemini message text out of a content[] block array instead of stringifying it', () => {+ const raw = JSON.stringify([+ {+ header: 'Gemini Apps',+ title: 'Explain black holes',+ time: '2026-03-01T10:00:00Z',+ messages: [+ { role: 'user', content: [{ text: 'What is a black hole?' }] },+ { role: 'model', content: [{ text: 'A region where gravity wins.' }] },+ ],+ },+ ])+ const c = parseJsonText(raw).conversations[0]+ expect(c.markdown).not.toContain('[object Object]')+ expect(c.markdown).toContain('What is a black hole?')+ expect(c.markdown).toContain('A region where gravity wins.')+ expect(c.messageCount).toBe(2)+ })++ it('never emits [object Object] for a content field it cannot read', () => {+ const raw = JSON.stringify([+ {+ header: 'Gemini Apps',+ title: 'Only a prompt',+ messages: [{ role: 'user', content: { parts: { nested: true } } }],+ },+ ])+ const md = parseJsonText(raw).conversations.map(c => c.markdown).join('\n')+ expect(md).not.toContain('[object Object]')+ })++ it('still reads the flat string content shape', () => {+ const raw = JSON.stringify([+ { header: 'Gemini Apps', title: 'Flat', messages: [{ role: 'user', content: 'plain text turn' }] },+ ])+ expect(parseJsonText(raw).conversations[0].markdown).toContain('plain text turn')+ })})describe('parseJsonText — robustness', () => {diff --git a/src/lib/__tests__/idbStorage-retry.test.ts b/src/lib/__tests__/idbStorage-retry.test.tsindex 32e1bd97..fd31d03c 100644--- a/src/lib/__tests__/idbStorage-retry.test.ts+++ b/src/lib/__tests__/idbStorage-retry.test.ts@@ -15,8 +15,9 @@ type OpenReq = {onerror: (() => void) | nullonblocked: (() => void) | nullonupgradeneeded: (() => void) | null- result: any- error: any+ /** The opened database — a stand-in for IDBDatabase, only what idbStorage reads. */+ result: unknown+ error: unknown}/** Minimal fake IDB: `failures` opens reject, everything after succeeds. */@@ -28,7 +29,8 @@ function fakeIndexedDB(failures: number, data: Record<string, string>) {transaction: () => ({objectStore: () => ({get: (k: string) => {- const r: any = { onsuccess: null, onerror: null, result: data[k] }+ const r: { onsuccess: (() => void) | null; onerror: (() => void) | null; result: string | undefined } =+ { onsuccess: null, onerror: null, result: data[k] }queueMicrotask(() => r.onsuccess?.())return r},diff --git a/src/lib/__tests__/idbStorage.test.ts b/src/lib/__tests__/idbStorage.test.tsindex 107576f7..d7e5907d 100644--- a/src/lib/__tests__/idbStorage.test.ts+++ b/src/lib/__tests__/idbStorage.test.ts@@ -1,5 +1,6 @@import { describe, it, expect, vi, afterEach } from 'vitest'import { idbStorage } from '../idbStorage'+import { prop } from '../../types/json-guards'// The vitest env is `node`: no `indexedDB`, so idbStorage takes its SYNC// localStorage fallback. That sync path is exactly what keeps Zustand@@ -19,7 +20,7 @@ function mockLS(init: Record<string, string> = {}): Storage {describe('idbStorage (no-IndexedDB fallback path)', () => {afterEach(() => {- try { delete (globalThis as any).localStorage } catch { /* ignore */ }+ try { Reflect.deleteProperty(globalThis, 'localStorage') } catch { /* ignore */ }})it('round-trips via localStorage SYNCHRONOUSLY (no Promise) when idb is absent', () => {@@ -29,7 +30,7 @@ describe('idbStorage (no-IndexedDB fallback path)', () => {expect(setResult).toBeUndefined()const got = idbStorage.getItem('chat-conversations')expect(got).toBe('{"state":{"conversations":[]}}')- expect(typeof (got as any)?.then).not.toBe('function') // sync string, not a thenable+ expect(typeof prop(got, 'then')).not.toBe('function') // sync string, not a thenableidbStorage.removeItem('chat-conversations')expect(idbStorage.getItem('chat-conversations')).toBeNull()})diff --git a/src/lib/__tests__/local-media-url.test.ts b/src/lib/__tests__/local-media-url.test.tsindex 1c625d88..ed891893 100644--- a/src/lib/__tests__/local-media-url.test.ts+++ b/src/lib/__tests__/local-media-url.test.ts@@ -19,7 +19,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'const backendCall = vi.fn()vi.mock('../../api/backend', () => ({- backendCall: (...args: any[]) => backendCall(...args),+ backendCall: (...args: unknown[]) => backendCall(...args),}))const { pathToFileUrl, fileUrlToPath, guessMimeFromName, readLocalFileAsBlobUrl } =@@ -81,14 +81,18 @@ describe('readLocalFileAsBlobUrl', () => {backendCall.mockResolvedValue(btoa('fake-bytes'))const created: { type: string }[] = []const origCreate = URL.createObjectURL- ;(URL as any).createObjectURL = (b: Blob) => { created.push({ type: b.type }); return 'blob:made' }+ // defineProperty rather than an assignment through a cast: `value` is+ // untyped, so the stub goes in without claiming to be the real overload.+ const setCreate = (fn: unknown) =>+ Object.defineProperty(URL, 'createObjectURL', { value: fn, configurable: true, writable: true })+ setCreate((b: Blob) => { created.push({ type: b.type }); return 'blob:made' })try {const url = await readLocalFileAsBlobUrl('/tmp/clip.mp4')expect(backendCall).toHaveBeenCalledWith('read_media_file', { path: '/tmp/clip.mp4' })expect(url).toBe('blob:made')expect(created[0].type).toBe('video/mp4')} finally {- ;(URL as any).createObjectURL = origCreate+ setCreate(origCreate)}})diff --git a/src/lib/__tests__/loose-tool-parse.test.ts b/src/lib/__tests__/loose-tool-parse.test.tsindex 712dffab..b04c7db2 100644--- a/src/lib/__tests__/loose-tool-parse.test.ts+++ b/src/lib/__tests__/loose-tool-parse.test.ts@@ -272,6 +272,17 @@ describe('parseLooseToolCalls — nested function object + string args (OpenAI/Pexpect(r.calls[0]).toEqual({ name: 'file_write', arguments: { path: 'a.txt', content: 'hi' } })})+ // Fehler 3: derselbe String-Argumente-Fall, aber ueber die HERMES-Schiene.+ // parseJsonObjectCalls hat die JSON-Zeichenkette selbst repariert, der+ // <tool_call>-Pfad nicht — dort ging `arguments` als STRING an den Executor,+ // der `args.path` liest. Ergebnis: "path is required", obwohl das Modell den+ // Pfad geschickt hatte, und der Agent probierte denselben Aufruf erneut.+ it('repairs string args that arrive inside a <tool_call> tag', () => {+ const txt = '<tool_call>{"name": "file_write", "arguments": "{\\"path\\": \\"a.txt\\", \\"content\\": \\"hi\\"}"}</tool_call>'+ const r = parseLooseToolCalls(txt, KN)+ expect(r.calls[0]).toEqual({ name: 'file_write', arguments: { path: 'a.txt', content: 'hi' } })+ })+it('accepts the name carried by a tool_call key', () => {const txt = '{"tool_call": "image_generate", "arguments": {"prompt": "y"}}'const r = parseLooseToolCalls(txt, KN)diff --git a/src/lib/__tests__/ollama-stream-tools-errors.test.ts b/src/lib/__tests__/ollama-stream-tools-errors.test.tsindex 9a59bb0d..6dc10657 100644--- a/src/lib/__tests__/ollama-stream-tools-errors.test.ts+++ b/src/lib/__tests__/ollama-stream-tools-errors.test.ts@@ -62,6 +62,42 @@ describe('streamOllamaChatWithTools — NDJSON error lines', () => {expect(turn.evalCount).toBe(7)})+ // Fehler 2: ein tool_calls-Eintrag ohne `function`-Huelle liess+ // `tc.function.arguments` werfen. Der TypeError entstand in der NDJSON-+ // Schleife, ausserhalb des try, das nur JSON.parse abdeckt — er ist also aus+ // dem ganzen Stream-Aufruf herausgeflogen und hat den Agentenzug samt aller+ // bereits gestreamten Tokens mitgenommen.+ it('survives a tool_calls entry with no function wrapper and keeps the streamed content', async () => {+ mockStream.mockResolvedValueOnce(new Response(+ '{"message":{"content":"here you go","tool_calls":[{"id":"call_1","name":"file_read","arguments":{"path":"a.txt"}}]}}\n' ++ '{"done":true}\n',+ { status: 200 },+ ))+ const turn = await run()+ expect(turn.content).toBe('here you go')+ expect(turn.toolCalls).toEqual([])+ })++ it('keeps the well-formed calls of a chunk that also carries a broken one', async () => {+ mockStream.mockResolvedValueOnce(new Response(+ '{"message":{"tool_calls":[' ++ '{"id":"call_1"},' ++ '{"function":{"name":"web_search","arguments":{"query":"x"}}}' ++ ']}}\n',+ { status: 200 },+ ))+ const turn = await run()+ expect(turn.toolCalls.map(c => c.function.name)).toEqual(['web_search'])+ })++ it('drops a nameless tool call instead of dispatching `undefined`', async () => {+ mockStream.mockResolvedValueOnce(new Response(+ '{"message":{"tool_calls":[{"function":{"arguments":{"query":"x"}}}]}}\n',+ { status: 200 },+ ))+ expect((await run()).toolCalls).toEqual([])+ })+it('skips partial JSON lines without dying', async () => {mockStream.mockResolvedValueOnce(new Response('{"message":{"content":"ok"}}\n{"mess\n',diff --git a/src/lib/__tests__/prefix-stability.test.ts b/src/lib/__tests__/prefix-stability.test.tsindex 50c7c5eb..d345add6 100644--- a/src/lib/__tests__/prefix-stability.test.ts+++ b/src/lib/__tests__/prefix-stability.test.ts@@ -16,6 +16,7 @@ import { readFileSync } from 'fs'import { resolve } from 'path'import { hostClockLine, hostEnvironmentBlock, platformPromptLine } from '../host-platform'import { pruneSupersededPlans, buildRequestMessages, SUPERSEDED_PLAN_NOTE, type DecayMessage } from '../context-decay'+import type { ToolCall } from '../../api/providers/types'const src = (...p: string[]) => readFileSync(resolve(__dirname, '..', '..', ...p), 'utf8')@@ -91,7 +92,7 @@ function planHistory(n: number, mixed = false): DecayMessage[] {{ role: 'user', content: 'build it' },]for (let i = 1; i <= n; i++) {- const calls: any[] = [{ id: `t${i}`, function: { name: 'todo_write', arguments: { todos: [`step ${i}`] } } }]+ const calls: ToolCall[] = [{ id: `t${i}`, function: { name: 'todo_write', arguments: { todos: [`step ${i}`] } } }]if (mixed) calls.push({ id: `r${i}`, function: { name: 'file_read', arguments: { path: 'a.ts' } } })out.push({ role: 'assistant', content: '', tool_calls: calls })out.push({ role: 'tool', content: `plan v${i}: ${'item '.repeat(200)}`, tool_call_id: `t${i}` })diff --git a/src/lib/__tests__/staged-apply-crlf.test.ts b/src/lib/__tests__/staged-apply-crlf.test.tsindex 40b7b437..43bae956 100644--- a/src/lib/__tests__/staged-apply-crlf.test.ts+++ b/src/lib/__tests__/staged-apply-crlf.test.ts@@ -40,10 +40,10 @@ const CHAT = 'chat-crlf'/** Route fs_read to the file on disk, fs_write to a recorder. */function onDisk(content: string) {const written: string[] = []- call.mockImplementation(async (cmd: string, args: any) => {+ call.mockImplementation(async (cmd: string, args: Record<string, unknown>) => {if (cmd === 'fs_read') return { content }if (cmd === 'fs_write') {- written.push(args.content)+ written.push(String(args.content))return { status: 'saved', path: args.path }}return nulldiff --git a/src/lib/__tests__/storage-quota.test.ts b/src/lib/__tests__/storage-quota.test.tsindex 4cd9d384..6f887ee1 100644--- a/src/lib/__tests__/storage-quota.test.ts+++ b/src/lib/__tests__/storage-quota.test.ts@@ -1,6 +1,21 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import { createJSONStorage } from 'zustand/middleware'import { getStorageUsage, createSafeStorage } from '../storage-quota'+import { prop, propPath, asString } from '../../types/json-guards'++/**+ * The ids of a pruned list, read back out of the JSON the adapter wrote. The+ * blob is deliberately handled as foreign data here — that is exactly the+ * position production is in when it reads it again.+ */+function idsOf(list: unknown): string[] {+ return Array.isArray(list) ? list.map((e) => asString(prop(e, 'id')) ?? '') : []+}++/** Element `i` of a value that may or may not be an array. */+function at(list: unknown, i: number): unknown {+ return Array.isArray(list) ? list[i] : undefined+}// Mock localStorage for testsfunction createMockStorage(items: Record<string, string> = {}): Storage {@@ -264,7 +279,7 @@ describe('storage-quota', () => {const parsed = JSON.parse(writeCalls[0][1])expect(parsed.state.conversations.length).toBeLessThanOrEqual(100)// Newest conversations should be kept (highest updatedAt)- const ids = parsed.state.conversations.map((c: any) => c.id)+ const ids = idsOf(parsed.state.conversations)expect(ids).toContain('c-119')expect(ids).toContain('c-119')}@@ -356,7 +371,7 @@ describe('storage-quota', () => {const pruned = JSON.parse(memWrites[memWrites.length - 1][1])expect(pruned.state.entries.length).toBeLessThanOrEqual(500)// …keeping the newest entries (highest updatedAt) and dropping the oldest.- const ids: string[] = pruned.state.entries.map((e: any) => e.id)+ const ids: string[] = idsOf(pruned.state.entries)expect(ids).toContain('m-599')expect(ids).not.toContain('m-0')// The target write eventually landed.@@ -392,7 +407,7 @@ describe('storage-quota', () => {const memWrites = (mock.setItem as ReturnType<typeof vi.fn>).mock.calls.filter(([k]) => k === 'locally-uncensored-memory')const pruned = JSON.parse(memWrites[memWrites.length - 1][1])- const ids: string[] = pruned.state.entries.map((e: any) => e.id)+ const ids: string[] = idsOf(pruned.state.entries)// The stale newest entry is the one dropped to get to 500.expect(pruned.state.entries.length).toBe(500)expect(ids).not.toContain('m-0')@@ -412,7 +427,7 @@ describe('storage-quota', () => {})const wrapped = createJSONStorage(() => createSafeStorage())!const value = { state: { conversations: [{ id: 'c1', title: 'hi' }] }, version: 0 }- wrapped.setItem('chat-conversations', value as any)+ wrapped.setItem('chat-conversations', value)const raw = globalThis.localStorage.getItem('chat-conversations')expect(raw).not.toBe('[object Object]')@@ -420,8 +435,8 @@ describe('storage-quota', () => {const parsed = JSON.parse(raw as string)expect(parsed.state.conversations[0].id).toBe('c1')// And getItem hydrates back to the original object (what zustand needs).- const readBack = wrapped.getItem('chat-conversations') as any- expect(readBack?.state?.conversations?.[0]?.title).toBe('hi')+ const readBack = wrapped.getItem('chat-conversations')+ expect(at(propPath(readBack, 'state', 'conversations'), 0)).toMatchObject({ title: 'hi' })})it('dispatches lu:storage-quota-exceeded once when pruning cannot free space', () => {@@ -430,13 +445,13 @@ describe('storage-quota', () => {// The vitest env is `node`, so there's no real `window`; install a// minimal stub that records dispatched events. The production guard// (`typeof window !== 'undefined'`) then takes the dispatch path.- const dispatched: any[] = []+ const dispatched: Event[] = []const fakeWindow = {- dispatchEvent: vi.fn((e: any) => { dispatched.push(e); return true }),+ dispatchEvent: vi.fn((e: Event) => { dispatched.push(e); return true }),}const hadWindow = 'window' in globalThis- const prevWindow = (globalThis as any).window- ;(globalThis as any).window = fakeWindow+ const prevWindow: unknown = Reflect.get(globalThis, 'window')+ Object.defineProperty(globalThis, 'window', { value: fakeWindow, writable: true, configurable: true })const quotaErr = new DOMException('full', 'QuotaExceededError')const store: Record<string, string> = {}@@ -457,11 +472,11 @@ describe('storage-quota', () => {expect(fakeWindow.dispatchEvent).toHaveBeenCalledTimes(1)expect(dispatched).toHaveLength(1)expect(dispatched[0].type).toBe('lu:storage-quota-exceeded')- expect(dispatched[0].detail).toEqual({ key: 'doomed' })+ expect(prop(dispatched[0], 'detail')).toEqual({ key: 'doomed' })} finally {warnSpy.mockRestore()- if (hadWindow) (globalThis as any).window = prevWindow- else delete (globalThis as any).window+ if (hadWindow) Object.defineProperty(globalThis, 'window', { value: prevWindow, writable: true, configurable: true })+ else Reflect.deleteProperty(globalThis, 'window')}})})diff --git a/src/lib/__tests__/systemCheck.test.ts b/src/lib/__tests__/systemCheck.test.tsindex 625d43ed..b57f3671 100644--- a/src/lib/__tests__/systemCheck.test.ts+++ b/src/lib/__tests__/systemCheck.test.ts@@ -2,13 +2,18 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'// Provide minimal DOM mocks for node environment before importing// systemCheck.ts needs `document.createElement('canvas')` and `navigator.deviceMemory`+// `defineProperty` rather than an assignment through a cast: its descriptor+// `value` is untyped in lib.dom, so the stub goes in without claiming to BE a+// Document or a Navigator — which it is not, and does not need to be.if (typeof document === 'undefined') {- (globalThis as any).document = {- createElement: () => ({ getContext: () => null }),- }+ Object.defineProperty(globalThis, 'document', {+ value: { createElement: () => ({ getContext: () => null }) },+ configurable: true,+ writable: true,+ })}if (typeof navigator === 'undefined') {- (globalThis as any).navigator = {}+ Object.defineProperty(globalThis, 'navigator', { value: {}, configurable: true, writable: true })}import { getRecommendations, detectSystem } from '../systemCheck'@@ -139,14 +144,34 @@ describe('systemCheck', () => {// ─── detectSystem ───describe('detectSystem', () => {- let originalCreateElement: any+ /** What detectSystem actually pulls out of a WebGL context. */+ interface StubGL {+ getExtension: (name?: string) => { UNMASKED_RENDERER_WEBGL: number } | null+ getParameter?: (p?: number) => string+ }++ /** Swap `document.createElement` for one that hands back a canvas-like+ * object whose getContext returns `gl` (or null for "no WebGL"). */+ const withGL = (gl: StubGL | null) => {+ Object.defineProperty(document, 'createElement', {+ value: () => ({ getContext: () => gl }),+ configurable: true,+ writable: true,+ })+ }++ let originalCreateElement: typeof document.createElementbeforeEach(() => {originalCreateElement = document.createElement})afterEach(() => {- (document as any).createElement = originalCreateElement+ Object.defineProperty(document, 'createElement', {+ value: originalCreateElement,+ configurable: true,+ writable: true,+ })})it('returns a SystemInfo object with expected fields', () => {@@ -160,20 +185,20 @@ describe('systemCheck', () => {it('tier is low when RAM <= 4GB and no GPU', () => {Object.defineProperty(navigator, 'deviceMemory', { value: 4, writable: true, configurable: true })- ;(document as any).createElement = () => ({ getContext: () => null })+ withGL(null)const info = detectSystem()expect(info.tier).toBe('low')})it('tier is high when RAM >= 16GB and no GPU', () => {Object.defineProperty(navigator, 'deviceMemory', { value: 16, writable: true, configurable: true })- ;(document as any).createElement = () => ({ getContext: () => null })+ withGL(null)const info = detectSystem()expect(['medium', 'high']).toContain(info.tier)})it('estimatedVRAM is "Unknown" when no WebGL', () => {- ;(document as any).createElement = () => ({ getContext: () => null })+ withGL(null)const info = detectSystem()expect(info.estimatedVRAM).toBe('Unknown')})@@ -183,7 +208,7 @@ describe('systemCheck', () => {getExtension: () => ({ UNMASKED_RENDERER_WEBGL: 0x9246 }),getParameter: () => 'NVIDIA GeForce RTX 4090',}- ;(document as any).createElement = () => ({ getContext: () => mockGL })+ withGL(mockGL)const info = detectSystem()expect(info.estimatedVRAM).toContain('24')expect(info.tier).toBe('high')@@ -195,7 +220,7 @@ describe('systemCheck', () => {getExtension: () => ({ UNMASKED_RENDERER_WEBGL: 0x9246 }),getParameter: () => 'NVIDIA GeForce RTX 3060',}- ;(document as any).createElement = () => ({ getContext: () => mockGL })+ withGL(mockGL)const info = detectSystem()expect(info.estimatedVRAM).toContain('8')})@@ -206,7 +231,7 @@ describe('systemCheck', () => {getExtension: () => ({ UNMASKED_RENDERER_WEBGL: 0x9246 }),getParameter: () => 'Intel UHD Graphics 630',}- ;(document as any).createElement = () => ({ getContext: () => mockGL })+ withGL(mockGL)const info = detectSystem()expect(info.estimatedVRAM).toContain('integrated')expect(info.tier).toBe('low')@@ -218,14 +243,14 @@ describe('systemCheck', () => {getExtension: () => ({ UNMASKED_RENDERER_WEBGL: 0x9246 }),getParameter: () => 'Apple M1',}- ;(document as any).createElement = () => ({ getContext: () => mockGL })+ withGL(mockGL)const info = detectSystem()expect(info.estimatedVRAM).toContain('shared')})it('handles WebGL getExtension returning null', () => {const mockGL = { getExtension: () => null }- ;(document as any).createElement = () => ({ getContext: () => mockGL })+ withGL(mockGL)const info = detectSystem()expect(info.gpuRenderer).toBeNull()expect(info.estimatedVRAM).toBe('Unknown')@@ -236,7 +261,7 @@ describe('systemCheck', () => {getExtension: () => ({ UNMASKED_RENDERER_WEBGL: 0x9246 }),getParameter: () => 'NVIDIA GeForce RTX 3080',}- ;(document as any).createElement = () => ({ getContext: () => mockGL })+ withGL(mockGL)Object.defineProperty(navigator, 'deviceMemory', { value: 16, writable: true, configurable: true })const info = detectSystem()expect(info.estimatedVRAM).toContain('16')@@ -248,7 +273,7 @@ describe('systemCheck', () => {getExtension: () => ({ UNMASKED_RENDERER_WEBGL: 0x9246 }),getParameter: () => 'NVIDIA GeForce GTX 1060',}- ;(document as any).createElement = () => ({ getContext: () => mockGL })+ withGL(mockGL)Object.defineProperty(navigator, 'deviceMemory', { value: 8, writable: true, configurable: true })const info = detectSystem()expect(info.estimatedVRAM).toContain('8')@@ -259,7 +284,7 @@ describe('systemCheck', () => {getExtension: () => ({ UNMASKED_RENDERER_WEBGL: 0x9246 }),getParameter: () => 'AMD Radeon RX 7900 XTX',}- ;(document as any).createElement = () => ({ getContext: () => mockGL })+ withGL(mockGL)const info = detectSystem()expect(info.gpuRenderer).toBe('AMD Radeon RX 7900 XTX')})diff --git a/src/lib/__tests__/tool-call-groups.test.ts b/src/lib/__tests__/tool-call-groups.test.tsindex a3197640..4d854d0f 100644--- a/src/lib/__tests__/tool-call-groups.test.ts+++ b/src/lib/__tests__/tool-call-groups.test.ts@@ -5,8 +5,21 @@ import {activeToolCall,groupDurationLabel,} from '../tool-call-groups'+import type { AgentBlockGroup, BandNote } from '../tool-call-groups'import type { AgentBlock, AgentToolCall } from '../../types/agent-mode'+// The group union is discriminated by `kind`; these narrow it and say so out+// loud when a test's premise is wrong. The `as any` they replace let a test+// read `.calls` off a 'single' group and compare undefined against undefined.+function asBand(g: AgentBlockGroup): Extract<AgentBlockGroup, { kind: 'tools' }> {+ if (g.kind !== 'tools') throw new Error(`expected a tools band, got kind=${g.kind}`)+ return g+}+function asSingle(g: AgentBlockGroup): Extract<AgentBlockGroup, { kind: 'single' }> {+ if (g.kind !== 'single') throw new Error(`expected a single block, got kind=${g.kind}`)+ return g+}+let ts = 0function call(name: string, status: AgentToolCall['status'], duration?: number): AgentToolCall {return { id: `c-${++ts}`, toolName: name, args: {}, status, duration, timestamp: ts }@@ -25,7 +38,7 @@ describe('groupAgentBlocks', () => {const groups = groupAgentBlocks([a, b])expect(groups).toHaveLength(1)expect(groups[0].kind).toBe('tools')- expect((groups[0] as any).calls.map((c: AgentToolCall) => c.toolName)).toEqual(['file_read', 'file_write'])+ expect(asBand(groups[0]).calls.map((c) => c.toolName)).toEqual(['file_read', 'file_write'])})// G14-4 (David 2026-08-07): this test used to assert the OPPOSITE, that an@@ -40,7 +53,7 @@ describe('groupAgentBlocks', () => {const t3 = toolBlock(call('shell_execute', 'completed'))const groups = groupAgentBlocks([t1, ans, t2, t3])expect(groups.map(g => g.kind)).toEqual(['tools'])- const band = groups[0] as any+ const band = asBand(groups[0])expect(band.calls).toHaveLength(3)expect(band.notes).toEqual([{ afterCall: 0, block: ans }])})@@ -53,7 +66,7 @@ describe('groupAgentBlocks', () => {const fin = answerBlock('All done, results above.')const groups = groupAgentBlocks([t1, t2, fin])expect(groups.map(g => g.kind)).toEqual(['tools', 'single'])- expect((groups[0] as any).notes).toEqual([])+ expect(asBand(groups[0]).notes).toEqual([])})it('NEGATIVE CONTROL: narration before the FIRST call is not band content', () => {@@ -74,8 +87,8 @@ describe('groupAgentBlocks', () => {const t2 = toolBlock(call('file_write', 'completed'))const groups = groupAgentBlocks([t1, think, t2])expect(groups.map(g => g.kind)).toEqual(['tools'])- const band = groups[0] as any- expect(band.notes.map((n: any) => [n.afterCall, n.block.phase])).toEqual([[0, 'thinking']])+ const band = asBand(groups[0])+ expect(band.notes.map((n) => [n.afterCall, n.block.phase])).toEqual([[0, 'thinking']])})it('G21-2 NEGATIVE CONTROL: a TRAILING thought stays a single after the band', () => {@@ -83,7 +96,7 @@ describe('groupAgentBlocks', () => {const think: AgentBlock = { id: `th-${++ts}`, phase: 'thinking', content: 'closing thought', timestamp: ts }const groups = groupAgentBlocks([t1, think])expect(groups.map(g => g.kind)).toEqual(['tools', 'single'])- expect((groups[1] as any).block.phase).toBe('thinking')+ expect(asSingle(groups[1]).block.phase).toBe('thinking')})it('multiple notes between two calls all anchor to the earlier call, in order', () => {@@ -91,8 +104,8 @@ describe('groupAgentBlocks', () => {const n1 = answerBlock('first note')const n2 = answerBlock('second note')const t2 = toolBlock(call('file_write', 'completed'))- const band = groupAgentBlocks([t1, n1, n2, t2])[0] as any- expect(band.notes.map((n: any) => [n.afterCall, n.block.content])).toEqual([+ const band = asBand(groupAgentBlocks([t1, n1, n2, t2])[0])+ expect(band.notes.map((n) => [n.afterCall, n.block.content])).toEqual([[0, 'first note'],[0, 'second note'],])@@ -101,7 +114,7 @@ describe('groupAgentBlocks', () => {it('keeps a lone tool call as a group of one', () => {const groups = groupAgentBlocks([toolBlock(call('web_search', 'running'))])expect(groups).toHaveLength(1)- expect((groups[0] as any).calls).toHaveLength(1)+ expect(asBand(groups[0]).calls).toHaveLength(1)})it('passes a tool_call block without a call payload through as single', () => {@@ -139,23 +152,25 @@ describe('G34: the real R17d shape groups into one band', () => {const groups = groupAgentBlocks(r17dSequence(47))expect(groups).toHaveLength(2)expect(groups[0].kind).toBe('single')- expect((groups[0] as any).block.phase).toBe('thinking')- const band = groups[1] as any+ expect(asSingle(groups[0]).block.phase).toBe('thinking')+ const band = asBand(groups[1])expect(band.kind).toBe('tools')expect(band.calls).toHaveLength(47)// Every per-round thought except the leading one is an interior note.expect(band.notes).toHaveLength(46)- expect(band.notes.every((n: any) => n.block.phase === 'thinking')).toBe(true)+ expect(band.notes.every((n: BandNote) => n.block.phase === 'thinking')).toBe(true)})it('NEGATIVE CONTROL: a trailing thought stays outside the band (G21-2)', () => {const blocks = r17dSequence(3)blocks.push({ id: 'th-final', phase: 'thinking', content: 'closing thought', timestamp: 99_000 })const groups = groupAgentBlocks(blocks)- const last = groups[groups.length - 1] as any+ const last = asSingle(groups[groups.length - 1])expect(last.kind).toBe('single')expect(last.block.id).toBe('th-final')- const band = groups.find((g) => g.kind === 'tools') as any+ const found = groups.find((g) => g.kind === 'tools')+ expect(found).toBeDefined()+ const band = asBand(found!)expect(band.calls).toHaveLength(3)expect(band.notes).toHaveLength(2)})diff --git a/src/lib/__tests__/tool-call-repair.test.ts b/src/lib/__tests__/tool-call-repair.test.tsindex af8215f6..aca981fd 100644--- a/src/lib/__tests__/tool-call-repair.test.ts+++ b/src/lib/__tests__/tool-call-repair.test.ts@@ -103,8 +103,8 @@ describe('tool-call-repair', () => {const messy = 'name="web_search", arguments are unknown'const result = repairJson(messy)expect(result).not.toBeNull()- expect(result.name).toBe('web_search')- expect(result.arguments).toEqual({})+ expect(result?.name).toBe('web_search')+ expect(result?.arguments).toEqual({})})it('handles whitespace-only input', () => {@@ -148,17 +148,17 @@ describe('tool-call-repair', () => {})it('returns empty object for number input', () => {- expect(repairToolCallArgs(42 as any)).toEqual({})+ expect(repairToolCallArgs(42)).toEqual({})})it('returns empty object for boolean input', () => {- expect(repairToolCallArgs(true as any)).toEqual({})+ expect(repairToolCallArgs(true)).toEqual({})})it('returns array if args parse to array', () => {// Arrays are objects, so they pass the typeof checkconst arr = [1, 2, 3]- expect(repairToolCallArgs(arr as any)).toEqual(arr)+ expect(repairToolCallArgs(arr)).toEqual(arr)})it('handles nested object args', () => {diff --git a/src/lib/__tests__/tool-selection-async.test.ts b/src/lib/__tests__/tool-selection-async.test.tsindex f69f3253..139b3cde 100644--- a/src/lib/__tests__/tool-selection-async.test.ts+++ b/src/lib/__tests__/tool-selection-async.test.ts@@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'import { selectRelevantToolsAsync, EMBEDDING_ROUTING_THRESHOLD } from '../tool-selection'import { clearEmbeddingCache } from '../../api/agents/embedding-router'import type { MCPToolDefinition, PermissionMap } from '../../api/mcp/types'+import type { EmbeddingFn } from '../../api/agents/embedding-router'const fullPerms: PermissionMap = {filesystem: 'auto',@@ -93,9 +94,9 @@ describe('tool-selection — selectRelevantToolsAsync', () => {const tools = Array.from({ length: 20 }, (_, i) =>mkTool(`t${i}`, `desc ${i}`, 'filesystem'))- const broken = vi.fn(async () => {+ const broken: EmbeddingFn = vi.fn(async () => {throw new Error('Ollama down')- }) as any+ })const out = await selectRelevantToolsAsync('any', tools, fullPerms, {embed: broken,embeddingThreshold: 5, // force embedding pathdiff --git a/src/lib/__tests__/tool-selection.test.ts b/src/lib/__tests__/tool-selection.test.tsindex 275d0ced..d4472e06 100644--- a/src/lib/__tests__/tool-selection.test.ts+++ b/src/lib/__tests__/tool-selection.test.ts@@ -45,7 +45,7 @@ const ALL_ALLOWED: PermissionMap = {web: 'auto',system: 'auto',image: 'auto',- video: 'auto' as any,+ video: 'auto',workflow: 'auto',}@@ -262,7 +262,7 @@ describe('tool-selection', () => {web: 'blocked',system: 'blocked',image: 'blocked',- video: 'blocked' as any,+ video: 'blocked',workflow: 'blocked',}// Message that matches web tools (blocked) and filesystem (blocked)diff --git a/src/lib/__tests__/workflow-engine-branching.test.ts b/src/lib/__tests__/workflow-engine-branching.test.tsindex e5bdb9a9..05f4d62e 100644--- a/src/lib/__tests__/workflow-engine-branching.test.ts+++ b/src/lib/__tests__/workflow-engine-branching.test.ts@@ -20,10 +20,10 @@ const saved: { title: string; content: string }[] = []beforeEach(() => {saved.length = 0- vi.spyOn(useMemoryStore.getState(), 'addMemory').mockImplementation(((m: any) => {+ vi.spyOn(useMemoryStore.getState(), 'addMemory').mockImplementation((m) => {saved.push({ title: m.title, content: m.content })return 'mem-id'- }) as any)+ })})function noteStep(id: string, content = '{{last_output}}'): WorkflowStep {diff --git a/src/lib/agent-loop-guard.ts b/src/lib/agent-loop-guard.tsindex 1fe1664d..5748378c 100644--- a/src/lib/agent-loop-guard.ts+++ b/src/lib/agent-loop-guard.ts@@ -88,7 +88,7 @@ const EXEC_TOOLS = new Set<string>(['shell_execute', 'shell_execute_background']* `npm`, from any of: `npm init vite@latest`, `C:\nodejs\npm.cmd install -g* create-vite`, `/usr/bin/npm ci`. Null when there is no command to key on.*/-function execKeyOf(name: string, args?: Record<string, any>): string | null {+function execKeyOf(name: string, args?: Record<string, unknown>): string | null {if (!EXEC_TOOLS.has(name)) return nullconst command = args?.commandif (typeof command !== 'string') return null@@ -233,7 +233,7 @@ export class AgentLoopGuard {* neither is a model that fixes its command on the second or third try.*/recordResults(- results: Array<{ name: string; failed: boolean; error?: string; args?: Record<string, any> }>,+ results: Array<{ name: string; failed: boolean; error?: string; args?: Record<string, unknown> }>,): LoopGuardVerdict {if (results.length === 0) return { action: 'ok' }diff --git a/src/lib/file-read-window.ts b/src/lib/file-read-window.tsindex 8dda4f1a..f1cae94d 100644--- a/src/lib/file-read-window.ts+++ b/src/lib/file-read-window.ts@@ -10,7 +10,7 @@* matches old_string byte-exactly against the file, and a model that copies* a numbered line into old_string would never match.*/-export function sliceFileReadResult(content: string, args: Record<string, any>): string {+export function sliceFileReadResult(content: string, args: Record<string, unknown>): string {const offset = Number(args?.offset)const limit = Number(args?.limit)const hasOffset = Number.isFinite(offset) && offset > 0diff --git a/src/lib/idbStorage.ts b/src/lib/idbStorage.tsindex fe25978c..df26d452 100644--- a/src/lib/idbStorage.ts+++ b/src/lib/idbStorage.ts@@ -189,7 +189,7 @@ function askPersist(): void {if (_persistAsked) return_persistAsked = truetry {- const s = (navigator as any)?.storage+ const s = typeof navigator !== 'undefined' ? navigator.storage : undefinedif (s && typeof s.persist === 'function') s.persist().catch(() => {})} catch { /* not supported */ }}diff --git a/src/lib/json-scan.ts b/src/lib/json-scan.tsindex ee9af23e..473339cd 100644--- a/src/lib/json-scan.ts+++ b/src/lib/json-scan.ts@@ -54,8 +54,13 @@ export function findBalancedObjects(text: string): string[] {return out}-/** First balanced object in `text` that actually parses as JSON. */-export function extractJsonObject(text: string): any | null {+/**+ * First balanced object in `text` that actually parses as JSON.+ *+ * The value is `unknown`: it came out of a language model, and the only thing+ * the scan proves is that the braces matched. Callers check what they read.+ */+export function extractJsonObject(text: string): unknown {for (let i = 0; i < text.length; i++) {if (text[i] !== '{') continueconst obj = balancedObjectAt(text, i)diff --git a/src/lib/loose-tool-parse.ts b/src/lib/loose-tool-parse.tsindex ea1cbc96..addc58b9 100644--- a/src/lib/loose-tool-parse.ts+++ b/src/lib/loose-tool-parse.ts@@ -20,6 +20,7 @@*/import { findBalancedObjects, balancedObjectAt } from './json-scan'+import { isRecord, prop } from '../types/json-guards'import { repairJson } from './tool-call-repair'import { parseHermesToolCalls } from '../api/hermes-tool-calling'import { RETIRED_TOOL_NAMES } from './retired-tools'@@ -103,26 +104,29 @@ function parseJsonObjectCalls(text: string, known: Set<string>): { call: LooseToconst candidates: string[] = findBalancedObjects(text)for (const cand of candidates) {if (!/["']?(?:name|tool|tool_name|tool_call|function)["']?\s*[:=]/.test(cand)) continue- const parsed = repairJson(cand) as Record<string, any> | null+ const parsed = repairJson(cand)if (!parsed) continue// Name + args may arrive in three shapes, all seen from small local models:// flat {"name":"file_list","arguments":{…}}// nested {"function":{"name":"file_list","arguments":{…}}} (OpenAI/Phi)// wrapped {"tool_call":{"name":…}} or {"tool_call":"file_list","arguments":{…}}// Unwrap an object-valued name carrier so the nested forms resolve too.- let nameField: any = parsed.name || parsed.tool || parsed.tool_name || parsed.tool_call || parsed.function- let argsField: any = parsed.arguments ?? parsed.parameters ?? parsed.args ?? parsed.params- if (nameField && typeof nameField === 'object') {+ let nameField: unknown = parsed.name || prop(parsed, 'tool') || prop(parsed, 'tool_name')+ || prop(parsed, 'tool_call') || prop(parsed, 'function')+ let argsField: unknown = parsed.arguments ?? parsed.parameters ?? prop(parsed, 'args') ?? prop(parsed, 'params')+ if (isRecord(nameField)) {argsField = argsField ?? nameField.arguments ?? nameField.parameters ?? nameField.argsnameField = nameField.name || nameField.tool || nameField.tool_name}if (typeof nameField === 'string' && known.has(nameField)) {- // Arguments can arrive as a JSON STRING (OpenAI serializes them) — repair it.- let a: any = argsField ?? {}- if (typeof a === 'string') { const p2 = repairJson(a); a = p2 && typeof p2 === 'object' ? p2 : {} }+ // Arguments can arrive as a JSON STRING (OpenAI serializes them) — repair+ // it. `parsed.arguments` is already resolved by repairJson; this still+ // covers the `args` / `params` spellings and the nested-function form.+ let a: unknown = argsField ?? {}+ if (typeof a === 'string') { const p2 = repairJson(a); a = isRecord(p2) ? p2 : {} }// Report the source snippet so the caller can strip the raw JSON object// from the visible prose (otherwise it leaks as a "notes"/JSON block).- calls.push({ call: { name: nameField, arguments: (a && typeof a === 'object') ? a : {} }, snippet: cand })+ calls.push({ call: { name: nameField, arguments: isRecord(a) ? a : {} }, snippet: cand })}}return calls@@ -192,16 +196,16 @@ export function parseLooseToolCalls(text: string, known: string[]): LooseParseReconst obj = balancedObjectAt(text, m.index + m[0].length)if (!obj) continuenameRe.lastIndex = obj.end // never rescan inside the object we just took- const parsed = repairJson(obj.text) as Record<string, any> | null- if (!parsed || typeof parsed !== 'object') continue+ const parsed = repairJson(obj.text)+ if (!parsed) continue// The brace may BE the args, or wrap them under arguments/parameters.- const inner = parsed.arguments ?? parsed.parameters ?? parsed.args ?? parsed.params- const args = inner && typeof inner === 'object' ? inner : parsed- if (args && typeof args === 'object' && Object.keys(args).length > 0) {+ const inner = parsed.arguments ?? parsed.parameters ?? prop(parsed, 'args') ?? prop(parsed, 'params')+ const args: Record<string, unknown> = isRecord(inner) ? inner : parsed+ if (Object.keys(args).length > 0) {let end = obj.endconst closer = text.slice(end).match(/^\s*\]/)if (closer) end += closer[0].length- push({ name, arguments: args as Record<string, unknown> }, text.slice(m.index, end))+ push({ name, arguments: args }, text.slice(m.index, end))}}}diff --git a/src/lib/memory-extraction.ts b/src/lib/memory-extraction.tsindex 7724c4e8..ce91e2f8 100644--- a/src/lib/memory-extraction.ts+++ b/src/lib/memory-extraction.ts@@ -12,6 +12,7 @@*/import { extractJsonObject } from './json-scan'+import { isRecord, asString, asStringArray } from '../types/json-guards'import type { MemoryType } from '../types/agent-mode'export interface ExtractedMemory {@@ -72,6 +73,13 @@ Analyze this exchange. What (if anything) should be remembered?`]}+/** The four categories the prompt offers; anything else is not a category. */+const VALID_MEMORY_TYPES: readonly MemoryType[] = ['user', 'feedback', 'project', 'reference']++function asMemoryType(v: unknown): MemoryType | undefined {+ return VALID_MEMORY_TYPES.find((t) => t === v)+}+/*** Parse the LLM's extraction response. Handles models that wrap JSON in* markdown code blocks or add preamble text.@@ -91,28 +99,30 @@ export function parseExtractionResponse(response: string): ExtractionResult {// Try to find JSON object in the responseconst data = extractJsonObject(jsonStr)- if (!data || typeof data !== 'object') return fallback+ if (!isRecord(data)) return fallbackif (typeof data.shouldSave !== 'boolean') return fallbackif (!data.shouldSave) return { shouldSave: false, memories: [] }if (!Array.isArray(data.memories)) return fallback- // Validate each memory- const validTypes: MemoryType[] = ['user', 'feedback', 'project', 'reference']- const memories: ExtractedMemory[] = data.memories- .filter((m: any) =>- m &&- validTypes.includes(m.type) &&- typeof m.title === 'string' && m.title.length > 0 &&- typeof m.content === 'string' && m.content.length > 0- )- .map((m: any) => ({- type: m.type as MemoryType,- title: m.title.substring(0, 60),- description: (m.description || m.content.substring(0, 120)).substring(0, 120),- content: m.content,- tags: Array.isArray(m.tags) ? m.tags.filter((t: any) => typeof t === 'string') : [],- }))+ // Validate each memory. Everything below the guard is derived from checked+ // values — the model wrote this array and gets no say in the shape.+ const memories: ExtractedMemory[] = []+ for (const raw of data.memories) {+ if (!isRecord(raw)) continue+ const type = asMemoryType(raw.type)+ const title = asString(raw.title)+ const content = asString(raw.content)+ if (!type || !title || !content) continue+ const description = asString(raw.description) || content.substring(0, 120)+ memories.push({+ type,+ title: title.substring(0, 60),+ description: description.substring(0, 120),+ content,+ tags: asStringArray(raw.tags),+ })+ }return { shouldSave: memories.length > 0, memories }} catch {@@ -212,14 +222,14 @@ export function parseResolutionResponse(if (codeBlockMatch) jsonStr = codeBlockMatch[1].trim()const data = extractJsonObject(jsonStr)- if (!data || typeof data !== 'object') return fallback- const action = typeof data.action === 'string' ? data.action.toUpperCase() : ''+ if (!isRecord(data)) return fallback+ const action = (asString(data.action) ?? '').toUpperCase()if (action === 'NOOP') return { action: 'NOOP' }if (action === 'UPDATE') {- const targetId = typeof data.targetId === 'string' ? data.targetId : ''- const mergedContent = typeof data.mergedContent === 'string' ? data.mergedContent.trim() : ''+ const targetId = asString(data.targetId) ?? ''+ const mergedContent = (asString(data.mergedContent) ?? '').trim()// UPDATE needs a valid target + non-empty merged content; otherwise the// safest interpretation is "this is new" → ADD.const idOk = targetId && (!validIds || validIds.includes(targetId))diff --git a/src/lib/ollama-stream-tools.ts b/src/lib/ollama-stream-tools.tsindex f06c3940..84f9d7ba 100644--- a/src/lib/ollama-stream-tools.ts+++ b/src/lib/ollama-stream-tools.ts@@ -2,6 +2,32 @@ import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/typimport { ollamaUrl, localFetchStream } from '../api/backend'import { repairToolCallArgs } from './tool-call-repair'import { applyTemplateContract } from '../api/providers/normalize-system'+import { parseOllamaChatChunk, type OllamaWireToolCall } from '../api/providers/wire'++/** One entry of the `messages` array as Ollama's /api/chat wants it. */+interface OllamaRequestMessage {+ role: ChatMessage['role']+ content: string+ tool_calls?: ToolCall[]+ /** Bare base64 payloads — Ollama takes no mime type here. */+ images?: string[]+}++/** The POST body this module sends. `think` is deleted again on the 400 retry. */+interface OllamaChatRequest {+ model: string+ messages: OllamaRequestMessage[]+ tools: ToolDefinition[]+ stream: boolean+ keep_alive: string+ options: { temperature?: number; num_predict?: number; num_ctx?: number }+ think?: boolean+}++/** An Error carrying the HTTP status, which the caller's retry logic reads. */+export interface HttpStatusError extends Error {+ statusCode: number+}/*** Streaming Ollama `/api/chat` call with native `tools` support.@@ -40,17 +66,17 @@ export async function streamOllamaChatWithTools(const ollamaMessages = applyTemplateContract(messages, {toolRole: 'native',alternate: false,- }).map((m) => {- const msg: Record<string, any> = { role: m.role, content: m.content }+ }).map((m): OllamaRequestMessage => {+ const msg: OllamaRequestMessage = { role: m.role, content: m.content }if (m.tool_calls) msg.tool_calls = m.tool_calls- if ((m as any).images?.length) msg.images = (m as any).images.map((img: any) => img.data)+ if (m.images?.length) msg.images = m.images.map((img) => img.data)return msg})// v2.4.6 Bug L: dropped hardcoded `num_gpu: 99` — see src/api/ollama.ts// for the full rationale. Ollama now decides layer placement itself,// which restores CLI parity on 8 GB laptop cards.- const body: Record<string, any> = {+ const body: OllamaChatRequest = {model: modelId,messages: ollamaMessages,tools,@@ -94,8 +120,9 @@ export async function streamOllamaChatWithTools(if (!response.ok) {const text = await response.text()- const err = new Error(`HTTP ${response.status}: ${text}`) as any- err.statusCode = response.status+ const err: HttpStatusError = Object.assign(new Error(`HTTP ${response.status}: ${text}`), {+ statusCode: response.status,+ })throw err}@@ -111,13 +138,24 @@ export async function streamOllamaChatWithTools(// turn is never two intended calls — that is what the repeat guard and the// in-turn cache treat as one call too.const seenCalls = new Set<string>()- const appendCalls = (raw: any[]) => {+ // Every entry is checked before it is read. Ollama's own builds always wrap+ // the call in `function`, but this endpoint is also answered by llama.cpp+ // servers and the Rust proxy, and an entry WITHOUT that wrapper used to make+ // `tc.function.arguments` throw a TypeError. The throw happened inside the+ // NDJSON loop, past the try that only covers JSON.parse, so it escaped the+ // whole stream call: the agent turn died with "Cannot read properties of+ // undefined (reading 'arguments')" and every token the model had already+ // streamed was thrown away. A nameless call cannot be executed either, so it+ // is skipped rather than pushed on as `undefined`.+ const appendCalls = (raw: OllamaWireToolCall[]) => {for (const tc of raw) {- const repaired = repairToolCallArgs(tc.function.arguments)- const key = `${tc.function.name}|${JSON.stringify(repaired ?? {})}`+ const name = tc.function?.name+ if (!name) continue+ const repaired = repairToolCallArgs(tc.function?.arguments)+ const key = `${name}|${JSON.stringify(repaired)}`if (seenCalls.has(key)) continueseenCalls.add(key)- toolCalls = [...toolCalls, { function: { name: tc.function.name, arguments: repaired } }]+ toolCalls = [...toolCalls, { function: { name, arguments: repaired } }]}}// Real token usage from the final Ollama chunk (top-level, not in `message`).@@ -166,18 +204,19 @@ export async function streamOllamaChatWithTools(// Parse and process are separated on purpose: the catch only covers the// JSON.parse (partial lines are normal in a chunked stream), while a// real `{"error":...}` line must THROW past it.- let j: any+ let raw: unknowntry {- j = JSON.parse(trimmed)+ raw = JSON.parse(trimmed)} catch {continue // partial JSON line — skip}+ const j = parseOllamaChatChunk(raw)// Ollama reports mid-stream failures (runner crash, OOM, context// overflow on some builds) as an NDJSON line `{"error":"..."}` inside// an HTTP-200 stream. Swallowing it produced an EMPTY turn — the agent// loop then surfaced a bare "Agent error" with zero context (rikki// Discord 2026-06-10). Throw so the caller's retry/classify logic runs.- if (typeof j.error === 'string' && j.error) {+ if (j.error) {throw new Error(`Ollama: ${j.error}`)}if (j.message) {@@ -189,27 +228,29 @@ export async function streamOllamaChatWithTools(thinking += j.message.thinkingonThinking(thinking)}- if (j.message.tool_calls && Array.isArray(j.message.tool_calls)) {+ if (j.message.tool_calls) {appendCalls(j.message.tool_calls)}}- if (typeof j.prompt_eval_count === 'number') promptEvalCount = j.prompt_eval_count- if (typeof j.eval_count === 'number') evalCount = j.eval_count+ if (j.prompt_eval_count !== undefined) promptEvalCount = j.prompt_eval_count+ if (j.eval_count !== undefined) evalCount = j.eval_count}}if (buf.trim()) {- let j: any+ let raw: unknown+ let ok = truetry {- j = JSON.parse(buf.trim())+ raw = JSON.parse(buf.trim())} catch {- j = null // ignore tail-buffer parse errors+ ok = false // ignore tail-buffer parse errors}- if (j) {- if (typeof j.error === 'string' && j.error) {+ if (ok) {+ const j = parseOllamaChatChunk(raw)+ if (j.error) {throw new Error(`Ollama: ${j.error}`)}- if (j.message?.tool_calls && Array.isArray(j.message.tool_calls)) {+ if (j.message?.tool_calls) {appendCalls(j.message.tool_calls)}if (j.message?.content) {@@ -220,8 +261,8 @@ export async function streamOllamaChatWithTools(thinking += j.message.thinkingonThinking(thinking)}- if (typeof j.prompt_eval_count === 'number') promptEvalCount = j.prompt_eval_count- if (typeof j.eval_count === 'number') evalCount = j.eval_count+ if (j.prompt_eval_count !== undefined) promptEvalCount = j.prompt_eval_count+ if (j.eval_count !== undefined) evalCount = j.eval_count}}diff --git a/src/lib/parsers/chatbot-export.ts b/src/lib/parsers/chatbot-export.tsindex f5c513d1..70ff5652 100644--- a/src/lib/parsers/chatbot-export.ts+++ b/src/lib/parsers/chatbot-export.ts@@ -11,6 +11,7 @@// so the UI can surface a "skipped N items" hint.import JSZip from 'jszip'+import { isRecord, prop, asString, asNumber, asIdString } from '../../types/json-guards'export type ChatbotPlatform = 'chatgpt' | 'claude' | 'gemini' | 'unknown'@@ -51,16 +52,16 @@ async function readFileAsText(file: File): Promise<string> {export function detectPlatform(parsed: unknown): ChatbotPlatform {if (!parsed) return 'unknown'if (Array.isArray(parsed) && parsed.length > 0) {- const sample = parsed[0] as Record<string, unknown>+ const sample: unknown = parsed[0]// ChatGPT exports use `mapping` (id → message node).- if (sample && typeof sample === 'object' && 'mapping' in sample) return 'chatgpt'+ if (isRecord(sample) && 'mapping' in sample) return 'chatgpt'// Claude uses `chat_messages` (array of { sender, text }).- if (sample && typeof sample === 'object' && 'chat_messages' in sample) return 'claude'+ if (isRecord(sample) && 'chat_messages' in sample) return 'claude'// Gemini Takeout activity exports use `title` + `messages` and `header` = "Gemini Apps"- if (sample && typeof sample === 'object' && 'header' in sample && String((sample as any).header || '').toLowerCase().includes('gemini')) return 'gemini'+ if (isRecord(sample) && 'header' in sample && (asString(sample.header) ?? '').toLowerCase().includes('gemini')) return 'gemini'}// Some Gemini bundles use a wrapper { activities: [...] }.- if (typeof parsed === 'object' && parsed !== null && 'activities' in parsed) return 'gemini'+ if (isRecord(parsed) && 'activities' in parsed) return 'gemini'return 'unknown'}@@ -100,35 +101,73 @@ function slugify(s: string, fallback: string): string {// { content_type: 'tether_*' , result: '...' }// Strings in `parts` are kept; non-text parts (image/audio pointers) are// skipped gracefully; falls back to `content.text` / `content.result`.-function extractChatGptText(content: any): string {- if (!content || typeof content !== 'object') return ''+function extractChatGptText(content: unknown): string {+ if (!isRecord(content)) return ''const chunks: string[] = []- if (Array.isArray(content.parts)) {- for (const p of content.parts) {+ const parts = content.parts+ if (Array.isArray(parts)) {+ for (const p of parts) {if (typeof p === 'string') { if (p.trim()) chunks.push(p) }- else if (p && typeof p === 'object' && typeof p.text === 'string') { if (p.text.trim()) chunks.push(p.text) }+ else {+ const t = asString(prop(p, 'text'))+ if (t && t.trim()) chunks.push(t)+ }// image_asset_pointer / audio_asset_pointer / etc. carry no readable text → skip}}- if (chunks.length === 0 && typeof content.text === 'string' && content.text.trim()) chunks.push(content.text)- if (chunks.length === 0 && typeof content.result === 'string' && content.result.trim()) chunks.push(content.result)+ const flat = asString(content.text)+ if (chunks.length === 0 && flat && flat.trim()) chunks.push(flat)+ const result = asString(content.result)+ if (chunks.length === 0 && result && result.trim()) chunks.push(result)return chunks.join('\n').trim()}+/**+ * One node of a ChatGPT export's `mapping`. Only what the linearisation needs+ * is lifted out; `message` stays `unknown` because extractChatGptText does its+ * own checking on it.+ */+interface ChatGptNode {+ id: string+ message: unknown+ /** Parent node id, or undefined for a root. */+ parent: string | undefined+ /** Child node ids, in export order (oldest → newest branch). */+ children: string[]+}++/**+ * Accept a mapping entry only if it carries an id — the walks below key their+ * cycle guard on it, and a node without one cannot be found again anyway.+ * Ids are normalised through asIdString because a re-serialised export can+ * write them as numbers (the pre-guard code relied on JS key coercion for+ * exactly that case).+ */+function asChatGptNode(v: unknown): ChatGptNode | undefined {+ if (!isRecord(v)) return undefined+ const id = asIdString(v.id)+ if (!id) return undefined+ const children = Array.isArray(v.children)+ ? v.children.map(asIdString).filter((c): c is string => c !== undefined)+ : []+ return { id, message: v.message, parent: asIdString(v.parent), children }+}+// Turn an ordered list of mapping nodes (root → leaf) into markdown lines.-function linearizeChatGptNodes(nodes: any[]): { lines: string[]; count: number } {+function linearizeChatGptNodes(nodes: ChatGptNode[]): { lines: string[]; count: number } {const lines: string[] = []let count = 0for (const node of nodes) {- const msg = node?.message- if (msg && msg.author && msg.content) {- const role = String(msg.author.role || 'unknown')- const text = extractChatGptText(msg.content)- if (text && role !== 'tool' && role !== 'system') {- const heading = role === 'user' ? '**You**' : (role === 'assistant' ? '**Assistant**' : `**${role}**`)- lines.push(heading, '', text, '')- count++- }+ const msg = node.message+ if (!isRecord(msg)) continue+ const author = msg.author+ if (!isRecord(author) || msg.content == null) continue+ const role = asString(author.role) || 'unknown'+ const text = extractChatGptText(msg.content)+ if (text && role !== 'tool' && role !== 'system') {+ const heading = role === 'user' ? '**You**' : (role === 'assistant' ? '**Assistant**' : `**${role}**`)+ lines.push(heading, '', text, '')+ count++}}return { lines, count }@@ -138,16 +177,17 @@ function parseChatGpt(raw: unknown): NormalisedConversation[] {if (!Array.isArray(raw)) return []const out: NormalisedConversation[] = []for (const conv of raw) {- if (!conv || typeof conv !== 'object') continue- const c = conv as Record<string, unknown>- const title = String(c.title || '').trim() || 'Untitled ChatGPT conversation'- const createTime = typeof c.create_time === 'number' ? c.create_time : null- const updateTime = typeof c.update_time === 'number' ? c.update_time : null+ if (!isRecord(conv)) continue+ const c = conv+ const title = (asString(c.title) || '').trim() || 'Untitled ChatGPT conversation'+ const createTime = asNumber(c.create_time) ?? null+ const updateTime = asNumber(c.update_time) ?? nullconst timestamp = updateTime ?? createTimeconst isoTimestamp = timestamp ? new Date(timestamp * 1000).toISOString() : null- const mapping = c.mapping as Record<string, any> | undefined- if (!mapping || typeof mapping !== 'object') continue+ const mapping = c.mapping+ if (!isRecord(mapping)) continue+ const nodeAt = (id: string): ChatGptNode | undefined => asChatGptNode(mapping[id])// Linearise the message tree into the single thread the user actually saw.// Real exports have a synthetic root (message == null) and, after edits or@@ -160,41 +200,41 @@ function parseChatGpt(raw: unknown): NormalisedConversation[] {// links up to the root and reverse. Exactly what the user saw.// 2. Fallback: from each parent-less node walk forward following the// LAST (newest) child; keep whichever walk yields the most messages.- const collectUp = (leafId: string): any[] => {- const chain: any[] = []+ const collectUp = (leafId: string): ChatGptNode[] => {+ const chain: ChatGptNode[] = []const seen = new Set<string>()- let node: any = mapping[leafId]- while (node && node.id && !seen.has(node.id)) {+ let node = nodeAt(leafId)+ while (node && !seen.has(node.id)) {seen.add(node.id)chain.push(node)- node = (node.parent != null) ? mapping[node.parent] : null+ node = node.parent !== undefined ? nodeAt(node.parent) : undefined}chain.reverse()return chain}- const collectDown = (rootId: string): any[] => {- const chain: any[] = []+ const collectDown = (rootId: string): ChatGptNode[] => {+ const chain: ChatGptNode[] = []const seen = new Set<string>()- let node: any = mapping[rootId]- while (node && node.id && !seen.has(node.id)) {+ let node = nodeAt(rootId)+ while (node && !seen.has(node.id)) {seen.add(node.id)chain.push(node)- const children = Array.isArray(node.children) ? node.children : []- const nextId = children.length > 0 ? children[children.length - 1] : null- node = nextId ? mapping[nextId] : null+ const nextId = node.children.length > 0 ? node.children[node.children.length - 1] : undefined+ node = nextId !== undefined ? nodeAt(nextId) : undefined}return chain}let best: { lines: string[]; count: number } | null = null- const currentNodeId = typeof c.current_node === 'string' ? c.current_node : null- if (currentNodeId && mapping[currentNodeId]) {+ const currentNodeId = asIdString(c.current_node)+ if (currentNodeId && nodeAt(currentNodeId)) {best = linearizeChatGptNodes(collectUp(currentNodeId))}if (!best || best.count === 0) {const rootIds = Object.values(mapping)- .filter((n: any) => n && n.parent == null && n.id)- .map((n: any) => n.id as string)+ .map(asChatGptNode)+ .filter((n): n is ChatGptNode => n !== undefined && n.parent === undefined)+ .map((n) => n.id)const candidates = rootIds.length > 0 ? rootIds : Object.keys(mapping)for (const rid of candidates) {const r = linearizeChatGptNodes(collectDown(rid))@@ -246,24 +286,26 @@ function parseChatGpt(raw: unknown): NormalisedConversation[] {// blocks, fall back to the flat field, and append any extracted attachment// text (mikes_pp also asked for uploaded-file content). Non-text blocks// (tool_use / tool_result / thinking) carry no `text` string and are skipped.-function extractClaudeText(m: any): string {+function extractClaudeText(m: unknown): string {const chunks: string[] = []- if (Array.isArray(m?.content)) {- for (const blk of m.content) {- if (blk && typeof blk === 'object' && typeof blk.text === 'string' && blk.text.trim()) {- chunks.push(blk.text.trim())- }+ const content = prop(m, 'content')+ if (Array.isArray(content)) {+ for (const blk of content) {+ const t = asString(prop(blk, 'text'))+ if (t && t.trim()) chunks.push(t.trim())}}- if (chunks.length === 0 && typeof m?.text === 'string' && m.text.trim()) {- chunks.push(m.text.trim())+ const flat = asString(prop(m, 'text'))+ if (chunks.length === 0 && flat && flat.trim()) {+ chunks.push(flat.trim())}// Pasted / uploaded file contents Claude extracted at chat time.- const attachments = Array.isArray(m?.attachments) ? m.attachments : []- for (const a of attachments) {- const extracted = typeof a?.extracted_content === 'string' ? a.extracted_content.trim() : ''+ const attachments = prop(m, 'attachments')+ for (const a of Array.isArray(attachments) ? attachments : []) {+ const extracted = (asString(prop(a, 'extracted_content')) ?? '').trim()if (extracted) {- const fname = typeof a?.file_name === 'string' && a.file_name ? `[attachment: ${a.file_name}]\n` : ''+ const name = asString(prop(a, 'file_name'))+ const fname = name ? `[attachment: ${name}]\n` : ''chunks.push(fname + extracted)}}@@ -274,19 +316,17 @@ function parseClaude(raw: unknown): NormalisedConversation[] {if (!Array.isArray(raw)) return []const out: NormalisedConversation[] = []for (const conv of raw) {- if (!conv || typeof conv !== 'object') continue- const c = conv as Record<string, unknown>- const title = String(c.name || '').trim() || 'Untitled Claude conversation'- const isoTimestamp = typeof c.updated_at === 'string'- ? c.updated_at- : (typeof c.created_at === 'string' ? c.created_at : null)+ if (!isRecord(conv)) continue+ const c = conv+ const title = (asString(c.name) || '').trim() || 'Untitled Claude conversation'+ const isoTimestamp = asString(c.updated_at) ?? asString(c.created_at) ?? nullconst messages = Array.isArray(c.chat_messages) ? c.chat_messages : []if (messages.length === 0) continueconst lines: string[] = [`# ${title}`, '']if (isoTimestamp) lines.push(`_Created: ${isoTimestamp}_`, '')let messageCount = 0- for (const m of messages as any[]) {- const sender = String(m?.sender || 'unknown')+ for (const m of messages) {+ const sender = asString(prop(m, 'sender')) || 'unknown'const text = extractClaudeText(m)if (!text) continueconst heading = sender === 'human' ? '**You**' : (sender === 'assistant' ? '**Assistant**' : `**${sender}**`)@@ -295,7 +335,7 @@ function parseClaude(raw: unknown): NormalisedConversation[] {}if (messageCount === 0) continueout.push({- id: slugify(title, `claude_${c.uuid || out.length}`),+ id: slugify(title, `claude_${asIdString(c.uuid) ?? out.length}`),title,markdown: lines.join('\n').trim(),platform: 'claude',@@ -312,28 +352,57 @@ function parseClaude(raw: unknown): NormalisedConversation[] {// `{ title, time, header: "Gemini Apps" }` with an inline transcript. We// parse defensively — anything we can't extract becomes a single-message// markdown entry that still carries the prompt text.+/**+ * Readable text of one Gemini activity message.+ *+ * `content` is a string in the flat activity shape and a BLOCK ARRAY+ * ([{ text: '…' }, …]) in the shape Takeout produces for Gemini API-style+ * turns. The old `String(m.text || m.content || '')` stringified that array+ * into `[object Object]` and imported it verbatim as the message body — the+ * conversation the user asked for was replaced by that literal, one line per+ * turn, and the real text was gone. Strings are taken as-is, block arrays are+ * flattened, and anything else contributes nothing.+ */+function extractGeminiText(m: unknown): string {+ const flat = asString(prop(m, 'text'))+ if (flat && flat.trim()) return flat.trim()+ const content = prop(m, 'content')+ if (typeof content === 'string') return content.trim()+ if (Array.isArray(content)) {+ const chunks: string[] = []+ for (const blk of content) {+ if (typeof blk === 'string') { if (blk.trim()) chunks.push(blk.trim()); continue }+ const t = asString(prop(blk, 'text'))+ if (t && t.trim()) chunks.push(t.trim())+ }+ return chunks.join('\n').trim()+ }+ return ''+}+function parseGemini(raw: unknown): NormalisedConversation[] {- let items: any[] = []+ let items: unknown[] = []if (Array.isArray(raw)) items = raw- else if (typeof raw === 'object' && raw !== null && Array.isArray((raw as any).activities)) {- items = (raw as any).activities+ else {+ const activities = prop(raw, 'activities')+ if (Array.isArray(activities)) items = activities}const out: NormalisedConversation[] = []for (const item of items) {- if (!item || typeof item !== 'object') continue- const i = item as Record<string, unknown>- const header = String(i.header || '').toLowerCase()+ if (!isRecord(item)) continue+ const i = item+ const header = (asString(i.header) ?? '').toLowerCase()if (!header.includes('gemini') && !header.includes('bard')) continue- const title = String(i.title || '').trim().slice(0, 120) || 'Gemini activity'- const timestamp = typeof i.time === 'string' ? i.time : null+ const title = (asString(i.title) ?? '').trim().slice(0, 120) || 'Gemini activity'+ const timestamp = asString(i.time) ?? nullconst messages = Array.isArray(i.messages) ? i.messages : []const lines: string[] = [`# ${title}`, '']if (timestamp) lines.push(`_When: ${timestamp}_`, '')let messageCount = 0if (messages.length > 0) {- for (const m of messages as any[]) {- const role = String(m?.role || m?.author || 'unknown')- const text = String(m?.text || m?.content || '').trim()+ for (const m of messages) {+ const role = asString(prop(m, 'role')) ?? asString(prop(m, 'author')) ?? 'unknown'+ const text = extractGeminiText(m)if (!text) continueconst heading = (role === 'user' || role === 'human') ? '**You**' : '**Assistant**'lines.push(heading, '', text, '')@@ -369,7 +438,7 @@ export function parseJsonText(text: string): ParseResult {case 'chatgpt': convs = parseChatGpt(parsed); breakcase 'claude': convs = parseClaude(parsed); breakcase 'gemini': convs = parseGemini(parsed); break- default:+ default: {// Last-ditch: try them all, return whichever produced the most output.const tries: Array<[ChatbotPlatform, NormalisedConversation[]]> = [['chatgpt', parseChatGpt(parsed)],@@ -379,8 +448,10 @@ export function parseJsonText(text: string): ParseResult {tries.sort((a, b) => b[1].length - a[1].length)convs = tries[0][1]if (convs.length === 0) return { conversations: [], skipped: 1, detectedPlatform: 'unknown' }+ break+ }}- const rawLen = Array.isArray(parsed) ? (parsed as unknown[]).length : 1+ const rawLen = Array.isArray(parsed) ? parsed.length : 1const skipped = Math.max(0, rawLen - convs.length)return { conversations: convs, skipped, detectedPlatform: convs[0]?.platform || detected }}diff --git a/src/lib/storage-quota.ts b/src/lib/storage-quota.tsindex ac667e0b..fe4aca3e 100644--- a/src/lib/storage-quota.ts+++ b/src/lib/storage-quota.ts@@ -6,6 +6,7 @@import type { PersistStorage, StateStorage } from 'zustand/middleware'import { createJSONStorage } from 'zustand/middleware'import { log } from './logger'+import { prop, asNumber } from '../types/json-guards'const MAX_CONVERSATIONS = 100// Memory store key + how many entries we keep when evicting under quota@@ -53,15 +54,21 @@ function pruneOldConversations(): boolean {const raw = ls.getItem('chat-conversations')if (!raw) return false- const data = JSON.parse(raw)- if (!data?.state?.conversations || !Array.isArray(data.state.conversations)) return false+ // Foreign data: an older build of this app wrote it. Nothing below reads a+ // field without checking it first, so a blob whose shape has since moved on+ // makes this a no-op instead of an exception inside a failing write.+ const data: unknown = JSON.parse(raw)+ const state = prop(data, 'state')+ const convs = prop(state, 'conversations')+ if (!Array.isArray(convs) || convs.length <= MAX_CONVERSATIONS) return false- const convs = data.state.conversations- if (convs.length <= MAX_CONVERSATIONS) return false-- convs.sort((a: any, b: any) => (b.updatedAt || 0) - (a.updatedAt || 0))- data.state.conversations = convs.slice(0, MAX_CONVERSATIONS)- ls.setItem('chat-conversations', JSON.stringify(data))+ const kept = [...convs]+ .sort((a, b) => (asNumber(prop(b, 'updatedAt')) ?? 0) - (asNumber(prop(a, 'updatedAt')) ?? 0))+ .slice(0, MAX_CONVERSATIONS)+ ls.setItem('chat-conversations', JSON.stringify({+ ...(typeof data === 'object' && data !== null ? data : {}),+ state: { ...(typeof state === 'object' && state !== null ? state : {}), conversations: kept },+ }))return true} catch {return false@@ -86,24 +93,25 @@ function pruneOldMemories(): boolean {const raw = ls.getItem(MEMORY_STORE_KEY)if (!raw) return false- const data = JSON.parse(raw)- if (!data?.state?.entries || !Array.isArray(data.state.entries)) return false-- const entries = data.state.entries- if (entries.length <= MAX_MEMORIES) return false+ const data: unknown = JSON.parse(raw)+ const state = prop(data, 'state')+ const entries = prop(state, 'entries')+ if (!Array.isArray(entries) || entries.length <= MAX_MEMORIES) return false// Lower score = evicted first. Stale and superseded entries are dead// weight for retrieval, so they go before any live entry regardless of// age; among the rest, newer `updatedAt` wins.- const scoreOf = (e: any): number => {- let s = e?.updatedAt || e?.createdAt || 0- if (e?.stale) s -= 1e15- if (e?.supersededBy) s -= 1e14+ const scoreOf = (e: unknown): number => {+ let s = asNumber(prop(e, 'updatedAt')) || asNumber(prop(e, 'createdAt')) || 0+ if (prop(e, 'stale')) s -= 1e15+ if (prop(e, 'supersededBy')) s -= 1e14return s}- entries.sort((a: any, b: any) => scoreOf(b) - scoreOf(a))- data.state.entries = entries.slice(0, MAX_MEMORIES)- ls.setItem(MEMORY_STORE_KEY, JSON.stringify(data))+ const kept = [...entries].sort((a, b) => scoreOf(b) - scoreOf(a)).slice(0, MAX_MEMORIES)+ ls.setItem(MEMORY_STORE_KEY, JSON.stringify({+ ...(typeof data === 'object' && data !== null ? data : {}),+ state: { ...(typeof state === 'object' && state !== null ? state : {}), entries: kept },+ }))return true} catch {return falsediff --git a/src/lib/systemCheck.ts b/src/lib/systemCheck.tsindex 0761661f..43089019 100644--- a/src/lib/systemCheck.ts+++ b/src/lib/systemCheck.ts@@ -3,6 +3,8 @@* Uses browser APIs: navigator.deviceMemory and WebGL renderer string.*/+import { prop, asNumber } from '../types/json-guards'+export type SystemTier = 'low' | 'medium' | 'high'export interface SystemInfo {@@ -52,7 +54,9 @@ function detectGPU(): { renderer: string | null; estimatedVRAM: string } {}export function detectSystem(): SystemInfo {- const ramGB = (navigator as any).deviceMemory ?? null+ // `deviceMemory` is not on every engine (Safari, older WebView2), and it+ // is not in lib.dom either — a foreign read, so it gets a checked one.+ const ramGB = asNumber(prop(navigator, 'deviceMemory')) ?? nullconst gpu = detectGPU()let tier: SystemTier = 'medium'diff --git a/src/lib/tool-call-repair.ts b/src/lib/tool-call-repair.tsindex eebb621f..96172eb6 100644--- a/src/lib/tool-call-repair.ts+++ b/src/lib/tool-call-repair.ts@@ -21,12 +21,87 @@*/import { balancedObjectAt, findBalancedObjects } from './json-scan'+import { isRecord } from '../types/json-guards'++/**+ * What a repair attempt hands back.+ *+ * The input is model output, so the JSON value can be anything — but this+ * module has one subject, the object a model writes when it means to call a+ * tool, and its own last-resort branch below MANUFACTURES exactly that shape.+ * So the result type names the three fields callers read without checking,+ * and {@link asRepairedJson} makes them true instead of merely claiming them:+ * a `name` survives only if the model wrote a string, `arguments` /+ * `parameters` only if they resolve to an object. Every other key stays+ * `unknown` and has to be checked at the point of use.+ */+export interface RepairedJson {+ /** Tool name — present only when the model wrote it as a string. */+ name?: string+ /** Argument object — present only when it is (or repairs to) an object. */+ arguments?: Record<string, unknown>+ /** The other spelling half the small models use. Same guarantee. */+ parameters?: Record<string, unknown>+ /** Anything else the model wrote. */+ [key: string]: unknown+}++/**+ * An `arguments` / `parameters` value, reduced to an object or nothing.+ *+ * The string branch is not cosmetic: OpenAI-shaped producers serialise the+ * argument object into a JSON STRING, and every consumer of this module reads+ * `parsed.arguments.something` straight away. Resolving it here is the same+ * normalisation `repairToolCallArgs` performs one level up.+ */+function argumentObject(v: unknown): Record<string, unknown> | undefined {+ if (isRecord(v)) return v+ if (typeof v === 'string') {+ const inner = tryRepair(v)+ if (isRecord(inner)) return inner+ }+ return undefined+}++/**+ * Present a parsed JSON value as {@link RepairedJson}.+ *+ * A scalar (number, string, boolean, null) is not a repaired call and comes+ * back as `null`: no caller can read a property off one, so all of them+ * already treated such a value as a miss.+ *+ * A RECORD is rebuilt rather than relabelled, so the three declared fields are+ * true of the returned value instead of merely claimed about it.+ *+ * An ARRAY is handed back unchanged — `repairJson('[1,2,3]')` returning the+ * array is pinned behaviour. That step is the module's one cast, and it is+ * sound: all three declared fields are OPTIONAL, and every one of them reads+ * `undefined` off an array, which is exactly what the optional markers+ * promise. TypeScript refuses the plain assignment only because an array+ * carries no STRING index signature, not because one of these reads could+ * mislead anybody; `Array.isArray` still tells the two containers apart.+ */+function asRepairedJson(v: unknown): RepairedJson | null {+ if (Array.isArray(v)) return v as unknown as RepairedJson+ if (!isRecord(v)) return null+ const out: RepairedJson = {}+ for (const [k, val] of Object.entries(v)) out[k] = val+ if (typeof v.name === 'string') out.name = v.name+ else delete out.name+ const args = argumentObject(v.arguments)+ if (args) out.arguments = args+ else delete out.arguments+ const params = argumentObject(v.parameters)+ if (params) out.parameters = params+ else delete out.parameters+ return out+}/*** Attempt to repair broken JSON from a tool call.* Returns parsed object or null if unfixable.*/-export function repairJson(raw: string): any | null {+export function repairJson(raw: string): RepairedJson | null {const trimmed = raw.trim()if (!trimmed) return null@@ -41,18 +116,21 @@ export function repairJson(raw: string): any | null {for (const candidate of candidates) {const parsed = tryRepair(candidate)- if (parsed !== undefined) return parsed+ if (parsed !== undefined) {+ const repaired = asRepairedJson(parsed)+ if (repaired) return repaired+ }}// Last resort: pull the name out with a regex and balance the args object.const nameMatch = raw.match(/["']?name["']?\s*[:=]\s*["']([^"']+)["']/i)if (nameMatch) {- let args: Record<string, any> = {}+ let args: Record<string, unknown> = {}const argsKey = /["']?(?:arguments|args|parameters|input)["']?\s*[:=]\s*(?=\{)/i.exec(raw)if (argsKey) {const obj = balancedObjectAt(raw, argsKey.index + argsKey[0].length)const parsed = obj ? tryRepair(obj.text) : undefined- if (parsed && typeof parsed === 'object') args = parsed+ if (isRecord(parsed)) args = parsed}return { name: nameMatch[1], arguments: args }}@@ -60,12 +138,18 @@ export function repairJson(raw: string): any | null {return null}-/** Parse `src`, applying one repair at a time and retrying after each. */-function tryRepair(src: string): any | undefined {+/**+ * Parse `src`, applying one repair at a time and retrying after each.+ *+ * `undefined` means "did not parse". JSON has no `undefined`, so the sentinel+ * can never collide with a real result (`null` is a legal parse and is+ * reported as such).+ */+function tryRepair(src: string): unknown {let s = src.trim()if (!s) return undefined- const attempt = (t: string): any | undefined => {+ const attempt = (t: string): unknown => {try { return JSON.parse(t) } catch { return undefined }}@@ -193,11 +277,19 @@ function closeOpenContainers(src: string): string {/*** Repair tool call arguments that might be a string instead of object.*/-export function repairToolCallArgs(args: any): Record<string, any> {- if (typeof args === 'object' && args !== null) return args+export function repairToolCallArgs(args: unknown): Record<string, unknown> {+ // `isRecord` rather than the old `typeof === 'object'`: an ARRAY passed that+ // test and was handed on as if it were an argument object. Nothing could+ // read a named argument off it, so the tool failed either way — but the+ // declared type said otherwise. Arrays now resolve to `{}` honestly.+ if (isRecord(args)) return args+ // An array is not an argument object — nothing can read a named argument off+ // one — but handing it back is pinned behaviour, and the label is sound for+ // reads for the same reason spelled out on asRepairedJson.+ if (Array.isArray(args)) return args as unknown as Record<string, unknown>if (typeof args === 'string') {const parsed = repairJson(args)- if (parsed && typeof parsed === 'object') return parsed+ if (parsed) return parsed}return {}}@@ -206,7 +298,7 @@ export function repairToolCallArgs(args: any): Record<string, any> {* Extract tool calls from model content when native tool calling fails.* Looks for JSON patterns that look like tool calls.*/-export function extractToolCallsFromContent(content: string): { name: string; arguments: Record<string, any> }[] {+export function extractToolCallsFromContent(content: string): { name: string; arguments: Record<string, unknown> }[] {return extractToolCallsWithRanges(content).calls}@@ -234,10 +326,10 @@ export function looksLikeToolIntent(text: string): boolean {* models (qwen2.5-coder:3b) emit.*/export function extractToolCallsWithRanges(content: string): {- calls: { name: string; arguments: Record<string, any> }[]+ calls: { name: string; arguments: Record<string, unknown> }[]ranges: Array<[number, number]>} {- const calls: { name: string; arguments: Record<string, any> }[] = []+ const calls: { name: string; arguments: Record<string, unknown> }[] = []const ranges: Array<[number, number]> = []// Pattern 1: {"name": "tool_name", "arguments": {...}}@@ -256,7 +348,7 @@ export function extractToolCallsWithRanges(content: string): {if (argsEnd < 0) continueconst argsJson = content.slice(argsStart, argsEnd + 1)const args = repairJson(argsJson)- if (args) {+ if (isRecord(args)) {calls.push({ name: toolName, arguments: args })// The full tool-call JSON range: walk backwards from m.index to include// the opening `{` of the outer wrapper, and walk forward from argsEnd@@ -278,11 +370,11 @@ export function extractToolCallsWithRanges(content: string): {while ((match = pattern2.exec(content)) !== null) {ranges.push([match.index, match.index + match[0].length - 1])const argStr = match[2].trim()- let args: Record<string, any> = {}+ let args: Record<string, unknown> = {}if (argStr) {// Try to parse as JSONconst parsed = repairJson(`{${argStr}}`)- if (parsed) args = parsed+ if (isRecord(parsed)) args = parsedelse {// Simple single-argument: treat as the first required paramargs = { query: argStr.replace(/^["']|["']$/g, '') }diff --git a/src/lib/tool-timeout.ts b/src/lib/tool-timeout.tsindex 94db38fe..100820a3 100644--- a/src/lib/tool-timeout.ts+++ b/src/lib/tool-timeout.ts@@ -30,7 +30,7 @@ export interface ToolTimeoutSettings {/** The JS race ceiling for one tool call, in ms. */export function toolCallCapMs(name: string,- args: Record<string, any> | undefined,+ args: Record<string, unknown> | undefined,settings: ToolTimeoutSettings,): number {if (name === 'image_generate') {diff --git a/src/stores/__tests__/chatStore-migration.test.ts b/src/stores/__tests__/chatStore-migration.test.tsindex 64bb1137..eb1071ca 100644--- a/src/stores/__tests__/chatStore-migration.test.ts+++ b/src/stores/__tests__/chatStore-migration.test.ts@@ -10,6 +10,22 @@ const legacyCall: AgentToolCall = {timestamp: 1,}+/**+ * The migration mutates in place and hands back the SAME object, so the+ * assertions below need a typed view of it. `migratePersistedChat` itself+ * reports `unknown`, which is honest: it takes whatever a previous build of+ * the app persisted.+ */+interface PersistedBlock {+ id: string+ toolCall?: AgentToolCall+ toolCalls?: AgentToolCall[]+}+interface PersistedChat {+ conversations: { messages: { content?: string; agentBlocks?: PersistedBlock[] }[] }[]+}+const migrated = (state: unknown): PersistedChat => migratePersistedChat(state) as PersistedChat+describe('chatStore — migratePersistedChat', () => {it('returns null/undefined/non-object shapes unchanged', () => {expect(migratePersistedChat(null)).toBe(null)@@ -26,7 +42,7 @@ describe('chatStore — migratePersistedChat', () => {},],}- const result = migratePersistedChat(state)+ const result = migrated(state)expect(result.conversations[0].messages[0].content).toBe('hi')})@@ -53,8 +69,8 @@ describe('chatStore — migratePersistedChat', () => {},],}- const result = migratePersistedChat(state)- const migratedBlock = result.conversations[0].messages[0].agentBlocks[0]+ const result = migrated(state)+ const migratedBlock = result.conversations[0].messages[0].agentBlocks![0]expect(migratedBlock.toolCalls).toEqual([legacyCall])expect(migratedBlock.toolCall).toBe(legacyCall) // preserved for transition})@@ -87,11 +103,11 @@ describe('chatStore — migratePersistedChat', () => {},],}- const result = migratePersistedChat(state)- expect(result.conversations[0].messages[0].agentBlocks[0].toolCalls).toHaveLength(1)+ const result = migrated(state)+ expect(result.conversations[0].messages[0].agentBlocks![0].toolCalls).toHaveLength(1)// Non-tool block untouched.- expect(result.conversations[0].messages[0].agentBlocks[1].toolCalls).toBeUndefined()- expect(result.conversations[1].messages[0].agentBlocks[0].toolCalls?.[0].id).toBe('t2')+ expect(result.conversations[0].messages[0].agentBlocks![1].toolCalls).toBeUndefined()+ expect(result.conversations[1].messages[0].agentBlocks![0].toolCalls?.[0].id).toBe('t2')})it('is idempotent — re-running migration does not double-wrap', () => {@@ -118,8 +134,8 @@ describe('chatStore — migratePersistedChat', () => {],}const once = migratePersistedChat(state)- const twice = migratePersistedChat(once)- expect(twice.conversations[0].messages[0].agentBlocks[0].toolCalls).toEqual([legacyCall])+ const twice = migrated(once)+ expect(twice.conversations[0].messages[0].agentBlocks![0].toolCalls).toEqual([legacyCall])})it('handles malformed agentBlocks array without crashing', () => {diff --git a/src/stores/__tests__/createStore-migrate.test.ts b/src/stores/__tests__/createStore-migrate.test.tsindex f9e3e227..3401f6df 100644--- a/src/stores/__tests__/createStore-migrate.test.ts+++ b/src/stores/__tests__/createStore-migrate.test.ts@@ -5,7 +5,7 @@ vi.mock('../../api/comfyui', () => ({ classifyModel: () => 'unknown' }))// zustand/persist defaults to `window.localStorage` — in the node test env both// need shimming BEFORE the store module is imported, or persist silently no-ops.const backing = new Map<string, string>()-;(globalThis as any).window = globalThis+Object.defineProperty(globalThis, 'window', { value: globalThis, configurable: true, writable: true })globalThis.localStorage = {getItem: (k: string) => backing.get(k) ?? null,setItem: (k: string, v: string) => void backing.set(k, String(v)),diff --git a/src/stores/__tests__/createStore.test.ts b/src/stores/__tests__/createStore.test.tsindex 541c0973..04c56cfc 100644--- a/src/stores/__tests__/createStore.test.ts+++ b/src/stores/__tests__/createStore.test.ts@@ -37,6 +37,7 @@ vi.mock('../../api/comfyui', () => ({import { useCreateStore, MODEL_TYPE_DEFAULTS } from '../createStore'import type { GalleryItem } from '../createStore'+import { prop } from '../../types/json-guards'// ── Helpers ─────────────────────────────────────────────────────@@ -179,37 +180,48 @@ describe('createStore', () => {// tests document the contract: the store does not throw, and its// CONSUMERS (which this mirrors) can always fall back to [].describe('activeList fallback contract (mirrors CreateTopControls)', () => {- const computeActiveList = (mode: string, iml: unknown, vml: unknown) => {+ const computeActiveList = (mode: string, iml: unknown, vml: unknown): unknown[] => {const raw = mode === 'image' ? iml : vmlreturn Array.isArray(raw) ? raw : []}+ /**+ * Write a value the store's own type forbids. That is the point of this+ * block: `imageModelList` is declared as an array, and these tests exist+ * because a rehydrated blob from an older build has arrived as+ * undefined / null / an object / a string. The store type says what the+ * app WRITES; the cast is confined to this one helper so no individual+ * test claims a corrupt value is a model list.+ */+ const forceState = (patch: Record<string, unknown>) =>+ useCreateStore.setState(patch as Partial<ReturnType<typeof useCreateStore.getState>>)+it('falls back to [] when imageModelList is undefined', () => {- useCreateStore.setState({ imageModelList: undefined as any, mode: 'image' })+ forceState({ imageModelList: undefined, mode: 'image' })const s = useCreateStore.getState()expect(computeActiveList(s.mode, s.imageModelList, s.videoModelList)).toEqual([])})it('falls back to [] when videoModelList is undefined in video mode', () => {- useCreateStore.setState({ videoModelList: undefined as any, mode: 'video' })+ forceState({ videoModelList: undefined, mode: 'video' })const s = useCreateStore.getState()expect(computeActiveList(s.mode, s.imageModelList, s.videoModelList)).toEqual([])})it('falls back to [] when the list is null', () => {- useCreateStore.setState({ imageModelList: null as any, mode: 'image' })+ forceState({ imageModelList: null, mode: 'image' })const s = useCreateStore.getState()expect(computeActiveList(s.mode, s.imageModelList, s.videoModelList)).toEqual([])})it('falls back to [] when the list is an object', () => {- useCreateStore.setState({ imageModelList: { foo: 'bar' } as any, mode: 'image' })+ forceState({ imageModelList: { foo: 'bar' }, mode: 'image' })const s = useCreateStore.getState()expect(computeActiveList(s.mode, s.imageModelList, s.videoModelList)).toEqual([])})it('falls back to [] when the list is a string', () => {- useCreateStore.setState({ imageModelList: 'corrupted' as any, mode: 'image' })+ forceState({ imageModelList: 'corrupted', mode: 'image' })const s = useCreateStore.getState()expect(computeActiveList(s.mode, s.imageModelList, s.videoModelList)).toEqual([])})@@ -222,16 +234,16 @@ describe('createStore', () => {})it('.length and .map never throw on the fallback', () => {- useCreateStore.setState({ imageModelList: undefined as any, videoModelList: null as any })+ forceState({ imageModelList: undefined, videoModelList: null })const s = useCreateStore.getState()const imgList = computeActiveList('image', s.imageModelList, s.videoModelList)const vidList = computeActiveList('video', s.imageModelList, s.videoModelList)// These are the exact two operations CreateTopControls performs// (line 175 `.length === 0` and line 180 `.map(...)`).expect(() => imgList.length === 0).not.toThrow()- expect(() => imgList.map((m: any) => m.name)).not.toThrow()+ expect(() => imgList.map((m) => prop(m, 'name'))).not.toThrow()expect(() => vidList.length === 0).not.toThrow()- expect(() => vidList.map((m: any) => m.name)).not.toThrow()+ expect(() => vidList.map((m) => prop(m, 'name'))).not.toThrow()})})})diff --git a/src/stores/__tests__/downloadStore-orphans.test.ts b/src/stores/__tests__/downloadStore-orphans.test.tsindex 38456cb5..466cfba7 100644--- a/src/stores/__tests__/downloadStore-orphans.test.ts+++ b/src/stores/__tests__/downloadStore-orphans.test.ts@@ -24,34 +24,40 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'// behind a `typeof window` check, and a half-faked window breaks the import.vi.hoisted(() => {const backing = new Map<string, string>()- ;(globalThis as any).localStorage = {- getItem: (k: string) => backing.get(k) ?? null,- setItem: (k: string, v: string) => void backing.set(k, String(v)),- removeItem: (k: string) => void backing.delete(k),- clear: () => backing.clear(),- key: (i: number) => [...backing.keys()][i] ?? null,- get length() { return backing.size },- }+ // defineProperty rather than an assignment through a cast: the descriptor's+ // `value` is untyped, so the shim goes in without claiming to BE a Storage.+ Object.defineProperty(globalThis, 'localStorage', {+ configurable: true,+ writable: true,+ value: {+ getItem: (k: string) => backing.get(k) ?? null,+ setItem: (k: string, v: string) => void backing.set(k, String(v)),+ removeItem: (k: string) => void backing.delete(k),+ clear: () => backing.clear(),+ key: (i: number) => [...backing.keys()][i] ?? null,+ get length() { return backing.size },+ },+ })})-const findOrphanDownloads = vi.fn(async (_extra: string[]) => [] as any[])+const findOrphanDownloads = vi.fn(async (_extra: string[]): Promise<OrphanDownload[]> => [])const deleteOrphanDownload = vi.fn(async () => {})const resumeDownload = vi.fn(async () => {})-const getDownloadProgress = vi.fn(async () => ({} as Record<string, any>))+const getDownloadProgress = vi.fn(async (): Promise<Record<string, DownloadProgress>> => ({}))vi.mock('../../api/discover', async () => {const actual = await vi.importActual<typeof import('../../api/discover')>('../../api/discover')return {- getDownloadProgress: (...a: any[]) => getDownloadProgress(...(a as [])),+ getDownloadProgress: (...a: unknown[]) => getDownloadProgress(...(a as [])),pauseDownload: vi.fn(async () => {}),cancelDownload: vi.fn(async () => {}),clearDownloadEntry: vi.fn(async () => {}),- resumeDownload: (...a: any[]) => resumeDownload(...(a as [])),+ resumeDownload: (...a: unknown[]) => resumeDownload(...(a as [])),startModelDownload: vi.fn(async () => {}),startModelDownloadToPath: vi.fn(async () => {}),lookupFileMeta: () => undefined,- findOrphanDownloads: (...a: any[]) => findOrphanDownloads(...(a as [any])),- deleteOrphanDownload: (...a: any[]) => deleteOrphanDownload(...(a as [])),+ findOrphanDownloads: (...a: unknown[]) => findOrphanDownloads(...(a as [string[]])),+ deleteOrphanDownload: (...a: unknown[]) => deleteOrphanDownload(...(a as [])),catalogFilenames: () => ['wan_2.1_vae.safetensors'],orphanFilename: actual.orphanFilename,isPermanentDownloadError: actual.isPermanentDownloadError,@@ -61,6 +67,8 @@ vi.mock('../../api/discover', async () => {})import { useDownloadStore, orphanRows, flushDownloadPersist } from '../downloadStore'+import type { DownloadProgress } from '../../types/downloads'+import type { OrphanDownload } from '../../api/discover'const GGUF_DIR = '/Users/x/.lmstudio/models'diff --git a/src/stores/__tests__/downloadStore-retry.test.ts b/src/stores/__tests__/downloadStore-retry.test.tsindex 9859d905..673393c3 100644--- a/src/stores/__tests__/downloadStore-retry.test.ts+++ b/src/stores/__tests__/downloadStore-retry.test.ts@@ -32,13 +32,13 @@ vi.mock('../../api/discover', async () => {// eine Attrappe davon.const actual = await vi.importActual<typeof import('../../api/discover')>('../../api/discover')return {- getDownloadProgress: (...a: any[]) => getDownloadProgress(...(a as [])),+ getDownloadProgress: (...a: unknown[]) => getDownloadProgress(...(a as [])),pauseDownload: vi.fn(async () => {}),- cancelDownload: (...a: any[]) => cancelDownload(...(a as [])),- clearDownloadEntry: (...a: any[]) => clearDownloadEntry(...(a as [])),- resumeDownload: (...a: any[]) => resumeDownload(...(a as [])),- startModelDownload: (...a: any[]) => startModelDownload(...(a as [])),- startModelDownloadToPath: (...a: any[]) => startModelDownloadToPath(...(a as [])),+ cancelDownload: (...a: unknown[]) => cancelDownload(...(a as [])),+ clearDownloadEntry: (...a: unknown[]) => clearDownloadEntry(...(a as [])),+ resumeDownload: (...a: unknown[]) => resumeDownload(...(a as [])),+ startModelDownload: (...a: unknown[]) => startModelDownload(...(a as [])),+ startModelDownloadToPath: (...a: unknown[]) => startModelDownloadToPath(...(a as [])),lookupFileMeta: () => undefined,findOrphanDownloads: vi.fn(async () => []),deleteOrphanDownload: vi.fn(async () => {}),@@ -51,11 +51,12 @@ vi.mock('../../api/discover', async () => {})import { useDownloadStore } from '../downloadStore'+import type { DownloadProgress } from '../../types/downloads'function seedErrored(id: string, error = 'boom') {useDownloadStore.setState({downloads: {- [id]: { progress: 10, total: 100, speed: 0, filename: id, status: 'error', error } as any,+ [id]: { progress: 10, total: 100, speed: 0, filename: id, status: 'error', error } satisfies DownloadProgress,},downloadMeta: { [id]: { url: 'https://example.test/m.safetensors', subfolder: 'checkpoints' } },orphans: {},@@ -100,7 +101,7 @@ describe('downloadStore.retry', () => {it('does not cancel a transfer that is merely paused', async () => {useDownloadStore.setState({downloads: {- 'm.gguf': { progress: 5, total: 100, speed: 0, filename: 'm.gguf', status: 'paused' } as any,+ 'm.gguf': { progress: 5, total: 100, speed: 0, filename: 'm.gguf', status: 'paused' } satisfies DownloadProgress,},downloadMeta: { 'm.gguf': { url: 'https://example.test/m.gguf', subfolder: 'unet' } },})diff --git a/src/stores/__tests__/memoryStore-migrate.test.ts b/src/stores/__tests__/memoryStore-migrate.test.tsnew file mode 100644index 00000000..677fa69d--- /dev/null+++ b/src/stores/__tests__/memoryStore-migrate.test.ts@@ -0,0 +1,138 @@+/**+ * Was eine kaputte Zeile im gespeicherten Memory-Blob kostet.+ *+ * `migrate` liest Daten, die eine ÄLTERE Version dieser App geschrieben hat,+ * und zustand gibt ihm keinen zweiten Versuch: wirft es, landet der Fehler in+ * persists `.catch`, die Hydration wird abgebrochen, `set()` läuft nie — der+ * Store bleibt auf seinem leeren Default stehen. Der nächste Schreibvorgang+ * persistiert dann GENAU DIESEN leeren Stand über den gespeicherten Blob.+ * Eine einzige Zeile, die die Migration nicht lesen kann, nimmt damit alle+ * Erinnerungen dauerhaft mit.+ *+ * Der erste Block misst diese Mechanik an der echten Bibliothek, statt sie zu+ * behaupten. Der Rest prüft, dass migrateMemoryState sie nicht mehr auslöst.+ *+ * Run: npx vitest run src/stores/__tests__/memoryStore-migrate.test.ts+ */+import { describe, it, expect } from 'vitest'+import { create } from 'zustand'+import { persist, createJSONStorage } from 'zustand/middleware'+import { migrateMemoryState } from '../memoryStore'+import type { MemoryFile } from '../../types/agent-mode'++function memoryStorage(seed?: [string, string]) {+ const mem = new Map<string, string>()+ if (seed) mem.set(seed[0], seed[1])+ return {+ mem,+ api: {+ getItem: (k: string) => mem.get(k) ?? null,+ setItem: (k: string, v: string) => void mem.set(k, v),+ removeItem: (k: string) => void mem.delete(k),+ },+ }+}++describe('a throwing migrate costs the whole store, measured not assumed', () => {+ // The unguarded migration's shape: a read straight into each entry.+ const storeOver = (blob: string) => {+ const { mem, api } = memoryStorage(['blast', blob])+ const s = create<{ entries: string[]; add: (e: string) => void }>()(persist((set) => ({+ entries: [],+ add: (e) => set((x) => ({ entries: [...x.entries, e] })),+ }), {+ name: 'blast',+ version: 3,+ storage: createJSONStorage(() => api as never),+ migrate: (p) => ({ entries: (p as { entries: string[] }).entries.map((e) => e.toUpperCase()) }) as never,+ }))+ return { mem, s }+ }++ it('hydrates normally while every entry is readable', async () => {+ const { s } = storeOver(JSON.stringify({ state: { entries: ['a', 'b'] }, version: 2 }))+ await s.persist.rehydrate()+ expect(s.getState().entries).toEqual(['A', 'B'])+ })++ it('leaves the store at its defaults and then overwrites the blob with them', async () => {+ const { mem, s } = storeOver(JSON.stringify({ state: { entries: ['a', null] }, version: 2 }))+ await s.persist.rehydrate()++ // Nothing hydrated — the good entry is lost along with the bad one…+ expect(s.getState().entries).toEqual([])+ // …and the next ordinary write persists that emptiness over the blob.+ s.getState().add('new')+ expect(JSON.parse(mem.get('blast')!).state.entries).toEqual(['new'])+ })+})++describe('migrateMemoryState — v2 blob (the migration every 2.5.x user runs)', () => {+ const good = (id: string): Record<string, unknown> => ({+ id,+ type: 'project',+ title: `t-${id}`,+ description: `d-${id}`,+ content: `c-${id}`,+ tags: ['x'],+ createdAt: 1,+ updatedAt: 2,+ source: 'manual',+ })++ const entriesOf = (v: unknown): MemoryFile[] => (v as { entries: MemoryFile[] }).entries++ it('drops the one unreadable entry instead of the whole store', () => {+ const out = migrateMemoryState({ entries: [good('a'), null, good('b')] }, 2)+ expect(entriesOf(out).map((e) => e.id)).toEqual(['a', 'b'])+ })++ it('survives a non-object where an entry should be', () => {+ const out = migrateMemoryState({ entries: ['just a string', 42, good('a')] }, 2)+ expect(entriesOf(out).map((e) => e.id)).toEqual(['a'])+ })++ it('keeps every readable field of a well-formed entry', () => {+ const out = migrateMemoryState({ entries: [good('a')] }, 2)+ expect(entriesOf(out)[0]).toMatchObject({+ id: 'a', type: 'project', title: 't-a', description: 'd-a',+ content: 'c-a', tags: ['x'], createdAt: 1, updatedAt: 2, source: 'manual',+ })+ })++ it('still concretises the stale flag, which is what v3 exists for', () => {+ const out = migrateMemoryState({ entries: [good('a'), { ...good('b'), stale: true }] }, 2)+ expect(entriesOf(out).map((e) => e.stale)).toEqual([false, true])+ })++ it('drops a type it does not know rather than carrying it into retrieval', () => {+ const out = migrateMemoryState({ entries: [{ ...good('a'), type: 'nonsense' }] }, 2)+ expect(entriesOf(out)[0].type).toBe('project')+ })+})++describe('migrateMemoryState — v1 blob (MemoryEntry[] → MemoryFile[])', () => {+ const legacy = (id: string) => ({ id, category: 'fact', content: `c-${id}`, timestamp: 7, source: 'user:manual' })++ const entriesOf = (v: unknown): MemoryFile[] => (v as { entries: MemoryFile[] }).entries++ it('maps the legacy category onto the new type', () => {+ const out = migrateMemoryState({ entries: [legacy('a')] }, 1)+ expect(entriesOf(out)[0]).toMatchObject({ id: 'a', type: 'user', content: 'c-a', createdAt: 7, updatedAt: 7 })+ })++ it('drops a legacy entry with no content instead of throwing on it', () => {+ const out = migrateMemoryState({ entries: [{ id: 'a', category: 'fact' }, legacy('b')] }, 1)+ expect(entriesOf(out).map((e) => e.id)).toEqual(['b'])+ })++ it('does not choke on a null first entry when testing "already migrated?"', () => {+ const out = migrateMemoryState({ entries: [null, legacy('b')] }, 1)+ expect(entriesOf(out).map((e) => e.id)).toEqual(['b'])+ })++ it('leaves a blob with no entries array alone', () => {+ expect(migrateMemoryState({ settings: { maxMemoriesInPrompt: 3 } }, 1))+ .toEqual({ settings: { maxMemoriesInPrompt: 3 } })+ })+})diff --git a/src/stores/__tests__/mlxInstallStore.test.ts b/src/stores/__tests__/mlxInstallStore.test.tsindex d443118e..143933d8 100644--- a/src/stores/__tests__/mlxInstallStore.test.ts+++ b/src/stores/__tests__/mlxInstallStore.test.ts@@ -18,12 +18,12 @@ const getMlxInstallStatus = vi.fn()const getModelInstallStatus = vi.fn()vi.mock('../../api/mlx-image', () => ({- getMlxImageEngineStatus: (...a: any[]) => getMlxImageEngineStatus(...(a as [])),- getMlxImageInstallStatus: (...a: any[]) => getMlxImageInstallStatus(...(a as [])),+ getMlxImageEngineStatus: (...a: unknown[]) => getMlxImageEngineStatus(...(a as [])),+ getMlxImageInstallStatus: (...a: unknown[]) => getMlxImageInstallStatus(...(a as [])),}))vi.mock('../../api/mlx-video', () => ({- getMlxInstallStatus: (...a: any[]) => getMlxInstallStatus(...(a as [])),- getModelInstallStatus: (...a: any[]) => getModelInstallStatus(...(a as [])),+ getMlxInstallStatus: (...a: unknown[]) => getMlxInstallStatus(...(a as [])),+ getModelInstallStatus: (...a: unknown[]) => getModelInstallStatus(...(a as [])),}))import { useMlxInstallStore } from '../mlxInstallStore'diff --git a/src/stores/__tests__/permissionStore-v24.test.ts b/src/stores/__tests__/permissionStore-v24.test.tsindex 588c40ee..27271973 100644--- a/src/stores/__tests__/permissionStore-v24.test.ts+++ b/src/stores/__tests__/permissionStore-v24.test.ts@@ -4,6 +4,7 @@ import {MODE_SCOPE_ALLOWED_CATEGORIES,modeAllowsCategory,} from '../permissionStore'+import type { ToolCategory } from '../../api/mcp/types'describe('permissionStore — Phase 12 per-tool overrides', () => {beforeEach(() => {@@ -89,10 +90,10 @@ describe('permissionStore — Phase 12 mode scopes', () => {})it('agent scope allows every category', () => {- const all: ReadonlyArray<string> = [+ const all: ReadonlyArray<ToolCategory> = ['filesystem', 'terminal', 'desktop', 'web', 'system', 'image', 'video', 'workflow',]- for (const c of all) expect(modeAllowsCategory('agent', c as any)).toBe(true)+ for (const c of all) expect(modeAllowsCategory('agent', c)).toBe(true)})it('allowed-category table is monotonic chat ⊆ edit ⊆ agent', () => {diff --git a/src/stores/__tests__/remoteStore-v2.test.ts b/src/stores/__tests__/remoteStore-v2.test.tsindex 6fe72e7a..135418de 100644--- a/src/stores/__tests__/remoteStore-v2.test.ts+++ b/src/stores/__tests__/remoteStore-v2.test.ts@@ -18,6 +18,7 @@ vi.mock('../../api/backend', () => ({isTauri: vi.fn(() => true),}))import { backendCall } from '../../api/backend'+import { prop } from '../../types/json-guards'const mockBackend = backendCall as unknown as ReturnType<typeof vi.fn>beforeEach(() => {@@ -40,7 +41,10 @@ beforeEach(() => {dispatchedConversationId: null,qrVisible: false,})- useMemoryStore.setState({ memories: [] } as any)+ // NOTE: this reset named `memories`, a field the memory store does not+ // have — `as any` let it compile, so it never reset anything. The real+ // field is `entries`.+ useMemoryStore.setState({ entries: [] })})afterEach(() => {@@ -101,9 +105,7 @@ describe('remoteStore › dispatch()', () => {})it('enriches systemPrompt with memory before sending', async () => {- useMemoryStore.setState({- getMemoriesForPrompt: () => 'MEM CONTEXT HERE',- } as any)+ useMemoryStore.setState({ getMemoriesForPrompt: () => 'MEM CONTEXT HERE' })mockBackend.mockResolvedValue({ port: 11435, passcode: '123456' })await useRemoteStore.getState().dispatch('c', 'm', 'BASE')const call = mockBackend.mock.calls.find(c => c[0] === 'start_remote_server')@@ -112,9 +114,7 @@ describe('remoteStore › dispatch()', () => {})it('uses memory-only prompt if base systemPrompt is empty', async () => {- useMemoryStore.setState({- getMemoriesForPrompt: () => 'ONLY_MEMORIES',- } as any)+ useMemoryStore.setState({ getMemoriesForPrompt: () => 'ONLY_MEMORIES' })mockBackend.mockResolvedValue({ port: 11435, passcode: '123456' })await useRemoteStore.getState().dispatch('c', 'm', '')const call = mockBackend.mock.calls.find(c => c[0] === 'start_remote_server')@@ -122,9 +122,7 @@ describe('remoteStore › dispatch()', () => {})it('leaves systemPrompt unchanged when no memories', async () => {- useMemoryStore.setState({- getMemoriesForPrompt: () => '',- } as any)+ useMemoryStore.setState({ getMemoriesForPrompt: () => '' })mockBackend.mockResolvedValue({ port: 11435, passcode: '123456' })await useRemoteStore.getState().dispatch('c', 'm', 'KEEP_THIS')const call = mockBackend.mock.calls.find(c => c[0] === 'start_remote_server')@@ -206,7 +204,7 @@ describe('remoteStore › undispatch()', () => {describe('remoteStore › memory enrichment behaviour', () => {it('prepends "remembered context" preamble to memory block', async () => {- useMemoryStore.setState({ getMemoriesForPrompt: () => 'FACT_A\nFACT_B' } as any)+ useMemoryStore.setState({ getMemoriesForPrompt: () => 'FACT_A\nFACT_B' })mockBackend.mockResolvedValue({})await useRemoteStore.getState().dispatch('c', 'm', '')const call = mockBackend.mock.calls.find(c => c[0] === 'start_remote_server')@@ -214,7 +212,7 @@ describe('remoteStore › memory enrichment behaviour', () => {})it('separates base prompt and memory with double newline', async () => {- useMemoryStore.setState({ getMemoriesForPrompt: () => 'MEM' } as any)+ useMemoryStore.setState({ getMemoriesForPrompt: () => 'MEM' })mockBackend.mockResolvedValue({})await useRemoteStore.getState().dispatch('c', 'm', 'BASE')const call = mockBackend.mock.calls.find(c => c[0] === 'start_remote_server')@@ -222,9 +220,7 @@ describe('remoteStore › memory enrichment behaviour', () => {})it('swallows memory-store errors gracefully', async () => {- useMemoryStore.setState({- getMemoriesForPrompt: () => { throw new Error('store broke') },- } as any)+ useMemoryStore.setState({ getMemoriesForPrompt: () => { throw new Error('store broke') } })mockBackend.mockResolvedValue({})await useRemoteStore.getState().dispatch('c', 'm', 'STILL_OK')const call = mockBackend.mock.calls.find(c => c[0] === 'start_remote_server')@@ -233,9 +229,10 @@ describe('remoteStore › memory enrichment behaviour', () => {})it('enrichment applies to restart as well (via restart_remote_server)', async () => {- useMemoryStore.setState({ getMemoriesForPrompt: () => 'MEM' } as any)+ useMemoryStore.setState({ getMemoriesForPrompt: () => 'MEM' })mockBackend.mockResolvedValue({})- const restart = (useRemoteStore.getState() as any).restart+ // `restart` is not on the store's interface; the test probes for it.+ const restart = prop(useRemoteStore.getState(), 'restart')if (typeof restart === 'function') {await restart('conv-r', 'm', 'BASE')const call = mockBackend.mock.calls.find(c => c[0] === 'restart_remote_server')diff --git a/src/stores/__tests__/settingsStore.test.ts b/src/stores/__tests__/settingsStore.test.tsindex 30144bed..b3dc7888 100644--- a/src/stores/__tests__/settingsStore.test.ts+++ b/src/stores/__tests__/settingsStore.test.ts@@ -104,7 +104,7 @@ describe('settingsStore', () => {})it('resets array/object-valued keys by default value (gpuIndices, defaultWorkspace)', () => {- useSettingsStore.getState().updateSettings({ gpuIndices: [1, 2], defaultWorkspace: { path: 'C:/tmp', label: 'tmp' } as any })+ useSettingsStore.getState().updateSettings({ gpuIndices: [1, 2], defaultWorkspace: { kind: 'folder', path: 'C:/tmp' } })useSettingsStore.getState().resetSettingsKeys(['gpuIndices', 'defaultWorkspace'])const s = useSettingsStore.getState().settingsexpect(s.gpuIndices).toEqual(DEFAULT_SETTINGS.gpuIndices)diff --git a/src/stores/agentWorkflowStore.ts b/src/stores/agentWorkflowStore.tsindex ffd14fd4..74483bc4 100644--- a/src/stores/agentWorkflowStore.ts+++ b/src/stores/agentWorkflowStore.ts@@ -4,6 +4,7 @@ import { safeJSONStorage } from '../lib/storage-quota'import { v4 as uuid } from 'uuid'import type { AgentWorkflow, WorkflowExecution, StepResult } from '../types/agent-workflows'import { BUILT_IN_WORKFLOWS } from '../lib/built-in-workflows'+import { isRecord, prop, asString } from '../types/json-guards'// ── Max execution history ─────────────────────────────────────@@ -147,17 +148,24 @@ export const useAgentWorkflowStore = create<AgentWorkflowState>()(storage: safeJSONStorage(),version: 1,migrate: (persistedState, version) => {- const state = persistedState as any- if (version < 1 || !state.workflows || state.workflows.length === 0) {- return { ...state, workflows: BUILT_IN_WORKFLOWS, executions: [], activeExecutionId: null }- }+ // Persisted state is foreign at read time: an older build wrote it. A+ // read that throws in here costs the WHOLE store — zustand abandons+ // hydration and the next write persists the empty default over the+ // blob — so `workflows` is checked for being an array instead of just+ // being truthy (`{}.length` is undefined, which is not 0, and the+ // `.map` below then threw).+ const state = isRecord(persistedState) ? persistedState : {}+ const workflows = Array.isArray(state.workflows) ? state.workflows : []// Ensure built-ins are present (may have been added in updates)- const existingIds = new Set(state.workflows.map((w: any) => w.id))+ const existingIds = new Set(workflows.map((w) => asString(prop(w, 'id'))))const missingBuiltIns = BUILT_IN_WORKFLOWS.filter(w => !existingIds.has(w.id))- return {- ...state,- workflows: [...missingBuiltIns, ...state.workflows],- }+ const next = version < 1 || workflows.length === 0+ ? { ...state, workflows: BUILT_IN_WORKFLOWS, executions: [], activeExecutionId: null }+ : { ...state, workflows: [...missingBuiltIns, ...workflows] }+ // zustand types migrate as returning the FULL store, but a blob only+ // ever carries the partialized slice and `merge` puts the actions+ // back. The cast claims exactly what went in, nothing about actions.+ return next as unknown as AgentWorkflowState},partialize: (state) => ({workflows: state.workflows,diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.tsindex f0243dcd..faa871c8 100644--- a/src/stores/chatStore.ts+++ b/src/stores/chatStore.ts@@ -13,6 +13,7 @@ import { useTodoStore } from './todoStore'import { usePermissionStore } from './permissionStore'import { useStagedChangesStore } from './stagedChangesStore'import { log } from '../lib/logger'+import { isRecord, prop } from '../types/json-guards'/*** Rehydration migration for Phase 1 (v2.4.0) — wraps legacy@@ -20,14 +21,20 @@ import { log } from '../lib/logger'* form. Idempotent: safe to run on already-migrated data. Leaves the legacy* field in place during a transition window so reads via either shape work.*/-export function migratePersistedChat(state: any): any {- if (!state || !Array.isArray(state.conversations)) return state- for (const conv of state.conversations) {- if (!conv || !Array.isArray(conv.messages)) continue- for (const msg of conv.messages) {- if (!msg || !Array.isArray(msg.agentBlocks)) continue- for (const block of msg.agentBlocks as AgentBlock[]) {- if (block) migrateBlockInPlace(block)+export function migratePersistedChat(state: unknown): unknown {+ const conversations = prop(state, 'conversations')+ if (!Array.isArray(conversations)) return state+ for (const conv of conversations) {+ const messages = prop(conv, 'messages')+ if (!Array.isArray(messages)) continue+ for (const msg of messages) {+ const blocks = prop(msg, 'agentBlocks')+ if (!Array.isArray(blocks)) continue+ for (const block of blocks) {+ // migrateBlockInPlace reads `toolCall` and `toolCalls` and writes+ // `toolCalls`; the cast claims no more than those three, and the+ // record check above is what makes even that much true.+ if (isRecord(block)) migrateBlockInPlace(block as unknown as AgentBlock)}}}@@ -425,7 +432,11 @@ export const useChatStore = create<ChatState>()(importConversations: (incoming, mode = 'merge') => {// Normalize legacy block shapes on the way in (the same migration the// persist layer runs on load), so an older export hydrates cleanly.- const clean = ((migratePersistedChat({ conversations: incoming })?.conversations ?? incoming) as Conversation[])+ // It mutates the array it is handed and returns the same object, so+ // `incoming` IS the normalised list afterwards — no cast needed, and+ // the old `?? incoming` fallback could never fire.+ migratePersistedChat({ conversations: incoming })+ const clean = incominglet added = 0let skipped = 0set((state) => {@@ -478,9 +489,9 @@ export const useChatStore = create<ChatState>()(// chat history away. That is the R1 DOWNGRADE-KONTRAKT (see codexStore) —// 2.6.x builds share one WebView profile — so stamping a number here would// buy nothing and cost a reset on every downgrade.- merge: (persistedState: any, currentState: ChatState) => {+ merge: (persistedState, currentState) => {const migrated = migratePersistedChat(persistedState)- return { ...currentState, ...(migrated || {}) }+ return { ...currentState, ...(isRecord(migrated) ? migrated : {}) }},})diff --git a/src/stores/createStore.ts b/src/stores/createStore.tsindex e3df4c17..5b43a68d 100644--- a/src/stores/createStore.ts+++ b/src/stores/createStore.ts@@ -1,6 +1,16 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'import { safeJSONStorage } from '../lib/storage-quota'+import { isRecord } from '../types/json-guards'++/**+ * Fields a persisted blob must never put back into live state: they steer the+ * backend axis or carry staged media (source image, mask, capability probe+ * results, the in-flight flag). Everything else in the blob is a preference.+ */+const RUNTIME_ONLY_KEYS: readonly string[] = [+ 'backend', 'source', 'mask', 'caps', 'isGenerating', 'comfyCorsBlocked',+]import type { ModelType, ClassifiedModel } from '../api/comfyui'import { classifyModel } from '../api/comfyui'import type { HiresUpscaleMethod } from '../api/hires-fix'@@ -866,20 +876,30 @@ export const useCreateStore = create<CreateState>()(// when the stored blob carries a NUMERIC version that differs — legacy// pre-version blobs skip it entirely, so their fixups must live in merge.version: 1,- migrate: (persisted: any) => persisted,- merge: (persisted: any, current: any) => {+ // Explicit annotations for the same reason the state creator carries+ // them (see above): under `strict: true` zustand v5 loses contextual+ // typing here and infers the store as Partial<CreateState>.+ migrate: (persisted: unknown): CreateState => persisted as CreateState,+ merge: (persisted: unknown, current: CreateState): CreateState => {// Never let runtime-only fields rehydrate (a foreign/corrupt blob must// not flip the backend axis or inject a stale source/mask), backfill// missing keys from defaults, and fix up legacy pre-version blobs// ('i2i' mode from the v2.3.0 refactor).- const { backend, source, mask, caps, isGenerating, comfyCorsBlocked, ...safe } =- persisted ?? {}- const merged = { ...current, ...safe }- if (merged.mode === 'i2i') {- merged.mode = 'image'- merged.imageSubMode = 'img2img'+ const raw = isRecord(persisted) ? persisted : {}+ const safe: Record<string, unknown> = {}+ for (const [k, v] of Object.entries(raw)) if (!RUNTIME_ONLY_KEYS.includes(k)) safe[k] = v+ // 'i2i' was a MODE of its own before v2.3.0; it is now mode 'image'+ // plus imageSubMode 'img2img'. Fixed on the raw blob, because the+ // value is not a member of the current union any more.+ if (safe.mode === 'i2i') {+ safe.mode = 'image'+ safe.imageSubMode = 'img2img'}- return merged+ // The persisted slice is ~30 independent scalar preferences (see+ // partialize). They are adopted as written, which is what the store+ // has always done; the fields that could actually do damage — the+ // backend axis and the staged media — are the ones dropped above.+ return { ...current, ...safe } as CreateState},})diff --git a/src/stores/memoryStore.ts b/src/stores/memoryStore.tsindex 5780befe..876b357c 100644--- a/src/stores/memoryStore.ts+++ b/src/stores/memoryStore.ts@@ -1,13 +1,14 @@import { create } from 'zustand'import { persist, createJSONStorage } from 'zustand/middleware'import { v4 as uuid } from 'uuid'-import type { MemoryEntry, MemoryCategory, MemoryFile, MemoryType, MemorySettings, MemoryBudgetTier } from '../types/agent-mode'+import type { MemoryCategory, MemoryFile, MemoryType, MemorySettings, MemoryBudgetTier } from '../types/agent-mode'import { MEMORY_MIGRATION_MAP, MEMORY_BUDGET_TIERS } from '../types/agent-mode'import { idbStorage } from '../lib/idbStorage'import { generateEmbeddings } from '../api/rag'import { saveVector, loadVectors, deleteVector, clearAll as clearAllVectors, type MemoryVectorRecord } from '../lib/memoryEmbedDB'import { scoreMemoriesBlended, isStale, type BlendCandidate } from '../lib/memory-retrieval'import type { ResolutionDecision } from '../lib/memory-extraction'+import { isRecord, prop, asString, asNumber, asStringArray } from '../types/json-guards'import { log } from '../lib/logger'// ── Embedding model + dim (mirrors rag.ts default) ────────────────@@ -277,27 +278,56 @@ interface MemoryState {}// ── Migration from v1 (old MemoryEntry[]) to v2 (MemoryFile[]) ──+//+// WHY EVERY FIELD IS CHECKED HERE. A migration reads data an OLDER build of+// this app wrote, and zustand gives it no second chance: a migrate that throws+// lands in persist's `.catch`, hydration is abandoned, the store keeps its+// empty default — and the next write persists that empty list back over the+// stored blob. One entry the migration cannot read would take every memory+// with it, permanently. So each entry is checked on its own and a broken one+// is dropped alone.++/** The v1 fields a MemoryEntry must have to be worth carrying forward. */+function asLegacyEntry(v: unknown): { id: string; category: string; content: string; timestamp: number; source?: string } | null {+ if (!isRecord(v)) return null+ const content = asString(v.content)+ if (!content) return null+ return {+ id: asString(v.id) ?? uuid(),+ category: asString(v.category) ?? '',+ content,+ timestamp: asNumber(v.timestamp) ?? Date.now(),+ source: asString(v.source),+ }+}-function migrateV1toV2(oldState: any): any {- if (!oldState || !Array.isArray(oldState.entries)) return oldState+function migrateV1toV2(oldState: unknown): unknown {+ if (!isRecord(oldState) || !Array.isArray(oldState.entries)) return oldState- // Check if already migrated (MemoryFile has 'type' field)- if (oldState.entries.length > 0 && 'type' in oldState.entries[0]) {+ // Check if already migrated (MemoryFile has 'type' field). Sampling the+ // first entry is the original test; `in` on a non-object used to throw.+ const first: unknown = oldState.entries[0]+ if (oldState.entries.length > 0 && isRecord(first) && 'type' in first) {return oldState}// Migrate old MemoryEntry[] to MemoryFile[]- const migratedEntries: MemoryFile[] = (oldState.entries as MemoryEntry[]).map((e) => ({- id: e.id,- type: MEMORY_MIGRATION_MAP[e.category] || 'project',- title: e.content.substring(0, 60).replace(/\n/g, ' '),- description: e.content.substring(0, 120).replace(/\n/g, ' '),- content: e.content,- tags: e.source ? [e.source] : [],- createdAt: e.timestamp,- updatedAt: e.timestamp,- source: e.source || 'migration',- }))+ const migratedEntries: MemoryFile[] = []+ for (const raw of oldState.entries) {+ const e = asLegacyEntry(raw)+ if (!e) continue+ migratedEntries.push({+ id: e.id,+ type: MEMORY_MIGRATION_MAP[e.category as MemoryCategory] || 'project',+ title: e.content.substring(0, 60).replace(/\n/g, ' '),+ description: e.content.substring(0, 120).replace(/\n/g, ' '),+ content: e.content,+ tags: e.source ? [e.source] : [],+ createdAt: e.timestamp,+ updatedAt: e.timestamp,+ source: e.source || 'migration',+ })+ }return {...oldState,@@ -319,15 +349,70 @@ function migrateV1toV2(oldState: any): any {// `stale` flag is a concrete boolean (false) on every entry, so retrieval's// `isStale` and the "Show outdated" filter behave deterministically on// freshly-rehydrated old stores. All other new fields stay undefined.-function migrateV2toV3(oldState: any): any {- if (!oldState || !Array.isArray(oldState.entries)) return oldState- const entries = (oldState.entries as MemoryFile[]).map((e) => ({- ...e,- stale: e.stale === true ? true : false,- }))+//+// This is the migration EVERY 2.5.x user runs, so the check above matters+// most here: `e.stale` on a non-object entry threw, and the throw cost the+// whole store.+function migrateV2toV3(oldState: unknown): unknown {+ if (!isRecord(oldState) || !Array.isArray(oldState.entries)) return oldState+ const entries: MemoryFile[] = []+ for (const raw of oldState.entries) {+ const e = asMemoryFile(raw)+ if (e) entries.push(e)+ }return { ...oldState, entries }}+/**+ * A persisted MemoryFile, rebuilt from checked fields. The four required+ * strings and the two timestamps decide whether an entry is usable at all;+ * the optional staleness fields are carried over when they have the right+ * type and dropped when they do not.+ */+function asMemoryFile(v: unknown): MemoryFile | null {+ if (!isRecord(v)) return null+ const content = asString(v.content)+ if (!content) return null+ const now = Date.now()+ const type = MEMORY_TYPES.find((t) => t === v.type) ?? 'project'+ return {+ id: asString(v.id) ?? uuid(),+ type,+ title: asString(v.title) ?? content.substring(0, 60).replace(/\n/g, ' '),+ description: asString(v.description) ?? content.substring(0, 120).replace(/\n/g, ' '),+ content,+ tags: asStringArray(v.tags),+ createdAt: asNumber(v.createdAt) ?? now,+ updatedAt: asNumber(v.updatedAt) ?? asNumber(v.createdAt) ?? now,+ source: asString(v.source) ?? 'migration',+ supersededBy: asString(v.supersededBy),+ supersedesId: asString(v.supersedesId),+ stale: v.stale === true,+ validFrom: asNumber(v.validFrom),+ }+}++const MEMORY_TYPES: readonly MemoryType[] = ['user', 'feedback', 'project', 'reference']++/**+ * The persist `migrate` hook. Exported so a test can drive it directly — the+ * persist internals are not reachable from vitest (same reason+ * migratePermissionState is exported).+ */+export function migrateMemoryState(persistedState: unknown, version: number): MemoryState {+ let state: unknown = persistedState+ if (version < 2) {+ state = migrateV1toV2(state)+ }+ if (version < 3) {+ state = migrateV2toV3(state)+ }+ // zustand types migrate as returning the FULL store, but a blob only ever+ // carries the partialized slice and `merge` puts the actions back. The cast+ // claims exactly what went in, nothing about the actions.+ return state as MemoryState+}+// ── Store ─────────────────────────────────────────────────────export const useMemoryStore = create<MemoryState>()(@@ -705,7 +790,7 @@ export const useMemoryStore = create<MemoryState>()(},importFromJSON: (json) => {- let raw: any+ let raw: unknowntry {raw = JSON.parse(json)} catch {@@ -715,28 +800,33 @@ export const useMemoryStore = create<MemoryState>()(// Tolerant shape handling: accept LU's own {entries:[...]} export, a// bare [...] array, or {memories:[...]} (konata-session 2026-06-07 —// imports silently produced 0 entries on any other shape).- const arr: any[] = Array.isArray(raw) ? raw- : Array.isArray(raw?.entries) ? raw.entries- : Array.isArray(raw?.memories) ? raw.memories+ const entriesField = prop(raw, 'entries')+ const memoriesField = prop(raw, 'memories')+ const arr: unknown[] = Array.isArray(raw) ? raw+ : Array.isArray(entriesField) ? entriesField+ : Array.isArray(memoriesField) ? memoriesField: []- const VALID: MemoryType[] = ['user', 'feedback', 'project', 'reference']const now = Date.now()const newEntries: MemoryFile[] = []for (const e of arr) {- const content = String(e?.content ?? e?.text ?? e?.value ?? '').trim()+ // `content` may also arrive as `text` / `value` — a foreign export's+ // spelling. Only a real string counts: the old String(...) turned an+ // object into the literal "[object Object]" and imported that.+ const content = (asString(prop(e, 'content')) ?? asString(prop(e, 'text')) ?? asString(prop(e, 'value')) ?? '').trim()if (!content) continue+ const type = MEMORY_TYPES.find((t) => t === prop(e, 'type')) ?? 'user'newEntries.push({// Always mint a fresh id so a re-imported export can never collide// with an existing entry's id (which broke edit/remove-by-id).id: uuid(),- type: VALID.includes(e?.type) ? e.type : 'user',- title: String(e?.title ?? content).slice(0, 60).replace(/\n/g, ' '),- description: String(e?.description ?? content).slice(0, 120),+ type,+ title: (asString(prop(e, 'title')) ?? content).slice(0, 60).replace(/\n/g, ' '),+ description: (asString(prop(e, 'description')) ?? content).slice(0, 120),content,- tags: Array.isArray(e?.tags) ? e.tags.map((t: any) => String(t)) : [],- createdAt: typeof e?.createdAt === 'number' ? e.createdAt : now,+ tags: asStringArray(prop(e, 'tags')),+ createdAt: asNumber(prop(e, 'createdAt')) ?? now,updatedAt: now,- source: String(e?.source ?? 'import'),+ source: asString(prop(e, 'source')) ?? 'import',})}if (newEntries.length > 0) {@@ -783,16 +873,7 @@ export const useMemoryStore = create<MemoryState>()(// localStorage data on first read. createJSONStorage wrap still required// (zustand v5 PersistStorage; raw StateStorage → "[object Object]", FIX-3).storage: createJSONStorage(() => idbStorage),- migrate: (persistedState, version) => {- let state: any = persistedState- if (version < 2) {- state = migrateV1toV2(state)- }- if (version < 3) {- state = migrateV2toV3(state)- }- return state as MemoryState- },+ migrate: migrateMemoryState,partialize: (state) => ({entries: state.entries,settings: state.settings,diff --git a/src/stores/permissionStore.ts b/src/stores/permissionStore.tsindex d84cf766..cc8fe072 100644--- a/src/stores/permissionStore.ts+++ b/src/stores/permissionStore.ts@@ -3,6 +3,7 @@ import { persist } from 'zustand/middleware'import { safeJSONStorage } from '../lib/storage-quota'import type { PermissionMap, PermissionLevel, ToolCategory } from '../api/mcp/types'import { DEFAULT_PERMISSIONS } from '../api/mcp/types'+import { isRecord, prop, asString } from '../types/json-guards'/** Per-tool override: takes precedence over the tool's category default. */export type ToolOverrides = Record<string, PermissionLevel>@@ -130,16 +131,21 @@ export const usePermissionStore = create<PermissionState>()(* old default, never a user's choice (the toggle was disabled). Lift exactly* that value to the new default; everything else persists. Exported for* direct unit-testing (the persist internals aren't reachable in vitest). */-export function migratePermissionState(persisted: any, version: number) {- if (version < 2 && persisted?.globalPermissions?.video === 'blocked') {- persisted.globalPermissions.video = DEFAULT_PERMISSIONS.video+export function migratePermissionState(persisted: unknown, version: number): PermissionState {+ // Foreign at read time — an older build wrote this. A read that throws in a+ // migrate costs the whole store: zustand abandons hydration and the next+ // write persists the empty default over the blob.+ const globals = prop(persisted, 'globalPermissions')+ if (version < 2 && isRecord(globals) && globals.video === 'blocked') {+ globals.video = DEFAULT_PERMISSIONS.video}// v3 (2.6.6 tool merge): the typed shell wrappers are gone, their calls run// through shell_execute now. A per-tool override on a retired name would be// silently dead, so lift the overrides onto shell_execute. Most restrictive// wins: a user who forced confirmation on git_push keeps that protection on// the tool the push actually runs through.- if (version < 3 && persisted?.perToolOverrides) {+ const overrides = prop(persisted, 'perToolOverrides')+ if (version < 3 && isRecord(overrides)) {// Frozen copy of the names retired in 2.6.6, NOT imported from// builtin-tools: a migration describes the past and must not drift with// the live registry (and the import would drag the whole tool module@@ -150,23 +156,24 @@ export function migratePermissionState(persisted: any, version: number) {'system_info', 'process_list', 'get_current_time','shell_execute_background', 'shell_task_status', 'shell_task_kill', 'shell_task_list',]- const overrides = persisted.perToolOverrides as Record<string, string>const RANK: Record<string, number> = { auto: 0, confirm: 1, blocked: 2 }let strictest: string | undefinedfor (const name of RETIRED_V3) {- const level = overrides[name]+ const level = asString(overrides[name])if (!level) continuedelete overrides[name]if (strictest === undefined || (RANK[level] ?? 0) > (RANK[strictest] ?? 0)) strictest = level}if (strictest !== undefined) {- const own = overrides['shell_execute']+ const own = asString(overrides['shell_execute'])if (own === undefined || (RANK[strictest] ?? 0) > (RANK[own] ?? 0)) {overrides['shell_execute'] = strictest}}}- return persisted+ // zustand types migrate as returning the FULL store, but a blob only ever+ // carries the partialized slice and `merge` puts the actions back.+ return persisted as PermissionState}/**diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex 333d3fb6..13f966cb 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -3,6 +3,7 @@ import { persist } from 'zustand/middleware'import { safeJSONStorage } from '../lib/storage-quota'import type { Settings, Persona } from '../types/settings'import { DEFAULT_SETTINGS, BUILT_IN_PERSONAS } from '../lib/constants'+import { isRecord, asString } from '../types/json-guards'// v5 (Feature EE v2.5.0): added settings.exclusiveVramMode. The migrate below// already merges { ...DEFAULT_SETTINGS, ...persisted.settings }, so bumping the@@ -155,11 +156,20 @@ export const useSettingsStore = create<SettingsState>()(name: 'chat-settings',storage: safeJSONStorage(),version: STORE_VERSION,- migrate: (persisted: any, version: number) => {+ migrate: (persisted: unknown, version: number): SettingsState => {+ // Foreign at read time — an older build wrote this. A read that throws+ // in a migrate costs the whole store: zustand abandons hydration and+ // the next write persists the empty default over the blob, which here+ // would mean every setting AND every custom persona.+ const blob = isRecord(persisted) ? persisted : {}if (version < STORE_VERSION) {- const customPersonas = (persisted.personas || []).filter((p: Persona) => !p.isBuiltIn)+ const storedPersonas = Array.isArray(blob.personas) ? blob.personas : []+ const customPersonas = storedPersonas.filter(+ (p): p is Persona => isRecord(p) && p.isBuiltIn !== true,+ )// Merge new default settings into existing (fills missing fields like thinkingEnabled)- const mergedSettings = { ...DEFAULT_SETTINGS, ...(persisted.settings || {}) }+ const storedSettings = isRecord(blob.settings) ? blob.settings : {}+ const mergedSettings = { ...DEFAULT_SETTINGS, ...storedSettings }// v10: clear the saved model-picker preferences ONCE so the picker is// shown first again on image + video (David 2026-06-16). The additive// merge above would otherwise preserve a previously-saved pick.@@ -176,14 +186,16 @@ export const useSettingsStore = create<SettingsState>()(if (isMac) mergedSettings.appMode = 'local'}return {- ...persisted,+ ...blob,settings: mergedSettings,personas: [...BUILT_IN_PERSONAS, ...customPersonas],- activePersonaId: persisted.activePersonaId || 'unrestricted',+ activePersonaId: asString(blob.activePersonaId) || 'unrestricted',_version: STORE_VERSION,- }+ } as unknown as SettingsState}- return persisted+ // zustand types migrate as returning the FULL store, but a blob only+ // ever carries the partialized slice and `merge` puts the actions back.+ return persisted as SettingsState},})diff --git a/src/stores/toolAuditStore.ts b/src/stores/toolAuditStore.tsindex f0b0f5ad..fe9d1b42 100644--- a/src/stores/toolAuditStore.ts+++ b/src/stores/toolAuditStore.ts@@ -33,7 +33,7 @@ export interface ToolAuditEntry {/** AgentToolCall.id — correlates with the block. */toolCallId: stringtoolName: string- args: Record<string, any>+ args: Record<string, unknown>/** Deterministic hash of args for cache / dedup. */argsHash: stringstatus: ToolAuditStatus@@ -89,7 +89,7 @@ interface ToolAuditState {convId: stringtoolCallId: stringtoolName: string- args: Record<string, any>+ args: Record<string, unknown>parentToolCallId?: stringstartedAt?: numberstatus?: ToolAuditStatus