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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: DataDog errors tab + enhanced error monitor job (#201)
[._.]/ Adam Eivybd1580bca3a1
diff --git a/client/src/components/apps/AppDetailView.jsx b/client/src/components/apps/AppDetailView.jsxindex ae85398071..c5fae3bcac 100644--- a/client/src/components/apps/AppDetailView.jsx+++ b/client/src/components/apps/AppDetailView.jsx@@ -16,6 +16,7 @@ import DocumentsTab from './tabs/DocumentsTab';import GitTab from './tabs/GitTab';import GsdTab from './tabs/GsdTab';import ProcessesTab from './tabs/ProcessesTab';+import DatadogTab from './tabs/DatadogTab';import UpdateTab from './tabs/UpdateTab';export default function AppDetailView() {@@ -91,8 +92,12 @@ export default function AppDetailView() {};const visibleTabs = useMemo(() =>- APP_DETAIL_TABS.filter(t => t.id !== 'update' || app?.id === api.PORTOS_APP_ID),- [app?.id]+ APP_DETAIL_TABS.filter(t => {+ if (t.id === 'update') return app?.id === api.PORTOS_APP_ID;+ if (t.id === 'datadog') return app?.datadog?.enabled;+ return true;+ }),+ [app?.id, app?.datadog?.enabled]);if (loading) {@@ -112,14 +117,18 @@ export default function AppDetailView() {);}+ const effectiveTab = visibleTabs.some(t => t.id === activeTab) ? activeTab : 'overview';+const renderTab = () => {- switch (activeTab) {+ switch (effectiveTab) {case 'overview':return <OverviewTab app={app} onRefresh={fetchApp} />;case 'tasks':return <TasksTab appId={appId} />;case 'automation':return <AutomationTab appId={appId} appName={app.name} />;+ case 'datadog':+ return <DatadogTab app={app} />;case 'documents':return <DocumentsTab appId={appId} repoPath={app.repoPath} />;case 'git':@@ -281,7 +290,7 @@ export default function AppDetailView() {key={t.id}onClick={() => navigate(`/apps/${appId}/${t.id}`)}className={`px-4 py-2 text-sm font-medium whitespace-nowrap border-b-2 transition-colors ${- activeTab === t.id+ effectiveTab === t.id? 'border-port-accent text-port-accent': 'border-transparent text-gray-400 hover:text-white hover:border-gray-600'}`}diff --git a/client/src/components/apps/EditAppModal.jsx b/client/src/components/apps/EditAppModal.jsxindex d6e47f69f2..d0b5e8ded9 100644--- a/client/src/components/apps/EditAppModal.jsx+++ b/client/src/components/apps/EditAppModal.jsx@@ -632,6 +632,7 @@ export default function EditAppModal({ app, onClose, onSave }) {className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"placeholder="e.g., my-app-service"/>+ <p className="text-xs text-gray-500 mt-1">The "service" tag your app reports to DataDog RUM/APM (not the Application ID)</p></div><div>@@ -643,6 +644,7 @@ export default function EditAppModal({ app, onClose, onSave }) {className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"placeholder="e.g., production"/>+ <p className="text-xs text-gray-500 mt-1">The "env" tag (e.g., production, qa, staging)</p></div></>)}diff --git a/client/src/components/apps/constants.js b/client/src/components/apps/constants.jsindex e819d57c16..802633ef61 100644--- a/client/src/components/apps/constants.js+++ b/client/src/components/apps/constants.js@@ -8,6 +8,7 @@ export const getAppTypeLabel = (type) =>export const APP_DETAIL_TABS = [{ id: 'overview', label: 'Overview' },{ id: 'automation', label: 'Automation' },+ { id: 'datadog', label: 'DataDog' },{ id: 'documents', label: 'Documents' },{ id: 'git', label: 'Git' },{ id: 'gsd', label: 'GSD' },diff --git a/client/src/components/apps/tabs/DatadogTab.jsx b/client/src/components/apps/tabs/DatadogTab.jsxnew file mode 100644index 0000000000..a4e300c7b8--- /dev/null+++ b/client/src/components/apps/tabs/DatadogTab.jsx@@ -0,0 +1,183 @@+import { useState, useEffect, useCallback, useRef } from 'react';+import { RefreshCw, AlertTriangle, Clock, ExternalLink } from 'lucide-react';+import BrailleSpinner from '../../BrailleSpinner';+import * as api from '../../../services/api';++const TIME_RANGES = [+ { value: '1h', label: 'Last 1 hour', ms: 60 * 60 * 1000 },+ { value: '6h', label: 'Last 6 hours', ms: 6 * 60 * 60 * 1000 },+ { value: '24h', label: 'Last 24 hours', ms: 24 * 60 * 60 * 1000 },+ { value: '7d', label: 'Last 7 days', ms: 7 * 24 * 60 * 60 * 1000 },+];++export default function DatadogTab({ app }) {+ const [errors, setErrors] = useState([]);+ const [loading, setLoading] = useState(true);+ const [fetchFailed, setFetchFailed] = useState(false);+ const [timeRange, setTimeRange] = useState('24h');+ const [expandedErrorId, setExpandedErrorId] = useState(null);+ const [ddSite, setDdSite] = useState(null);+ const abortRef = useRef(null);++ const dd = app?.datadog;+ const configured = dd?.enabled && dd?.instanceId && dd?.serviceName;++ useEffect(() => {+ if (!dd?.instanceId) return;+ api.getDatadogInstances().then(res => {+ const inst = (res.instances || {})[dd.instanceId];+ if (inst?.site) setDdSite(inst.site);+ }).catch(() => {});+ }, [dd?.instanceId]);++ const fetchErrors = useCallback(async () => {+ if (!dd?.enabled || !dd?.instanceId || !dd?.serviceName) { setLoading(false); return; }+ if (abortRef.current) abortRef.current.abort();+ const controller = new AbortController();+ abortRef.current = controller;+ setLoading(true);+ setFetchFailed(false);+ const range = TIME_RANGES.find(r => r.value === timeRange);+ const fromTime = new Date(Date.now() - range.ms).toISOString();+ const result = await api.searchDatadogErrors(dd.instanceId, dd.serviceName, dd.environment || 'production', fromTime, { signal: controller.signal, silent: true }).catch(err => {+ if (err.name === 'AbortError') return 'aborted';+ return null;+ });+ if (controller.signal.aborted) return;+ if (result === 'aborted') return;+ if (result) {+ setErrors(result.data || []);+ } else {+ setFetchFailed(true);+ }+ setLoading(false);+ }, [dd?.enabled, dd?.instanceId, dd?.serviceName, dd?.environment, timeRange]);++ useEffect(() => {+ fetchErrors();+ return () => { if (abortRef.current) abortRef.current.abort(); };+ }, [fetchErrors]);++ if (!configured) {+ return (+ <div className="p-6 text-center">+ <AlertTriangle size={32} className="mx-auto text-port-warning mb-3" />+ <p className="text-gray-400 mb-2">DataDog monitoring is not configured for this app.</p>+ <p className="text-gray-500 text-sm">+ Enable DataDog in the app settings and set a Service Name and Environment.+ </p>+ </div>+ );+ }++ return (+ <div className="space-y-4">+ <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">+ <div>+ <h2 className="text-lg font-semibold text-white">DataDog Errors</h2>+ <p className="text-sm text-gray-400">+ Service: <span className="text-gray-300">{dd.serviceName}</span>+ {' '}· Env: <span className="text-gray-300">{dd.environment || 'production'}</span>+ </p>+ </div>+ <div className="flex items-center gap-2">+ <select+ value={timeRange}+ onChange={e => setTimeRange(e.target.value)}+ aria-label="Error time range"+ className="px-3 py-1.5 bg-port-bg border border-port-border rounded-lg text-sm text-white focus:border-port-accent focus:outline-hidden"+ >+ {TIME_RANGES.map(r => <option key={r.value} value={r.value}>{r.label}</option>)}+ </select>+ <button+ onClick={fetchErrors}+ disabled={loading}+ aria-label="Refresh errors"+ className="p-2 bg-port-bg border border-port-border rounded-lg text-gray-400 hover:text-white hover:border-port-accent transition-colors disabled:opacity-50"+ >+ <RefreshCw size={16} className={loading ? 'animate-spin' : ''} />+ </button>+ </div>+ </div>++ {loading ? (+ <BrailleSpinner text="Fetching errors from DataDog" />+ ) : fetchFailed ? (+ <div className="p-8 text-center bg-port-card border border-port-border rounded-lg">+ <AlertTriangle size={24} className="mx-auto text-port-error mb-2" />+ <p className="text-port-error font-medium">Failed to fetch errors</p>+ <p className="text-gray-500 text-sm mt-1">Could not reach DataDog. Check the instance configuration.</p>+ </div>+ ) : errors.length === 0 ? (+ <div className="p-8 text-center bg-port-card border border-port-border rounded-lg">+ <p className="text-port-success font-medium">No errors found</p>+ <p className="text-gray-500 text-sm mt-1">No error-level logs in the selected time range.</p>+ </div>+ ) : (+ <div className="space-y-2">+ <p className="text-sm text-gray-400">+ {errors.length} error{errors.length !== 1 ? 's' : ''} found+ {errors.length >= 100 && <span className="text-port-warning ml-1">(results may be truncated)</span>}+ </p>+ {errors.map((err, idx) => {+ const attrs = err.attributes || {};+ const errId = err.id || attrs.timestamp || `${attrs.message}-${idx}`;+ const message = attrs.message || attrs.attributes?.message || 'Unknown error';+ const timestamp = attrs.timestamp || err.id?.split?.('-')?.[0];+ const service = attrs.service || dd.serviceName;+ const status = attrs.status || 'error';+ const expanded = expandedErrorId === errId;++ return (+ <div+ key={errId}+ className="bg-port-card border border-port-border rounded-lg overflow-hidden"+ >+ <button+ onClick={() => setExpandedErrorId(expanded ? null : errId)}+ aria-expanded={expanded}+ className="w-full text-left px-4 py-3 hover:bg-port-border/30 transition-colors"+ >+ <div className="flex items-start gap-3">+ <AlertTriangle size={16} className="text-port-error mt-0.5 shrink-0" />+ <div className="flex-1 min-w-0">+ <p className="text-sm text-white truncate">{message}</p>+ <div className="flex items-center gap-3 mt-1 text-xs text-gray-500">+ {timestamp && (+ <span className="flex items-center gap-1">+ <Clock size={12} />+ {new Date(timestamp).toLocaleString()}+ </span>+ )}+ <span className="px-1.5 py-0.5 bg-port-error/20 text-port-error rounded">{status}</span>+ <span className="text-gray-600">{service}</span>+ </div>+ </div>+ </div>+ </button>++ {expanded && (+ <div className="px-4 py-3 border-t border-port-border bg-port-bg">+ <pre className="text-xs text-gray-300 whitespace-pre-wrap break-words max-h-64 overflow-auto">+ {JSON.stringify(attrs, null, 2)}+ </pre>+ {attrs.attributes?.['dd.trace_id'] && ddSite && (+ <a+ href={`https://${ddSite.replace(/^api\./, 'app.')}/apm/trace/${attrs.attributes['dd.trace_id']}`}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center gap-1 mt-2 text-xs text-port-accent hover:underline"+ >+ <ExternalLink size={12} /> View Trace in DataDog+ </a>+ )}+ </div>+ )}+ </div>+ );+ })}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 531852fac9..8973e0d5ff 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -160,6 +160,12 @@ export const deleteTool = (id) => request(`/tools/${id}`, { method: 'DELETE' });// DataDogexport const getDatadogInstances = () => request('/datadog/instances');+export const searchDatadogErrors = (instanceId, serviceName, environment, fromTime, options) =>+ request(`/datadog/instances/${instanceId}/search-errors`, {+ method: 'POST',+ body: JSON.stringify({ serviceName, environment, fromTime }),+ ...options+ });// JIRAexport const getJiraInstances = () => request('/jira/instances');diff --git a/data.sample/prompts/skills/jobs/datadog-error-monitor.md b/data.sample/prompts/skills/jobs/datadog-error-monitor.mdindex 6c431735e0..259316be7d 100644--- a/data.sample/prompts/skills/jobs/datadog-error-monitor.md+++ b/data.sample/prompts/skills/jobs/datadog-error-monitor.md@@ -1,10 +1,10 @@# DataDog Error Monitor Job-Autonomous job that monitors DataDog for new application errors across all configured apps. Runs daily at 8 AM. Creates CoS tasks for new errors and optionally creates JIRA tickets for apps with JIRA integration enabled.+Autonomous job that monitors DataDog for new application errors across all configured apps. Runs daily at 8 AM. Creates JIRA tickets for new errors and queues CoS sub-agent fix tasks.## Prompt Template-You are acting as my Chief of Staff, monitoring DataDog for new application errors.+You are acting as my Chief of Staff, monitoring DataDog for new application errors and orchestrating fixes.## Steps@@ -25,24 +25,55 @@ You are acting as my Chief of Staff, monitoring DataDog for new application erro```- Compare results against the error cache in `/data/cos/datadog-errors.json`- Identify new errors by fingerprint or message hash+ - Group duplicate errors by message similarity-### Phase 3 — Act on New Errors+### Phase 3 — File Issues and Queue Fixes-3. **Create tasks and tickets for new errors**- - For each new error:- - Create a CoS task describing the error, affected app, stack trace, and frequency- - If the app also has `jira.enabled === true`, create a JIRA ticket:+3. **Update the error cache**+ - For each genuinely new error (regardless of JIRA config), add its fingerprint to `/data/cos/datadog-errors.json`++4. **Create JIRA tickets for new errors** (only if fully configured)+ - For each new error where the app has `jira.enabled === true` AND `jira.instanceId` AND `jira.projectKey` are set:+ - Create a JIRA ticket:```POST /api/jira/instances/:instanceId/tickets- Body: { "projectKey": "<app.jira.projectKey>", "summary": "DD Error: <error message>", "description": "<full error details>", "issueType": "Bug" }+ Body: {+ "projectKey": "<app.jira.projectKey>",+ "summary": "DD Error: <concise error message>",+ "description": "<full error details including stack trace, frequency, first/last seen>",+ "issueType": "Bug",+ "labels": ["datadog-auto", "cos-detected"]+ }```- - Update the error cache with the new error fingerprint+ - Skip JIRA ticket creation if `instanceId` or `projectKey` is missing++5. **Create CoS fix tasks**+ - For each new error, create a CoS task that will:+ - Work in an isolated worktree of the app's repo+ - Analyze the error stack trace and identify the root cause+ - Implement a fix+ - Run tests to verify the fix+ - Open a PR with the fix+ - Task configuration:+ ```+ POST /api/cos/tasks+ Body: {+ "description": "[Auto-Fix] DD Error in <app.name>: <error message>\n\nJIRA: <ticket key if created>\nStack trace: <stack>\n\nInstructions:\n1. Clone/worktree the repo at <app.repoPath>\n2. Analyze the error and identify root cause\n3. Implement a fix\n4. Run tests\n5. Open a PR referencing the JIRA ticket (if one was created)",+ "priority": "HIGH",+ "type": "internal",+ "app": "<app.id>",+ "useWorktree": true,+ "openPR": true+ }+ ```### Phase 4 — Report-4. **Generate summary report** covering:+6. **Generate summary report** covering:- Apps checked and error counts per app- - New errors found and tasks/tickets created+ - New errors found vs. already-known errors+ - JIRA tickets created+ - CoS fix tasks queued- Recurring errors that are increasing in frequency- Overall error trend (improving or degrading)@@ -53,11 +84,12 @@ You are acting as my Chief of Staff, monitoring DataDog for new application erro| `/api/apps` | GET | List all managed apps || `/api/datadog/instances/:id/search-errors` | POST | Search DataDog logs for errors || `/api/jira/instances/:id/tickets` | POST | Create JIRA ticket for error |+| `/api/cos/tasks` | POST | Create CoS fix task |## Expected Outputs-1. **CoS Tasks** - One per new error discovered-2. **JIRA Tickets** - Created for errors in apps with JIRA enabled+1. **JIRA Tickets** - Created for genuinely new errors (not duplicates)+2. **CoS Fix Tasks** - One per new error, configured with worktree isolation and PR creation3. **Error Cache Update** - New fingerprints added to prevent duplicate alerts4. **Summary Report** - Saved via CoS reporting system@@ -65,14 +97,14 @@ You are acting as my Chief of Staff, monitoring DataDog for new application erro- All DataDog-enabled apps are checked- New errors are identified by comparing against cached fingerprints-- CoS tasks created for each new error-- JIRA tickets created where applicable+- JIRA tickets created where applicable with `datadog-auto` label+- CoS fix tasks queued with full context (stack trace, JIRA ref, worktree instructions)- Error cache updated with new fingerprints-- Report provides clear visibility into error trends+- Report provides clear visibility into error trends and actions taken## Job Metadata- **Category**: datadog-error-monitor- **Interval**: Daily at 8:00 AM- **Priority**: MEDIUM-- **Autonomy Level**: manager (creates tasks and tickets but does not fix errors)+- **Autonomy Level**: manager (creates tickets and tasks, does not directly fix errors)diff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.jsindex 9216508fab..2434d622e0 100644--- a/server/services/autonomousJobs.js+++ b/server/services/autonomousJobs.js@@ -268,13 +268,13 @@ Write the briefing in a concise, actionable format. Save it as a CoS report. Notcategory: 'datadog-error-monitor',interval: 'daily',intervalMs: DAY,- scheduledTime: '00:00',+ scheduledTime: '08:00',enabled: false,priority: 'MEDIUM',autonomyLevel: 'manager',promptTemplate: `[Autonomous Job] DataDog Error Monitor-You are acting as my Chief of Staff, monitoring DataDog for new application errors.+You are acting as my Chief of Staff, monitoring DataDog for new application errors and orchestrating fixes.Phase 1 — Discover:1. Call GET /api/apps to get all managed apps@@ -287,17 +287,22 @@ Phase 2 — Check Errors:- Compare results against the error cache in /data/cos/datadog-errors.json- Identify new errors (by fingerprint/message hash)-Phase 3 — Act on New Errors:-5. For each new error:- - Create a CoS task describing the error and the app it affects- - If the app also has jira.enabled = true, create a JIRA ticket for the error- - Update the error cache with the new error fingerprint+Phase 3 — File Issues and Queue Fixes:+5. For each genuinely new error:+ - Update the error cache with the new fingerprint (always, regardless of JIRA config)+ - If app has jira.enabled = true AND jira.instanceId AND jira.projectKey are set:+ Create a JIRA ticket with labels ["datadog-auto", "cos-detected"]:+ POST /api/jira/instances/:instanceId/tickets with projectKey, summary, description, issueType: "Bug", labels+ - Create a CoS task to fix the error in an isolated worktree:+ POST /api/cos/tasks with type: "internal", useWorktree: true, openPR: true, the error stack trace, JIRA ticket reference (if created), and instructions to implement fix + open PRPhase 4 — Report:6. Generate a summary report covering:- Apps checked and error counts- - New errors found and tasks/tickets created- - Recurring errors that are increasing in frequency`,+ - New errors vs already-known errors+ - JIRA tickets created+ - CoS fix tasks queued+ - Recurring errors increasing in frequency`,lastRun: null,runCount: 0,createdAt: null,@@ -426,6 +431,7 @@ let initPromise = null*/async function initJobs() {await ensureDir(DATA_DIR)+ await syncSkillTemplatesFromSample()const loaded = await readJSONFile(JOBS_FILE, null)if (!loaded) {@@ -444,6 +450,24 @@ async function initJobs() {return merged}+async function syncSkillTemplatesFromSample() {+ if (!PATHS.root) return+ const sampleDir = join(PATHS.root, 'data.sample', 'prompts', 'skills', 'jobs')+ if (!existsSync(sampleDir)) return+ await ensureDir(JOBS_SKILLS_DIR)+ const files = await readdir(sampleDir).catch(() => [])+ for (const file of files) {+ if (!file.endsWith('.md')) continue+ const destPath = join(JOBS_SKILLS_DIR, file)+ const existingContent = await readFile(destPath, 'utf-8').catch(() => null)+ if (existingContent) continue+ const sampleContent = await readFile(join(sampleDir, file), 'utf-8').catch(() => null)+ if (!sampleContent) continue+ await writeFile(destPath, sampleContent)+ console.log(`📝 Seeded missing job skill template: ${file}`)+ }+}+/*** Load jobs from disk. On first call, runs one-time init (migration + defaults).* Subsequent calls are read-only with in-memory default merging.