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 2: Tool-call audit store with stable argsHash (v2.4.0)
PurpleDoubleD35a2eef9947a
diff --git a/src/stores/__tests__/toolAuditStore.test.ts b/src/stores/__tests__/toolAuditStore.test.tsnew file mode 100644index 00000000..57da94fd--- /dev/null+++ b/src/stores/__tests__/toolAuditStore.test.ts@@ -0,0 +1,235 @@+import { describe, it, expect, beforeEach } from 'vitest'+import {+ useToolAuditStore,+ AUDIT_MAX_PER_CONV,+ AUDIT_RESULT_PREVIEW_CHARS,+} from '../toolAuditStore'++describe('toolAuditStore', () => {+ beforeEach(() => {+ useToolAuditStore.getState().clearAll()+ })++ describe('record', () => {+ it('appends a running entry with derived argsHash and default startedAt', () => {+ const id = useToolAuditStore.getState().record({+ convId: 'c1',+ toolCallId: 'tc1',+ toolName: 'web_search',+ args: { q: 'x' },+ })+ const list = useToolAuditStore.getState().forConversation('c1')+ expect(list).toHaveLength(1)+ const e = list[0]+ expect(e.id).toBe(id)+ expect(e.status).toBe('running')+ expect(e.argsHash).toBeTypeOf('string')+ expect(e.startedAt).toBeGreaterThan(0)+ })++ it('isolates entries per conversation', () => {+ const s = useToolAuditStore.getState()+ s.record({ convId: 'a', toolCallId: 'tc', toolName: 't', args: {} })+ s.record({ convId: 'b', toolCallId: 'tc', toolName: 't', args: {} })+ expect(s.forConversation('a')).toHaveLength(1)+ expect(s.forConversation('b')).toHaveLength(1)+ })++ it('honours explicit startedAt', () => {+ useToolAuditStore.getState().record({+ convId: 'c1',+ toolCallId: 'tc',+ toolName: 't',+ args: {},+ startedAt: 1000,+ })+ expect(useToolAuditStore.getState().forConversation('c1')[0].startedAt).toBe(1000)+ })++ it('stores parentToolCallId for sub-agent lineage', () => {+ useToolAuditStore.getState().record({+ convId: 'c1',+ toolCallId: 'child',+ toolName: 't',+ args: {},+ parentToolCallId: 'parent',+ })+ expect(useToolAuditStore.getState().forConversation('c1')[0].parentToolCallId).toBe(+ 'parent'+ )+ })+ })++ describe('ring-buffer eviction', () => {+ it(`evicts oldest once ${AUDIT_MAX_PER_CONV} is exceeded`, () => {+ const s = useToolAuditStore.getState()+ for (let i = 0; i < AUDIT_MAX_PER_CONV + 20; i++) {+ s.record({+ convId: 'c1',+ toolCallId: `tc${i}`,+ toolName: 't',+ args: { i },+ })+ }+ const list = s.forConversation('c1')+ expect(list).toHaveLength(AUDIT_MAX_PER_CONV)+ // Newest first — last inserted toolCallId is at the top.+ expect(list[0].toolCallId).toBe(`tc${AUDIT_MAX_PER_CONV + 19}`)+ // Oldest 20 are gone.+ expect(list.some((e) => e.toolCallId === 'tc0')).toBe(false)+ expect(list.some((e) => e.toolCallId === 'tc19')).toBe(false)+ expect(list.some((e) => e.toolCallId === 'tc20')).toBe(true)+ })+ })++ describe('complete', () => {+ it('patches status/durationMs/resultPreview and clips long previews', () => {+ const s = useToolAuditStore.getState()+ const id = s.record({+ convId: 'c1',+ toolCallId: 'tc1',+ toolName: 't',+ args: {},+ startedAt: 1000,+ })+ const big = 'x'.repeat(AUDIT_RESULT_PREVIEW_CHARS + 200)+ s.complete(id, {+ status: 'completed',+ completedAt: 1500,+ resultPreview: big,+ })+ const e = s.forConversation('c1')[0]+ expect(e.status).toBe('completed')+ expect(e.completedAt).toBe(1500)+ expect(e.durationMs).toBe(500)+ expect(e.resultPreview?.length).toBe(AUDIT_RESULT_PREVIEW_CHARS)+ })++ it('completing unknown id is a no-op (no throw)', () => {+ expect(() =>+ useToolAuditStore.getState().complete('nope', { status: 'failed' })+ ).not.toThrow()+ })++ it('derives durationMs using Date.now() when completedAt omitted', () => {+ const s = useToolAuditStore.getState()+ const id = s.record({+ convId: 'c1',+ toolCallId: 'tc',+ toolName: 't',+ args: {},+ startedAt: Date.now() - 100,+ })+ s.complete(id, { status: 'completed' })+ const e = s.forConversation('c1')[0]+ expect(e.durationMs).toBeGreaterThanOrEqual(100)+ })+ })++ describe('findByToolCallId', () => {+ it('finds within a specific conversation', () => {+ const s = useToolAuditStore.getState()+ s.record({ convId: 'a', toolCallId: 'x', toolName: 't', args: {} })+ s.record({ convId: 'b', toolCallId: 'x', toolName: 't', args: {} })+ expect(s.findByToolCallId('x', 'a')?.convId).toBe('a')+ expect(s.findByToolCallId('x', 'b')?.convId).toBe('b')+ })+ it('searches across all conversations when convId omitted', () => {+ const s = useToolAuditStore.getState()+ s.record({ convId: 'a', toolCallId: 'only-in-a', toolName: 't', args: {} })+ expect(s.findByToolCallId('only-in-a')).toBeDefined()+ })+ it('returns undefined when missing', () => {+ expect(useToolAuditStore.getState().findByToolCallId('missing')).toBeUndefined()+ })+ })++ describe('findCacheCandidate', () => {+ it('returns matching completed entry with same (tool, argsHash) after sinceMs', () => {+ const s = useToolAuditStore.getState()+ const id = s.record({+ convId: 'c1',+ toolCallId: 'tc1',+ toolName: 'web_search',+ args: { q: 'abc' },+ startedAt: 1000,+ })+ s.complete(id, { status: 'completed', completedAt: 1100, resultPreview: 'r' })+ const list = s.forConversation('c1')+ const hash = list[0].argsHash+ expect(s.findCacheCandidate('c1', 'web_search', hash, 500)).toBeDefined()+ })++ it('ignores entries older than sinceMs', () => {+ const s = useToolAuditStore.getState()+ const id = s.record({+ convId: 'c1',+ toolCallId: 'tc',+ toolName: 'web_search',+ args: { q: 'x' },+ startedAt: 100,+ })+ s.complete(id, { status: 'completed' })+ const hash = s.forConversation('c1')[0].argsHash+ expect(s.findCacheCandidate('c1', 'web_search', hash, 10_000)).toBeUndefined()+ })++ it('ignores failed entries', () => {+ const s = useToolAuditStore.getState()+ const id = s.record({+ convId: 'c1',+ toolCallId: 'tc',+ toolName: 'web_search',+ args: { q: 'x' },+ })+ s.complete(id, { status: 'failed' })+ const hash = s.forConversation('c1')[0].argsHash+ expect(s.findCacheCandidate('c1', 'web_search', hash, 0)).toBeUndefined()+ })++ it('does not match different toolName or different args', () => {+ const s = useToolAuditStore.getState()+ const id = s.record({ convId: 'c1', toolCallId: 'tc', toolName: 'web_search', args: { q: 'a' } })+ s.complete(id, { status: 'completed' })+ const hash = s.forConversation('c1')[0].argsHash+ expect(s.findCacheCandidate('c1', 'web_fetch', hash, 0)).toBeUndefined()+ expect(s.findCacheCandidate('c1', 'web_search', 'different-hash', 0)).toBeUndefined()+ })+ })++ describe('countsByStatus', () => {+ it('counts entries by status', () => {+ const s = useToolAuditStore.getState()+ const a = s.record({ convId: 'c1', toolCallId: 'a', toolName: 't', args: {} })+ const b = s.record({ convId: 'c1', toolCallId: 'b', toolName: 't', args: {} })+ s.record({ convId: 'c1', toolCallId: 'c', toolName: 't', args: {} })+ s.complete(a, { status: 'completed' })+ s.complete(b, { status: 'failed' })+ const counts = s.countsByStatus('c1')+ expect(counts.completed).toBe(1)+ expect(counts.failed).toBe(1)+ expect(counts.running).toBe(1)+ })+ it('all zeros for unknown conv', () => {+ const c = useToolAuditStore.getState().countsByStatus('nope')+ expect(Object.values(c).every((n) => n === 0)).toBe(true)+ })+ })++ describe('clearConversation / clearAll', () => {+ it('removes only the specified conversation', () => {+ const s = useToolAuditStore.getState()+ s.record({ convId: 'a', toolCallId: 'x', toolName: 't', args: {} })+ s.record({ convId: 'b', toolCallId: 'y', toolName: 't', args: {} })+ s.clearConversation('a')+ expect(s.forConversation('a')).toEqual([])+ expect(s.forConversation('b')).toHaveLength(1)+ })+ it('clearAll drops everything', () => {+ const s = useToolAuditStore.getState()+ s.record({ convId: 'a', toolCallId: 'x', toolName: 't', args: {} })+ s.clearAll()+ expect(s.forConversation('a')).toEqual([])+ })+ })+})diff --git a/src/stores/toolAuditStore.ts b/src/stores/toolAuditStore.tsnew file mode 100644index 00000000..9af99d89--- /dev/null+++ b/src/stores/toolAuditStore.ts@@ -0,0 +1,230 @@+import { create } from 'zustand'++/**+ * Phase 2 (v2.4.0) — per-conversation ring-buffered tool-call audit log.+ *+ * Ephemeral by default: entries live for the session and are not persisted.+ * This keeps the store cheap, avoids localStorage bloat, and matches the+ * privacy model (tool-call args can contain file contents / shell output).+ *+ * A capped number of entries is retained per conversation so the debug+ * panel (Phase 5+) can render a scroll-back without unbounded growth.+ *+ * Identity:+ * - toolCallId: stable per call (from AgentToolCall.id)+ * - argsHash: canonical stableArgsHash(args) for cache lookup (Phase 6)+ */++import { stableArgsHash } from '../api/agents/block-helpers'++export type ToolAuditStatus =+ | 'pending_approval'+ | 'running'+ | 'completed'+ | 'failed'+ | 'rejected'+ | 'cached'++export interface ToolAuditEntry {+ /** Internal audit row id. */+ id: string+ /** Conversation this call was made in. */+ convId: string+ /** AgentToolCall.id — correlates with the block. */+ toolCallId: string+ toolName: string+ args: Record<string, any>+ /** Deterministic hash of args for cache / dedup. */+ argsHash: string+ status: ToolAuditStatus+ /** Epoch ms when dispatched (after approval). */+ startedAt: number+ /** Epoch ms when result landed. May be missing for still-running. */+ completedAt?: number+ /** Convenience — derived when completedAt is set. */+ durationMs?: number+ /** True when served from in-turn cache (Phase 6). */+ cacheHit?: boolean+ /** Parent toolCallId when spawned by a sub-agent (Phase 13). */+ parentToolCallId?: string+ /** Structured error hint (Phase 7). */+ errorHint?: string+ /** String preview of result, clipped to keep panel performant. */+ resultPreview?: string+ /** Raw error string when status=failed. */+ error?: string+}++/** Max retained entries per conversation. Oldest evicted on overflow. */+export const AUDIT_MAX_PER_CONV = 500++/** Max length of result preview kept in the store. */+export const AUDIT_RESULT_PREVIEW_CHARS = 500++interface ToolAuditState {+ /** convId → entries (newest last for cheap append; query helpers reverse). */+ entries: Record<string, ToolAuditEntry[]>+ /**+ * Record the dispatch of a tool call. Call this after permission approval+ * and BEFORE actual execution. Returns the inserted entry id.+ */+ record: (input: {+ id?: string+ convId: string+ toolCallId: string+ toolName: string+ args: Record<string, any>+ parentToolCallId?: string+ startedAt?: number+ status?: ToolAuditStatus+ }) => string+ /** Update an in-progress entry with completion data. */+ complete: (+ entryId: string,+ patch: {+ status: ToolAuditStatus+ completedAt?: number+ resultPreview?: string+ error?: string+ errorHint?: string+ cacheHit?: boolean+ }+ ) => void+ /** Query entries for a conversation, newest first. */+ forConversation: (convId: string) => ToolAuditEntry[]+ /** Find entry by toolCallId across all conversations (or within one). */+ findByToolCallId: (toolCallId: string, convId?: string) => ToolAuditEntry | undefined+ /**+ * In-turn cache lookup (Phase 6 helper): return most recent completed entry+ * matching (toolName, argsHash, convId) since a cut-off epoch ms.+ */+ findCacheCandidate: (+ convId: string,+ toolName: string,+ argsHash: string,+ sinceMs: number+ ) => ToolAuditEntry | undefined+ /** Aggregate status counts per conversation for the debug panel. */+ countsByStatus: (convId: string) => Record<ToolAuditStatus, number>+ /** Drop all entries for a conversation (called on conversation delete). */+ clearConversation: (convId: string) => void+ /** Drop everything (dev utility / tests). */+ clearAll: () => void+}++let _seq = 0+const newId = (): string => {+ _seq = (_seq + 1) & 0x7fffffff+ return `audit-${Date.now().toString(36)}-${_seq.toString(36)}`+}++export const useToolAuditStore = create<ToolAuditState>((set, get) => ({+ entries: {},++ record: ({+ id,+ convId,+ toolCallId,+ toolName,+ args,+ parentToolCallId,+ startedAt,+ status,+ }) => {+ const entryId = id ?? newId()+ const entry: ToolAuditEntry = {+ id: entryId,+ convId,+ toolCallId,+ toolName,+ args,+ argsHash: stableArgsHash(args),+ status: status ?? 'running',+ startedAt: startedAt ?? Date.now(),+ parentToolCallId,+ }+ set((state) => {+ const existing = state.entries[convId] ?? []+ const next = existing.length >= AUDIT_MAX_PER_CONV+ ? [...existing.slice(existing.length - AUDIT_MAX_PER_CONV + 1), entry]+ : [...existing, entry]+ return { entries: { ...state.entries, [convId]: next } }+ })+ return entryId+ },++ complete: (entryId, patch) =>+ set((state) => {+ const next: Record<string, ToolAuditEntry[]> = {}+ for (const [convId, list] of Object.entries(state.entries)) {+ let mutated = false+ const updated = list.map((e) => {+ if (e.id !== entryId) return e+ mutated = true+ const completedAt = patch.completedAt ?? Date.now()+ const durationMs = completedAt - e.startedAt+ return {+ ...e,+ ...patch,+ completedAt,+ durationMs,+ resultPreview: patch.resultPreview?.slice(0, AUDIT_RESULT_PREVIEW_CHARS),+ }+ })+ next[convId] = mutated ? updated : list+ }+ return { entries: next }+ }),++ forConversation: (convId) => {+ const list = get().entries[convId] ?? []+ // Newest first.+ return [...list].reverse()+ },++ findByToolCallId: (toolCallId, convId) => {+ const state = get()+ const pools = convId ? [state.entries[convId] ?? []] : Object.values(state.entries)+ for (const pool of pools) {+ for (let i = pool.length - 1; i >= 0; i--) {+ if (pool[i].toolCallId === toolCallId) return pool[i]+ }+ }+ return undefined+ },++ findCacheCandidate: (convId, toolName, argsHash, sinceMs) => {+ const list = get().entries[convId] ?? []+ for (let i = list.length - 1; i >= 0; i--) {+ const e = list[i]+ if (e.startedAt < sinceMs) return undefined+ if (e.status !== 'completed') continue+ if (e.toolName !== toolName) continue+ if (e.argsHash !== argsHash) continue+ return e+ }+ return undefined+ },++ countsByStatus: (convId) => {+ const list = get().entries[convId] ?? []+ const counts: Record<ToolAuditStatus, number> = {+ pending_approval: 0,+ running: 0,+ completed: 0,+ failed: 0,+ rejected: 0,+ cached: 0,+ }+ for (const e of list) counts[e.status] = (counts[e.status] ?? 0) + 1+ return counts+ },++ clearConversation: (convId) =>+ set((state) => {+ const { [convId]: _dropped, ...rest } = state.entries+ return { entries: rest }+ }),++ clearAll: () => set({ entries: {} }),+}))