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 1: Schema migration toolCall → toolCalls[] (v2.4.0)
PurpleDoubleDa486538a8476
diff --git a/src/api/agents/__tests__/block-helpers.test.ts b/src/api/agents/__tests__/block-helpers.test.tsnew file mode 100644index 00000000..d2f5b079--- /dev/null+++ b/src/api/agents/__tests__/block-helpers.test.ts@@ -0,0 +1,162 @@+import { describe, it, expect } from 'vitest'+import {+ getBlockToolCalls,+ getFirstToolCall,+ migrateBlockInPlace,+ hasToolCalls,+ stableArgsHash,+} from '../block-helpers'+import type { AgentBlock, AgentToolCall } from '../../../types/agent-mode'++const mkCall = (id: string, overrides: Partial<AgentToolCall> = {}): AgentToolCall => ({+ id,+ toolName: 'web_search',+ args: { query: 'x' },+ status: 'completed',+ timestamp: 1,+ ...overrides,+})++const mkBlock = (overrides: Partial<AgentBlock> = {}): AgentBlock => ({+ id: 'b1',+ phase: 'tool_call',+ content: '',+ timestamp: 1,+ ...overrides,+})++describe('block-helpers — getBlockToolCalls', () => {+ it('returns [] when no tool calls present', () => {+ expect(getBlockToolCalls(mkBlock())).toEqual([])+ })++ it('returns legacy singular call wrapped in array', () => {+ const call = mkCall('a')+ expect(getBlockToolCalls(mkBlock({ toolCall: call }))).toEqual([call])+ })++ it('returns new plural array as-is', () => {+ const calls = [mkCall('a'), mkCall('b')]+ expect(getBlockToolCalls(mkBlock({ toolCalls: calls }))).toBe(calls)+ })++ it('prefers plural over singular when both present (post-migration shape)', () => {+ const legacy = mkCall('old')+ const current = [mkCall('new1'), mkCall('new2')]+ const block = mkBlock({ toolCall: legacy, toolCalls: current })+ expect(getBlockToolCalls(block)).toBe(current)+ })++ it('falls back to singular when plural array is empty', () => {+ const legacy = mkCall('old')+ const block = mkBlock({ toolCall: legacy, toolCalls: [] })+ expect(getBlockToolCalls(block)).toEqual([legacy])+ })+})++describe('block-helpers — getFirstToolCall', () => {+ it('returns undefined when no tool calls', () => {+ expect(getFirstToolCall(mkBlock())).toBeUndefined()+ })++ it('returns first of plural array', () => {+ const calls = [mkCall('a'), mkCall('b')]+ expect(getFirstToolCall(mkBlock({ toolCalls: calls }))).toBe(calls[0])+ })++ it('falls back to legacy singular', () => {+ const legacy = mkCall('old')+ expect(getFirstToolCall(mkBlock({ toolCall: legacy }))).toBe(legacy)+ })+})++describe('block-helpers — migrateBlockInPlace', () => {+ it('wraps legacy singular into plural array', () => {+ const call = mkCall('a')+ const block = mkBlock({ toolCall: call })+ migrateBlockInPlace(block)+ expect(block.toolCalls).toEqual([call])+ // Legacy field preserved during transition.+ expect(block.toolCall).toBe(call)+ })++ it('is idempotent when already migrated', () => {+ const calls = [mkCall('a')]+ const block = mkBlock({ toolCalls: calls })+ migrateBlockInPlace(block)+ expect(block.toolCalls).toBe(calls)+ })++ it('does nothing when there are no calls at all', () => {+ const block = mkBlock()+ migrateBlockInPlace(block)+ expect(block.toolCall).toBeUndefined()+ expect(block.toolCalls).toBeUndefined()+ })++ it('prefers existing plural array over legacy field', () => {+ // Defensive: if both somehow exist with non-empty plural, do not overwrite.+ const legacy = mkCall('old')+ const plural = [mkCall('new')]+ const block = mkBlock({ toolCall: legacy, toolCalls: plural })+ migrateBlockInPlace(block)+ expect(block.toolCalls).toBe(plural)+ })++ it('replaces empty plural with legacy-wrapped array', () => {+ const legacy = mkCall('old')+ const block = mkBlock({ toolCall: legacy, toolCalls: [] })+ migrateBlockInPlace(block)+ expect(block.toolCalls).toEqual([legacy])+ })+})++describe('block-helpers — hasToolCalls', () => {+ it('detects plural present', () => {+ expect(hasToolCalls(mkBlock({ toolCalls: [mkCall('a')] }))).toBe(true)+ })+ it('detects legacy singular', () => {+ expect(hasToolCalls(mkBlock({ toolCall: mkCall('a') }))).toBe(true)+ })+ it('empty plural + no legacy → false', () => {+ expect(hasToolCalls(mkBlock({ toolCalls: [] }))).toBe(false)+ })+ it('neither → false', () => {+ expect(hasToolCalls(mkBlock())).toBe(false)+ })+})++describe('block-helpers — stableArgsHash', () => {+ it('produces same hash regardless of key order', () => {+ const a = stableArgsHash({ query: 'x', limit: 3 })+ const b = stableArgsHash({ limit: 3, query: 'x' })+ expect(a).toBe(b)+ })++ it('differs for different values', () => {+ expect(stableArgsHash({ q: 'a' })).not.toBe(stableArgsHash({ q: 'b' }))+ })++ it('hashes empty object', () => {+ expect(stableArgsHash({})).toBeTypeOf('string')+ expect(stableArgsHash({}).length).toBeGreaterThan(0)+ })++ it('canonicalises nested objects and arrays', () => {+ const a = stableArgsHash({ a: { x: 1, y: [1, 2, 3] } })+ const b = stableArgsHash({ a: { y: [1, 2, 3], x: 1 } })+ expect(a).toBe(b)+ })++ it('distinguishes array order', () => {+ expect(stableArgsHash({ v: [1, 2] })).not.toBe(stableArgsHash({ v: [2, 1] }))+ })++ it('handles null / undefined / boolean / number', () => {+ expect(stableArgsHash({ n: null, u: undefined, b: true, x: 3 })).toBeTypeOf('string')+ })++ it('differentiates string "1" from number 1', () => {+ expect(stableArgsHash({ v: '1' })).not.toBe(stableArgsHash({ v: 1 }))+ })+})diff --git a/src/api/agents/block-helpers.ts b/src/api/agents/block-helpers.tsnew file mode 100644index 00000000..8e01aaea--- /dev/null+++ b/src/api/agents/block-helpers.ts@@ -0,0 +1,86 @@+/**+ * Helpers for reading AgentBlock tool calls uniformly across legacy+ * (singular `toolCall`) and v2.4+ (plural `toolCalls[]`) shapes.+ *+ * Phase 1 migration (v2.4.0): blocks can carry either:+ * - legacy `block.toolCall?: AgentToolCall` — written by pre-v2.4 code+ * - v2.4 `block.toolCalls?: AgentToolCall[]` — written by parallel executor+ *+ * All READS must go through `getBlockToolCalls(block)`. All WRITES in new+ * code MUST populate `toolCalls` and leave `toolCall` untouched.+ */++import type { AgentBlock, AgentToolCall } from '../../types/agent-mode'++/**+ * Uniform accessor: returns all tool calls on a block, regardless of shape.+ * Returns an empty array if the block has none.+ */+export function getBlockToolCalls(block: AgentBlock): AgentToolCall[] {+ if (block.toolCalls && block.toolCalls.length > 0) return block.toolCalls+ if (block.toolCall) return [block.toolCall]+ return []+}++/**+ * Returns the first tool call on a block, or undefined.+ * Convenience for UI renderers that only show one at a time during legacy display.+ */+export function getFirstToolCall(block: AgentBlock): AgentToolCall | undefined {+ if (block.toolCalls && block.toolCalls.length > 0) return block.toolCalls[0]+ return block.toolCall+}++/**+ * Rehydration shim for persisted blocks. If a block carries the legacy+ * `toolCall` field and no `toolCalls`, wrap the single call into the array+ * form IN PLACE (mutates input — suitable for use inside a persist merger).+ *+ * Leaves both fields populated when migrating, so anything reading either+ * shape still works mid-migration. A future release can drop `toolCall`+ * after enough users have rehydrated.+ */+export function migrateBlockInPlace(block: AgentBlock): AgentBlock {+ if (block.toolCall && (!block.toolCalls || block.toolCalls.length === 0)) {+ block.toolCalls = [block.toolCall]+ }+ return block+}++/**+ * Returns true if the block has at least one tool call in either shape.+ */+export function hasToolCalls(block: AgentBlock): boolean {+ return (block.toolCalls?.length ?? 0) > 0 || !!block.toolCall+}++/**+ * Compute stable args-hash for cache/audit keying. Sorts object keys so+ * `{a:1,b:2}` and `{b:2,a:1}` hash identically. Non-cryptographic.+ */+export function stableArgsHash(args: Record<string, any>): string {+ const normalized = canonicalize(args)+ return djb2(normalized)+}++function canonicalize(value: any): string {+ if (value === null || value === undefined) return 'null'+ if (typeof value === 'number' || typeof value === 'boolean') return JSON.stringify(value)+ if (typeof value === 'string') return JSON.stringify(value)+ if (Array.isArray(value)) return '[' + value.map(canonicalize).join(',') + ']'+ if (typeof value === 'object') {+ const keys = Object.keys(value).sort()+ return '{' + keys.map((k) => JSON.stringify(k) + ':' + canonicalize(value[k])).join(',') + '}'+ }+ return JSON.stringify(String(value))+}++// djb2 hash — compact, stable, not crypto. Plenty for an in-turn cache key.+function djb2(s: string): string {+ let h = 5381+ for (let i = 0; i < s.length; i++) {+ h = (h * 33) ^ s.charCodeAt(i)+ }+ // Unsigned 32-bit hex.+ return (h >>> 0).toString(16)+}diff --git a/src/stores/__tests__/chatStore-migration.test.ts b/src/stores/__tests__/chatStore-migration.test.tsnew file mode 100644index 00000000..64bb1137--- /dev/null+++ b/src/stores/__tests__/chatStore-migration.test.ts@@ -0,0 +1,145 @@+import { describe, it, expect } from 'vitest'+import { migratePersistedChat } from '../chatStore'+import type { AgentBlock, AgentToolCall } from '../../types/agent-mode'++const legacyCall: AgentToolCall = {+ id: 't1',+ toolName: 'web_search',+ args: { query: 'x' },+ status: 'completed',+ timestamp: 1,+}++describe('chatStore — migratePersistedChat', () => {+ it('returns null/undefined/non-object shapes unchanged', () => {+ expect(migratePersistedChat(null)).toBe(null)+ expect(migratePersistedChat(undefined)).toBe(undefined)+ expect(migratePersistedChat({})).toEqual({})+ })++ it('leaves conversations without agentBlocks untouched', () => {+ const state = {+ conversations: [+ {+ id: 'c1',+ messages: [{ id: 'm1', role: 'user', content: 'hi' }],+ },+ ],+ }+ const result = migratePersistedChat(state)+ expect(result.conversations[0].messages[0].content).toBe('hi')+ })++ it('wraps legacy singular toolCall into toolCalls array across nested messages', () => {+ const block: AgentBlock = {+ id: 'b1',+ phase: 'tool_call',+ content: '',+ timestamp: 1,+ toolCall: legacyCall,+ }+ const state = {+ conversations: [+ {+ id: 'c1',+ messages: [+ {+ id: 'm1',+ role: 'assistant',+ content: 'ok',+ agentBlocks: [block],+ },+ ],+ },+ ],+ }+ const result = migratePersistedChat(state)+ const migratedBlock = result.conversations[0].messages[0].agentBlocks[0]+ expect(migratedBlock.toolCalls).toEqual([legacyCall])+ expect(migratedBlock.toolCall).toBe(legacyCall) // preserved for transition+ })++ it('migrates multiple blocks in multiple conversations', () => {+ const state = {+ conversations: [+ {+ id: 'c1',+ messages: [+ {+ id: 'm1',+ agentBlocks: [+ { id: 'b1', phase: 'tool_call', content: '', timestamp: 1, toolCall: legacyCall },+ { id: 'b2', phase: 'thinking', content: 'hmm', timestamp: 2 },+ ],+ },+ ],+ },+ {+ id: 'c2',+ messages: [+ {+ id: 'm2',+ agentBlocks: [+ { id: 'b3', phase: 'tool_call', content: '', timestamp: 3, toolCall: { ...legacyCall, id: 't2' } },+ ],+ },+ ],+ },+ ],+ }+ const result = migratePersistedChat(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')+ })++ it('is idempotent — re-running migration does not double-wrap', () => {+ const state = {+ conversations: [+ {+ id: 'c1',+ messages: [+ {+ id: 'm1',+ agentBlocks: [+ {+ id: 'b1',+ phase: 'tool_call',+ content: '',+ timestamp: 1,+ toolCall: legacyCall,+ toolCalls: [legacyCall],+ },+ ],+ },+ ],+ },+ ],+ }+ const once = migratePersistedChat(state)+ const twice = migratePersistedChat(once)+ expect(twice.conversations[0].messages[0].agentBlocks[0].toolCalls).toEqual([legacyCall])+ })++ it('handles malformed agentBlocks array without crashing', () => {+ const state = {+ conversations: [+ {+ id: 'c1',+ messages: [+ {+ id: 'm1',+ agentBlocks: [null, undefined, { id: 'b1', phase: 'tool_call', content: '', timestamp: 1 }],+ },+ ],+ },+ ],+ }+ expect(() => migratePersistedChat(state)).not.toThrow()+ })++ it('tolerates non-array conversations gracefully', () => {+ expect(migratePersistedChat({ conversations: 'not-an-array' })).toEqual({ conversations: 'not-an-array' })+ })+})diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.tsindex a6edf1af..52ff255e 100644--- a/src/stores/chatStore.ts+++ b/src/stores/chatStore.ts@@ -4,6 +4,27 @@ import { v4 as uuid } from 'uuid'import type { Conversation, Message } from '../types/chat'import type { AgentBlock } from '../types/agent-mode'import { createSafeStorage } from '../lib/storage-quota'+import { migrateBlockInPlace } from '../api/agents/block-helpers'++/**+ * Rehydration migration for Phase 1 (v2.4.0) — wraps legacy+ * `AgentBlock.toolCall` (singular) into the new `toolCalls: AgentToolCall[]`+ * 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)+ }+ }+ }+ return state+}interface ChatState {conversations: Conversation[]@@ -152,6 +173,16 @@ export const useChatStore = create<ChatState>()()},}),- { name: 'chat-conversations', storage: createSafeStorage() }+ {+ name: 'chat-conversations',+ storage: createSafeStorage(),+ // Phase 1 (v2.4.0) — rehydrate legacy singular `toolCall` into `toolCalls[]`.+ // Persisted shape is whatever was last written; migration runs on every load+ // and is idempotent, so version bumps are not required.+ merge: (persistedState: any, currentState: ChatState) => {+ const migrated = migratePersistedChat(persistedState)+ return { ...currentState, ...(migrated || {}) }+ },+ }))diff --git a/src/types/agent-mode.ts b/src/types/agent-mode.tsindex 5f36eef5..89ea03df 100644--- a/src/types/agent-mode.ts+++ b/src/types/agent-mode.ts@@ -60,9 +60,13 @@ export interface AgentChatChunk {}// Tool call lifecycle status-export type ToolCallStatus = 'pending_approval' | 'running' | 'completed' | 'failed' | 'rejected'+export type ToolCallStatus = 'pending_approval' | 'running' | 'completed' | 'failed' | 'rejected' | 'cached'-// Internal tracking of a tool call+// Internal tracking of a tool call.+// Observability fields (startedAt / completedAt / cacheHit / parentToolCallId /+// schemaValidated / sideEffectKey / errorHint) are additive — they were introduced+// in v2.4.0 for the agent overhaul (parallel execution, caching, audit, sub-agents).+// All are optional to preserve rehydration of pre-v2.4 persisted messages.export interface AgentToolCall {id: stringtoolName: string@@ -70,19 +74,42 @@ export interface AgentToolCall {status: ToolCallStatusresult?: stringerror?: string+ /** User-facing, model-facing hint appended to error for recovery (Phase 7). */+ errorHint?: stringduration?: numbertimestamp: number+ /** Epoch ms when dispatch started (after permission approval). */+ startedAt?: number+ /** Epoch ms when result became available. */+ completedAt?: number+ /** True when result came from in-turn cache (Phase 6). */+ cacheHit?: boolean+ /** Parent toolCallId when spawned by a sub-agent delegation (Phase 13). */+ parentToolCallId?: string+ /** True when args passed JSON-schema validation (Phase 4). */+ schemaValidated?: boolean+ /** Group key for serial execution within a parallel batch (Phase 5).+ * Writes to the same file path or the singleton "shell" share a key. */+ sideEffectKey?: string}// Phases rendered as distinct UI blocks in chatexport type AgentPhase = 'thinking' | 'planning' | 'tool_call' | 'reflection' | 'answer'// A block in the agent's response (tool call, thinking, etc.)+//+// v2.4 migration:+// `toolCall` (singular) is preserved for legacy rehydration only.+// New code MUST write to `toolCalls` (plural). Use `getBlockToolCalls(block)`+// from src/api/agents/block-helpers.ts to read both shapes uniformly.export interface AgentBlock {id: stringphase: AgentPhasecontent: string+ /** @deprecated since v2.4 — use `toolCalls`. Kept for legacy persist rehydration. */toolCall?: AgentToolCall+ /** v2.4+ — array of tool calls attached to this block (enables parallel execution). */+ toolCalls?: AgentToolCall[]timestamp: number}diff --git a/src/types/agents.ts b/src/types/agents.tsindex 17b142f6..e9ba6eda 100644--- a/src/types/agents.ts+++ b/src/types/agents.ts@@ -48,9 +48,18 @@ export interface ToolCall {| "completed"| "failed"| "approved"- | "rejected";+ | "rejected"+ | "cached";timestamp: number;duration?: number;+ // v2.4 observability — all optional, additive.+ startedAt?: number;+ completedAt?: number;+ cacheHit?: boolean;+ parentToolCallId?: string;+ schemaValidated?: boolean;+ errorHint?: string;+ sideEffectKey?: string;}export interface AgentTask {