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

feat(cos): add AI prompt enhancement for new tasks

Adam Eivy9bf86c259f6e
diff --git a/.changelog/v0.10.x.md b/.changelog/v0.10.x.md
index e2736b9288..f1fb627192 100644
--- a/.changelog/v0.10.x.md
+++ b/.changelog/v0.10.x.md
@@ -139,6 +139,13 @@ This release introduces a structured changelog documentation system for creating
- **Learning Data Reset**: When a task type is rehabilitated, its historical learning data is reset, giving it a clean slate to prove the underlying issue was fixed
- **Status Visibility**: New `getSkippedTaskTypesWithStatus()` function provides detailed info about skipped tasks including days until rehabilitation eligibility
+### CoS Task Prompt Enhancement
+- **AI-Powered Prompt Enhancement**: New "Enhance with AI" checkbox in the Add Task form that uses AI to expand brief task descriptions into comprehensive, detailed prompts
+- **Actionable Prompts**: Enhanced prompts include specific steps, relevant context, success criteria, and edge cases to watch for
+- **Provider Flexibility**: Uses OpenAI Codex by default for enhancement, with fallback to the active provider if OpenAI is unavailable
+- **Visual Feedback**: Loading spinner and "Enhancing..." state during prompt processing, with clear success/error toasts
+- **API Endpoint**: New `POST /api/cos/tasks/enhance` endpoint for programmatic access to prompt enhancement
+
## 🔧 Improvements
### Release Process
diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsx
index 73fbd50b80..f7e6438fec 100644
--- a/client/src/components/cos/tabs/TasksTab.jsx
+++ b/client/src/components/cos/tabs/TasksTab.jsx
@@ -1,5 +1,5 @@
import { useState, useEffect, useRef, useMemo } from 'react';
-import { Plus, Play, Image, X, ChevronDown, ChevronRight } from 'lucide-react';
+import { Plus, Play, Image, X, ChevronDown, ChevronRight, Sparkles, Loader2 } from 'lucide-react';
import toast from 'react-hot-toast';
import {
DndContext,
@@ -29,6 +29,8 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
const [durations, setDurations] = useState(null);
const [showCompletedUserTasks, setShowCompletedUserTasks] = useState(false);
const [showCompletedSystemTasks, setShowCompletedSystemTasks] = useState(false);
+ const [enhancePrompt, setEnhancePrompt] = useState(false);
+ const [isEnhancing, setIsEnhancing] = useState(false);
const fileInputRef = useRef(null);
// Fetch task duration estimates from learning data
@@ -153,8 +155,31 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
return;
}
+ let finalDescription = newTask.description;
+
+ // If enhance checkbox is checked, call the enhance API first
+ if (enhancePrompt) {
+ setIsEnhancing(true);
+ const enhanceResult = await api.enhanceCosTaskPrompt({
+ description: newTask.description,
+ context: newTask.context
+ }).catch(err => {
+ toast.error(`Enhancement failed: ${err.message}`);
+ setIsEnhancing(false);
+ return null;
+ });
+
+ if (!enhanceResult) {
+ return;
+ }
+
+ finalDescription = enhanceResult.enhancedDescription;
+ toast.success('Prompt enhanced');
+ setIsEnhancing(false);
+ }
+
await api.addCosTask({
- description: newTask.description,
+ description: finalDescription,
context: newTask.context,
model: newTask.model || undefined,
provider: newTask.provider || undefined,
@@ -170,6 +195,7 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
setNewTask({ description: '', context: '', model: '', provider: '', app: '' });
setScreenshots([]);
setAddToTop(false);
+ setEnhancePrompt(false);
setShowAddTask(false);
onRefresh();
};
@@ -219,21 +245,35 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
aria-required="true"
/>
</div>
- <div className="flex items-center gap-3">
- <label htmlFor="add-position" className="text-sm text-gray-400">Queue Position:</label>
- <button
- id="add-position"
- type="button"
- onClick={() => setAddToTop(!addToTop)}
- className={`flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm transition-colors ${
- addToTop
- ? 'bg-port-accent/20 text-port-accent border border-port-accent/50'
- : 'bg-port-bg text-gray-400 border border-port-border'
- }`}
- aria-pressed={addToTop}
- >
- {addToTop ? 'Top of Queue' : 'Bottom of Queue'}
- </button>
+ <div className="flex items-center gap-6 flex-wrap">
+ <div className="flex items-center gap-3">
+ <label htmlFor="add-position" className="text-sm text-gray-400">Queue Position:</label>
+ <button
+ id="add-position"
+ type="button"
+ onClick={() => setAddToTop(!addToTop)}
+ className={`flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm transition-colors ${
+ addToTop
+ ? 'bg-port-accent/20 text-port-accent border border-port-accent/50'
+ : 'bg-port-bg text-gray-400 border border-port-border'
+ }`}
+ aria-pressed={addToTop}
+ >
+ {addToTop ? 'Top of Queue' : 'Bottom of Queue'}
+ </button>
+ </div>
+ <label className="flex items-center gap-2 cursor-pointer select-none">
+ <input
+ type="checkbox"
+ checked={enhancePrompt}
+ onChange={(e) => setEnhancePrompt(e.target.checked)}
+ className="w-4 h-4 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent focus:ring-offset-0"
+ />
+ <span className="flex items-center gap-1.5 text-sm text-gray-400">
+ <Sparkles size={14} className="text-yellow-500" />
+ Enhance with AI
+ </span>
+ </label>
</div>
<div>
<label htmlFor="task-context" className="sr-only">Context</label>
@@ -344,17 +384,29 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
onClick={() => {
setShowAddTask(false);
setScreenshots([]);
+ setEnhancePrompt(false);
}}
className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"
+ disabled={isEnhancing}
>
Cancel
</button>
<button
onClick={handleAddTask}
- className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors"
+ disabled={isEnhancing}
+ className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed min-h-[40px]"
>
- <Plus size={14} aria-hidden="true" />
- Add
+ {isEnhancing ? (
+ <>
+ <Loader2 size={14} className="animate-spin" aria-hidden="true" />
+ Enhancing...
+ </>
+ ) : (
+ <>
+ <Plus size={14} aria-hidden="true" />
+ {enhancePrompt ? 'Enhance & Add' : 'Add'}
+ </>
+ )}
</button>
</div>
</div>
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 18471b7e84..0da2e75a8e 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -239,6 +239,10 @@ export const addCosTask = (task) => request('/cos/tasks', {
method: 'POST',
body: JSON.stringify(task)
});
+export const enhanceCosTaskPrompt = (data) => request('/cos/tasks/enhance', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
export const updateCosTask = (id, updates) => request(`/cos/tasks/${id}`, {
method: 'PUT',
body: JSON.stringify(updates)
diff --git a/server/routes/cos.js b/server/routes/cos.js
index 33a1714693..5a14c2b9ed 100644
--- a/server/routes/cos.js
+++ b/server/routes/cos.js
@@ -9,6 +9,7 @@ import * as appActivity from '../services/appActivity.js';
import * as taskLearning from '../services/taskLearning.js';
import * as weeklyDigest from '../services/weeklyDigest.js';
import * as taskSchedule from '../services/taskSchedule.js';
+import { enhanceTaskPrompt } from '../services/taskEnhancer.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
const router = Router();
@@ -94,6 +95,18 @@ router.post('/tasks/reorder', asyncHandler(async (req, res) => {
res.json(result);
}));
+// POST /api/cos/tasks/enhance - Enhance a task prompt with AI
+router.post('/tasks/enhance', asyncHandler(async (req, res) => {
+ const { description, context } = req.body;
+
+ if (!description) {
+ throw new ServerError('Description is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+
+ const result = await enhanceTaskPrompt(description, context);
+ res.json(result);
+}));
+
// POST /api/cos/tasks - Add a new task
router.post('/tasks', asyncHandler(async (req, res) => {
const { description, priority, context, model, provider, app, type = 'user', approvalRequired, screenshots, position = 'bottom' } = req.body;
diff --git a/server/services/taskEnhancer.js b/server/services/taskEnhancer.js
new file mode 100644
index 0000000000..cddbf2843f
--- /dev/null
+++ b/server/services/taskEnhancer.js
@@ -0,0 +1,139 @@
+/**
+ * Task Enhancer Service
+ *
+ * Uses AI to enhance task descriptions/prompts to be more detailed,
+ * actionable, and comprehensive for agent execution.
+ */
+
+import { executeApiRun, createRun } from './runner.js';
+import { getActiveProvider, getProviderById } from './providers.js';
+import { getConfig } from './cos.js';
+
+/**
+ * Default enhancement prompt template
+ */
+const ENHANCEMENT_PROMPT = `You are a task prompt enhancer for an AI agent system. Your job is to take a brief task description and expand it into a comprehensive, detailed prompt that an AI coding agent can execute effectively.
+
+## Guidelines
+
+1. **Preserve the original intent** - Don't change what the user wants, just make it clearer and more actionable
+2. **Add specific steps** - Break down the task into clear, sequential steps when appropriate
+3. **Include relevant context** - Mention file paths, patterns, or conventions that should be followed
+4. **Define success criteria** - What does "done" look like?
+5. **Anticipate edge cases** - Mention potential issues to watch out for
+6. **Keep it focused** - Don't add unrelated tasks or scope creep
+
+## Original Task Description
+{description}
+
+{contextSection}
+
+## Your Enhanced Prompt
+
+Provide an enhanced version of this task that an AI agent can execute. Output ONLY the enhanced prompt text, nothing else. Do not include any preamble like "Here is the enhanced prompt:" - just output the prompt itself.`;
+
+/**
+ * Enhance a task prompt using AI
+ *
+ * @param {string} description - The original task description
+ * @param {string} context - Optional additional context
+ * @returns {Promise<{enhancedDescription: string, originalDescription: string, model: string, provider: string}>}
+ */
+export async function enhanceTaskPrompt(description, context = '') {
+ console.log(`✨ Enhancing task prompt: "${description.substring(0, 50)}..."`);
+
+ // Get CoS config for default enhancement settings
+ const config = await getConfig();
+
+ // Determine provider and model to use
+ // Priority: CoS config -> active provider default
+ let provider = await getActiveProvider();
+ let model = 'codex';
+
+ // Use OpenAI for enhancement by default if available, otherwise fall back to active provider
+ const openaiProvider = await getProviderById('openai').catch(() => null);
+ if (openaiProvider?.enabled) {
+ provider = openaiProvider;
+ model = 'codex';
+ } else if (provider) {
+ // Fall back to active provider's default model
+ model = provider.defaultModel || provider.models?.[0] || 'claude-sonnet-4-20250514';
+ }
+
+ if (!provider) {
+ throw new Error('No AI provider available for enhancement');
+ }
+
+ // Build the enhancement prompt
+ const contextSection = context
+ ? `## Additional Context\n${context}`
+ : '';
+
+ const fullPrompt = ENHANCEMENT_PROMPT
+ .replace('{description}', description)
+ .replace('{contextSection}', contextSection);
+
+ // Create a run for this enhancement
+ const runId = `enhance-${Date.now().toString(36)}`;
+ await createRun({
+ id: runId,
+ providerId: provider.id,
+ model,
+ prompt: fullPrompt,
+ source: 'task-enhancement',
+ status: 'running'
+ });
+
+ // Collect the response
+ let enhancedDescription = '';
+
+ await new Promise((resolve, reject) => {
+ executeApiRun(
+ runId,
+ provider,
+ model,
+ fullPrompt,
+ process.cwd(),
+ [], // No screenshots needed
+ (data) => {
+ if (data?.text) {
+ enhancedDescription += data.text;
+ }
+ },
+ (result) => {
+ if (result?.error) {
+ reject(new Error(result.error));
+ } else {
+ resolve(result);
+ }
+ }
+ );
+ });
+
+ // Clean up the response - remove any leading/trailing whitespace and common prefixes
+ enhancedDescription = enhancedDescription.trim();
+
+ // Remove common AI response prefixes
+ const prefixesToRemove = [
+ /^Here is the enhanced prompt[:\s]*/i,
+ /^Enhanced prompt[:\s]*/i,
+ /^Here's the enhanced version[:\s]*/i,
+ /^Certainly[!,.\s]*/i,
+ /^Sure[!,.\s]*/i
+ ];
+
+ for (const prefix of prefixesToRemove) {
+ enhancedDescription = enhancedDescription.replace(prefix, '');
+ }
+
+ enhancedDescription = enhancedDescription.trim();
+
+ console.log(`✅ Enhanced task prompt (${enhancedDescription.length} chars) using ${provider.name}/${model}`);
+
+ return {
+ enhancedDescription,
+ originalDescription: description,
+ model,
+ provider: provider.id
+ };
+}