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
Phase 6: In-turn tool-result cache (v2.4.0)
PurpleDoubleD93f021a7187e
diff --git a/src/api/agents/__tests__/in-turn-cache.test.ts b/src/api/agents/__tests__/in-turn-cache.test.tsnew file mode 100644index 00000000..c615d79c--- /dev/null+++ b/src/api/agents/__tests__/in-turn-cache.test.ts@@ -0,0 +1,126 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { makeInTurnCacheLookup } from '../in-turn-cache'+import { useToolAuditStore } from '../../../stores/toolAuditStore'+import { stableArgsHash } from '../block-helpers'+import type { ExecutionRequest } from '../tool-executor'++const req = (id: string, toolName: string, args: Record<string, any>): ExecutionRequest => ({+ id, toolName, args,+})++describe('in-turn-cache — makeInTurnCacheLookup', () => {+ beforeEach(() => {+ useToolAuditStore.getState().clearAll()+ })++ it('returns undefined when no prior call exists', () => {+ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: Date.now() - 1000 })+ const args = { query: 'test' }+ const hit = lookup(req('1', 'web_search', args), stableArgsHash(args))+ expect(hit).toBeUndefined()+ })++ it('returns cached result for matching (tool, args) within turn window', () => {+ const s = useToolAuditStore.getState()+ const args = { query: 'hello' }+ const id = s.record({+ convId: 'c1',+ toolCallId: 'prior',+ toolName: 'web_search',+ args,+ startedAt: 1000,+ })+ s.complete(id, { status: 'completed', completedAt: 1100, resultPreview: 'cached-value' })++ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 500 })+ const hit = lookup(req('new', 'web_search', args), stableArgsHash(args))+ expect(hit).toBe('cached-value')+ })++ it('returns undefined when prior call predates turn start (previous turn)', () => {+ const s = useToolAuditStore.getState()+ const args = { query: 'hello' }+ const id = s.record({+ convId: 'c1',+ toolCallId: 'prior',+ toolName: 'web_search',+ args,+ startedAt: 100, // long before turnStartMs+ })+ s.complete(id, { status: 'completed', completedAt: 200, resultPreview: 'stale' })++ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 10_000 })+ const hit = lookup(req('new', 'web_search', args), stableArgsHash(args))+ expect(hit).toBeUndefined()+ })++ it('does not cross conversations', () => {+ const s = useToolAuditStore.getState()+ const args = { query: 'hello' }+ const id = s.record({ convId: 'c1', toolCallId: 'x', toolName: 'web_search', args })+ s.complete(id, { status: 'completed', resultPreview: 'from-c1' })++ const lookup = makeInTurnCacheLookup({ convId: 'c2', turnStartMs: 0 })+ const hit = lookup(req('new', 'web_search', args), stableArgsHash(args))+ expect(hit).toBeUndefined()+ })++ it('distinguishes args by canonical hash (key order independent)', () => {+ const s = useToolAuditStore.getState()+ const id = s.record({+ convId: 'c1',+ toolCallId: 'x',+ toolName: 'web_search',+ args: { a: 1, b: 2 },+ startedAt: 1000,+ })+ s.complete(id, { status: 'completed', completedAt: 1100, resultPreview: 'same' })++ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 500 })+ const reorderedArgs = { b: 2, a: 1 }+ const hit = lookup(req('new', 'web_search', reorderedArgs), stableArgsHash(reorderedArgs))+ expect(hit).toBe('same')+ })++ it('ignores failed prior calls even within turn window', () => {+ const s = useToolAuditStore.getState()+ const args = { query: 'hello' }+ const id = s.record({ convId: 'c1', toolCallId: 'x', toolName: 'web_search', args })+ s.complete(id, { status: 'failed', error: 'boom' })++ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 0 })+ const hit = lookup(req('new', 'web_search', args), stableArgsHash(args))+ expect(hit).toBeUndefined()+ })++ it('returns undefined when the cached entry has no resultPreview', () => {+ const s = useToolAuditStore.getState()+ const args = { query: 'x' }+ const id = s.record({ convId: 'c1', toolCallId: 'x', toolName: 'web_search', args })+ // Mark completed but without a resultPreview — should not be cached.+ s.complete(id, { status: 'completed' })++ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 0 })+ expect(lookup(req('new', 'web_search', args), stableArgsHash(args))).toBeUndefined()+ })++ it('cached entry with empty string preview IS returned (empty is valid)', () => {+ const s = useToolAuditStore.getState()+ const args = { q: 'x' }+ const id = s.record({ convId: 'c1', toolCallId: 'x', toolName: 'web_search', args })+ s.complete(id, { status: 'completed', resultPreview: '' })++ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 0 })+ expect(lookup(req('new', 'web_search', args), stableArgsHash(args))).toBe('')+ })++ it('does not match different tool with same args', () => {+ const s = useToolAuditStore.getState()+ const args = { url: 'https://x' }+ const id = s.record({ convId: 'c1', toolCallId: 'x', toolName: 'web_fetch', args })+ s.complete(id, { status: 'completed', resultPreview: 'fetched' })++ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 0 })+ expect(lookup(req('new', 'web_search', args), stableArgsHash(args))).toBeUndefined()+ })+})diff --git a/src/api/agents/in-turn-cache.ts b/src/api/agents/in-turn-cache.tsnew file mode 100644index 00000000..0746f798--- /dev/null+++ b/src/api/agents/in-turn-cache.ts@@ -0,0 +1,48 @@+/**+ * Phase 6 (v2.4.0) — In-turn tool-result cache.+ *+ * Dedupes identical (toolName, argsHash) calls within a single agent run.+ *+ * Scope is deliberately narrow: one agent TURN (from sendAgentMessage or+ * sendInstruction start until the ReAct loop exits). We do NOT cache across+ * turns because many tools return time-sensitive data (web_search results,+ * process_list, get_current_time, file_read on a file that may have just+ * been overwritten). Scoping to a single turn keeps the semantics trivial:+ * everything inside one user prompt sees a consistent view of each tool's+ * output; the next user prompt starts fresh.+ *+ * The implementation delegates to the audit store's findCacheCandidate,+ * which indexes completed entries by (convId, toolName, argsHash, startedAt).+ * Turn start time is passed as the cut-off: anything older is treated as+ * belonging to a previous turn and ignored.+ */++import { useToolAuditStore } from '../../stores/toolAuditStore'+import type { ExecutionRequest } from './tool-executor'++export interface InTurnCacheOptions {+ convId: string+ /** Epoch ms when the current agent run started. Audit entries older than+ * this are treated as belonging to a previous turn and not served. */+ turnStartMs: number+}++/**+ * Factory producing a `lookupCache` callback suitable for passing into+ * executeParallel's ExecutorRuntime.lookupCache. Returns the cached result+ * string when a matching prior call exists within the current turn.+ */+export function makeInTurnCacheLookup(opts: InTurnCacheOptions) {+ const { convId, turnStartMs } = opts+ return (req: ExecutionRequest, argsHash: string): string | undefined => {+ const candidate = useToolAuditStore+ .getState()+ .findCacheCandidate(convId, req.toolName, argsHash, turnStartMs)+ // Only return a cached payload if the prior call actually produced one.+ // Empty strings are cacheable (tool legitimately returned ""); undefined+ // is not (failed calls record no resultPreview).+ if (!candidate) return undefined+ if (typeof candidate.resultPreview !== 'string') return undefined+ return candidate.resultPreview+ }+}diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex f6dc0042..cf611e8b 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -28,6 +28,7 @@ import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/typimport type { StepResult, WorkflowEngineCallbacks } from '../types/agent-workflows'import { executeParallel, applyResultToToolCall, type ExecutionRequest } from '../api/agents/tool-executor'import { useToolAuditStore } from '../stores/toolAuditStore'+import { makeInTurnCacheLookup } from '../api/agents/in-turn-cache'// ── Standalone memory extraction (usable outside React hooks) ──@@ -365,6 +366,10 @@ export function useAgentChat() {}}+ // Phase 6: lock in the start-of-turn timestamp so the in-turn cache+ // only serves results from calls made during THIS user prompt.+ const turnStartMs = Date.now()+try {// ── Agent Loop ──────────────────────────────────────────while (runningRef.current && !abort.signal.aborted) {@@ -527,6 +532,7 @@ export function useAgentChat() {return td ? { name: td.name, inputSchema: td.inputSchema } : undefined},execute: (name: string, args: Record<string, any>) => toolRegistry.execute(name, args),+ lookupCache: convId ? makeInTurnCacheLookup({ convId, turnStartMs }) : undefined,awaitApproval: async (req) => {const entry = batch.find((e) => e.ac.id === req.id)if (!entry) return falsediff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 642c86ac..b034dd27 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -17,6 +17,7 @@ import { isThinkingCompatible } from '../lib/model-compatibility'import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'import { executeParallel, applyResultToToolCall, type ExecutionRequest } from '../api/agents/tool-executor'import { useToolAuditStore } from '../stores/toolAuditStore'+import { makeInTurnCacheLookup } from '../api/agents/in-turn-cache'const CODEX_SYSTEM_PROMPT = `You are Codex, an autonomous coding agent inside Locally Uncensored. You execute coding tasks by reading files, writing code, and running shell commands. You MUST use tools to interact with the filesystem — never guess file contents.@@ -152,6 +153,9 @@ export function useCodex() {let fullContent = ''+ // Phase 6: pin turn start so in-turn cache scopes to this user prompt.+ const turnStartMs = Date.now()+try {// Agent loop — max 20 iterationsfor (let i = 0; i < 20 && runningRef.current && !abort.signal.aborted; i++) {@@ -314,6 +318,7 @@ export function useCodex() {return td ? { name: td.name, inputSchema: td.inputSchema } : undefined},execute: (name: string, args: Record<string, any>) => withTimeout(name, args),+ lookupCache: convId ? makeInTurnCacheLookup({ convId, turnStartMs }) : undefined,// Codex is auto-approve (coding agent runs unattended). The// awaitApproval hook is intentionally omitted so the executor// dispatches immediately.