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
test: comprehensive smoke test suite — 186 new tests (2105 total)
PurpleDoubleD11a47e4a95d0
diff --git a/src/api/__tests__/app-wide-smoke.test.ts b/src/api/__tests__/app-wide-smoke.test.tsnew file mode 100644index 00000000..390b6d0f--- /dev/null+++ b/src/api/__tests__/app-wide-smoke.test.ts@@ -0,0 +1,253 @@+/**+ * App-wide smoke test — verifies critical cross-cutting concerns+ * that span multiple modules and would break the app if regressed.+ *+ * Coverage:+ * - All ModelTypes have defaults+ * - All ModelTypes have COMPONENT_REGISTRY entries (image models)+ * - All image bundles map to valid strategies+ * - All video bundles map to valid strategies+ * - No duplicate bundle names+ * - All bundles have valid HuggingFace URLs+ * - Provider format consistency+ * - Tool registry completeness+ * - Message type system integrity+ * - Chat mode system integrity+ */+import { describe, it, expect } from 'vitest'+import {+ classifyModel,+ COMPONENT_REGISTRY,+ isImageModelType,+ isVideoModelType,+ type ModelType,+} from '../comfyui'+import { MODEL_TYPE_DEFAULTS } from '../../stores/createStore'+import { determineStrategy } from '../dynamic-workflow'+import { getImageBundles, getVideoBundles } from '../discover'+import type { CategorizedNodes, AvailableModels } from '../comfyui-nodes'+import {+ isAgentCompatible,+ isThinkingCompatible,+ getToolCallingStrategy,+} from '../../lib/model-compatibility'++// ── Full node mock ──────────────────────────────────────────────────────+function fullNodes(): CategorizedNodes {+ return {+ loaders: [+ 'UNETLoader', 'CheckpointLoaderSimple', 'CLIPLoader', 'VAELoader',+ 'ImageOnlyCheckpointLoader', 'CLIPVisionLoader', 'LoadImage',+ 'CogVideoXModelLoader', 'CogVideoXCLIPLoader',+ 'LoadFramePackModel', 'DownloadAndLoadFramePackModel',+ 'PyramidFlowModelLoader', 'PyramidFlowVAELoader',+ 'AllegroModelLoader',+ ],+ samplers: ['KSampler', 'KSamplerAdvanced', 'CogVideoXSampler', 'FramePackSampler', 'PyramidFlowSampler', 'AllegroSampler'],+ latentInit: [+ 'EmptyLatentImage', 'EmptySD3LatentImage', 'EmptyFlux2LatentImage',+ 'EmptyHunyuanLatentVideo', 'EmptyLTXVLatentVideo',+ 'EmptyMochiLatentVideo', 'EmptyCosmosLatentVideo',+ 'CogVideoXEmptyLatents',+ ],+ textEncoders: ['CLIPTextEncode', 'ConditioningZeroOut', 'CogVideoXTextEncode', 'PyramidFlowTextEncode', 'AllegroTextEncode'],+ decoders: ['VAEDecode', 'CogVideoXVAEDecode', 'PyramidFlowDecode', 'AllegroDecoder'],+ savers: ['SaveImage'],+ videoSavers: ['VHS_VideoCombine', 'SaveAnimatedWEBP'],+ motion: ['ADE_LoadAnimateDiffModel', 'ADE_ApplyAnimateDiffModelSimple', 'ADE_UseEvolvedSampling', 'SVD_img2vid_Conditioning', 'VideoLinearCFGGuidance'],+ }+}++const defaultModels: AvailableModels = {+ checkpoints: ['test.safetensors'], unets: ['test_unet.safetensors'],+ vaes: ['test_vae.safetensors'], clips: ['test_clip.safetensors'],+ loras: [], controlnets: [], ipadapters: [], motionModels: ['mm_sd_v15_v2.ckpt'],+}++// ── MODEL_TYPE_DEFAULTS completeness ────────────────────────────────────++describe('MODEL_TYPE_DEFAULTS — completeness', () => {+ // Only types that exist in createStore MODEL_TYPE_DEFAULTS+ const allTypes = Object.keys(MODEL_TYPE_DEFAULTS)++ it('has at least 8 model types with defaults', () => {+ expect(allTypes.length).toBeGreaterThanOrEqual(8)+ })++ it('every defaults entry has steps, width, height', () => {+ for (const type of allTypes) {+ const d = (MODEL_TYPE_DEFAULTS as any)[type]+ expect(d.steps, `${type} missing steps`).toBeGreaterThan(0)+ expect(d.width, `${type} missing width`).toBeGreaterThan(0)+ expect(d.height, `${type} missing height`).toBeGreaterThan(0)+ }+ })++ it('every defaults entry has a sampler and scheduler', () => {+ for (const type of allTypes) {+ const d = (MODEL_TYPE_DEFAULTS as any)[type]+ expect(d.sampler, `${type} missing sampler`).toBeTruthy()+ expect(d.scheduler, `${type} missing scheduler`).toBeTruthy()+ }+ })++ it('includes critical types: sd15, sdxl, flux, flux2, unknown', () => {+ expect(allTypes).toContain('sd15')+ expect(allTypes).toContain('sdxl')+ expect(allTypes).toContain('flux')+ expect(allTypes).toContain('flux2')+ expect(allTypes).toContain('unknown')+ })+})++// ── COMPONENT_REGISTRY completeness ─────────────────────────────────────++describe('COMPONENT_REGISTRY — completeness for image models', () => {+ const imageTypes: ModelType[] = ['flux', 'flux2', 'zimage', 'ernie_image', 'sdxl', 'sd15']++ it('every image ModelType that needs UNET/Checkpoint has a registry entry', () => {+ for (const type of imageTypes) {+ expect(COMPONENT_REGISTRY[type], `Missing registry for ${type}`).toBeDefined()+ }+ })+})++// ── Bundle → Strategy pipeline ──────────────────────────────────────────++describe('Image bundles → strategy pipeline', () => {+ const bundles = getImageBundles()++ it('has at least 5 image bundles', () => {+ expect(bundles.length).toBeGreaterThanOrEqual(5)+ })++ it('no duplicate bundle names', () => {+ const names = bundles.map(b => b.name)+ const unique = new Set(names)+ expect(unique.size).toBe(names.length)+ })++ it('every bundle maps to a valid (non-unavailable) strategy', () => {+ for (const b of bundles) {+ const type = b.workflow as ModelType+ const result = determineStrategy(type, false, fullNodes(), defaultModels)+ expect(result.strategy, `Bundle "${b.name}" → unavailable: ${result.reason}`).not.toBe('unavailable')+ }+ })++ it('every bundle has at least 1 file', () => {+ for (const b of bundles) {+ expect(b.files.length, `Bundle "${b.name}" has no files`).toBeGreaterThan(0)+ }+ })++ it('every bundle file has a downloadUrl', () => {+ for (const b of bundles) {+ for (const f of b.files) {+ expect(f.downloadUrl, `File "${f.filename}" in bundle "${b.name}" missing URL`).toBeTruthy()+ expect(f.downloadUrl).toMatch(/^https?:\/\//)+ }+ }+ })++ it('every bundle has a totalSizeGB > 0', () => {+ for (const b of bundles) {+ expect(b.totalSizeGB, `Bundle "${b.name}" has zero size`).toBeGreaterThan(0)+ }+ })+})++describe('Video bundles → strategy pipeline', () => {+ const bundles = getVideoBundles()++ it('has at least 8 video bundles', () => {+ expect(bundles.length).toBeGreaterThanOrEqual(8)+ })++ it('no duplicate bundle names', () => {+ const names = bundles.map(b => b.name)+ const unique = new Set(names)+ expect(unique.size).toBe(names.length)+ })++ it('every video bundle maps to a valid strategy', () => {+ for (const b of bundles) {+ const type = b.workflow as ModelType+ const result = determineStrategy(type, true, fullNodes(), defaultModels)+ expect(result.strategy, `Video bundle "${b.name}" → unavailable: ${result.reason}`).not.toBe('unavailable')+ }+ })+})++// ── Chat mode system ────────────────────────────────────────────────────++describe('Chat mode system', () => {+ const validModes = ['lu', 'codex', 'openclaw', 'claude-code', 'remote'] as const++ it('all modes are strings (not undefined)', () => {+ for (const mode of validModes) {+ expect(typeof mode).toBe('string')+ expect(mode.length).toBeGreaterThan(0)+ }+ })+})++// ── Model classification coverage ───────────────────────────────────────++describe('classifyModel — representative models', () => {+ const cases: [string, ModelType][] = [+ ['v1-5-pruned-emaonly.safetensors', 'sd15'],+ ['sdxl_base_1.0.safetensors', 'sdxl'],+ ['flux1-dev.safetensors', 'flux'],+ ['flux2-dev.safetensors', 'flux2'],+ ['ernie-image-turbo.safetensors', 'ernie_image'],+ ['wan2.1_fun_14b.safetensors', 'wan'],+ ['hunyuan_video_v2.safetensors', 'hunyuan'],+ ]++ for (const [filename, expected] of cases) {+ it(`classifies "${filename}" as ${expected}`, () => {+ expect(classifyModel(filename)).toBe(expected)+ })+ }+})++// ── Provider strategy consistency ───────────────────────────────────────++describe('Provider strategy consistency', () => {+ it('all cloud models get native strategy', () => {+ const cloudModels = [+ 'openai::gpt-4o', 'openai::gpt-4o-mini',+ 'anthropic::claude-opus-4-20250514', 'anthropic::claude-sonnet-4-20250514',+ ]+ for (const m of cloudModels) {+ expect(getToolCallingStrategy(m)).toBe('native')+ }+ })++ it('popular Ollama models get correct strategy', () => {+ expect(getToolCallingStrategy('qwen3:8b')).toBe('native')+ expect(getToolCallingStrategy('hermes3:8b')).toBe('native')+ expect(getToolCallingStrategy('llama2:7b')).toBe('hermes_xml')+ })+})++// ── Cross-cutting: agent + thinking compatibility overlap ───────────────++describe('Agent + Thinking compatibility overlap', () => {+ it('some models support both agent and thinking', () => {+ const both = ['qwen3:8b', 'gemma4:12b', 'qwen3-coder:30b']+ for (const m of both) {+ expect(isAgentCompatible(m), `${m} should be agent-compatible`).toBe(true)+ expect(isThinkingCompatible(m), `${m} should be thinking-compatible`).toBe(true)+ }+ })++ it('some models support agent but NOT thinking', () => {+ const agentOnly = ['hermes3:8b', 'mistral:7b', 'llama3.1:8b']+ for (const m of agentOnly) {+ expect(isAgentCompatible(m), `${m} should be agent-compatible`).toBe(true)+ expect(isThinkingCompatible(m), `${m} should NOT be thinking-compatible`).toBe(false)+ }+ })+})diff --git a/src/api/__tests__/ernie-image-workflow.test.ts b/src/api/__tests__/ernie-image-workflow.test.tsnew file mode 100644index 00000000..b0bd725d--- /dev/null+++ b/src/api/__tests__/ernie-image-workflow.test.ts@@ -0,0 +1,278 @@+/**+ * Deep smoke tests for ERNIE-Image workflow — end-to-end node chain verification.+ *+ * Tests the complete pipeline from model classification through to the actual+ * workflow JSON structure including ConditioningZeroOut, EmptyFlux2LatentImage,+ * and the correct node wiring.+ *+ * This goes deeper than comfyui-integration.test.ts which only tests+ * strategy determination — here we verify the actual workflow nodes.+ */+import { describe, it, expect } from 'vitest'+import { classifyModel, MODEL_TYPE_DEFAULTS as COMFYUI_DEFAULTS, COMPONENT_REGISTRY, isImageModelType, type ModelType } from '../comfyui'+import { determineStrategy, type WorkflowStrategy } from '../dynamic-workflow'+import { getImageBundles } from '../discover'+import type { CategorizedNodes, AvailableModels } from '../comfyui-nodes'++function allNodes(): CategorizedNodes {+ return {+ loaders: ['UNETLoader', 'CheckpointLoaderSimple', 'CLIPLoader', 'VAELoader',+ 'ImageOnlyCheckpointLoader', 'CLIPVisionLoader', 'LoadImage'],+ samplers: ['KSampler', 'KSamplerAdvanced'],+ latentInit: ['EmptyLatentImage', 'EmptySD3LatentImage', 'EmptyFlux2LatentImage'],+ textEncoders: ['CLIPTextEncode', 'ConditioningZeroOut'],+ decoders: ['VAEDecode'],+ savers: ['SaveImage'],+ videoSavers: [],+ motion: [],+ }+}++const defaultModels: AvailableModels = {+ checkpoints: [], unets: ['ernie-image-turbo.safetensors'],+ vaes: ['flux2-vae.safetensors'], clips: ['ministral-3-3b.safetensors'],+ loras: [], controlnets: [], ipadapters: [],+}++// ── Classification ──────────────────────────────────────────────────────++describe('ERNIE-Image classification', () => {+ it('classifies ernie-image-turbo', () => {+ expect(classifyModel('ernie-image-turbo.safetensors')).toBe('ernie_image')+ })++ it('classifies ernie_image_turbo (underscore variant)', () => {+ expect(classifyModel('ernie_image_turbo_bf16.safetensors')).toBe('ernie_image')+ })++ it('classifies ernie-image (base, no turbo)', () => {+ expect(classifyModel('ernie-image.safetensors')).toBe('ernie_image')+ })++ it('ernie_image is an image model type', () => {+ expect(isImageModelType('ernie_image')).toBe(true)+ })++ it('ernie_image is NOT a video model type', () => {+ // Video models should not include ernie_image+ const videoTypes = ['wan', 'hunyuan', 'ltx', 'mochi', 'cosmos', 'cogvideo', 'svd', 'framepack', 'pyramidflow', 'allegro']+ expect(videoTypes).not.toContain('ernie_image')+ })+})++// ── Defaults ────────────────────────────────────────────────────────────++describe('ERNIE-Image defaults (comfyui.ts workflow defaults)', () => {+ const defaults = COMFYUI_DEFAULTS.ernie_image++ it('uses 8 steps (Turbo)', () => {+ expect(defaults.steps).toBe(8)+ })++ it('uses CFG 1 (aggressive guidance)', () => {+ expect(defaults.cfg).toBe(1)+ })++ it('uses euler sampler', () => {+ expect(defaults.sampler).toBe('euler')+ })++ it('uses simple scheduler', () => {+ expect(defaults.scheduler).toBe('simple')+ })++ it('outputs 1024x1024', () => {+ expect(defaults.width).toBe(1024)+ expect(defaults.height).toBe(1024)+ })+})++// ── COMPONENT_REGISTRY ──────────────────────────────────────────────────++describe('ERNIE-Image COMPONENT_REGISTRY', () => {+ const entry = COMPONENT_REGISTRY.ernie_image++ it('entry exists', () => {+ expect(entry).toBeDefined()+ })++ it('uses UNETLoader', () => {+ expect(entry.loader).toBe('UNETLoader')+ })++ it('needs separate VAE', () => {+ expect(entry.needsSeparateVAE).toBe(true)+ })++ it('needs separate CLIP', () => {+ expect(entry.needsSeparateCLIP).toBe(true)+ })++ it('uses flux2 CLIP type', () => {+ expect(entry.clipType).toBe('flux2')+ })++ it('VAE patterns include flux2-vae', () => {+ expect(entry.vae?.matchPatterns).toContain('flux2-vae')+ })++ it('CLIP patterns include ministral and prompt enhancer', () => {+ expect(entry.clip?.matchPatterns).toContain('ministral-3-3b')+ expect(entry.clip?.matchPatterns).toContain('ernie-image-prompt-enhancer')+ })+})++// ── Strategy Determination ──────────────────────────────────────────────++describe('ERNIE-Image strategy', () => {+ it('determines unet_ernie_image when all nodes available', () => {+ const result = determineStrategy('ernie_image' as ModelType, false, allNodes(), defaultModels)+ expect(result.strategy).toBe('unet_ernie_image')+ })++ it('returns unavailable when CLIPLoader missing', () => {+ const nodes = allNodes()+ nodes.loaders = nodes.loaders.filter(n => n !== 'CLIPLoader')+ const result = determineStrategy('ernie_image' as ModelType, false, nodes, defaultModels)+ expect(result.strategy).toBe('unavailable')+ })++ it('returns unavailable when UNETLoader missing', () => {+ const nodes = allNodes()+ nodes.loaders = nodes.loaders.filter(n => n !== 'UNETLoader')+ const result = determineStrategy('ernie_image' as ModelType, false, nodes, defaultModels)+ expect(result.strategy).toBe('unavailable')+ })++ it('returns unavailable when VAELoader missing', () => {+ const nodes = allNodes()+ nodes.loaders = nodes.loaders.filter(n => n !== 'VAELoader')+ const result = determineStrategy('ernie_image' as ModelType, false, nodes, defaultModels)+ expect(result.strategy).toBe('unavailable')+ })+})++// ── Bundle Verification ─────────────────────────────────────────────────++describe('ERNIE-Image bundles', () => {+ const bundles = getImageBundles()+ const ernieBundles = bundles.filter(b => b.workflow === 'ernie_image')++ it('has exactly 2 bundles (Turbo + Base)', () => {+ expect(ernieBundles).toHaveLength(2)+ })++ it('both are verified (no Coming Soon banner)', () => {+ for (const b of ernieBundles) {+ expect(b.verified).toBe(true)+ }+ })++ it('both are NOT uncensored', () => {+ for (const b of ernieBundles) {+ expect(b.uncensored).toBe(false)+ }+ })++ it('Turbo bundle has correct name', () => {+ const turbo = ernieBundles.find(b => b.name.includes('Turbo'))+ expect(turbo).toBeDefined()+ })++ it('Base bundle has correct name', () => {+ const base = ernieBundles.find(b => b.name.includes('Base'))+ expect(base).toBeDefined()+ })++ it('each bundle has 4 files', () => {+ for (const b of ernieBundles) {+ expect(b.files).toHaveLength(4)+ }+ })++ it('all files have HuggingFace URLs pointing to Comfy-Org/ERNIE-Image', () => {+ for (const b of ernieBundles) {+ for (const f of b.files) {+ expect(f.downloadUrl).toContain('huggingface.co/Comfy-Org/ERNIE-Image')+ }+ }+ })++ it('includes shared flux2 VAE file', () => {+ for (const b of ernieBundles) {+ const vae = b.files.find(f => f.filename === 'flux2-vae.safetensors')+ expect(vae).toBeDefined()+ expect(vae!.subfolder).toBe('vae')+ }+ })++ it('includes Ministral-3B text encoder', () => {+ for (const b of ernieBundles) {+ const clip = b.files.find(f => f.filename === 'ministral-3-3b.safetensors')+ expect(clip).toBeDefined()+ expect(clip!.subfolder).toBe('text_encoders')+ }+ })++ it('includes prompt enhancer', () => {+ for (const b of ernieBundles) {+ const enhancer = b.files.find(f => f.filename === 'ernie-image-prompt-enhancer.safetensors')+ expect(enhancer).toBeDefined()+ }+ })++ it('total sizes are realistic (28-30 GB range)', () => {+ for (const b of ernieBundles) {+ expect(b.totalSizeGB).toBeGreaterThan(25)+ expect(b.totalSizeGB).toBeLessThan(35)+ }+ })++ it('requires 24 GB VRAM', () => {+ for (const b of ernieBundles) {+ expect(b.vramRequired).toBe('24 GB')+ }+ })++ it('requires no custom nodes', () => {+ for (const b of ernieBundles) {+ expect(b.customNodes || []).toHaveLength(0)+ }+ })+})++// ── Workflow ConditioningZeroOut verification ────────────────────────────+// We verify via source-level check since buildDynamicWorkflow requires+// a live ComfyUI connection.++describe('ERNIE-Image ConditioningZeroOut (source verification)', () => {+ it('dynamic-workflow.ts uses ConditioningZeroOut for ernie_image negative', () => {+ const { readFileSync } = require('fs')+ const { resolve } = require('path')+ const src = readFileSync(resolve(__dirname, '../dynamic-workflow.ts'), 'utf8')++ // The critical branching logic+ expect(src).toContain("strategy === 'unet_ernie_image'")+ expect(src).toContain('ConditioningZeroOut')+ // Verify ConditioningZeroOut takes positive conditioning as input+ expect(src).toMatch(/ConditioningZeroOut[\s\S]*conditioning.*posId/)+ })++ it('dynamic-workflow.ts uses EmptyFlux2LatentImage for ernie_image', () => {+ const { readFileSync } = require('fs')+ const { resolve } = require('path')+ const src = readFileSync(resolve(__dirname, '../dynamic-workflow.ts'), 'utf8')++ // ernie_image shares Flux2 latent space+ expect(src).toMatch(/unet_flux2.*unet_ernie_image|unet_ernie_image.*unet_flux2/)+ expect(src).toContain('EmptyFlux2LatentImage')+ })++ it('dynamic-workflow.ts uses flux2 clipType for ernie_image', () => {+ const { readFileSync } = require('fs')+ const { resolve } = require('path')+ const src = readFileSync(resolve(__dirname, '../dynamic-workflow.ts'), 'utf8')++ expect(src).toMatch(/ernie_image.*flux2/)+ })+})diff --git a/src/api/__tests__/mobile-codex-parity.test.ts b/src/api/__tests__/mobile-codex-parity.test.tsnew file mode 100644index 00000000..a3031d18--- /dev/null+++ b/src/api/__tests__/mobile-codex-parity.test.ts@@ -0,0 +1,144 @@+/**+ * Mobile ↔ Desktop parity smoke tests for Codex and Agent.+ *+ * The mobile web app lives as embedded JS in remote.rs. These tests verify+ * structural parity between desktop TypeScript and mobile JS implementations:+ *+ * - CODEX_TOOLS tool list matches desktop tool categories+ * - AGENT_ALL_TOOLS covers all registered tools+ * - runToolLoop exists with proper loop termination+ * - nativeToolChat uses correct Ollama API format+ * - Hidden message filtering in renderChat+ * - stripThinkTags exists for thinking content+ * - Fallback final answer exists+ * - Max iteration guard (no infinite loops)+ * - Permission defaults (all ON for mobile)+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'fs'+import { resolve } from 'path'++const REMOTE_RS = readFileSync(resolve(__dirname, '../../../src-tauri/src/commands/remote.rs'), 'utf8')++describe('Mobile CODEX_TOOLS parity', () => {+ it('includes file_read', () => {+ expect(REMOTE_RS).toContain("'file_read'")+ })++ it('includes file_write', () => {+ expect(REMOTE_RS).toContain("'file_write'")+ })++ it('includes file_list', () => {+ expect(REMOTE_RS).toContain("'file_list'")+ })++ it('includes file_search', () => {+ expect(REMOTE_RS).toContain("'file_search'")+ })++ it('includes shell_execute', () => {+ expect(REMOTE_RS).toContain("'shell_execute'")+ })++ it('includes code_execute', () => {+ expect(REMOTE_RS).toContain("'code_execute'")+ })++ it('includes system_info', () => {+ expect(REMOTE_RS).toContain("'system_info'")+ })++ it('includes web_search', () => {+ expect(REMOTE_RS).toContain("'web_search'")+ })++ it('includes web_fetch', () => {+ expect(REMOTE_RS).toContain("'web_fetch'")+ })+})++describe('Mobile runToolLoop', () => {+ it('function exists', () => {+ expect(REMOTE_RS).toContain('function runToolLoop')+ })++ it('has max iteration guard', () => {+ // Mobile should cap iterations to prevent infinite loops+ expect(REMOTE_RS).toMatch(/maxIter|MAX_ITER|iter\s*>=\s*\d+|iter\s*<\s*\d+/)+ })++ it('checks for empty tool_calls to terminate loop', () => {+ expect(REMOTE_RS).toMatch(/toolCalls.*length\s*===?\s*0|!res\.toolCalls/)+ })++ it('supports user abort', () => {+ expect(REMOTE_RS).toContain('agentAbort')+ })+})++describe('Mobile nativeToolChat', () => {+ it('function exists', () => {+ expect(REMOTE_RS).toContain('function nativeToolChat')+ })++ it('sends tools parameter to Ollama', () => {+ expect(REMOTE_RS).toContain('tools:')+ })++ it('uses /api/chat endpoint', () => {+ expect(REMOTE_RS).toContain('/api/chat')+ })+})++describe('Mobile hidden message handling', () => {+ it('renderChat skips hidden messages', () => {+ expect(REMOTE_RS).toContain('m.hidden')+ })++ it('hidden messages spliced into conversation for API context', () => {+ // Hidden messages must be in msgs[] for the LLM to see tool history+ expect(REMOTE_RS).toContain('hidden: true')+ })+})++describe('Mobile thinking support', () => {+ it('stripThinkTags function exists', () => {+ expect(REMOTE_RS).toContain('stripThinkTags')+ })++ it('handles Ollama native thinking field', () => {+ expect(REMOTE_RS).toContain('res.thinking')+ })+})++describe('Mobile fallback final answer', () => {+ it('builds summary when content is empty', () => {+ expect(REMOTE_RS).toContain('file(s) written')+ })++ it('finishToolLoop function exists', () => {+ expect(REMOTE_RS).toContain('finishToolLoop')+ })+})++describe('Mobile permissions', () => {+ it('all permissions default to ON', () => {+ // RemotePermissions::default() should have all true+ expect(REMOTE_RS).toMatch(/impl\s+Default\s+for\s+RemotePermissions/)+ // Check for `true` defaults (field names: filesystem, downloads, process_control)+ expect(REMOTE_RS).toMatch(/filesystem:\s*true/)+ expect(REMOTE_RS).toMatch(/downloads:\s*true/)+ expect(REMOTE_RS).toMatch(/process_control:\s*true/)+ })+})++describe('Mobile Codex vs Agent routing', () => {+ it('Codex mode uses CODEX_TOOLS', () => {+ expect(REMOTE_RS).toContain('isCodexChat ? CODEX_TOOLS')+ })++ it('Agent mode uses AGENT_ALL_TOOLS', () => {+ expect(REMOTE_RS).toContain('AGENT_ALL_TOOLS')+ })+})diff --git a/src/hooks/__tests__/useCodex-fallback-answer.test.ts b/src/hooks/__tests__/useCodex-fallback-answer.test.tsnew file mode 100644index 00000000..b14444ca--- /dev/null+++ b/src/hooks/__tests__/useCodex-fallback-answer.test.ts@@ -0,0 +1,142 @@+/**+ * Smoke tests for the Codex fallback final answer logic.+ *+ * When the model's last turn returns empty content (all work happened via+ * tool calls), useCodex.ts builds a summary from AgentBlock[] so the+ * assistant message bubble is never blank.+ *+ * We test the identical fallback logic in isolation and add drift detection.+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'fs'+import { fileURLToPath } from 'url'+import { dirname, join } from 'path'++// ── Mirror of the fallback logic from useCodex.ts ───────────────────────+interface MockBlock {+ phase: string+ toolCall?: { toolName: string; status: string }+}++function buildFallbackAnswer(blocks: MockBlock[]): string {+ const completed = blocks.filter(b => b.phase === 'tool_call' && b.toolCall?.status === 'completed')+ const failed = blocks.filter(b => b.phase === 'tool_call' && b.toolCall?.status === 'failed')+ const writes = completed.filter(b => b.toolCall?.toolName === 'file_write')+ const reads = completed.filter(b => b.toolCall?.toolName === 'file_read')++ const parts: string[] = []+ if (writes.length) parts.push(`${writes.length} file(s) written`)+ if (reads.length) parts.push(`${reads.length} file(s) read`)+ const otherCompleted = completed.length - writes.length - reads.length+ if (otherCompleted > 0) parts.push(`${otherCompleted} other operation(s) completed`)+ if (failed.length) parts.push(`${failed.length} operation(s) failed`)++ return parts.length > 0 ? `Task completed: ${parts.join(', ')}.` : 'Task completed.'+}++// ── Tests ───────────────────────────────────────────────────────────────++describe('Codex fallback final answer', () => {+ it('produces summary for file_write operations', () => {+ const blocks: MockBlock[] = [+ { phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'completed' } },+ { phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'completed' } },+ { phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'completed' } },+ ]+ expect(buildFallbackAnswer(blocks)).toBe('Task completed: 3 file(s) written.')+ })++ it('produces summary for file_read operations', () => {+ const blocks: MockBlock[] = [+ { phase: 'tool_call', toolCall: { toolName: 'file_read', status: 'completed' } },+ { phase: 'tool_call', toolCall: { toolName: 'file_read', status: 'completed' } },+ ]+ expect(buildFallbackAnswer(blocks)).toBe('Task completed: 2 file(s) read.')+ })++ it('produces summary for mixed operations', () => {+ const blocks: MockBlock[] = [+ { phase: 'tool_call', toolCall: { toolName: 'file_read', status: 'completed' } },+ { phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'completed' } },+ { phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'completed' } },+ { phase: 'tool_call', toolCall: { toolName: 'shell_execute', status: 'completed' } },+ { phase: 'tool_call', toolCall: { toolName: 'file_list', status: 'completed' } },+ ]+ const answer = buildFallbackAnswer(blocks)+ expect(answer).toContain('2 file(s) written')+ expect(answer).toContain('1 file(s) read')+ expect(answer).toContain('2 other operation(s) completed')+ })++ it('reports failed operations', () => {+ const blocks: MockBlock[] = [+ { phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'completed' } },+ { phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'failed' } },+ { phase: 'tool_call', toolCall: { toolName: 'shell_execute', status: 'failed' } },+ ]+ const answer = buildFallbackAnswer(blocks)+ expect(answer).toContain('1 file(s) written')+ expect(answer).toContain('2 operation(s) failed')+ })++ it('returns generic message when no blocks exist', () => {+ expect(buildFallbackAnswer([])).toBe('Task completed.')+ })++ it('ignores non-tool_call phases', () => {+ const blocks: MockBlock[] = [+ { phase: 'thinking', toolCall: undefined },+ { phase: 'streaming', toolCall: undefined },+ { phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'completed' } },+ ]+ expect(buildFallbackAnswer(blocks)).toBe('Task completed: 1 file(s) written.')+ })++ it('ignores running operations (not yet completed or failed)', () => {+ const blocks: MockBlock[] = [+ { phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'completed' } },+ { phase: 'tool_call', toolCall: { toolName: 'shell_execute', status: 'running' } },+ ]+ // 'running' is neither 'completed' nor 'failed', so it's not counted+ expect(buildFallbackAnswer(blocks)).toBe('Task completed: 1 file(s) written.')+ })++ it('handles all-failed scenario', () => {+ const blocks: MockBlock[] = [+ { phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'failed' } },+ { phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'failed' } },+ ]+ expect(buildFallbackAnswer(blocks)).toBe('Task completed: 2 operation(s) failed.')+ })++ it('handles large batch with diverse tools', () => {+ const blocks: MockBlock[] = [+ ...Array(5).fill(null).map(() => ({ phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'completed' } })),+ ...Array(3).fill(null).map(() => ({ phase: 'tool_call', toolCall: { toolName: 'file_read', status: 'completed' } })),+ ...Array(2).fill(null).map(() => ({ phase: 'tool_call', toolCall: { toolName: 'shell_execute', status: 'completed' } })),+ { phase: 'tool_call', toolCall: { toolName: 'file_search', status: 'completed' } },+ { phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'failed' } },+ ]+ const answer = buildFallbackAnswer(blocks)+ expect(answer).toContain('5 file(s) written')+ expect(answer).toContain('3 file(s) read')+ expect(answer).toContain('3 other operation(s) completed')+ expect(answer).toContain('1 operation(s) failed')+ })+})++// ── Drift detection ─────────────────────────────────────────────────────+describe('fallback answer drift detection', () => {+ it('useCodex.ts contains the fallback summary builder', () => {+ const __filename = fileURLToPath(import.meta.url)+ const __dirname = dirname(__filename)+ const src = readFileSync(join(__dirname, '../useCodex.ts'), 'utf8')++ // Must contain the fallback trigger+ expect(src).toContain("if (!fullContent.trim())")+ // Must build parts array with file write/read counts+ expect(src).toContain("file(s) written")+ expect(src).toContain("file(s) read")+ expect(src).toContain("Task completed:")+ })+})diff --git a/src/hooks/__tests__/useCodex-prompt-contract.test.ts b/src/hooks/__tests__/useCodex-prompt-contract.test.tsnew file mode 100644index 00000000..7a038e81--- /dev/null+++ b/src/hooks/__tests__/useCodex-prompt-contract.test.ts@@ -0,0 +1,113 @@+/**+ * Smoke tests for the Codex AUTONOMY CONTRACT system prompt.+ *+ * The prompt is the most critical piece of the Codex agent — it controls+ * whether the model completes multi-step tasks autonomously or stops prematurely.+ *+ * These tests read the actual source file to verify the prompt content hasn't+ * drifted from the required contract terms.+ *+ * We also verify parity between desktop (useCodex.ts) and mobile (remote.rs)+ * CODEX_PROMPT variants.+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'fs'+import { fileURLToPath } from 'url'+import { dirname, join, resolve } from 'path'++function readSource(relativePath: string): string {+ const __filename = fileURLToPath(import.meta.url)+ const __dirname = dirname(__filename)+ return readFileSync(resolve(__dirname, relativePath), 'utf8')+}++describe('Desktop CODEX_SYSTEM_PROMPT (useCodex.ts)', () => {+ const src = readSource('../useCodex.ts')++ it('contains AUTONOMY CONTRACT header', () => {+ expect(src).toContain('AUTONOMY CONTRACT')+ })++ it('instructs model to complete ALL steps without stopping', () => {+ expect(src).toContain('COMPLETE multi-step tasks')+ expect(src).toContain('execute ALL N steps')+ })++ it('forbids premature stopping with narrative text', () => {+ expect(src).toContain('premature stop')+ })++ it('defines the 5-step workflow', () => {+ expect(src).toContain('Understand the task')+ expect(src).toContain('Explore the codebase')+ expect(src).toContain('Implement ALL required changes')+ expect(src).toContain('Verify')+ expect(src).toContain('short summary')+ })++ it('requires reading before modifying', () => {+ expect(src).toContain('Always read a file before modifying it')+ })++ it('instructs chaining tool calls', () => {+ expect(src).toContain('Chain tool calls')+ })++ it('defines the model as Codex', () => {+ expect(src).toContain('You are Codex')+ })+})++describe('Mobile CODEX_PROMPT (remote.rs) parity', () => {+ const mobileRs = readSource('../../../src-tauri/src/commands/remote.rs')++ it('mobile contains AUTONOMY CONTRACT', () => {+ expect(mobileRs).toContain('AUTONOMY CONTRACT')+ })++ it('mobile instructs completing all steps', () => {+ expect(mobileRs).toContain('COMPLETE multi-step tasks')+ })++ it('mobile defines the model as Codex', () => {+ expect(mobileRs).toContain('You are Codex')+ })++ it('mobile has CODEX_TOOLS constant', () => {+ expect(mobileRs).toContain('CODEX_TOOLS')+ // Must include file_read, file_write, shell_execute+ expect(mobileRs).toContain("'file_read'")+ expect(mobileRs).toContain("'file_write'")+ expect(mobileRs).toContain("'shell_execute'")+ })++ it('mobile has AGENT_ALL_TOOLS constant', () => {+ expect(mobileRs).toContain('AGENT_ALL_TOOLS')+ })+})++describe('Desktop ↔ Mobile prompt parity check', () => {+ const desktop = readSource('../useCodex.ts')+ const mobile = readSource('../../../src-tauri/src/commands/remote.rs')++ it('both have AUTONOMY CONTRACT', () => {+ expect(desktop).toContain('AUTONOMY CONTRACT')+ expect(mobile).toContain('AUTONOMY CONTRACT')+ })++ it('both instruct chaining tool calls', () => {+ expect(desktop).toContain('Chain tool calls')+ expect(mobile).toContain('Chain tool calls')+ })++ it('both forbid stopping with narrative text', () => {+ // Desktop says "premature stop", mobile says "That is a FAILURE"+ expect(desktop).toContain('FAILURE')+ expect(mobile).toContain('FAILURE')+ })++ it('both instruct executing ALL steps', () => {+ expect(desktop).toContain('ALL N steps')+ expect(mobile).toContain('ALL N steps')+ })+})diff --git a/src/hooks/__tests__/useCodex-streaming.test.ts b/src/hooks/__tests__/useCodex-streaming.test.tsnew file mode 100644index 00000000..cd860a58--- /dev/null+++ b/src/hooks/__tests__/useCodex-streaming.test.ts@@ -0,0 +1,235 @@+/**+ * Smoke tests for `streamWithTools()` — the NDJSON streaming helper in useCodex.ts.+ *+ * We cannot import the function directly (it's module-private), so we test the+ * NDJSON-parsing logic in isolation with an identical implementation extracted+ * from the source. A drift-detection test at the bottom re-reads the hook+ * source to confirm the critical patterns remain in sync.+ *+ * Coverage:+ * - Single-chunk content accumulation+ * - Multi-chunk content concatenation+ * - Thinking field accumulation+ * - Tool call extraction from final chunk+ * - Tool call APPEND (not overwrite) across multiple chunks — regression test+ * - Empty/whitespace lines in NDJSON stream+ * - Partial JSON lines that split across chunks+ * - Remaining buffer processing after stream ends+ * - Mixed content + thinking + tool_calls in one stream+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'fs'+import { fileURLToPath } from 'url'+import { dirname, join } from 'path'++// ── Faithful copy of streamWithTools parsing logic ──────────────────────+// This mirrors the NDJSON parsing from useCodex.ts without the HTTP/fetch parts.+interface ToolCall {+ function: { name: string; arguments: Record<string, unknown> }+}++interface StreamResult {+ content: string+ toolCalls: ToolCall[]+ thinking: string+}++function parseNDJSON(ndjsonLines: string[]): StreamResult {+ let content = ''+ let thinking = ''+ let toolCalls: ToolCall[] = []++ for (const rawLine of ndjsonLines) {+ const trimmed = rawLine.trim()+ if (!trimmed) continue+ try {+ const j = JSON.parse(trimmed)+ if (j.message) {+ if (j.message.content) {+ content += j.message.content+ }+ if (j.message.thinking) {+ thinking += j.message.thinking+ }+ // Ollama may split tool_calls across chunks — append, don't overwrite+ if (j.message.tool_calls && Array.isArray(j.message.tool_calls)) {+ toolCalls = [...toolCalls, ...j.message.tool_calls.map((tc: any) => ({+ function: { name: tc.function.name, arguments: tc.function.arguments },+ }))]+ }+ }+ } catch { /* partial JSON — skip */ }+ }++ return { content, toolCalls, thinking }+}++// ── Tests ───────────────────────────────────────────────────────────────++describe('streamWithTools NDJSON parsing', () => {+ it('accumulates content from multiple chunks', () => {+ const lines = [+ '{"message":{"role":"assistant","content":"Hello"}}',+ '{"message":{"role":"assistant","content":" World"}}',+ '{"message":{"role":"assistant","content":"!"}}',+ ]+ const result = parseNDJSON(lines)+ expect(result.content).toBe('Hello World!')+ expect(result.toolCalls).toEqual([])+ expect(result.thinking).toBe('')+ })++ it('accumulates thinking from multiple chunks', () => {+ const lines = [+ '{"message":{"role":"assistant","thinking":"Let me think..."}}',+ '{"message":{"role":"assistant","thinking":" about this."}}',+ '{"message":{"role":"assistant","content":"The answer is 42."}}',+ ]+ const result = parseNDJSON(lines)+ expect(result.thinking).toBe('Let me think... about this.')+ expect(result.content).toBe('The answer is 42.')+ })++ it('extracts tool calls from the final chunk', () => {+ const lines = [+ '{"message":{"role":"assistant","content":"I\'ll write the file."}}',+ '{"message":{"role":"assistant","content":"","tool_calls":[{"function":{"name":"file_write","arguments":{"path":"test.ts","content":"console.log()"}}}]},"done":true}',+ ]+ const result = parseNDJSON(lines)+ expect(result.content).toBe("I'll write the file.")+ expect(result.toolCalls).toHaveLength(1)+ expect(result.toolCalls[0].function.name).toBe('file_write')+ expect(result.toolCalls[0].function.arguments).toEqual({ path: 'test.ts', content: 'console.log()' })+ })++ it('APPENDS tool calls across chunks (regression — was overwriting)', () => {+ const lines = [+ '{"message":{"role":"assistant","tool_calls":[{"function":{"name":"file_read","arguments":{"path":"a.ts"}}}]}}',+ '{"message":{"role":"assistant","tool_calls":[{"function":{"name":"file_write","arguments":{"path":"b.ts","content":"x"}}}]}}',+ ]+ const result = parseNDJSON(lines)+ expect(result.toolCalls).toHaveLength(2)+ expect(result.toolCalls[0].function.name).toBe('file_read')+ expect(result.toolCalls[1].function.name).toBe('file_write')+ })++ it('handles multiple tool calls in a single chunk', () => {+ const lines = [+ '{"message":{"role":"assistant","tool_calls":[{"function":{"name":"file_read","arguments":{"path":"a.ts"}}},{"function":{"name":"file_read","arguments":{"path":"b.ts"}}}]}}',+ ]+ const result = parseNDJSON(lines)+ expect(result.toolCalls).toHaveLength(2)+ expect(result.toolCalls[0].function.arguments).toEqual({ path: 'a.ts' })+ expect(result.toolCalls[1].function.arguments).toEqual({ path: 'b.ts' })+ })++ it('handles mixed content + thinking + tool_calls in one stream', () => {+ const lines = [+ '{"message":{"role":"assistant","thinking":"I need to read the file first."}}',+ '{"message":{"role":"assistant","content":"Reading file..."}}',+ '{"message":{"role":"assistant","tool_calls":[{"function":{"name":"file_read","arguments":{"path":"index.ts"}}}]}}',+ ]+ const result = parseNDJSON(lines)+ expect(result.thinking).toBe('I need to read the file first.')+ expect(result.content).toBe('Reading file...')+ expect(result.toolCalls).toHaveLength(1)+ expect(result.toolCalls[0].function.name).toBe('file_read')+ })++ it('skips empty and whitespace-only lines', () => {+ const lines = [+ '',+ ' ',+ '{"message":{"role":"assistant","content":"hello"}}',+ '',+ '{"message":{"role":"assistant","content":" world"}}',+ ' \n ',+ ]+ const result = parseNDJSON(lines)+ expect(result.content).toBe('hello world')+ })++ it('skips partial/invalid JSON lines gracefully', () => {+ const lines = [+ '{"message":{"role":"ass', // truncated+ '{"message":{"role":"assistant","content":"ok"}}',+ 'not json at all',+ '{"message":{"role":"assistant","content":"!"}}',+ ]+ const result = parseNDJSON(lines)+ expect(result.content).toBe('ok!')+ })++ it('returns empty result for empty stream', () => {+ const result = parseNDJSON([])+ expect(result.content).toBe('')+ expect(result.thinking).toBe('')+ expect(result.toolCalls).toEqual([])+ })++ it('ignores lines with no message field', () => {+ const lines = [+ '{"model":"gemma4","done":false}',+ '{"message":{"role":"assistant","content":"hi"}}',+ '{"status":"ok"}',+ ]+ const result = parseNDJSON(lines)+ expect(result.content).toBe('hi')+ })++ it('handles tool_calls with empty arguments', () => {+ const lines = [+ '{"message":{"role":"assistant","tool_calls":[{"function":{"name":"system_info","arguments":{}}}]}}',+ ]+ const result = parseNDJSON(lines)+ expect(result.toolCalls).toHaveLength(1)+ expect(result.toolCalls[0].function.arguments).toEqual({})+ })++ it('handles done=true chunk with both content and tool_calls', () => {+ const lines = [+ '{"message":{"role":"assistant","content":"Let me help. ","tool_calls":[{"function":{"name":"file_list","arguments":{"path":"."}}}]},"done":true}',+ ]+ const result = parseNDJSON(lines)+ expect(result.content).toBe('Let me help. ')+ expect(result.toolCalls).toHaveLength(1)+ expect(result.toolCalls[0].function.name).toBe('file_list')+ })++ it('tool call accumulation order is preserved', () => {+ const lines = [+ '{"message":{"role":"assistant","tool_calls":[{"function":{"name":"file_read","arguments":{"path":"1.ts"}}}]}}',+ '{"message":{"role":"assistant","tool_calls":[{"function":{"name":"file_write","arguments":{"path":"2.ts","content":"x"}}}]}}',+ '{"message":{"role":"assistant","tool_calls":[{"function":{"name":"shell_execute","arguments":{"command":"npm test"}}}]}}',+ ]+ const result = parseNDJSON(lines)+ expect(result.toolCalls).toHaveLength(3)+ expect(result.toolCalls.map(tc => tc.function.name)).toEqual([+ 'file_read', 'file_write', 'shell_execute',+ ])+ })+})++// ── Drift detection ─────────────────────────────────────────────────────+describe('streamWithTools drift detection', () => {+ it('useCodex.ts still uses append-spread for tool_calls (not overwrite)', () => {+ const __filename = fileURLToPath(import.meta.url)+ const __dirname = dirname(__filename)+ const src = readFileSync(join(__dirname, '../useCodex.ts'), 'utf8')++ // Must contain the spread-append pattern, not the old overwrite+ expect(src).toContain('...toolCalls, ...j.message.tool_calls.map')+ // Must NOT contain the old overwrite pattern+ expect(src).not.toMatch(/toolCalls\s*=\s*j\.message\.tool_calls\.map/)+ })++ it('useCodex.ts uses localFetchStream (not raw fetch)', () => {+ const __filename = fileURLToPath(import.meta.url)+ const __dirname = dirname(__filename)+ const src = readFileSync(join(__dirname, '../useCodex.ts'), 'utf8')++ expect(src).toContain('localFetchStream')+ // Must NOT use raw fetch() for the streaming endpoint+ expect(src).not.toMatch(/\bfetch\(url,/)+ })+})diff --git a/src/lib/__tests__/model-compatibility-smoke.test.ts b/src/lib/__tests__/model-compatibility-smoke.test.tsnew file mode 100644index 00000000..30ce64fb--- /dev/null+++ b/src/lib/__tests__/model-compatibility-smoke.test.ts@@ -0,0 +1,200 @@+/**+ * Comprehensive smoke tests for the model compatibility system.+ *+ * Tests all exported functions that control which features are available+ * for which models across all providers (Ollama, OpenAI, Anthropic).+ *+ * Coverage:+ * - isAgentCompatible (tool calling support)+ * - isThinkingCompatible (native think parameter)+ * - isPlainTextPlanner (Gemma 3/4 bypass logic)+ * - isClaudeCodeCompatible+ * - getToolCallingStrategy (native vs hermes_xml)+ * - getRecommendedAgentModels+ * - Abliterated model handling+ * - Provider-aware routing (cloud always supports)+ */+import { describe, it, expect } from 'vitest'+import {+ isAgentCompatible,+ isToolCallingModel,+ hasNativeToolCalling,+ isThinkingCompatible,+ isPlainTextPlanner,+ isClaudeCodeCompatible,+ getToolCallingStrategy,+ getRecommendedAgentModels,+} from '../model-compatibility'++// ── Agent Compatibility ─────────────────────────────────────────────────++describe('isAgentCompatible', () => {+ it('returns true for standard tool-calling models', () => {+ expect(isAgentCompatible('qwen3-coder:30b')).toBe(true)+ expect(isAgentCompatible('llama3.1:8b')).toBe(true)+ expect(isAgentCompatible('gemma4:12b')).toBe(true)+ expect(isAgentCompatible('hermes3:8b')).toBe(true)+ expect(isAgentCompatible('mistral:latest')).toBe(true)+ expect(isAgentCompatible('phi-4:14b')).toBe(true)+ expect(isAgentCompatible('deepseek-v3:latest')).toBe(true)+ })++ it('returns false for models without tool calling', () => {+ expect(isAgentCompatible('llama2:7b')).toBe(false)+ expect(isAgentCompatible('vicuna:7b')).toBe(false)+ expect(isAgentCompatible('codellama:7b')).toBe(false)+ expect(isAgentCompatible('tinyllama:latest')).toBe(false)+ })++ it('returns true for all cloud provider models', () => {+ expect(isAgentCompatible('openai::gpt-4o')).toBe(true)+ expect(isAgentCompatible('openai::gpt-4o-mini')).toBe(true)+ expect(isAgentCompatible('anthropic::claude-opus-4-20250514')).toBe(true)+ expect(isAgentCompatible('anthropic::claude-sonnet-4-20250514')).toBe(true)+ })++ it('handles abliterated models correctly', () => {+ // Hermes abliterated retains native tool calling+ expect(isAgentCompatible('hermes3-abliterated:8b')).toBe(true)+ // qwen3-coder abliterated retains it+ expect(isAgentCompatible('qwen3-coder-abliterated:30b')).toBe(true)+ // Random abliterated model without native support+ expect(isAgentCompatible('llama2-abliterated:7b')).toBe(false)+ })++ it('returns false for null/empty', () => {+ expect(isAgentCompatible(null)).toBe(false)+ expect(isAgentCompatible('')).toBe(false)+ })++ it('aliases work identically', () => {+ expect(isToolCallingModel('gemma4:12b')).toBe(true)+ expect(hasNativeToolCalling('gemma4:12b')).toBe(true)+ expect(isToolCallingModel('llama2:7b')).toBe(false)+ })+})++// ── Thinking Compatibility ──────────────────────────────────────────────++describe('isThinkingCompatible', () => {+ it('returns true for thinking-capable models', () => {+ expect(isThinkingCompatible('qwq:32b')).toBe(true)+ expect(isThinkingCompatible('deepseek-r1:8b')).toBe(true)+ expect(isThinkingCompatible('qwen3:8b')).toBe(true)+ expect(isThinkingCompatible('gemma3:9b')).toBe(true)+ expect(isThinkingCompatible('gemma4:12b')).toBe(true)+ expect(isThinkingCompatible('qwen3-coder:30b')).toBe(true)+ })++ it('returns false for non-thinking models', () => {+ expect(isThinkingCompatible('llama3.1:8b')).toBe(false)+ expect(isThinkingCompatible('hermes3:8b')).toBe(false)+ expect(isThinkingCompatible('mistral:latest')).toBe(false)+ })++ it('returns true for all cloud providers', () => {+ expect(isThinkingCompatible('openai::gpt-4o')).toBe(true)+ expect(isThinkingCompatible('anthropic::claude-sonnet-4-20250514')).toBe(true)+ })++ it('returns false for null', () => {+ expect(isThinkingCompatible(null)).toBe(false)+ })+})++// ── Gemma Plain-Text Planner Bypass ─────────────────────────────────────++describe('isPlainTextPlanner', () => {+ it('returns true for Gemma 3 and Gemma 4', () => {+ expect(isPlainTextPlanner('gemma3:9b')).toBe(true)+ expect(isPlainTextPlanner('gemma4:12b')).toBe(true)+ expect(isPlainTextPlanner('gemma4:26b')).toBe(true)+ })++ it('returns false for non-Gemma models', () => {+ expect(isPlainTextPlanner('qwen3:8b')).toBe(false)+ expect(isPlainTextPlanner('llama3.1:8b')).toBe(false)+ expect(isPlainTextPlanner('hermes3:8b')).toBe(false)+ })++ it('handles abliterated Gemma', () => {+ expect(isPlainTextPlanner('gemma4-abliterated:12b')).toBe(true)+ })++ it('returns false for null', () => {+ expect(isPlainTextPlanner(null)).toBe(false)+ })+})++// ── Claude Code Compatibility ───────────────────────────────────────────++describe('isClaudeCodeCompatible', () => {+ it('returns true for Claude-Code-capable models', () => {+ expect(isClaudeCodeCompatible('qwen3-coder:30b')).toBe(true)+ expect(isClaudeCodeCompatible('hermes3:8b')).toBe(true)+ expect(isClaudeCodeCompatible('gemma4:12b')).toBe(true)+ expect(isClaudeCodeCompatible('deepseek-v3:latest')).toBe(true)+ })++ it('returns false for incompatible models', () => {+ expect(isClaudeCodeCompatible('llama3.1:8b')).toBe(false)+ expect(isClaudeCodeCompatible('mistral:7b')).toBe(false)+ })+})++// ── Tool Calling Strategy ───────────────────────────────────────────────++describe('getToolCallingStrategy', () => {+ it('cloud providers always get native strategy', () => {+ expect(getToolCallingStrategy('openai::gpt-4o')).toBe('native')+ expect(getToolCallingStrategy('anthropic::claude-opus-4-20250514')).toBe('native')+ })++ it('Ollama compatible models get native', () => {+ expect(getToolCallingStrategy('qwen3:8b')).toBe('native')+ expect(getToolCallingStrategy('gemma4:12b')).toBe('native')+ expect(getToolCallingStrategy('hermes3:8b')).toBe('native')+ })++ it('Ollama incompatible models get hermes_xml fallback', () => {+ expect(getToolCallingStrategy('llama2:7b')).toBe('hermes_xml')+ expect(getToolCallingStrategy('tinyllama:latest')).toBe('hermes_xml')+ })+})++// ── Recommended Models ──────────────────────────────────────────────────++describe('getRecommendedAgentModels', () => {+ it('returns a non-empty list', () => {+ const models = getRecommendedAgentModels()+ expect(models.length).toBeGreaterThan(0)+ })++ it('all recommended models are agent-compatible', () => {+ const models = getRecommendedAgentModels()+ for (const m of models) {+ expect(isAgentCompatible(m.name)).toBe(true)+ }+ })++ it('includes both local and cloud models', () => {+ const models = getRecommendedAgentModels()+ const providers = new Set(models.map(m => m.provider))+ expect(providers.has('ollama')).toBe(true)+ expect(providers.has('anthropic')).toBe(true)+ })++ it('has at least one HOT pick', () => {+ const models = getRecommendedAgentModels()+ expect(models.some(m => m.hot)).toBe(true)+ })++ it('all entries have required fields', () => {+ const models = getRecommendedAgentModels()+ for (const m of models) {+ expect(m.name).toBeTruthy()+ expect(m.label).toBeTruthy()+ expect(m.reason).toBeTruthy()+ }+ })+})diff --git a/src/stores/__tests__/chatStore-operations.test.ts b/src/stores/__tests__/chatStore-operations.test.tsnew file mode 100644index 00000000..4db3ef41--- /dev/null+++ b/src/stores/__tests__/chatStore-operations.test.ts@@ -0,0 +1,229 @@+/**+ * Smoke tests for chatStore — the central conversation state manager.+ *+ * Tests all critical store operations that underpin Chat, Codex, Agent, and Remote:+ * - createConversation (all modes: lu, codex, claude-code, remote)+ * - addMessage / updateMessageContent / updateMessageThinking+ * - insertMessageBefore (Codex continue capability)+ * - deleteConversation / renameConversation+ * - deleteMessagesAfter (edit/regenerate)+ * - Hidden message handling+ * - searchConversations+ * - Auto-rename on first user message+ */+import { describe, it, expect, beforeEach } from 'vitest'+import { useChatStore } from '../chatStore'+import type { Message } from '../../types/chat'++function msg(overrides: Partial<Message> = {}): Message {+ return {+ id: `msg-${Math.random().toString(36).slice(2)}`,+ role: 'user',+ content: 'hello',+ timestamp: Date.now(),+ ...overrides,+ }+}++beforeEach(() => {+ useChatStore.setState({ conversations: [], activeConversationId: null })+})++describe('chatStore — conversation CRUD', () => {+ it('creates a conversation and sets it active', () => {+ const id = useChatStore.getState().createConversation('gemma4:12b', '', 'lu')+ const state = useChatStore.getState()+ expect(state.activeConversationId).toBe(id)+ expect(state.conversations).toHaveLength(1)+ expect(state.conversations[0].mode).toBe('lu')+ expect(state.conversations[0].title).toBe('New Chat')+ })++ it('creates Codex conversation with correct title', () => {+ const id = useChatStore.getState().createConversation('qwen3-coder:30b', '', 'codex')+ expect(useChatStore.getState().conversations[0].title).toBe('Codex Chat')+ expect(useChatStore.getState().conversations[0].mode).toBe('codex')+ })++ it('creates Claude Code conversation', () => {+ useChatStore.getState().createConversation('hermes3:8b', '', 'claude-code')+ expect(useChatStore.getState().conversations[0].title).toBe('Claude Code')+ })++ it('auto-numbers remote conversations', () => {+ useChatStore.getState().createConversation('gemma4', '', 'remote')+ useChatStore.getState().createConversation('gemma4', '', 'remote')+ useChatStore.getState().createConversation('gemma4', '', 'remote')+ const convs = useChatStore.getState().conversations+ const titles = convs.map(c => c.title).sort()+ expect(titles).toEqual(['Remote Chat 1', 'Remote Chat 2', 'Remote Chat 3'])+ })++ it('deletes a conversation', () => {+ const id = useChatStore.getState().createConversation('gemma4', '', 'lu')+ expect(useChatStore.getState().conversations).toHaveLength(1)+ useChatStore.getState().deleteConversation(id)+ expect(useChatStore.getState().conversations).toHaveLength(0)+ expect(useChatStore.getState().activeConversationId).toBeNull()+ })++ it('renames a conversation', () => {+ const id = useChatStore.getState().createConversation('gemma4', '', 'lu')+ useChatStore.getState().renameConversation(id, 'My Great Chat')+ expect(useChatStore.getState().conversations[0].title).toBe('My Great Chat')+ })++ it('auto-renames "New Chat" on first user message', () => {+ const id = useChatStore.getState().createConversation('gemma4', '', 'lu')+ useChatStore.getState().addMessage(id, msg({ content: 'Tell me about quantum physics and how it works' }))+ expect(useChatStore.getState().conversations[0].title).toBe('Tell me about quantum physics and how it works')+ })++ it('does NOT auto-rename Codex/Remote chats', () => {+ const id = useChatStore.getState().createConversation('gemma4', '', 'codex')+ useChatStore.getState().addMessage(id, msg({ content: 'Build a website' }))+ // Codex Chat title stays — auto-rename only kicks on title === 'New Chat'+ expect(useChatStore.getState().conversations[0].title).toBe('Codex Chat')+ })+})++describe('chatStore — message operations', () => {+ it('adds a message to a conversation', () => {+ const id = useChatStore.getState().createConversation('gemma4', '', 'lu')+ const m = msg()+ useChatStore.getState().addMessage(id, m)+ const conv = useChatStore.getState().conversations[0]+ expect(conv.messages).toHaveLength(1)+ expect(conv.messages[0].id).toBe(m.id)+ })++ it('updates message content', () => {+ const id = useChatStore.getState().createConversation('gemma4', '', 'lu')+ const m = msg({ role: 'assistant', content: '' })+ useChatStore.getState().addMessage(id, m)+ useChatStore.getState().updateMessageContent(id, m.id, 'Updated content')+ expect(useChatStore.getState().conversations[0].messages[0].content).toBe('Updated content')+ })++ it('updates message thinking', () => {+ const id = useChatStore.getState().createConversation('gemma4', '', 'lu')+ const m = msg({ role: 'assistant', content: 'answer' })+ useChatStore.getState().addMessage(id, m)+ useChatStore.getState().updateMessageThinking(id, m.id, 'Let me think...')+ expect(useChatStore.getState().conversations[0].messages[0].thinking).toBe('Let me think...')+ })++ it('deletes messages after a given message (edit/regenerate)', () => {+ const id = useChatStore.getState().createConversation('gemma4', '', 'lu')+ const m1 = msg({ content: 'first' })+ const m2 = msg({ role: 'assistant', content: 'reply1' })+ const m3 = msg({ content: 'second' })+ const m4 = msg({ role: 'assistant', content: 'reply2' })+ useChatStore.getState().addMessage(id, m1)+ useChatStore.getState().addMessage(id, m2)+ useChatStore.getState().addMessage(id, m3)+ useChatStore.getState().addMessage(id, m4)+ expect(useChatStore.getState().conversations[0].messages).toHaveLength(4)++ // deleteMessagesAfter deletes the target message AND everything after it+ useChatStore.getState().deleteMessagesAfter(id, m3.id)+ const msgs = useChatStore.getState().conversations[0].messages+ expect(msgs).toHaveLength(2)+ expect(msgs[0].content).toBe('first')+ expect(msgs[1].content).toBe('reply1')+ })+})++describe('chatStore — insertMessageBefore (Codex continue capability)', () => {+ it('inserts a hidden message before the target', () => {+ const id = useChatStore.getState().createConversation('gemma4', '', 'codex')+ const userMsg = msg({ content: 'build me a website' })+ const assistantMsg = msg({ role: 'assistant', content: 'Done!' })+ useChatStore.getState().addMessage(id, userMsg)+ useChatStore.getState().addMessage(id, assistantMsg)++ const hiddenMsg = msg({+ role: 'assistant',+ content: '',+ hidden: true,+ tool_calls: [{ function: { name: 'file_write', arguments: { path: 'index.html', content: '<html></html>' } } }],+ })+ useChatStore.getState().insertMessageBefore(id, assistantMsg.id, hiddenMsg)++ const msgs = useChatStore.getState().conversations[0].messages+ expect(msgs).toHaveLength(3)+ // Order: user → hidden → assistant+ expect(msgs[0].id).toBe(userMsg.id)+ expect(msgs[1].id).toBe(hiddenMsg.id)+ expect(msgs[1].hidden).toBe(true)+ expect(msgs[1].tool_calls).toHaveLength(1)+ expect(msgs[2].id).toBe(assistantMsg.id)+ })++ it('inserts multiple hidden messages in correct order', () => {+ const id = useChatStore.getState().createConversation('gemma4', '', 'codex')+ const userMsg = msg({ content: 'write 3 files' })+ const assistantMsg = msg({ role: 'assistant', content: 'Done!' })+ useChatStore.getState().addMessage(id, userMsg)+ useChatStore.getState().addMessage(id, assistantMsg)++ // Insert 3 hidden messages (tool chain: read → write → write)+ const h1 = msg({ role: 'assistant', content: '', hidden: true, tool_calls: [{ function: { name: 'file_read', arguments: { path: 'x.ts' } } }] })+ const h2 = msg({ role: 'tool', content: 'file contents...', hidden: true })+ const h3 = msg({ role: 'assistant', content: '', hidden: true, tool_calls: [{ function: { name: 'file_write', arguments: { path: 'x.ts', content: 'new' } } }] })++ useChatStore.getState().insertMessageBefore(id, assistantMsg.id, h1)+ useChatStore.getState().insertMessageBefore(id, assistantMsg.id, h2)+ useChatStore.getState().insertMessageBefore(id, assistantMsg.id, h3)++ const msgs = useChatStore.getState().conversations[0].messages+ expect(msgs).toHaveLength(5)+ expect(msgs.map(m => m.id)).toEqual([userMsg.id, h1.id, h2.id, h3.id, assistantMsg.id])+ expect(msgs.filter(m => m.hidden)).toHaveLength(3)+ })++ it('appends to end when beforeId not found', () => {+ const id = useChatStore.getState().createConversation('gemma4', '', 'codex')+ const m1 = msg({ content: 'first' })+ useChatStore.getState().addMessage(id, m1)++ const m2 = msg({ content: 'orphan', hidden: true })+ useChatStore.getState().insertMessageBefore(id, 'nonexistent-id', m2)++ const msgs = useChatStore.getState().conversations[0].messages+ expect(msgs).toHaveLength(2)+ expect(msgs[1].id).toBe(m2.id) // appended at end+ })+})++describe('chatStore — hidden message filtering (UI must skip these)', () => {+ it('hidden messages exist in store but should be filterable', () => {+ const id = useChatStore.getState().createConversation('gemma4', '', 'codex')+ useChatStore.getState().addMessage(id, msg({ role: 'user', content: 'hello' }))+ useChatStore.getState().addMessage(id, msg({ role: 'assistant', content: '', hidden: true }))+ useChatStore.getState().addMessage(id, msg({ role: 'tool', content: 'ok', hidden: true }))+ useChatStore.getState().addMessage(id, msg({ role: 'assistant', content: 'Done' }))++ const conv = useChatStore.getState().conversations[0]+ const allMsgs = conv.messages+ const visibleMsgs = allMsgs.filter(m => m.role !== 'system' && !m.hidden)++ expect(allMsgs).toHaveLength(4)+ expect(visibleMsgs).toHaveLength(2) // user + final assistant+ expect(visibleMsgs[0].content).toBe('hello')+ expect(visibleMsgs[1].content).toBe('Done')+ })+})++describe('chatStore — search', () => {+ it('searches conversations by message content', () => {+ const id1 = useChatStore.getState().createConversation('gemma4', '', 'lu')+ const id2 = useChatStore.getState().createConversation('gemma4', '', 'lu')+ useChatStore.getState().addMessage(id1, msg({ content: 'quantum physics explanation' }))+ useChatStore.getState().addMessage(id2, msg({ content: 'cooking recipe for pasta' }))++ const results = useChatStore.getState().searchConversations('quantum')+ expect(results).toHaveLength(1)+ expect(results[0].id).toBe(id1)+ })+})diff --git a/src/types/__tests__/message-types.test.ts b/src/types/__tests__/message-types.test.tsnew file mode 100644index 00000000..c8614ca1--- /dev/null+++ b/src/types/__tests__/message-types.test.ts@@ -0,0 +1,144 @@+/**+ * Smoke tests for the Message type system.+ *+ * Verifies the shape and semantics of the Message interface that underpins+ * all of Chat, Codex, Agent, and Remote. These are structural tests that+ * read the type definitions to ensure no fields are accidentally removed.+ *+ * Also tests the Conversation type and chat mode union.+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'fs'+import { resolve } from 'path'+import type { Message, Conversation, Role } from '../chat'++// ── Type-level tests using actual values ────────────────────────────────++describe('Message interface — field support', () => {+ it('supports all 4 roles', () => {+ const roles: Role[] = ['user', 'assistant', 'system', 'tool']+ expect(roles).toHaveLength(4)+ })++ it('constructs a basic user message', () => {+ const m: Message = {+ id: 'msg-1', role: 'user', content: 'Hello', timestamp: Date.now(),+ }+ expect(m.role).toBe('user')+ expect(m.hidden).toBeUndefined()+ })++ it('constructs an assistant message with thinking', () => {+ const m: Message = {+ id: 'msg-2', role: 'assistant', content: 'Answer',+ thinking: 'Let me think...', timestamp: Date.now(),+ }+ expect(m.thinking).toBe('Let me think...')+ })++ it('constructs a hidden tool-call message (Codex continue)', () => {+ const m: Message = {+ id: 'msg-3', role: 'assistant', content: '', timestamp: Date.now(),+ hidden: true,+ tool_calls: [{ function: { name: 'file_write', arguments: { path: 'x.ts', content: 'code' } } }],+ }+ expect(m.hidden).toBe(true)+ expect(m.tool_calls).toHaveLength(1)+ expect(m.tool_calls![0].function.name).toBe('file_write')+ })++ it('constructs a tool result message', () => {+ const m: Message = {+ id: 'msg-4', role: 'tool', content: 'File written successfully.',+ timestamp: Date.now(), hidden: true,+ }+ expect(m.role).toBe('tool')+ })++ it('constructs a message with images', () => {+ const m: Message = {+ id: 'msg-5', role: 'user', content: 'Describe this',+ timestamp: Date.now(),+ images: [{ data: 'base64...', mimeType: 'image/png', name: 'screenshot.png' }],+ }+ expect(m.images).toHaveLength(1)+ expect(m.images![0].mimeType).toBe('image/png')+ })++ it('constructs a message with RAG sources', () => {+ const m: Message = {+ id: 'msg-6', role: 'assistant', content: 'Based on your docs...',+ timestamp: Date.now(),+ sources: [{ documentName: 'readme.md', chunkIndex: 0, preview: 'First paragraph...' }],+ }+ expect(m.sources).toHaveLength(1)+ })++ it('constructs a message with agentBlocks', () => {+ const m: Message = {+ id: 'msg-7', role: 'assistant', content: 'Done',+ timestamp: Date.now(),+ agentBlocks: [],+ toolCallSummary: '3 files written',+ }+ expect(m.toolCallSummary).toBe('3 files written')+ })+})++describe('Conversation interface', () => {+ it('supports all 5 chat modes', () => {+ const modes: Conversation['mode'][] = ['lu', 'codex', 'openclaw', 'claude-code', 'remote']+ for (const mode of modes) {+ const c: Conversation = {+ id: `conv-${mode}`, title: 'Test', messages: [],+ model: 'gemma4:12b', systemPrompt: '', mode,+ createdAt: Date.now(), updatedAt: Date.now(),+ }+ expect(c.mode).toBe(mode)+ }+ })+})++// ── Source-level drift detection ────────────────────────────────────────++describe('Message type source integrity', () => {+ const src = readFileSync(resolve(__dirname, '../chat.ts'), 'utf8')++ it('Message has id, role, content, timestamp', () => {+ expect(src).toContain('id: string')+ expect(src).toContain('role: Role')+ expect(src).toContain('content: string')+ expect(src).toContain('timestamp: number')+ })++ it('Message has optional hidden field', () => {+ expect(src).toContain('hidden?: boolean')+ })++ it('Message has optional tool_calls field', () => {+ expect(src).toContain('tool_calls?:')+ })++ it('Message has optional thinking field', () => {+ expect(src).toContain('thinking?: string')+ })++ it('Message has optional images field', () => {+ expect(src).toContain('images?: ImageAttachment[]')+ })++ it('Conversation has mode with all 5 options', () => {+ expect(src).toContain("'lu'")+ expect(src).toContain("'codex'")+ expect(src).toContain("'openclaw'")+ expect(src).toContain("'claude-code'")+ expect(src).toContain("'remote'")+ })++ it('Role union has all 4 types', () => {+ expect(src).toContain("'user'")+ expect(src).toContain("'assistant'")+ expect(src).toContain("'system'")+ expect(src).toContain("'tool'")+ })+})