Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: address second round of PR review feedback

Adam Eivy9c1c2df92582
diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsx
index 2f58493cf8..dace20a3e6 100644
--- a/client/src/components/cos/tabs/TasksTab.jsx
+++ b/client/src/components/cos/tabs/TasksTab.jsx
@@ -329,10 +329,13 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
{showTemplates && (
<div className="flex flex-wrap gap-2">
{templates.map(template => (
- <button
+ <div
key={template.id}
+ role="button"
+ tabIndex={0}
onClick={() => applyTemplate(template)}
- className="group relative flex items-center gap-1.5 px-3 py-1.5 bg-port-card border border-port-border rounded-lg text-sm text-gray-300 hover:text-white hover:border-port-accent/50 transition-colors"
+ onKeyDown={(e) => e.key === 'Enter' && applyTemplate(template)}
+ className="group relative flex items-center gap-1.5 px-3 py-1.5 bg-port-card border border-port-border rounded-lg text-sm text-gray-300 hover:text-white hover:border-port-accent/50 transition-colors cursor-pointer"
title={template.description}
>
<span>{template.icon || '📝'}</span>
@@ -349,7 +352,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
<X size={10} />
</button>
)}
- </button>
+ </div>
))}
</div>
)}
diff --git a/client/src/hooks/useProviderModels.js b/client/src/hooks/useProviderModels.js
index 5628de15f5..eb33b6ef81 100644
--- a/client/src/hooks/useProviderModels.js
+++ b/client/src/hooks/useProviderModels.js
@@ -24,7 +24,7 @@ export default function useProviderModels({ filter } = {}) {
setSelectedModel(filtered[0].defaultModel || '');
}
setLoading(false);
- }, [filter]);
+ }, [filter, selectedProviderId]);
useEffect(() => { load(); }, [load]);
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index 0313819080..dc9c1ff5c9 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -152,12 +152,14 @@ function createStreamJsonParser() {
if (event?.type === 'content_block_stop') {
const idx = event.index;
const tool = activeTools.get(idx);
- if (tool && tool.inputJson) {
- const input = safeParse(tool.inputJson);
- if (input) {
- const detail = summarizeToolInput(tool.name, input);
- if (detail) {
- lines.push(` → ${detail}`);
+ if (tool) {
+ if (tool.inputJson) {
+ const input = safeParse(tool.inputJson);
+ if (input) {
+ const detail = summarizeToolInput(tool.name, input);
+ if (detail) {
+ lines.push(` → ${detail}`);
+ }
}
}
activeTools.delete(idx);
diff --git a/server/services/autonomousJobs.test.js b/server/services/autonomousJobs.test.js
new file mode 100644
index 0000000000..587ac18818
--- /dev/null
+++ b/server/services/autonomousJobs.test.js
@@ -0,0 +1,447 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+
+// Mock modules before import
+vi.mock('./cosEvents.js', () => ({
+ cosEvents: { emit: vi.fn() }
+}))
+
+vi.mock('../lib/fileUtils.js', () => ({
+ readJSONFile: vi.fn()
+}))
+
+vi.mock('fs', () => ({
+ existsSync: vi.fn().mockReturnValue(true),
+ promises: {
+ writeFile: vi.fn().mockResolvedValue(),
+ mkdir: vi.fn().mockResolvedValue()
+ }
+}))
+
+// Import after mocks
+import {
+ getAllJobs,
+ getJob,
+ getDueJobs,
+ createJob,
+ updateJob,
+ deleteJob,
+ recordJobExecution,
+ toggleJob,
+ generateTaskFromJob,
+ getJobStats,
+ INTERVAL_OPTIONS
+} from './autonomousJobs.js'
+import { readJSONFile } from '../lib/fileUtils.js'
+import { cosEvents } from './cosEvents.js'
+
+describe('autonomousJobs', () => {
+ const mockJobsData = {
+ version: 1,
+ lastUpdated: '2025-01-01T00:00:00.000Z',
+ jobs: [
+ {
+ id: 'job-test-1',
+ name: 'Test Job',
+ description: 'A test job',
+ category: 'test',
+ interval: 'daily',
+ intervalMs: 86400000,
+ enabled: true,
+ priority: 'MEDIUM',
+ autonomyLevel: 'manager',
+ promptTemplate: 'Do the test thing',
+ lastRun: null,
+ runCount: 0,
+ createdAt: '2025-01-01T00:00:00.000Z',
+ updatedAt: '2025-01-01T00:00:00.000Z'
+ }
+ ]
+ }
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ readJSONFile.mockResolvedValue(JSON.parse(JSON.stringify(mockJobsData)))
+ })
+
+ describe('getDueJobs', () => {
+ it('never-run enabled job is always due', async () => {
+ const due = await getDueJobs()
+
+ expect(due).toHaveLength(1)
+ expect(due[0].id).toBe('job-test-1')
+ expect(due[0].reason).toBe('never-run')
+ expect(due[0].overdueBy).toBeGreaterThan(0)
+ })
+
+ it('recently-run job is NOT due', async () => {
+ const now = new Date()
+ const oneHourAgo = new Date(now - 60 * 60 * 1000).toISOString()
+
+ readJSONFile.mockResolvedValue({
+ ...mockJobsData,
+ jobs: [{
+ ...mockJobsData.jobs[0],
+ lastRun: oneHourAgo
+ }]
+ })
+
+ const due = await getDueJobs()
+
+ expect(due).toHaveLength(0)
+ })
+
+ it('jobs sort by most overdue first', async () => {
+ const now = new Date()
+ const twoDaysAgo = new Date(now - 2 * 24 * 60 * 60 * 1000).toISOString()
+ const fourDaysAgo = new Date(now - 4 * 24 * 60 * 60 * 1000).toISOString()
+
+ readJSONFile.mockResolvedValue({
+ ...mockJobsData,
+ jobs: [
+ {
+ ...mockJobsData.jobs[0],
+ id: 'job-1',
+ name: 'Less Overdue',
+ lastRun: twoDaysAgo,
+ intervalMs: 86400000
+ },
+ {
+ ...mockJobsData.jobs[0],
+ id: 'job-2',
+ name: 'More Overdue',
+ lastRun: fourDaysAgo,
+ intervalMs: 86400000
+ }
+ ]
+ })
+
+ const due = await getDueJobs()
+
+ expect(due).toHaveLength(2)
+ expect(due[0].id).toBe('job-2')
+ expect(due[1].id).toBe('job-1')
+ expect(due[0].overdueBy).toBeGreaterThan(due[1].overdueBy)
+ })
+ })
+
+ describe('generateTaskFromJob', () => {
+ it('returns correct task structure with metadata', () => {
+ const job = mockJobsData.jobs[0]
+ const task = generateTaskFromJob(job)
+
+ expect(task).toMatchObject({
+ description: job.promptTemplate,
+ priority: job.priority,
+ metadata: {
+ autonomousJob: true,
+ jobId: job.id,
+ jobName: job.name,
+ jobCategory: job.category,
+ autonomyLevel: job.autonomyLevel
+ },
+ taskType: 'internal',
+ autoApprove: false
+ })
+ expect(task.id).toContain(job.id)
+ })
+
+ it('autoApprove true when autonomyLevel is yolo', () => {
+ const yoloJob = {
+ ...mockJobsData.jobs[0],
+ autonomyLevel: 'yolo'
+ }
+
+ const task = generateTaskFromJob(yoloJob)
+
+ expect(task.autoApprove).toBe(true)
+ expect(task.metadata.autonomyLevel).toBe('yolo')
+ })
+ })
+
+ describe('createJob with resolveIntervalMs', () => {
+ it('hourly interval produces correct intervalMs', async () => {
+ const jobData = {
+ name: 'Hourly Job',
+ interval: 'hourly',
+ promptTemplate: 'Do hourly thing'
+ }
+
+ const job = await createJob(jobData)
+
+ expect(job.intervalMs).toBe(60 * 60 * 1000)
+ expect(job.interval).toBe('hourly')
+ })
+
+ it('daily interval produces correct intervalMs', async () => {
+ const jobData = {
+ name: 'Daily Job',
+ interval: 'daily',
+ promptTemplate: 'Do daily thing'
+ }
+
+ const job = await createJob(jobData)
+
+ expect(job.intervalMs).toBe(24 * 60 * 60 * 1000)
+ expect(job.interval).toBe('daily')
+ })
+
+ it('weekly interval produces correct intervalMs', async () => {
+ const jobData = {
+ name: 'Weekly Job',
+ interval: 'weekly',
+ promptTemplate: 'Do weekly thing'
+ }
+
+ const job = await createJob(jobData)
+
+ expect(job.intervalMs).toBe(7 * 24 * 60 * 60 * 1000)
+ expect(job.interval).toBe('weekly')
+ })
+ })
+
+ describe('INTERVAL_OPTIONS', () => {
+ it('has expected options', () => {
+ expect(INTERVAL_OPTIONS).toContainEqual({
+ value: 'hourly',
+ label: 'Every Hour',
+ ms: 60 * 60 * 1000
+ })
+
+ expect(INTERVAL_OPTIONS).toContainEqual({
+ value: 'daily',
+ label: 'Daily',
+ ms: 24 * 60 * 60 * 1000
+ })
+
+ expect(INTERVAL_OPTIONS).toContainEqual({
+ value: 'weekly',
+ label: 'Weekly',
+ ms: 7 * 24 * 60 * 60 * 1000
+ })
+
+ expect(INTERVAL_OPTIONS.length).toBeGreaterThan(3)
+ })
+ })
+
+ describe('mergeWithDefaults (tested indirectly via loadJobs)', () => {
+ it('missing default jobs get added', async () => {
+ readJSONFile.mockResolvedValueOnce({
+ version: 1,
+ lastUpdated: '2025-01-01T00:00:00.000Z',
+ jobs: [
+ {
+ id: 'job-custom-only',
+ name: 'Custom Job',
+ description: 'Only custom job',
+ category: 'custom',
+ interval: 'daily',
+ intervalMs: 86400000,
+ enabled: false,
+ priority: 'MEDIUM',
+ autonomyLevel: 'manager',
+ promptTemplate: 'Custom work',
+ lastRun: null,
+ runCount: 0,
+ createdAt: '2025-01-01T00:00:00.000Z',
+ updatedAt: '2025-01-01T00:00:00.000Z'
+ }
+ ]
+ })
+
+ const jobs = await getAllJobs()
+
+ expect(jobs.length).toBeGreaterThan(1)
+ expect(jobs.find(j => j.id === 'job-custom-only')).toBeDefined()
+ expect(jobs.find(j => j.id === 'job-git-maintenance')).toBeDefined()
+ expect(jobs.find(j => j.id === 'job-brain-processing')).toBeDefined()
+ })
+ })
+
+ describe('getAllJobs', () => {
+ it('returns all jobs from storage', async () => {
+ const jobs = await getAllJobs()
+
+ expect(jobs.length).toBeGreaterThan(0)
+ expect(jobs.find(j => j.id === 'job-test-1')).toBeDefined()
+ })
+ })
+
+ describe('getJob', () => {
+ it('returns job by ID', async () => {
+ const job = await getJob('job-test-1')
+
+ expect(job).toBeDefined()
+ expect(job.id).toBe('job-test-1')
+ })
+
+ it('returns null for non-existent job', async () => {
+ const job = await getJob('nonexistent')
+
+ expect(job).toBeNull()
+ })
+ })
+
+ describe('createJob', () => {
+ it('creates job with defaults', async () => {
+ const newJob = {
+ name: 'New Job',
+ promptTemplate: 'Do new thing'
+ }
+
+ const job = await createJob(newJob)
+
+ expect(job.name).toBe('New Job')
+ expect(job.priority).toBe('MEDIUM')
+ expect(job.autonomyLevel).toBe('manager')
+ expect(job.enabled).toBe(false)
+ expect(job.interval).toBe('weekly')
+ expect(cosEvents.emit).toHaveBeenCalledWith('jobs:created', {
+ id: expect.any(String),
+ name: 'New Job'
+ })
+ })
+ })
+
+ describe('updateJob', () => {
+ it('updates existing job', async () => {
+ const updates = {
+ name: 'Updated Name',
+ enabled: true
+ }
+
+ const job = await updateJob('job-test-1', updates)
+
+ expect(job.name).toBe('Updated Name')
+ expect(job.enabled).toBe(true)
+ expect(cosEvents.emit).toHaveBeenCalledWith('jobs:updated', {
+ id: 'job-test-1',
+ updates
+ })
+ })
+
+ it('returns null for non-existent job', async () => {
+ const job = await updateJob('nonexistent', { name: 'Updated' })
+
+ expect(job).toBeNull()
+ })
+ })
+
+ describe('deleteJob', () => {
+ it('deletes existing job', async () => {
+ const result = await deleteJob('job-test-1')
+
+ expect(result).toBe(true)
+ expect(cosEvents.emit).toHaveBeenCalledWith('jobs:deleted', {
+ id: 'job-test-1'
+ })
+ })
+
+ it('returns false for non-existent job', async () => {
+ const result = await deleteJob('nonexistent')
+
+ expect(result).toBe(false)
+ })
+ })
+
+ describe('recordJobExecution', () => {
+ it('updates lastRun and increments runCount', async () => {
+ const job = await recordJobExecution('job-test-1')
+
+ expect(job.lastRun).toBeDefined()
+ expect(job.runCount).toBe(1)
+ expect(cosEvents.emit).toHaveBeenCalledWith('jobs:executed', {
+ id: 'job-test-1',
+ runCount: 1
+ })
+ })
+
+ it('returns null for non-existent job', async () => {
+ const job = await recordJobExecution('nonexistent')
+
+ expect(job).toBeNull()
+ })
+ })
+
+ describe('toggleJob', () => {
+ it('toggles enabled state from true to false', async () => {
+ const job = await toggleJob('job-test-1')
+
+ expect(job.enabled).toBe(false)
+ expect(cosEvents.emit).toHaveBeenCalledWith('jobs:toggled', {
+ id: 'job-test-1',
+ enabled: false
+ })
+ })
+
+ it('toggles enabled state from false to true', async () => {
+ readJSONFile.mockResolvedValue({
+ ...mockJobsData,
+ jobs: [{
+ ...mockJobsData.jobs[0],
+ enabled: false
+ }]
+ })
+
+ const job = await toggleJob('job-test-1')
+
+ expect(job.enabled).toBe(true)
+ })
+
+ it('returns null for non-existent job', async () => {
+ const job = await toggleJob('nonexistent')
+
+ expect(job).toBeNull()
+ })
+ })
+
+ describe('getJobStats', () => {
+ it('returns correct statistics', async () => {
+ readJSONFile.mockResolvedValueOnce({
+ version: 1,
+ lastUpdated: '2025-01-01T00:00:00.000Z',
+ jobs: [
+ {
+ id: 'job-1',
+ name: 'Job 1',
+ description: '',
+ category: 'test',
+ interval: 'daily',
+ intervalMs: 86400000,
+ enabled: true,
+ priority: 'MEDIUM',
+ autonomyLevel: 'manager',
+ promptTemplate: '',
+ lastRun: null,
+ runCount: 5,
+ createdAt: '2025-01-01T00:00:00.000Z',
+ updatedAt: '2025-01-01T00:00:00.000Z'
+ },
+ {
+ id: 'job-2',
+ name: 'Job 2',
+ description: '',
+ category: 'brain-processing',
+ interval: 'daily',
+ intervalMs: 86400000,
+ enabled: false,
+ priority: 'MEDIUM',
+ autonomyLevel: 'manager',
+ promptTemplate: '',
+ lastRun: null,
+ runCount: 3,
+ createdAt: '2025-01-01T00:00:00.000Z',
+ updatedAt: '2025-01-01T00:00:00.000Z'
+ }
+ ]
+ })
+
+ const stats = await getJobStats()
+
+ expect(stats.total).toBeGreaterThan(0)
+ expect(stats.enabled).toBeGreaterThanOrEqual(1)
+ expect(stats.disabled).toBeGreaterThanOrEqual(1)
+ expect(stats.byCategory.test).toBe(1)
+ expect(stats.totalRuns).toBeGreaterThanOrEqual(8)
+ })
+ })
+})
diff --git a/server/services/cos.js b/server/services/cos.js
index f5c9495f06..8a95541d89 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -671,7 +671,6 @@ export async function evaluateTasks() {
if (tasksToSpawn.length >= availableSlots) break;
const task = generateTaskFromJob(job);
tasksToSpawn.push(task);
- await recordJobExecution(job.id);
emitLog('info', `Autonomous job due: ${job.name} (${job.reason})`, {
jobId: job.id,
category: job.category
@@ -2845,6 +2844,13 @@ async function init() {
setImmediate(() => dequeueNextTask());
});
+ // Record autonomous job execution only after the agent actually spawns
+ cosEvents.on('job:spawned', async ({ jobId }) => {
+ await recordJobExecution(jobId).catch(err =>
+ console.error(`❌ Failed to record job execution for ${jobId}: ${err.message}`)
+ );
+ });
+
const state = await loadState();
// Auto-start if alwaysOn mode is enabled (or legacy autoStart)
diff --git a/server/services/runner.js b/server/services/runner.js
index f0b7fe0202..0fc829b227 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -3,7 +3,7 @@
* Re-exports toolkit runner service functions with local overrides
*/
import { spawn } from 'child_process';
-import { writeFile, readFile } from 'fs/promises';
+import { writeFile, readFile, mkdir } from 'fs/promises';
import { join } from 'path';
// This will be initialized by server/index.js and set via setAIToolkit()
@@ -27,6 +27,7 @@ export async function executeCliRun(runId, provider, prompt, workspacePath, onDa
const runsPath = join(aiToolkitInstance.config.dataDir || './data', 'runs');
const runDir = join(runsPath, runId);
+ await mkdir(runDir, { recursive: true });
const outputPath = join(runDir, 'output.txt');
const metadataPath = join(runDir, 'metadata.json');
@@ -118,6 +119,13 @@ export async function executeApiRun(runId, provider, model, prompt, workspacePat
export async function stopRun(runId) {
if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized');
+ // Check local active runs first (CLI runs spawned by this override)
+ const localProcess = aiToolkitInstance.services.runner._portosActiveRuns?.get(runId);
+ if (localProcess && !localProcess.killed) {
+ localProcess.kill('SIGTERM');
+ aiToolkitInstance.services.runner._portosActiveRuns.delete(runId);
+ return { stopped: true, runId };
+ }
return aiToolkitInstance.services.runner.stopRun(runId);
}
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 71e80d7f17..f70bff6f2a 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -997,10 +997,19 @@ async function syncRunnerAgents() {
return syncedCount;
}
+// Guard against duplicate spawns for the same task (e.g. immediate spawn + evaluation loop race)
+const spawningTasks = new Set();
+
/**
* Spawn an agent for a task
*/
export async function spawnAgentForTask(task) {
+ if (spawningTasks.has(task.id)) {
+ console.log(`⚠️ Task ${task.id} already being spawned, skipping duplicate`);
+ return null;
+ }
+ spawningTasks.add(task.id);
+
const agentId = `agent-${uuidv4().slice(0, 8)}`;
// Determine execution lane and acquire slot
@@ -1031,6 +1040,7 @@ export async function spawnAgentForTask(task) {
// Helper to cleanup on early exit
const cleanupOnError = (error) => {
+ spawningTasks.delete(task.id);
release(agentId);
errorExecution(toolExecution.id, { message: error });
completeExecution(toolExecution.id, { success: false });
@@ -1211,6 +1221,12 @@ export async function spawnAgentForTask(task) {
// Mark the task as in_progress to prevent re-spawning
await updateTask(task.id, { status: 'in_progress' }, task.taskType || 'user');
+ spawningTasks.delete(task.id);
+
+ // Record autonomous job execution now that the task is confirmed spawning
+ if (task.metadata?.autonomousJob && task.metadata?.jobId) {
+ cosEvents.emit('job:spawned', { jobId: task.metadata.jobId });
+ }
// Build CLI-specific spawn configuration
const cliConfig = buildCliSpawnConfig(provider, selectedModel);
@@ -1754,12 +1770,14 @@ function createStreamJsonParser() {
if (event?.type === 'content_block_stop') {
const idx = event.index;
const tool = activeTools.get(idx);
- if (tool && tool.inputJson) {
- const input = safeParse(tool.inputJson);
- if (input) {
- const detail = summarizeToolInput(tool.name, input);
- if (detail) {
- lines.push(` → ${detail}`);
+ if (tool) {
+ if (tool.inputJson) {
+ const input = safeParse(tool.inputJson);
+ if (input) {
+ const detail = summarizeToolInput(tool.name, input);
+ if (detail) {
+ lines.push(` → ${detail}`);
+ }
}
}
activeTools.delete(idx);
diff --git a/server/services/taskTemplates.test.js b/server/services/taskTemplates.test.js
new file mode 100644
index 0000000000..3c4e4e2dd6
--- /dev/null
+++ b/server/services/taskTemplates.test.js
@@ -0,0 +1,234 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+// Mock dependencies before importing the module
+vi.mock('../lib/fileUtils.js', () => ({
+ readJSONFile: vi.fn()
+}));
+
+vi.mock('fs/promises', () => ({
+ writeFile: vi.fn().mockResolvedValue(),
+ mkdir: vi.fn().mockResolvedValue()
+}));
+
+vi.mock('fs', () => ({
+ existsSync: vi.fn().mockReturnValue(true)
+}));
+
+// Import after mocking
+const { readJSONFile } = await import('../lib/fileUtils.js');
+const { writeFile, mkdir } = await import('fs/promises');
+const { existsSync } = await import('fs');
+const {
+ getAllTemplates,
+ getPopularTemplates,
+ recordTemplateUsage,
+ createTemplate,
+ deleteTemplate
+} = await import('./taskTemplates.js');
+
+describe('taskTemplates service', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('getAllTemplates', () => {
+ it('returns built-in templates when no user templates exist', async () => {
+ readJSONFile.mockResolvedValue(null);
+
+ const templates = await getAllTemplates();
+
+ expect(templates.length).toBeGreaterThan(0);
+ expect(templates.every(t => t.isBuiltin)).toBe(true);
+ expect(templates.every(t => t.id.startsWith('builtin-'))).toBe(true);
+ expect(templates.every(t => t.useCount === 0)).toBe(true);
+ });
+
+ it('merges built-in and user templates', async () => {
+ readJSONFile.mockResolvedValue({
+ userTemplates: [
+ {
+ id: 'user-abc123',
+ name: 'My Template',
+ description: 'Custom',
+ icon: '🔥',
+ context: 'some context',
+ isBuiltin: false
+ }
+ ],
+ usage: {},
+ lastUpdated: '2025-01-01T00:00:00.000Z'
+ });
+
+ const templates = await getAllTemplates();
+
+ const builtInCount = templates.filter(t => t.isBuiltin).length;
+ const userCount = templates.filter(t => !t.isBuiltin).length;
+
+ expect(builtInCount).toBeGreaterThan(0);
+ expect(userCount).toBe(1);
+ expect(templates.find(t => t.id === 'user-abc123')).toBeDefined();
+ });
+
+ it('includes usage counts from state', async () => {
+ readJSONFile.mockResolvedValue({
+ userTemplates: [
+ {
+ id: 'user-abc123',
+ name: 'My Template',
+ description: 'Custom',
+ icon: '🔥',
+ context: 'some context',
+ isBuiltin: false
+ }
+ ],
+ usage: {
+ 'user-abc123': 5,
+ 'builtin-mobile-fix': 3
+ },
+ lastUpdated: '2025-01-01T00:00:00.000Z'
+ });
+
+ const templates = await getAllTemplates();
+
+ const userTemplate = templates.find(t => t.id === 'user-abc123');
+ const builtinTemplate = templates.find(t => t.id === 'builtin-mobile-fix');
+
+ expect(userTemplate.useCount).toBe(5);
+ expect(builtinTemplate.useCount).toBe(3);
+ });
+ });
+
+ describe('createTemplate', () => {
+ it('creates with generated ID and correct fields', async () => {
+ readJSONFile.mockResolvedValue({
+ userTemplates: [],
+ usage: {},
+ lastUpdated: null
+ });
+
+ const templateData = {
+ name: 'Test Template',
+ icon: '🚀',
+ description: 'Test description',
+ context: 'Test context',
+ category: 'testing',
+ provider: 'openai',
+ model: 'gpt-4',
+ app: 'test-app'
+ };
+
+ const newTemplate = await createTemplate(templateData);
+
+ expect(newTemplate.id).toMatch(/^user-/);
+ expect(newTemplate.name).toBe('Test Template');
+ expect(newTemplate.icon).toBe('🚀');
+ expect(newTemplate.description).toBe('Test description');
+ expect(newTemplate.context).toBe('Test context');
+ expect(newTemplate.category).toBe('testing');
+ expect(newTemplate.provider).toBe('openai');
+ expect(newTemplate.model).toBe('gpt-4');
+ expect(newTemplate.app).toBe('test-app');
+ expect(newTemplate.isBuiltin).toBe(false);
+ expect(newTemplate.createdAt).toBeDefined();
+
+ expect(writeFile).toHaveBeenCalled();
+ });
+ });
+
+ describe('deleteTemplate', () => {
+ it('returns error for built-in templates', async () => {
+ readJSONFile.mockResolvedValue({
+ userTemplates: [],
+ usage: {},
+ lastUpdated: null
+ });
+
+ const result = await deleteTemplate('builtin-mobile-fix');
+
+ expect(result.error).toBe('Cannot delete built-in templates');
+ expect(writeFile).not.toHaveBeenCalled();
+ });
+
+ it('deletes user templates', async () => {
+ readJSONFile.mockResolvedValue({
+ userTemplates: [
+ {
+ id: 'user-abc123',
+ name: 'My Template',
+ description: 'Custom',
+ icon: '🔥',
+ context: 'some context',
+ isBuiltin: false
+ }
+ ],
+ usage: {
+ 'user-abc123': 5
+ },
+ lastUpdated: '2025-01-01T00:00:00.000Z'
+ });
+
+ const result = await deleteTemplate('user-abc123');
+
+ expect(result.success).toBe(true);
+ expect(result.deleted.id).toBe('user-abc123');
+ expect(writeFile).toHaveBeenCalled();
+
+ const savedState = JSON.parse(writeFile.mock.calls[0][1]);
+ expect(savedState.userTemplates.length).toBe(0);
+ expect(savedState.usage['user-abc123']).toBeUndefined();
+ });
+ });
+
+ describe('recordTemplateUsage', () => {
+ it('increments usage counter', async () => {
+ readJSONFile.mockResolvedValue({
+ userTemplates: [],
+ usage: {
+ 'builtin-mobile-fix': 3
+ },
+ lastUpdated: '2025-01-01T00:00:00.000Z'
+ });
+
+ const count = await recordTemplateUsage('builtin-mobile-fix');
+
+ expect(count).toBe(4);
+ expect(writeFile).toHaveBeenCalled();
+
+ const savedState = JSON.parse(writeFile.mock.calls[0][1]);
+ expect(savedState.usage['builtin-mobile-fix']).toBe(4);
+ });
+ });
+
+ describe('getPopularTemplates', () => {
+ it('returns sorted by useCount descending', async () => {
+ readJSONFile.mockResolvedValue({
+ userTemplates: [
+ {
+ id: 'user-abc123',
+ name: 'My Template',
+ description: 'Custom',
+ icon: '🔥',
+ context: 'some context',
+ isBuiltin: false
+ }
+ ],
+ usage: {
+ 'user-abc123': 10,
+ 'builtin-mobile-fix': 3,
+ 'builtin-add-feature': 7
+ },
+ lastUpdated: '2025-01-01T00:00:00.000Z'
+ });
+
+ const popular = await getPopularTemplates(3);
+
+ expect(popular.length).toBe(3);
+ expect(popular[0].id).toBe('user-abc123');
+ expect(popular[0].useCount).toBe(10);
+ expect(popular[1].id).toBe('builtin-add-feature');
+ expect(popular[1].useCount).toBe(7);
+ expect(popular[2].id).toBe('builtin-mobile-fix');
+ expect(popular[2].useCount).toBe(3);
+ });
+ });
+});