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
architecture: better audit remediation
Adam Eivy792fb88c64bf
diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsxnew file mode 100644index 0000000000..3083e3515b--- /dev/null+++ b/client/src/components/settings/BackupTab.jsx@@ -0,0 +1,133 @@+import { useState, useEffect } from 'react';+import { Save, Plus, X } from 'lucide-react';+import toast from '../ui/Toast';+import BrailleSpinner from '../BrailleSpinner';+import { getSettings, updateSettings } from '../../services/api';++export function BackupTab() {+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [destPath, setDestPath] = useState('');+ const [enabled, setEnabled] = useState(false);+ const [cronExpression, setCronExpression] = useState('0 2 * * *');+ const [excludePaths, setExcludePaths] = useState([]);+ const [newExclude, setNewExclude] = useState('');++ useEffect(() => {+ getSettings()+ .then(settings => {+ const backup = settings?.backup || {};+ setDestPath(backup.destPath || '');+ setEnabled(backup.enabled ?? false);+ setCronExpression(backup.cronExpression || '0 2 * * *');+ setExcludePaths(backup.excludePaths || []);+ })+ .catch(() => toast.error('Failed to load settings'))+ .finally(() => setLoading(false));+ }, []);++ const handleSave = async () => {+ setSaving(true);+ await updateSettings({ backup: { destPath, enabled, cronExpression, excludePaths } })+ .then(() => toast.success('Settings saved'))+ .catch(() => toast.error('Failed to save settings'))+ .finally(() => setSaving(false));+ };++ const addExclude = () => {+ const trimmed = newExclude.trim();+ if (!trimmed || excludePaths.includes(trimmed)) return;+ setExcludePaths([...excludePaths, trimmed]);+ setNewExclude('');+ };++ const removeExclude = (index) => {+ setExcludePaths(excludePaths.filter((_, i) => i !== index));+ };++ if (loading) {+ return <BrailleSpinner text="Loading backup settings" />;+ }++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-5">+ <div className="space-y-1">+ <label className="block text-sm text-gray-400">Destination Path</label>+ <input+ type="text"+ value={destPath}+ onChange={e => setDestPath(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"+ placeholder="/path/to/backups"+ />+ </div>++ <div className="flex items-center gap-3">+ <label className="text-sm text-gray-400">Enabled</label>+ <button+ onClick={() => setEnabled(!enabled)}+ className={`relative w-10 h-5 rounded-full transition-colors ${enabled ? 'bg-port-accent' : 'bg-port-border'}`}+ >+ <span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${enabled ? 'translate-x-5' : ''}`} />+ </button>+ </div>++ <div className="space-y-1">+ <label className="block text-sm text-gray-400">Schedule (cron)</label>+ <input+ type="text"+ value={cronExpression}+ onChange={e => setCronExpression(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"+ placeholder="0 2 * * *"+ />+ <p className="text-xs text-gray-500">Default: 2:00 AM daily</p>+ </div>++ <div className="space-y-2">+ <label className="block text-sm text-gray-400">Exclude Paths</label>+ <p className="text-xs text-gray-500">Directories/patterns to skip during backup (relative to data/)</p>+ <div className="flex gap-2">+ <input+ type="text"+ value={newExclude}+ onChange={e => setNewExclude(e.target.value)}+ onKeyDown={e => e.key === 'Enter' && addExclude()}+ className="flex-1 bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"+ placeholder="repos/"+ />+ <button+ onClick={addExclude}+ disabled={!newExclude.trim()}+ className="px-3 py-2 bg-port-border hover:bg-port-border/70 text-white rounded-lg transition-colors disabled:opacity-50"+ >+ <Plus size={16} />+ </button>+ </div>+ {excludePaths.length > 0 && (+ <div className="flex flex-wrap gap-2 mt-2">+ {excludePaths.map((path, i) => (+ <span key={i} className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-port-bg border border-port-border rounded-lg text-sm text-gray-300">+ <code className="text-xs">{path}</code>+ <button onClick={() => removeExclude(i)} className="text-gray-500 hover:text-port-error transition-colors">+ <X size={14} />+ </button>+ </span>+ ))}+ </div>+ )}+ </div>++ <button+ onClick={handleSave}+ disabled={saving}+ className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"+ >+ {saving ? <BrailleSpinner /> : <Save size={16} />}+ Save+ </button>+ </div>+ );+}++export default BackupTab;diff --git a/client/src/components/settings/DatabaseTab.jsx b/client/src/components/settings/DatabaseTab.jsxnew file mode 100644index 0000000000..ca59ac33b6--- /dev/null+++ b/client/src/components/settings/DatabaseTab.jsx@@ -0,0 +1,342 @@+import { useState, useEffect, useRef, useCallback } from 'react';+import { Container, HardDrive, Download, ArrowRightLeft, Wrench, RefreshCw, Square, RotateCw, Play, Trash2 } from 'lucide-react';+import toast from '../ui/Toast';+import BrailleSpinner from '../BrailleSpinner';+import { formatBytes } from '../../utils/formatters';+import {+ getDatabaseStatus, switchDatabase, setupNativeDatabase, exportDatabase, fixDatabase,+ syncDatabase, startDatabase, stopDatabase, destroyDatabase+} from '../../services/api';+import socket from '../../services/socket';++function BackendCard({ label, icon: Icon, backend, isActive, dbStatus, runAction, setConfirmAction, actionInProgress, busy, exportDatabase: exportDb }) {+ const data = dbStatus?.[backend];+ const isRunning = backend === 'docker' ? data?.containerRunning : data?.running;+ const canStart = backend === 'docker'+ ? data?.installed && data?.daemonRunning && !data?.containerRunning+ : data?.configured && !data?.running;+ const canDestroy = !isActive && !isRunning && (backend === 'docker' ? data?.installed : data?.configured);+ const statusLabel = isRunning ? 'Running'+ : (backend === 'docker' ? (data?.installed ? 'Stopped' : 'Not installed')+ : (data?.configured ? 'Stopped' : data?.installed ? 'Not configured' : 'Not installed'));+ const statusColor = isRunning ? 'bg-port-success' : (data?.installed || data?.configured) ? 'bg-port-warning' : 'bg-gray-600';+ const displayLabel = backend === 'docker' ? 'Docker' : 'Native';+ const activeLabel = backend === 'docker' ? 'Native' : 'Docker';++ const btnClass = 'flex items-center gap-1.5 px-2 py-1 text-xs font-medium rounded transition-colors disabled:opacity-50';++ return (+ <div className="bg-port-bg border border-port-border rounded-lg p-3 space-y-2">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2 text-sm text-gray-400">+ <Icon size={14} />+ {label}+ </div>+ <div className="flex items-center gap-1.5">+ {isActive && (+ <span className="text-xs px-1.5 py-0.5 bg-port-accent/20 text-port-accent rounded">Active</span>+ )}+ <span className={`w-2 h-2 rounded-full ${statusColor}`} />+ </div>+ </div>++ <div className="text-sm text-white">{statusLabel}</div>++ {/* Resource stats */}+ {data?.stats && (+ <div className="grid grid-cols-2 gap-x-4 gap-y-0.5 text-xs text-gray-400 pt-1 border-t border-port-border/50">+ <span>CPU: <span className="text-gray-300">{data.stats.cpu}</span></span>+ <span>Memory: <span className="text-gray-300">{data.stats.memUsage}</span></span>+ <span>Mem%: <span className="text-gray-300">{data.stats.memPercent}</span></span>+ <span>PIDs: <span className="text-gray-300">{data.stats.pids}</span></span>+ {data.stats.netIO && <span>Net I/O: <span className="text-gray-300">{data.stats.netIO}</span></span>}+ {data.stats.blockIO && <span>Block I/O: <span className="text-gray-300">{data.stats.blockIO}</span></span>}+ </div>+ )}+ {data?.diskUsage && (+ <div className="text-xs text-gray-400">+ Disk: <span className="text-gray-300">{data.diskUsage}</span>+ </div>+ )}++ {/* Card actions */}+ <div className="flex flex-wrap gap-1.5 pt-1 border-t border-port-border/50">+ {/* Start / Stop */}+ {isRunning && !isActive && (+ <button+ onClick={() => runAction(`stop-${backend}`, () => stopDatabase(backend), `${displayLabel} stopped`)}+ disabled={busy}+ className={`${btnClass} bg-port-border hover:bg-port-border/70 text-white`}+ >+ {actionInProgress === `stop-${backend}` ? <BrailleSpinner /> : <Square size={12} />}+ Stop+ </button>+ )}+ {canStart && (+ <button+ onClick={() => runAction(`start-${backend}`, () => startDatabase(backend), `${displayLabel} started`)}+ disabled={busy}+ className={`${btnClass} bg-port-success/20 hover:bg-port-success/30 text-port-success`}+ >+ {actionInProgress === `start-${backend}` ? <BrailleSpinner /> : <Play size={12} />}+ Start+ </button>+ )}++ {/* Export/Backup from this backend */}+ {isRunning && (+ <button+ onClick={() => runAction(`export-${backend}`, () => exportDb(backend), (r) => `Backed up to ${r.dumpFile}`)}+ disabled={busy}+ className={`${btnClass} bg-port-border hover:bg-port-border/70 text-white`}+ title={`Export ${displayLabel} database to SQL dump`}+ >+ {actionInProgress === `export-${backend}` ? <BrailleSpinner /> : <Download size={12} />}+ Backup+ </button>+ )}++ {/* Non-active backend actions */}+ {!isActive && (data?.installed || data?.configured) && (+ <>+ {/* Migrate & switch to this backend */}+ <button+ onClick={() => setConfirmAction({+ type: 'migrate',+ label: `Migrate to ${displayLabel} and switch?`,+ detail: `Exports data from ${activeLabel}, imports into ${displayLabel}, and makes ${displayLabel} the active backend.`,+ action: () => runAction(`migrate-${backend}`, () => switchDatabase(backend, true), `Migrated to ${displayLabel}`)+ })}+ disabled={busy}+ className={`${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent`}+ >+ <ArrowRightLeft size={12} />+ Migrate to {displayLabel}+ </button>++ {/* Switch without migration */}+ <button+ onClick={() => setConfirmAction({+ type: 'switch',+ label: `Switch to ${displayLabel} without migrating data?`,+ action: () => runAction(`switch-${backend}`, () => switchDatabase(backend, false), `Switched to ${displayLabel}`)+ })}+ disabled={busy}+ className={`${btnClass} bg-port-border hover:bg-port-border/70 text-white`}+ >+ <ArrowRightLeft size={12} />+ Switch+ </button>++ {/* Sync data from active into this backend */}+ <button+ onClick={() => setConfirmAction({+ type: 'sync',+ label: `Sync from ${activeLabel} to ${displayLabel}?`,+ detail: `Copies data from the active ${activeLabel} database into ${displayLabel}. ${displayLabel} will be left in its current state (running or stopped).`,+ action: () => runAction(`sync-${backend}`, syncDatabase, `Data synced from ${activeLabel} to ${displayLabel}`)+ })}+ disabled={busy}+ className={`${btnClass} bg-port-border hover:bg-port-border/70 text-white`}+ >+ <RotateCw size={12} />+ Sync from {activeLabel}+ </button>++ {/* Destroy */}+ {canDestroy && (+ <button+ onClick={() => setConfirmAction({+ type: 'destroy',+ label: `Destroy ${displayLabel} database and all its data?`,+ detail: 'This permanently removes the database files. You can set it up again later.',+ action: () => runAction(`destroy-${backend}`, () => destroyDatabase(backend), `${displayLabel} database destroyed`)+ })}+ disabled={busy}+ className={`${btnClass} bg-port-error/20 hover:bg-port-error/30 text-port-error`}+ >+ <Trash2 size={12} />+ Destroy+ </button>+ )}+ </>+ )}++ {/* Setup native (when not configured) */}+ {backend === 'native' && !data?.configured && (+ <button+ onClick={() => runAction('setup', setupNativeDatabase, 'Native PostgreSQL installed and configured')}+ disabled={busy}+ className={`${btnClass} bg-port-border hover:bg-port-border/70 text-white`}+ >+ {actionInProgress === 'setup' ? <BrailleSpinner /> : <HardDrive size={12} />}+ {data?.installed ? 'Setup' : 'Install'}+ </button>+ )}+ </div>+ </div>+ );+}++export function DatabaseTab() {+ const [dbStatus, setDbStatus] = useState(null);+ const [dbLoading, setDbLoading] = useState(true);+ const [actionInProgress, setActionInProgress] = useState(null);+ const [progressMsg, setProgressMsg] = useState('');+ const [confirmAction, setConfirmAction] = useState(null);+ const progressTimer = useRef(null);++ const loadStatus = useCallback(() => {+ setDbLoading(true);+ getDatabaseStatus()+ .then(setDbStatus)+ .catch(() => toast.error('Failed to load database status'))+ .finally(() => setDbLoading(false));+ }, []);++ useEffect(() => {+ loadStatus();++ const handleProgress = (data) => {+ clearTimeout(progressTimer.current);+ setProgressMsg(data.message || '');+ if (data.event === 'complete') {+ progressTimer.current = setTimeout(() => setProgressMsg(''), 3000);+ loadStatus();+ }+ if (data.event === 'error') {+ progressTimer.current = setTimeout(() => setProgressMsg(''), 5000);+ }+ };++ socket.on('database:progress', handleProgress);+ return () => {+ socket.off('database:progress', handleProgress);+ clearTimeout(progressTimer.current);+ };+ }, [loadStatus]);++ const runAction = useCallback((key, fn, successMsg) => {+ setConfirmAction(null);+ setActionInProgress(key);+ fn()+ .then((result) => {+ if (successMsg) toast.success(typeof successMsg === 'function' ? successMsg(result) : successMsg);+ loadStatus();+ })+ .catch(() => {})+ .finally(() => setActionInProgress(null));+ }, [loadStatus]);++ const busy = actionInProgress != null;++ return (+ <div className="space-y-4">+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-5">+ {/* Connection summary */}+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-3">+ <span className={`w-2 h-2 rounded-full ${dbStatus?.connected ? 'bg-port-success' : 'bg-port-error'}`} />+ <span className="text-sm text-gray-300">+ {dbStatus?.connected ? 'Connected' : dbStatus ? 'Disconnected' : ''}+ {dbStatus?.memoryCount != null && ` \u2014 ${dbStatus.memoryCount.toLocaleString()} memories`}+ {dbStatus?.dbBytes != null && ` \u2014 ${formatBytes(dbStatus.dbBytes)}`}+ {dbStatus?.tableCount != null && ` (${dbStatus.tableCount} tables)`}+ </span>+ </div>+ <button+ onClick={loadStatus}+ disabled={dbLoading}+ className="p-1.5 text-gray-400 hover:text-white transition-colors"+ title="Refresh status"+ >+ <RefreshCw size={14} className={dbLoading ? 'animate-spin' : ''} />+ </button>+ </div>++ {dbLoading && !dbStatus ? (+ <BrailleSpinner text="Loading database status" />+ ) : dbStatus ? (+ <>+ {/* Backend cards with inline actions */}+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <BackendCard+ label="Docker" icon={Container} backend="docker"+ isActive={dbStatus.mode === 'docker'} dbStatus={dbStatus}+ runAction={runAction} setConfirmAction={setConfirmAction}+ actionInProgress={actionInProgress} busy={busy}+ exportDatabase={exportDatabase}+ />+ <BackendCard+ label="Native" icon={HardDrive} backend="native"+ isActive={dbStatus.mode === 'native'} dbStatus={dbStatus}+ runAction={runAction} setConfirmAction={setConfirmAction}+ actionInProgress={actionInProgress} busy={busy}+ exportDatabase={exportDatabase}+ />+ </div>++ {/* Progress indicator */}+ {progressMsg && (+ <div className="flex items-center gap-2 text-sm text-port-accent bg-port-accent/10 border border-port-accent/20 rounded-lg px-3 py-2">+ <BrailleSpinner />+ {progressMsg}+ </div>+ )}++ {/* Confirmation dialog */}+ {confirmAction && (+ <div className={`bg-port-bg border rounded-lg p-4 space-y-3 ${+ confirmAction.type === 'destroy' ? 'border-port-error/30' : 'border-port-warning/30'+ }`}>+ <p className="text-sm text-white">{confirmAction.label}</p>+ {confirmAction.detail && (+ <p className="text-xs text-gray-400">{confirmAction.detail}</p>+ )}+ <div className="flex items-center gap-2">+ <button+ onClick={confirmAction.action}+ disabled={busy}+ className={`flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-lg transition-colors disabled:opacity-50 ${+ confirmAction.type === 'destroy'+ ? 'bg-port-error/20 hover:bg-port-error/30 text-port-error'+ : 'bg-port-warning/20 hover:bg-port-warning/30 text-port-warning'+ }`}+ >+ {busy ? <BrailleSpinner /> : <ArrowRightLeft size={14} />}+ Confirm+ </button>+ <button+ onClick={() => setConfirmAction(null)}+ className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"+ >+ Cancel+ </button>+ </div>+ </div>+ )}++ {/* Global actions */}+ {!dbStatus.connected && (+ <div className="flex flex-wrap items-center gap-2">+ <button+ onClick={() => runAction('fix', fixDatabase, 'Database fixed')}+ disabled={busy}+ className="flex items-center gap-2 px-3 py-1.5 bg-port-error/20 hover:bg-port-error/30 text-port-error text-sm font-medium rounded-lg transition-colors disabled:opacity-50"+ title="Fix stale PID files and other issues"+ >+ {actionInProgress === 'fix' ? <BrailleSpinner /> : <Wrench size={14} />}+ Fix+ </button>+ </div>+ )}+ </>+ ) : (+ <p className="text-sm text-gray-500">Unable to load database status</p>+ )}+ </div>+ </div>+ );+}++export default DatabaseTab;diff --git a/client/src/components/settings/GeneralTab.jsx b/client/src/components/settings/GeneralTab.jsxnew file mode 100644index 0000000000..3164b03388--- /dev/null+++ b/client/src/components/settings/GeneralTab.jsx@@ -0,0 +1,104 @@+import { useState, useEffect, useMemo } from 'react';+import { Save } from 'lucide-react';+import toast from '../ui/Toast';+import BrailleSpinner from '../BrailleSpinner';+import { getSettings, updateSettings } from '../../services/api';++export function GeneralTab() {+ const [loading, setLoading] = useState(true);+ const [timezone, setTimezone] = useState('');+ const [saving, setSaving] = useState(false);+ const detectedTz = Intl.DateTimeFormat().resolvedOptions().timeZone;+ const allTimezones = useMemo(() => Intl.supportedValuesOf?.('timeZone') ?? [], []);++ useEffect(() => {+ getSettings()+ .then(settings => setTimezone(settings?.timezone || ''))+ .catch(() => toast.error('Failed to load settings'))+ .finally(() => setLoading(false));+ }, []);++ const handleSave = async (tz) => {+ const tzToSave = tz || detectedTz;+ if (!tzToSave) {+ toast.error('Timezone is required.');+ return;+ }++ // Validate timezone string+ let isValid = false;+ if (allTimezones.length > 0) {+ isValid = allTimezones.includes(tzToSave);+ } else {+ try {+ new Intl.DateTimeFormat('en-US', { timeZone: tzToSave });+ isValid = true;+ } catch { isValid = false; }+ }+ if (!isValid) {+ toast.error('Invalid timezone. Please select a valid IANA timezone.');+ return;+ }++ setSaving(true);+ await updateSettings({ timezone: tzToSave })+ .then(() => {+ setTimezone(tzToSave);+ toast.success(`Timezone set to ${tzToSave}`);+ })+ .catch(() => toast.error('Failed to save timezone'))+ .finally(() => setSaving(false));+ };++ if (loading) return <BrailleSpinner />;++ return (+ <div className="space-y-6">+ <div className="bg-port-card border border-port-border rounded-lg p-6">+ <h3 className="text-lg font-semibold text-white mb-4">Timezone</h3>+ <p className="text-sm text-gray-400 mb-4">+ Used for job scheduling (cron expressions & scheduled times) and briefing dates.+ </p>+ <div className="flex items-center gap-3">+ <input+ type="text"+ value={timezone}+ onChange={e => setTimezone(e.target.value)}+ placeholder={detectedTz}+ className="flex-1 max-w-xs px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ list="tz-list"+ />+ <button+ onClick={() => handleSave(timezone)}+ disabled={saving}+ className="px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-50"+ >+ <Save size={14} className="inline mr-1" />+ {saving ? 'Saving...' : 'Save'}+ </button>+ {!timezone && (+ <button+ onClick={() => handleSave(detectedTz)}+ disabled={saving}+ className="px-3 py-2 text-sm text-gray-400 hover:text-white transition-colors"+ >+ Use detected: {detectedTz}+ </button>+ )}+ </div>+ {timezone && timezone !== detectedTz && (+ <p className="text-xs text-gray-500 mt-2">+ Browser detected: {detectedTz}+ </p>+ )}+ <datalist id="tz-list">+ {allTimezones.map(tz => (+ <option key={tz} value={tz} />+ ))}+ </datalist>+ </div>+ </div>+ );+}++export default GeneralTab;diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsxnew file mode 100644index 0000000000..702c82bad3--- /dev/null+++ b/client/src/components/settings/ImageGenTab.jsx@@ -0,0 +1,147 @@+import { useState, useEffect, useCallback } from 'react';+import { Save, Image, Zap, Wrench } from 'lucide-react';+import toast from '../ui/Toast';+import BrailleSpinner from '../BrailleSpinner';+import {+ getSettings, updateSettings, getImageGenStatus, registerTool, updateTool, getToolsList+} from '../../services/api';++const SDAPI_TOOL_ID = 'sdapi';++export function ImageGenTab() {+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [sdapiUrl, setSdapiUrl] = useState('');+ const [savedUrl, setSavedUrl] = useState('');+ const [status, setStatus] = useState(null);+ const [checking, setChecking] = useState(false);+ const [toolRegistered, setToolRegistered] = useState(false);++ useEffect(() => {+ Promise.all([getSettings(), getToolsList()])+ .then(([settings, tools]) => {+ const rawUrl = settings?.imageGen?.sdapiUrl || '';+ const normalizedUrl = rawUrl.trim().replace(/\/+$/, '');+ setSdapiUrl(normalizedUrl);+ setSavedUrl(normalizedUrl);+ setToolRegistered(tools.some(t => t.id === SDAPI_TOOL_ID));+ })+ .catch(() => toast.error('Failed to load image gen settings'))+ .finally(() => setLoading(false));+ }, []);++ const checkStatus = useCallback(() => {+ setChecking(true);+ getImageGenStatus()+ .then(setStatus)+ .catch(() => setStatus({ connected: false, reason: 'Check failed' }))+ .finally(() => setChecking(false));+ }, []);++ const handleSave = async () => {+ setSaving(true);+ const url = sdapiUrl.trim().replace(/\/+$/, '') || undefined;++ let settingsSaved = false;+ await updateSettings({ imageGen: { sdapiUrl: url } })+ .then(() => { settingsSaved = true; setSavedUrl(url || ''); toast.success('Image gen settings saved'); })+ .catch(() => toast.error('Failed to save settings'));++ if (!settingsSaved) {+ setSaving(false);+ return;+ }++ // Register or update the tool in the CoS tools registry+ const toolData = {+ name: 'Stable Diffusion',+ category: 'image-generation',+ description: 'Generate images via Stable Diffusion API (AUTOMATIC1111 / Forge WebUI)',+ enabled: !!url,+ config: { sdapiUrl: url },+ promptHints: 'Use POST /api/image-gen/generate with { prompt, negativePrompt, width, height, steps, cfgScale }. Use POST /api/image-gen/avatar for character portraits.'+ };+ if (toolRegistered) {+ await updateTool(SDAPI_TOOL_ID, toolData).catch(() => {+ toast.error('Failed to update CoS tools registry');+ });+ } else if (url) {+ await registerTool({ id: SDAPI_TOOL_ID, ...toolData })+ .then(() => setToolRegistered(true))+ .catch(() => {+ toast.error('Failed to register in CoS tools registry');+ });+ }++ setSaving(false);+ };++ if (loading) return <BrailleSpinner text="Loading image gen settings" />;++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-5">+ <div className="flex items-center gap-2 text-white">+ <Image size={18} />+ <h2 className="text-lg font-semibold">Stable Diffusion API</h2>+ </div>++ <div className="space-y-1">+ <label className="block text-sm text-gray-400">API URL</label>+ <p className="text-xs text-gray-500 mb-1">+ Base URL for AUTOMATIC1111 / Forge WebUI (e.g. http://localhost:7860)+ </p>+ <input+ type="text"+ value={sdapiUrl}+ onChange={e => setSdapiUrl(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"+ placeholder="http://localhost:7860"+ />+ </div>++ <div className="flex items-center gap-3">+ <button+ onClick={handleSave}+ disabled={saving}+ className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white text-sm rounded-lg transition-colors disabled:opacity-50"+ >+ {saving ? <BrailleSpinner /> : <Save size={14} />}+ Save+ </button>++ <button+ onClick={checkStatus}+ disabled={checking || !sdapiUrl.trim() || sdapiUrl.trim().replace(/\/+$/, '') !== savedUrl}+ className="flex items-center gap-2 px-4 py-2 bg-port-border hover:bg-port-border/70 text-white text-sm rounded-lg transition-colors disabled:opacity-50"+ title={sdapiUrl.trim().replace(/\/+$/, '') !== savedUrl ? 'Save settings first to test' : 'Test connection to SD API'}+ >+ {checking ? <BrailleSpinner /> : <Zap size={14} />}+ Test Connection+ </button>+ </div>++ {status && (+ <div className={`flex items-center gap-2 text-sm ${status.connected ? 'text-port-success' : 'text-port-error'}`}>+ <span className={`w-2 h-2 rounded-full ${status.connected ? 'bg-port-success' : 'bg-port-error'}`} />+ {status.connected ? `Connected — model: ${status.model}` : status.reason || 'Not connected'}+ </div>+ )}++ <div className="border-t border-port-border pt-4 space-y-2">+ <h3 className="text-sm font-medium text-gray-300">CoS Integration</h3>+ <p className="text-xs text-gray-500">+ When configured, this tool is registered with the CoS tools registry. Agents can use it to generate+ images for briefings, character avatars, and other visual content. Images are stored in <code className="text-gray-400">./data/images/</code>.+ </p>+ {toolRegistered && (+ <div className="flex items-center gap-2 text-xs text-port-success">+ <Wrench size={12} />+ Registered as CoS tool+ </div>+ )}+ </div>+ </div>+ );+}++export default ImageGenTab;diff --git a/client/src/components/settings/TelegramTab.jsx b/client/src/components/settings/TelegramTab.jsxnew file mode 100644index 0000000000..d658c69482--- /dev/null+++ b/client/src/components/settings/TelegramTab.jsx@@ -0,0 +1,313 @@+import { useState, useEffect } from 'react';+import { Save, Eye, EyeOff, Trash2, Send } from 'lucide-react';+import toast from '../ui/Toast';+import BrailleSpinner from '../BrailleSpinner';+import {+ getSettings, getTelegramStatus, updateTelegramConfig,+ deleteTelegramConfig, testTelegram, updateTelegramForwardTypes, updateTelegramMethod+} from '../../services/api';++const NOTIFICATION_TYPES = [+ { key: 'memory_approval', label: 'Memory Approvals' },+ { key: 'task_approval', label: 'Task Approvals' },+ { key: 'code_review', label: 'Code Reviews' },+ { key: 'health_issue', label: 'Health Issues' },+ { key: 'briefing_ready', label: 'Briefings' },+ { key: 'autobiography_prompt', label: 'Autobiography Prompts' },+ { key: 'plan_question', label: 'Plan Questions' }+];++export function TelegramTab() {+ const [loading, setLoading] = useState(true);+ const [method, setMethod] = useState('manual');+ const [switching, setSwitching] = useState(false);+ const [tgToken, setTgToken] = useState('');+ const [tgChatId, setTgChatId] = useState('');+ const [tgShowToken, setTgShowToken] = useState(false);+ const [tgStatus, setTgStatus] = useState(null);+ const [tgSaving, setTgSaving] = useState(false);+ const [tgTesting, setTgTesting] = useState(false);+ const [tgDisconnecting, setTgDisconnecting] = useState(false);+ const [tgForwardTypes, setTgForwardTypes] = useState([]);++ useEffect(() => {+ Promise.all([+ getSettings(),+ getTelegramStatus().catch(() => null)+ ]).then(([settings, status]) => {+ if (status) {+ setTgStatus(status);+ setMethod(status.method || 'manual');+ setTgChatId(settings?.telegram?.chatId || '');+ setTgForwardTypes(status.forwardTypes || []);+ }+ }).catch(() => toast.error('Failed to load Telegram settings'))+ .finally(() => setLoading(false));+ }, []);++ const handleMethodChange = (newMethod) => {+ setSwitching(true);+ updateTelegramMethod(newMethod)+ .then(status => {+ setMethod(newMethod);+ setTgStatus(status);+ toast.success(newMethod === 'mcp-bridge'+ ? 'Switched to Claude MCP Bridge'+ : 'Switched to Manual Bot');+ })+ .catch(() => toast.error('Failed to switch method'))+ .finally(() => setSwitching(false));+ };++ const handleTelegramSave = () => {+ if (!tgToken && !tgStatus?.hasToken) {+ toast.error('Bot token is required');+ return;+ }+ setTgSaving(true);+ updateTelegramConfig({ token: tgToken, chatId: tgChatId })+ .then(status => {+ setTgStatus(status);+ toast.success(tgChatId+ ? 'Telegram connected — check your chat for a test message'+ : 'Bot connected — now message your bot /start to get your Chat ID');+ })+ .catch(() => toast.error('Failed to configure Telegram'))+ .finally(() => setTgSaving(false));+ };++ const handleTelegramTest = () => {+ setTgTesting(true);+ testTelegram()+ .then(() => toast.success('Test message sent'))+ .catch(() => toast.error('Failed to send test message'))+ .finally(() => setTgTesting(false));+ };++ const handleTelegramDisconnect = () => {+ setTgDisconnecting(true);+ deleteTelegramConfig()+ .then(() => {+ setTgStatus(null);+ setTgToken('');+ setTgChatId('');+ setTgForwardTypes([]);+ toast.success('Telegram disconnected');+ })+ .catch(() => toast.error('Failed to disconnect'))+ .finally(() => setTgDisconnecting(false));+ };++ const toggleForwardType = (type) => {+ const updated = tgForwardTypes.includes(type)+ ? tgForwardTypes.filter(t => t !== type)+ : [...tgForwardTypes, type];+ setTgForwardTypes(updated);+ updateTelegramForwardTypes(updated).catch(() => toast.error('Failed to update forward types'));+ };++ if (loading) {+ return <BrailleSpinner text="Loading Telegram settings" />;+ }++ return (+ <div className="space-y-4">+ {/* Method Selector */}+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4">+ <label className="block text-sm text-gray-400">Integration Method</label>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <button+ onClick={() => method !== 'manual' && handleMethodChange('manual')}+ disabled={switching}+ className={`p-4 rounded-lg border text-left transition-colors ${+ method === 'manual'+ ? 'border-port-accent bg-port-accent/10'+ : 'border-port-border bg-port-bg hover:border-port-accent/50'+ }`}+ >+ <div className="text-sm font-medium text-white">Manual Bot</div>+ <div className="text-xs text-gray-500 mt-1">+ Self-hosted polling bot with /status, /goals, /checkin commands. Requires bot token and chat ID.+ </div>+ </button>+ <button+ onClick={() => method !== 'mcp-bridge' && handleMethodChange('mcp-bridge')}+ disabled={switching}+ className={`p-4 rounded-lg border text-left transition-colors ${+ method === 'mcp-bridge'+ ? 'border-port-accent bg-port-accent/10'+ : 'border-port-border bg-port-bg hover:border-port-accent/50'+ }`}+ >+ <div className="text-sm font-medium text-white">Claude MCP Bridge</div>+ <div className="text-xs text-gray-500 mt-1">+ Uses Claude Code's Telegram plugin. Natural language inbound, PortOS notifications outbound.+ </div>+ </button>+ </div>+ {switching && <BrailleSpinner text="Switching..." />}+ </div>++ {/* Method-specific config */}+ {method === 'manual' ? (+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-5">+ <div className="flex items-center justify-between">+ <div className="text-sm">+ {tgStatus?.connected && (+ <span className="flex items-center gap-2 text-port-success">+ <span className="w-2 h-2 rounded-full bg-port-success" />+ @{tgStatus.botUsername}+ </span>+ )}+ {tgStatus && !tgStatus.connected && tgStatus.hasToken && (+ <span className="flex items-center gap-2 text-port-error">+ <span className="w-2 h-2 rounded-full bg-port-error" />+ Disconnected+ </span>+ )}+ </div>+ </div>++ <div className="space-y-1">+ <label className="block text-sm text-gray-400">Bot Token</label>+ <div className="flex gap-2">+ <input+ type={tgShowToken ? 'text' : 'password'}+ value={tgToken}+ onChange={e => setTgToken(e.target.value)}+ className="flex-1 bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"+ placeholder={tgStatus?.hasToken ? '••••••••••• (configured)' : 'Paste bot token from @BotFather'}+ />+ <button+ onClick={() => setTgShowToken(!tgShowToken)}+ className="px-3 py-2 bg-port-border hover:bg-port-border/70 text-white rounded-lg transition-colors"+ >+ {tgShowToken ? <EyeOff size={16} /> : <Eye size={16} />}+ </button>+ </div>+ </div>++ <div className="space-y-1">+ <label className="block text-sm text-gray-400">Chat ID</label>+ <input+ type="text"+ value={tgChatId}+ onChange={e => setTgChatId(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"+ placeholder="Message your bot /start to get your chat ID"+ />+ </div>++ <p className="text-xs text-gray-500">+ 1. Message <code>@BotFather</code> on Telegram, send <code>/newbot</code>, copy the token, paste above, click Save.+ 2. Message your bot <code>/start</code> — it will reply with your Chat ID.+ 3. Paste the Chat ID above and click Save & Test.+ </p>++ <div className="flex items-center gap-3">+ <button+ onClick={handleTelegramSave}+ disabled={tgSaving || (!tgToken && !tgStatus?.hasToken)}+ className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"+ >+ {tgSaving ? <BrailleSpinner /> : <Save size={16} />}+ {tgStatus?.connected && tgChatId ? 'Save & Test' : 'Save'}+ </button>+ {tgStatus?.connected && (+ <button+ onClick={handleTelegramTest}+ disabled={tgTesting}+ className="flex items-center gap-2 px-4 py-2 bg-port-border hover:bg-port-border/70 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"+ >+ {tgTesting ? <BrailleSpinner /> : <Send size={16} />}+ Send Test+ </button>+ )}+ {(tgStatus?.hasToken || tgStatus?.hasChatId) && (+ <button+ onClick={handleTelegramDisconnect}+ disabled={tgDisconnecting}+ className="flex items-center gap-2 px-4 py-2 bg-port-error/20 hover:bg-port-error/30 text-port-error text-sm font-medium rounded-lg transition-colors disabled:opacity-50"+ >+ {tgDisconnecting ? <BrailleSpinner /> : <Trash2 size={16} />}+ Disconnect+ </button>+ )}+ </div>+ </div>+ ) : (+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-5">+ <div className="flex items-center justify-between">+ <div className="text-sm">+ {tgStatus?.connected ? (+ <span className="flex items-center gap-2 text-port-success">+ <span className="w-2 h-2 rounded-full bg-port-success" />+ @{tgStatus.botUsername} → {tgStatus.chatId}+ </span>+ ) : (+ <span className="flex items-center gap-2 text-port-warning">+ <span className="w-2 h-2 rounded-full bg-port-warning" />+ Not connected+ </span>+ )}+ </div>+ </div>++ <div className="text-xs text-gray-500 space-y-2">+ <p>+ The MCP Bridge reads config from Claude Code's Telegram plugin at <code>~/.claude/channels/telegram/</code>.+ Bot token comes from <code>.env</code>, chat ID from the first entry in <code>access.json</code> allowlist.+ </p>+ <p>+ <b>Outbound:</b> PortOS sends notifications via direct Telegram Bot API calls (no polling conflict).+ </p>+ <p>+ <b>Inbound:</b> Messages are handled by Claude Code via the MCP plugin — natural language instead of rigid commands.+ </p>+ {!tgStatus?.connected && (+ <p className="text-port-warning">+ Set up the Claude Code Telegram plugin first: run <code>/telegram:configure</code> in Claude Code, then <code>/telegram:access pair <code></code> to approve your chat.+ </p>+ )}+ </div>++ {tgStatus?.connected && (+ <div className="flex items-center gap-3">+ <button+ onClick={handleTelegramTest}+ disabled={tgTesting}+ className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"+ >+ {tgTesting ? <BrailleSpinner /> : <Send size={16} />}+ Send Test+ </button>+ </div>+ )}+ </div>+ )}++ {/* Forward types (shared between both methods) */}+ {tgStatus?.connected && (+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-2">+ <label className="block text-sm text-gray-400">Forward Notification Types</label>+ <p className="text-xs text-gray-500">When all are unchecked, all types are forwarded</p>+ <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">+ {NOTIFICATION_TYPES.map(({ key, label }) => (+ <label key={key} className="flex items-center gap-2 text-sm text-gray-300 cursor-pointer">+ <input+ type="checkbox"+ checked={tgForwardTypes.includes(key)}+ onChange={() => toggleForwardType(key)}+ className="rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"+ />+ {label}+ </label>+ ))}+ </div>+ </div>+ )}+ </div>+ );+}++export default TelegramTab;diff --git a/client/src/pages/AgentsPage.jsx b/client/src/pages/AgentsPage.jsxnew file mode 100644index 0000000000..1c8827b9f3--- /dev/null+++ b/client/src/pages/AgentsPage.jsx@@ -0,0 +1,354 @@+import { useState, useEffect, Fragment } from 'react';+import { RefreshCw, Activity, XCircle, Cpu, MemoryStick, Terminal } from 'lucide-react';+import * as api from '../services/api';++export function AgentsPage() {+ const [agents, setAgents] = useState([]);+ const [loading, setLoading] = useState(true);+ const [killing, setKilling] = useState({});+ const [expandedPid, setExpandedPid] = useState(null);+ const REFRESH_INTERVAL = 3;++ useEffect(() => {+ loadAgents();+ const interval = setInterval(loadAgents, REFRESH_INTERVAL * 1000);+ return () => clearInterval(interval);+ }, []);++ const loadAgents = async () => {+ const data = await api.getAgents().catch(() => []);+ setAgents(data);+ setLoading(false);+ };++ const handleKill = async (pid) => {+ setKilling(prev => ({ ...prev, [pid]: true }));+ await api.killAgent(pid).catch(() => null);+ setTimeout(() => {+ setKilling(prev => ({ ...prev, [pid]: false }));+ loadAgents();+ }, 1000);+ };++ const toggleExpand = (pid) => {+ setExpandedPid(prev => prev === pid ? null : pid);+ };++ const formatStartTime = (timestamp) => {+ return new Date(timestamp).toLocaleString();+ };++ const totalCpu = agents.reduce((sum, a) => sum + (a.cpu || 0), 0);+ const totalMemory = agents.reduce((sum, a) => sum + (a.memory || 0), 0);++ if (loading) {+ return <div className="text-center py-8 text-gray-400">Scanning for AI agents...</div>;+ }++ return (+ <div className="space-y-4 lg:space-y-6">+ {/* Header */}+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">+ <div className="flex items-center gap-2 sm:gap-3">+ <Activity size={24} className="sm:w-7 sm:h-7 text-purple-400" />+ <h1 className="text-lg sm:text-2xl font-bold text-white font-mono">AI Agent Processes</h1>+ <span className="hidden sm:inline text-gray-500 text-sm">({REFRESH_INTERVAL}s)</span>+ </div>+ <button+ onClick={loadAgents}+ className="flex items-center justify-center gap-2 px-3 py-1.5 sm:px-4 sm:py-2 bg-port-card border border-port-border hover:border-gray-500 text-white text-sm rounded-lg transition-colors"+ >+ <RefreshCw size={14} className="sm:w-4 sm:h-4" />+ <span className="sm:inline">Refresh</span>+ </button>+ </div>++ {/* Summary Cards */}+ <div className="grid grid-cols-3 gap-2 sm:gap-4">+ <div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl p-2 sm:p-5 flex items-center justify-between">+ <div>+ <div className="text-gray-400 text-[10px] sm:text-sm mb-0.5 sm:mb-1">Processes</div>+ <div className="text-lg sm:text-3xl font-bold text-white font-mono">{agents.length}</div>+ </div>+ <Terminal size={20} className="sm:w-8 sm:h-8 text-purple-400" />+ </div>+ <div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl p-2 sm:p-5 flex items-center justify-between">+ <div>+ <div className="text-gray-400 text-[10px] sm:text-sm mb-0.5 sm:mb-1">CPU</div>+ <div className="text-lg sm:text-3xl font-bold text-white font-mono">{totalCpu.toFixed(1)}%</div>+ </div>+ <Cpu size={20} className="sm:w-8 sm:h-8 text-blue-400" />+ </div>+ <div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl p-2 sm:p-5 flex items-center justify-between">+ <div>+ <div className="text-gray-400 text-[10px] sm:text-sm mb-0.5 sm:mb-1">Memory</div>+ <div className="text-lg sm:text-3xl font-bold text-white font-mono">{totalMemory.toFixed(1)}%</div>+ </div>+ <MemoryStick size={20} className="sm:w-8 sm:h-8 text-green-400" />+ </div>+ </div>++ {/* Running Processes */}+ <div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl">+ <div className="px-3 sm:px-6 py-3 sm:py-4 border-b border-port-border">+ <h2 className="text-base sm:text-lg font-semibold text-white">Running Processes</h2>+ </div>++ {/* Mobile Card View */}+ <div className="sm:hidden divide-y divide-port-border">+ {agents.map(agent => (+ <div key={agent.pid} className="p-3">+ {/* Top row: Name, PID, Runtime, Kill button */}+ <div className="flex items-center justify-between gap-2 mb-2">+ <div className="flex items-center gap-2 min-w-0 flex-1">+ <span className="font-mono text-white text-sm truncate">{agent.agentName.toLowerCase()}</span>+ {agent.source === 'cos' && (+ <span className="px-1.5 py-0.5 text-[10px] bg-purple-500/20 text-purple-400 rounded shrink-0">CoS</span>+ )}+ <span className="text-gray-500 text-xs shrink-0">#{agent.pid}</span>+ <span className="font-mono text-cyan-400 text-xs shrink-0 whitespace-nowrap">{agent.runtimeFormatted}</span>+ </div>+ <button+ onClick={() => handleKill(agent.pid)}+ disabled={killing[agent.pid]}+ className="shrink-0 px-2 py-1 bg-red-500/20 text-red-400 hover:bg-red-500/30 hover:text-red-300 disabled:opacity-50 rounded text-xs font-medium flex items-center gap-1"+ >+ <XCircle size={14} className={killing[agent.pid] ? 'animate-pulse' : ''} />+ Kill+ </button>+ </div>+ {/* Stats row: CPU & Memory */}+ <div className="flex items-center gap-4 text-xs">+ <div className="flex items-center gap-1">+ <span className="text-gray-500">CPU</span>+ <span className="font-mono text-green-400">{agent.cpu?.toFixed(1)}%</span>+ </div>+ <div className="flex items-center gap-1">+ <span className="text-gray-500">Mem</span>+ <span className="font-mono text-blue-400">{agent.memory?.toFixed(1)}%</span>+ </div>+ </div>+ <button+ onClick={() => toggleExpand(agent.pid)}+ className="mt-2 text-xs text-gray-500 hover:text-white flex items-center gap-1"+ >+ <span className={`inline-block transition-transform ${expandedPid === agent.pid ? 'rotate-90' : ''}`}>▶</span>+ {expandedPid === agent.pid ? 'Hide details' : 'Show details'}+ </button>+ {expandedPid === agent.pid && (+ <div className="mt-3 pt-3 border-t border-port-border space-y-3">+ <div className="grid grid-cols-2 gap-3 text-xs">+ <div>+ <div className="text-gray-500 uppercase tracking-wide mb-0.5">Agent Type</div>+ <div className="text-purple-400">{agent.agentName}</div>+ </div>+ <div>+ <div className="text-gray-500 uppercase tracking-wide mb-0.5">Parent PID</div>+ <div className="text-gray-300 font-mono">{agent.ppid}</div>+ </div>+ {agent.model && (+ <div>+ <div className="text-gray-500 uppercase tracking-wide mb-0.5">Model</div>+ <div className="text-yellow-400 font-mono">{agent.model}</div>+ </div>+ )}+ {agent.taskId && (+ <div>+ <div className="text-gray-500 uppercase tracking-wide mb-0.5">Task ID</div>+ <div className="text-gray-300 font-mono truncate">{agent.taskId}</div>+ </div>+ )}+ </div>+ {agent.prompt && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Task</div>+ <div className="bg-port-bg border border-port-border rounded p-2 text-xs text-gray-300 line-clamp-3">+ {agent.prompt}+ </div>+ </div>+ )}+ </div>+ )}+ </div>+ ))}+ {agents.length === 0 && (+ <div className="px-3 py-8 text-center text-gray-500 text-sm">+ No AI agents currently running+ </div>+ )}+ </div>++ {/* Desktop Table View */}+ <div className="hidden sm:block overflow-x-auto">+ <table className="w-full min-w-[600px]">+ <thead>+ <tr className="border-b border-port-border">+ <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400 w-8"></th>+ <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400">PID</th>+ <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400">Runtime</th>+ <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400">CPU %</th>+ <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400">Memory %</th>+ <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400">Command</th>+ <th className="px-4 py-4 text-center text-sm font-semibold text-gray-400">Actions</th>+ </tr>+ </thead>+ <tbody>+ {agents.map(agent => (+ <Fragment key={agent.pid}>+ <tr className="border-b border-port-border/50 hover:bg-port-border/20">+ <td className="px-4 py-4">+ <button+ onClick={() => toggleExpand(agent.pid)}+ className="text-gray-400 hover:text-white transition-transform"+ >+ <span className={`inline-block transition-transform ${expandedPid === agent.pid ? 'rotate-90' : ''}`}>▶</span>+ </button>+ </td>+ <td className="px-4 py-4 font-mono text-white">{agent.pid}</td>+ <td className="px-4 py-4 font-mono text-cyan-400">{agent.runtimeFormatted}</td>+ <td className="px-4 py-4 font-mono text-green-400">{agent.cpu?.toFixed(1)}%</td>+ <td className="px-4 py-4 font-mono text-blue-400">{agent.memory?.toFixed(1)}%</td>+ <td className="px-4 py-4 font-mono text-gray-300">+ {agent.agentName.toLowerCase()}+ {agent.source === 'cos' && (+ <span className="ml-2 px-1.5 py-0.5 text-[10px] bg-purple-500/20 text-purple-400 rounded">CoS</span>+ )}+ </td>+ <td className="px-4 py-4 text-center">+ <button+ onClick={() => handleKill(agent.pid)}+ disabled={killing[agent.pid]}+ className="px-3 py-1.5 bg-red-500/20 text-red-400 hover:bg-red-500/30 hover:text-red-300 disabled:opacity-50 rounded text-sm font-medium inline-flex items-center gap-1.5 transition-colors"+ title="Kill process"+ >+ <XCircle size={16} className={killing[agent.pid] ? 'animate-pulse' : ''} />+ Kill+ </button>+ </td>+ </tr>+ {expandedPid === agent.pid && (+ <tr>+ <td colSpan={7} className="p-0">+ <div className="bg-port-bg border-t border-port-border">+ <div className="px-3 sm:px-6 py-4 space-y-4">+ {/* Process Details Grid */}+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4">+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Agent Type</div>+ <div className="text-sm text-purple-400 font-medium">+ {agent.agentName}+ {agent.source === 'cos' && <span className="ml-1 text-xs text-purple-300">(CoS)</span>}+ </div>+ </div>+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Parent PID</div>+ <div className="text-sm text-gray-300 font-mono">{agent.ppid}</div>+ </div>+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Started At</div>+ <div className="text-sm text-gray-300">{formatStartTime(agent.startTime)}</div>+ </div>+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Runtime (ms)</div>+ <div className="text-sm text-gray-300 font-mono">{agent.runtime?.toLocaleString()}</div>+ </div>+ {agent.model && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Model</div>+ <div className="text-sm text-yellow-400 font-mono">{agent.model}</div>+ </div>+ )}+ {agent.agentId && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Agent ID</div>+ <div className="text-sm text-gray-300 font-mono">{agent.agentId}</div>+ </div>+ )}+ {agent.taskId && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Task ID</div>+ <div className="text-sm text-gray-300 font-mono">{agent.taskId}</div>+ </div>+ )}+ {agent.workspacePath && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Workspace</div>+ <div className="text-sm text-gray-300 font-mono truncate" title={agent.workspacePath}>+ {agent.workspacePath.split('/').pop()}+ </div>+ </div>+ )}+ </div>++ {/* Full Command */}+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Full Command</div>+ <div className="bg-port-card border border-port-border rounded-lg p-3 overflow-x-auto">+ <code className="text-sm text-cyan-300 font-mono whitespace-pre-wrap break-all">+ {agent.command}+ </code>+ </div>+ </div>++ {/* Task Prompt (for CoS agents) */}+ {agent.prompt && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Task Prompt</div>+ <div className="bg-port-card border border-port-border rounded-lg p-3 overflow-x-auto max-h-48 overflow-y-auto">+ <p className="text-sm text-gray-300 whitespace-pre-wrap">+ {agent.prompt}+ </p>+ </div>+ </div>+ )}++ {/* Resource Usage Bar */}+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">+ <div>+ <div className="flex items-center justify-between text-xs mb-1">+ <span className="text-gray-500 uppercase tracking-wide">CPU Usage</span>+ <span className="text-green-400 font-mono">{agent.cpu?.toFixed(1)}%</span>+ </div>+ <div className="h-2 bg-port-border rounded-full overflow-hidden">+ <div+ className="h-full bg-green-500 rounded-full transition-all"+ style={{ width: `${Math.min(agent.cpu || 0, 100)}%` }}+ />+ </div>+ </div>+ <div>+ <div className="flex items-center justify-between text-xs mb-1">+ <span className="text-gray-500 uppercase tracking-wide">Memory Usage</span>+ <span className="text-blue-400 font-mono">{agent.memory?.toFixed(1)}%</span>+ </div>+ <div className="h-2 bg-port-border rounded-full overflow-hidden">+ <div+ className="h-full bg-blue-500 rounded-full transition-all"+ style={{ width: `${Math.min(agent.memory || 0, 100)}%` }}+ />+ </div>+ </div>+ </div>+ </div>+ </div>+ </td>+ </tr>+ )}+ </Fragment>+ ))}+ {agents.length === 0 && (+ <tr>+ <td colSpan={7} className="px-6 py-12 text-center text-gray-500">+ No AI agents currently running+ </td>+ </tr>+ )}+ </tbody>+ </table>+ </div>+ </div>+ </div>+ );+}++export default AgentsPage;diff --git a/client/src/pages/DevTools.jsx b/client/src/pages/DevTools.jsxindex 1fff349409..5481fb8c03 100644--- a/client/src/pages/DevTools.jsx+++ b/client/src/pages/DevTools.jsx@@ -1,1808 +1,7 @@-import { useState, useEffect, useRef, useCallback, Fragment } from 'react';-import { useLocation, useNavigate } from 'react-router-dom';-import { Clock, RefreshCw, Activity, Image, X, XCircle, Cpu, MemoryStick, Terminal, Trash2, MessageSquarePlus, Info, Save, RotateCcw } from 'lucide-react';-import ProcessesTab from '../components/apps/tabs/ProcessesTab';-import toast from '../components/ui/Toast';-import * as api from '../services/api';-import socket from '../services/socket';-import { formatTime, formatRuntime } from '../utils/formatters';-import { processScreenshotUploads } from '../utils/fileUpload';-import BrailleSpinner from '../components/BrailleSpinner';--export function HistoryPage() {- const [history, setHistory] = useState([]);- const [stats, setStats] = useState(null);- const [loading, setLoading] = useState(true);- const [filter, setFilter] = useState({ action: '', success: '' });- const [actions, setActions] = useState([]);- const [confirmingClear, setConfirmingClear] = useState(false);- const [expandedId, setExpandedId] = useState(null);-- const loadData = useCallback(async () => {- setLoading(true);- const [historyData, statsData, actionsData] = await Promise.all([- api.getHistory({- limit: 100,- action: filter.action || undefined,- success: filter.success !== '' ? filter.success === 'true' : undefined- }).catch(() => ({ entries: [] })),- api.getHistoryStats().catch(() => null),- api.getHistoryActions().catch(() => [])- ]);- setHistory(historyData.entries || []);- setStats(statsData);- setActions(actionsData);- setLoading(false);- }, [filter]);-- useEffect(() => {- loadData();- }, [loadData]);-- const handleClear = async () => {- await api.clearHistory();- setConfirmingClear(false);- loadData();- };-- const handleDelete = async (id, e) => {- e.stopPropagation();- await api.deleteHistoryEntry(id);- setHistory(prev => prev.filter(entry => entry.id !== id));- if (expandedId === id) setExpandedId(null);- };-- const getActionIcon = (action) => {- const icons = {- start: '▶️',- stop: '⏹️',- restart: '🔄',- command: '💻',- scaffold: '🏗️',- 'ai-run': '🤖'- };- return icons[action] || '📋';- };-- const toggleExpand = (id) => {- setExpandedId(prev => prev === id ? null : id);- };-- if (loading) {- return <div className="text-center py-8"><BrailleSpinner text="Loading history" /></div>;- }-- return (- <div className="space-y-6">- <h1 className="text-2xl font-bold text-white">Action History</h1>-- {/* Stats */}- {stats && (- <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">- <div className="bg-port-card border border-port-border rounded-lg p-4 text-center">- <div className="text-2xl font-bold text-white">{stats.total}</div>- <div className="text-sm text-gray-400">Total Actions</div>- </div>- <div className="bg-port-card border border-port-border rounded-lg p-4 text-center">- <div className="text-2xl font-bold text-port-success">{stats.successRate}%</div>- <div className="text-sm text-gray-400">Success Rate</div>- </div>- <div className="bg-port-card border border-port-border rounded-lg p-4 text-center">- <div className="text-2xl font-bold text-white">{stats.last24h}</div>- <div className="text-sm text-gray-400">Last 24h</div>- </div>- <div className="bg-port-card border border-port-border rounded-lg p-4 text-center">- <div className="text-2xl font-bold text-white">{Object.keys(stats.byAction).length}</div>- <div className="text-sm text-gray-400">Action Types</div>- </div>- </div>- )}-- {/* Filters */}- <div className="flex flex-col sm:flex-row gap-3 sm:gap-4 sm:items-center">- <div className="flex flex-wrap gap-2 sm:gap-4">- <select- value={filter.action}- onChange={(e) => setFilter(prev => ({ ...prev, action: e.target.value }))}- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:outline-hidden focus:ring-2 focus:ring-port-accent"- aria-label="Filter by action type"- >- <option value="">All Actions</option>- {actions.map(action => (- <option key={action} value={action}>{action}</option>- ))}- </select>-- <select- value={filter.success}- onChange={(e) => setFilter(prev => ({ ...prev, success: e.target.value }))}- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:outline-hidden focus:ring-2 focus:ring-port-accent"- aria-label="Filter by result status"- >- <option value="">All Results</option>- <option value="true">Success</option>- <option value="false">Failed</option>- </select>- </div>-- <div className="flex-1" />-- {confirmingClear ? (- <div className="flex items-center gap-2">- <span className="text-sm text-gray-400">Clear all?</span>- <button- onClick={handleClear}- className="px-3 py-1.5 bg-port-error/20 text-port-error hover:bg-port-error/30 rounded-lg transition-colors"- >- Yes- </button>- <button- onClick={() => setConfirmingClear(false)}- className="px-3 py-1.5 text-gray-400 hover:text-white"- >- No- </button>- </div>- ) : (- <button- onClick={() => setConfirmingClear(true)}- className="px-4 py-2 bg-port-error/20 text-port-error hover:bg-port-error/30 rounded-lg transition-colors"- >- Clear History- </button>- )}- </div>-- {/* History List */}- <div className="bg-port-card border border-port-border rounded-xl overflow-hidden">- {history.length === 0 ? (- <div className="text-center py-12 text-gray-500">No history entries</div>- ) : (- <div className="divide-y divide-port-border">- {history.map(entry => (- <div key={entry.id}>- <div- className="p-3 sm:p-4 hover:bg-port-border/20 cursor-pointer group"- onClick={() => toggleExpand(entry.id)}- >- <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4">- <div className="flex items-center gap-3 flex-1 min-w-0">- <button- className="text-gray-400 hover:text-white shrink-0 focus:outline-hidden focus:ring-2 focus:ring-port-accent rounded"- aria-expanded={expandedId === entry.id}- aria-label={`${expandedId === entry.id ? 'Collapse' : 'Expand'} ${entry.action} details`}- >- <span className={`inline-block transition-transform ${expandedId === entry.id ? 'rotate-90' : ''}`} aria-hidden="true">▶</span>- </button>- <span className="text-xl shrink-0">{getActionIcon(entry.action)}</span>- <div className="flex-1 min-w-0">- <div className="flex flex-wrap items-center gap-x-2 gap-y-1">- <span className="font-medium text-white">{entry.action}</span>- {entry.targetName && (- <span className="text-gray-400 text-sm sm:text-base">→ {entry.targetName}</span>- )}- {entry.details?.runtime && (- <span className="text-xs text-cyan-400 font-mono">{formatRuntime(entry.details.runtime)}</span>- )}- </div>- {entry.details?.command && (- <code className="text-xs text-gray-500 font-mono truncate block mt-1">{entry.details.command}</code>- )}- </div>- </div>- <div className="flex items-center gap-3 pl-8 sm:pl-0">- <span- className={`w-2 h-2 rounded-full shrink-0 ${entry.success ? 'bg-port-success' : 'bg-port-error'}`}- role="img"- aria-label={entry.success ? 'Success' : 'Failed'}- />- <span className="text-sm text-gray-500 shrink-0">{formatTime(entry.timestamp)}</span>- <button- onClick={(e) => handleDelete(entry.id, e)}- className="p-1 text-gray-500 hover:text-port-error transition-colors sm:opacity-0 sm:group-hover:opacity-100 focus:opacity-100 focus:outline-hidden focus:ring-2 focus:ring-port-accent rounded"- title="Delete entry"- aria-label={`Delete ${entry.action} entry from ${formatTime(entry.timestamp)}`}- >- <Trash2 size={14} aria-hidden="true" />- </button>- </div>- </div>- </div>-- {/* Expanded Details */}- {expandedId === entry.id && (- <div className="px-4 pb-4 bg-port-bg border-t border-port-border">- <div className="pt-4 space-y-4">- {/* Metadata Grid */}- <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 text-sm">- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Timestamp</div>- <div className="text-gray-300">{new Date(entry.timestamp).toLocaleString()}</div>- </div>- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Status</div>- <div className={entry.success ? 'text-port-success' : 'text-port-error'}>- {entry.success ? 'Success' : 'Failed'}- </div>- </div>- {entry.details?.runtime && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Runtime</div>- <div className="text-cyan-400 font-mono">{formatRuntime(entry.details.runtime)}</div>- </div>- )}- {entry.details?.exitCode !== undefined && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Exit Code</div>- <div className={`font-mono ${entry.details.exitCode === 0 ? 'text-port-success' : 'text-port-error'}`}>- {entry.details.exitCode}- </div>- </div>- )}- </div>-- {/* Command */}- {entry.details?.command && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Command</div>- <div className="bg-port-card border border-port-border rounded-lg p-3">- <code className="text-sm text-cyan-300 font-mono whitespace-pre-wrap break-all">- {entry.details.command}- </code>- </div>- </div>- )}-- {/* Output */}- {entry.details?.output && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Output</div>- <div className="bg-port-card border border-port-border rounded-lg p-3 max-h-64 overflow-auto">- <pre className="text-xs text-gray-300 font-mono whitespace-pre-wrap break-all">- {entry.details.output}- </pre>- </div>- </div>- )}-- {/* Error */}- {entry.error && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Error</div>- <div className="bg-port-error/10 border border-port-error/30 rounded-lg p-3">- <pre className="text-sm text-port-error font-mono whitespace-pre-wrap">- {entry.error}- </pre>- </div>- </div>- )}-- {/* Other Details */}- {entry.details && Object.keys(entry.details).filter(k => !['command', 'output', 'runtime', 'exitCode'].includes(k)).length > 0 && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Additional Details</div>- <div className="bg-port-card border border-port-border rounded-lg p-3">- <pre className="text-xs text-gray-400 font-mono whitespace-pre-wrap">- {JSON.stringify(- Object.fromEntries(- Object.entries(entry.details).filter(([k]) => !['command', 'output', 'runtime', 'exitCode'].includes(k))- ),- null,- 2- )}- </pre>- </div>- </div>- )}- </div>- </div>- )}- </div>- ))}- </div>- )}- </div>- </div>- );-}--export function RunsHistoryPage() {- const navigate = useNavigate();- const [runs, setRuns] = useState([]);- const [loading, setLoading] = useState(true);- const [expandedId, setExpandedId] = useState(null);- const [expandedDetails, setExpandedDetails] = useState({});- const [sourceFilter, setSourceFilter] = useState('all');- const [statusFilter, setStatusFilter] = useState('all');-- const loadRuns = useCallback(async () => {- setLoading(true);- const data = await api.getRuns(100, 0, sourceFilter).catch(() => ({ runs: [] }));- setRuns(data.runs || []);- setLoading(false);- }, [sourceFilter]);-- useEffect(() => {- loadRuns();- }, [loadRuns]);-- // Filter runs by source and status- const filteredRuns = runs.filter(run => {- // Source filter (already applied via API, but kept for client-side consistency)- const matchesSource = sourceFilter === 'all' || run.source === sourceFilter;-- // Status filter- let matchesStatus = true;- if (statusFilter === 'success') matchesStatus = run.success === true;- else if (statusFilter === 'running') matchesStatus = run.success === null;- else if (statusFilter === 'failed') matchesStatus = run.success === false;-- return matchesSource && matchesStatus;- });-- const handleDelete = async (id, e) => {- e.stopPropagation();- await api.deleteRun(id);- setRuns(prev => prev.filter(run => run.id !== id));- if (expandedId === id) setExpandedId(null);- };-- const toggleExpand = async (id) => {- if (expandedId === id) {- setExpandedId(null);- return;- }-- setExpandedId(id);-- // Load full prompt and output if not already loaded- if (!expandedDetails[id]) {- const [prompt, output] = await Promise.all([- api.getRunPrompt(id).catch(() => ''),- api.getRunOutput(id).catch(() => '')- ]);- setExpandedDetails(prev => ({- ...prev,- [id]: { prompt, output }- }));- }- };-- const handleContinue = (run) => {- const details = expandedDetails[run.id] || {};- navigate('/devtools/runner', {- state: {- continueFrom: {- prompt: details.prompt || run.prompt,- output: details.output || '',- runId: run.id,- providerId: run.providerId,- providerName: run.providerName,- model: run.model,- workspacePath: run.workspacePath,- workspaceName: run.workspaceName- }- }- });- };-- const handleResume = async (run, e) => {- e.stopPropagation();- // Fetch details if not already loaded- let details = expandedDetails[run.id];- if (!details) {- const [prompt, output] = await Promise.all([- api.getRunPrompt(run.id).catch(() => ''),- api.getRunOutput(run.id).catch(() => '')- ]);- details = { prompt, output };- }- navigate('/devtools/runner', {- state: {- continueFrom: {- prompt: details.prompt || run.prompt,- output: details.output || '',- runId: run.id,- providerId: run.providerId,- providerName: run.providerName,- model: run.model,- workspacePath: run.workspacePath,- workspaceName: run.workspaceName,- error: run.error,- errorCategory: run.errorCategory,- suggestedFix: run.suggestedFix,- success: run.success- }- }- });- };-- const getExitCodeInfo = (exitCode) => {- const codeInfo = {- 1: { label: 'Error', description: 'Generic error - check the output for details' },- 2: { label: 'Misuse', description: 'Incorrect command usage or invalid arguments' },- 126: { label: 'Not Executable', description: 'Command found but not executable' },- 127: { label: 'Not Found', description: 'Command not found - check if CLI is installed' },- 128: { label: 'Invalid Exit', description: 'Invalid exit argument' },- 130: { label: 'Interrupted', description: 'Process interrupted (Ctrl+C / SIGINT)' },- 137: { label: 'Killed', description: 'Process killed (SIGKILL) - likely out of memory' },- 143: { label: 'Terminated', description: 'Process terminated (SIGTERM) - likely hit timeout' }- };- return codeInfo[exitCode] || { label: 'Unknown', description: `Exit code ${exitCode}` };- };-- if (loading) {- return <div className="text-center py-8"><BrailleSpinner text="Loading runs history" /></div>;- }-- const failedCount = runs.filter(r => r.success === false).length;-- const handleClearFailed = async () => {- const result = await api.deleteFailedRuns().catch(() => null);- if (result) {- setRuns(prev => prev.filter(r => r.success !== false));- }- };-- return (- <div className="space-y-4 lg:space-y-6">- <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">- <h1 className="text-lg sm:text-2xl font-bold text-white">AI Runs History</h1>- {failedCount > 0 && (- <button- onClick={handleClearFailed}- className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-error/20 hover:bg-port-error/30 text-port-error rounded-lg transition-colors self-end sm:self-auto"- >- <Trash2 size={14} />- Clear Failed ({failedCount})- </button>- )}- </div>-- {/* Source Filter */}- <div className="flex flex-wrap gap-1.5 sm:gap-2">- {[- { value: 'all', label: 'All' },- { value: 'devtools', label: 'DevTools' },- { value: 'cos-agent', label: 'CoS' }- ].map(filter => (- <button- key={filter.value}- onClick={() => setSourceFilter(filter.value)}- className={`px-3 py-1.5 sm:px-4 sm:py-2 rounded-lg text-xs sm:text-sm font-medium transition-colors ${- sourceFilter === filter.value- ? 'bg-port-accent text-white'- : 'bg-port-card text-gray-400 hover:text-white border border-port-border'- }`}- >- {filter.label}- </button>- ))}- </div>-- {/* Status Filter */}- <div className="flex flex-wrap gap-1.5 sm:gap-2">- {[- { value: 'all', label: 'All Status' },- { value: 'success', label: 'Success' },- { value: 'running', label: 'Running' },- { value: 'failed', label: 'Failed' }- ].map(filter => (- <button- key={filter.value}- onClick={() => setStatusFilter(filter.value)}- className={`px-3 py-1.5 sm:px-4 sm:py-2 rounded-lg text-xs sm:text-sm font-medium transition-colors ${- statusFilter === filter.value- ? 'bg-port-accent text-white'- : 'bg-port-card text-gray-400 hover:text-white border border-port-border'- }`}- >- {filter.label}- </button>- ))}- </div>-- {/* Runs List */}- <div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl overflow-hidden">- {filteredRuns.length === 0 ? (- <div className="text-center py-12 text-gray-500">- {runs.length === 0 ? 'No AI runs yet' : 'No runs match the selected filters'}- </div>- ) : (- <div className="divide-y divide-port-border">- {filteredRuns.map(run => (- <div key={run.id}>- <div- className="p-3 sm:p-4 hover:bg-port-border/20 cursor-pointer group"- onClick={() => toggleExpand(run.id)}- data-testid={`run-row-${run.id}`}- >- <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4">- <div className="flex items-center gap-3 flex-1 min-w-0">- <button className="text-gray-400 hover:text-white shrink-0">- <span className={`inline-block transition-transform ${expandedId === run.id ? 'rotate-90' : ''}`}>▶</span>- </button>- <span className="text-xl shrink-0">🤖</span>- <div className="flex-1 min-w-0">- <div className="flex flex-wrap items-center gap-x-2 gap-y-1">- <span className="font-medium text-white">{run.providerName}</span>- <span className="text-gray-500 text-sm">{run.model}</span>- {run.source === 'cos-agent' && (- <span className="text-xs text-purple-400 bg-purple-500/10 px-2 py-0.5 rounded">- CoS- </span>- )}- {run.workspaceName && (- <span className="text-xs text-port-accent bg-port-accent/10 px-2 py-0.5 rounded">- {run.workspaceName}- </span>- )}- {run.duration && (- <span className="text-xs text-cyan-400 font-mono">{formatRuntime(run.duration)}</span>- )}- </div>- <div className="text-xs text-gray-500 font-mono truncate mt-1">- {run.prompt?.substring(0, 100)}{run.prompt?.length > 100 ? '...' : ''}- </div>- {/* Show error preview for failed runs in collapsed view */}- {run.success === false && expandedId !== run.id && (- <div className="text-xs text-port-error/80 font-mono truncate mt-1">- ⚠ {run.error- ? (() => {- const firstLine = run.error.split('\n')[0] || '';- return `${firstLine.substring(0, 80)}${firstLine.length > 80 ? '...' : ''}`;- })()- : run.errorCategory && run.errorCategory !== 'unknown'- ? `${run.errorCategory}: ${run.suggestedFix || 'See details'}`- : `${getExitCodeInfo(run.exitCode).label}: ${getExitCodeInfo(run.exitCode).description}`}- </div>- )}- </div>- </div>- <div className="flex items-center gap-3 pl-8 sm:pl-0">- <span className={`w-2 h-2 rounded-full shrink-0 ${run.success ? 'bg-port-success' : run.success === false ? 'bg-port-error' : 'bg-port-warning'}`} />- <span className="text-sm text-gray-500 shrink-0">{formatTime(run.startTime)}</span>- {run.success !== null && (- <button- onClick={(e) => handleResume(run, e)}- className="p-1 text-gray-500 hover:text-port-accent transition-colors sm:opacity-0 sm:group-hover:opacity-100"- title="Resume run"- data-testid={`resume-run-${run.id}`}- >- <RotateCcw size={14} />- </button>- )}- <button- onClick={(e) => handleDelete(run.id, e)}- className="p-1 text-gray-500 hover:text-port-error transition-colors sm:opacity-0 sm:group-hover:opacity-100"- title="Delete run"- data-testid={`delete-run-${run.id}`}- >- <Trash2 size={14} />- </button>- </div>- </div>- </div>-- {/* Expanded Details */}- {expandedId === run.id && (- <div className="px-4 pb-4 bg-port-bg border-t border-port-border">- <div className="pt-4 space-y-4">- {/* Execution ID */}- <div className="mb-4">- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Execution ID</div>- <div className="flex items-center gap-2">- <code className="text-xs text-gray-400 font-mono select-all">{run.id}</code>- <button- onClick={(e) => {- e.stopPropagation();- navigator.clipboard.writeText(run.id);- }}- className="p-1 text-gray-500 hover:text-white transition-colors"- title="Copy execution ID"- >- <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />- </svg>- </button>- </div>- </div>-- {/* Metadata Grid */}- <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4 text-sm">- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Started</div>- <div className="text-gray-300">{new Date(run.startTime).toLocaleString()}</div>- </div>- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Status</div>- <div className={run.success ? 'text-port-success' : run.success === false ? 'text-port-error' : 'text-port-warning'}>- {run.success ? 'Success' : run.success === false ? 'Failed' : 'Running'}- </div>- </div>- {run.duration && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Duration</div>- <div className="text-cyan-400 font-mono">{formatRuntime(run.duration)}</div>- </div>- )}- {run.exitCode !== undefined && run.exitCode !== null && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Exit Code</div>- <div className={`font-mono ${run.exitCode === 0 ? 'text-port-success' : 'text-port-error'}`}>- {run.exitCode}- </div>- </div>- )}- {run.outputSize && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Output Size</div>- <div className="text-gray-300 font-mono">{(run.outputSize / 1024).toFixed(1)} KB</div>- </div>- )}- </div>-- {/* Prompt */}- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Prompt</div>- <div className="bg-port-card border border-port-border rounded-lg p-3 max-h-48 overflow-auto">- <pre className="text-sm text-gray-300 font-mono whitespace-pre-wrap break-all">- {expandedDetails[run.id]?.prompt || run.prompt || 'Loading...'}- </pre>- </div>- </div>-- {/* Output - show for all completed runs */}- {run.success !== null && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Output</div>- <div className="bg-port-card border border-port-border rounded-lg p-3 max-h-64 overflow-auto">- <pre className="text-xs text-gray-300 font-mono whitespace-pre-wrap break-all">- {expandedDetails[run.id]?.output !== undefined- ? (expandedDetails[run.id].output || '(no output)')- : 'Loading output...'}- </pre>- </div>- </div>- )}-- {/* Error - show for failed runs with error message OR exit code */}- {(run.error || (run.success === false && run.exitCode !== 0)) && (() => {- const exitInfo = getExitCodeInfo(run.exitCode);- return (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-2 flex items-center gap-2">- Error- {run.exitCode !== undefined && run.exitCode !== null && run.exitCode !== 0 && (- <span className="text-port-error/70">(exit code: {run.exitCode})</span>- )}- {run.errorCategory && run.errorCategory !== 'unknown' ? (- <span className="px-1.5 py-0.5 bg-port-error/20 text-port-error/80 rounded text-xs">- {run.errorCategory}- </span>- ) : run.exitCode !== 0 && exitInfo.label !== 'Unknown' && (- <span className="px-1.5 py-0.5 bg-port-error/20 text-port-error/80 rounded text-xs">- {exitInfo.label}- </span>- )}- </div>- <div className="bg-port-error/10 border border-port-error/30 rounded-lg p-3">- <pre className="text-sm text-port-error font-mono whitespace-pre-wrap break-all">- {run.error || exitInfo.description}- </pre>- </div>- {/* Show additional error details if available and different from error */}- {run.errorDetails && run.errorDetails !== run.error && (- <div className="mt-2 bg-port-error/5 border border-port-error/20 rounded-lg p-3">- <div className="text-xs text-gray-500 mb-1">Additional Details</div>- <pre className="text-xs text-port-error/80 font-mono whitespace-pre-wrap break-all">- {run.errorDetails}- </pre>- </div>- )}- {/* Show suggested fix if available, or fallback to exit code info */}- {(run.suggestedFix || (!run.error && exitInfo.description)) && (- <div className="mt-2 bg-port-warning/10 border border-port-warning/30 rounded-lg p-3">- <div className="text-xs text-port-warning mb-1 font-medium">Suggested Fix</div>- <div className="text-sm text-gray-300">- {run.suggestedFix || 'Check the output above for specific error details. If the output is empty, the process may have been terminated before producing output.'}- </div>- </div>- )}- </div>- );- })()}-- {/* Continue Button */}- {run.success && expandedDetails[run.id]?.output && (- <div className="flex justify-end pt-2">- <button- onClick={() => handleContinue(run)}- className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"- data-testid="continue-conversation-btn"- >- <MessageSquarePlus size={16} />- Continue Conversation- </button>- </div>- )}- </div>- </div>- )}- </div>- ))}- </div>- )}- </div>- </div>- );-}--export function RunnerPage() {- const location = useLocation();- const [mode, setMode] = useState('ai'); // 'ai' or 'command'- const [prompt, setPrompt] = useState('');- const [command, setCommand] = useState('');- const [selectedAppId, setSelectedAppId] = useState('');- const [output, setOutput] = useState('');- const [running, setRunning] = useState(false);- const [runId, setRunId] = useState(null);- const [commandId, setCommandId] = useState(null);- const [apps, setApps] = useState([]);- const [providers, setProviders] = useState([]);- const [selectedProvider, setSelectedProvider] = useState('');- const [selectedModel, setSelectedModel] = useState('');- const [timeout, setTimeout] = useState(30);- const [allowedCommands, setAllowedCommands] = useState([]);- const [screenshots, setScreenshots] = useState([]);- const [continueContext, setContinueContext] = useState(null);- const fileInputRef = useRef(null);- const outputRef = useRef(null);-- // Get the selected app's repoPath- const selectedApp = apps.find(a => a.id === selectedAppId);- const workspacePath = selectedApp?.repoPath || '';-- // Handle continuation context from navigation- useEffect(() => {- const continueFrom = location.state?.continueFrom;- if (continueFrom) {- setContinueContext(continueFrom);- // Set provider and model from previous run if available- if (continueFrom.providerId) {- setSelectedProvider(continueFrom.providerId);- }- if (continueFrom.model) {- setSelectedModel(continueFrom.model);- }- // Set workspace from previous run if available- if (continueFrom.workspacePath) {- const app = apps.find(a => a.repoPath === continueFrom.workspacePath);- if (app) {- setSelectedAppId(app.id);- }- }- // Clear location state to prevent re-triggering on refresh- window.history.replaceState({}, document.title);- }- }, [location.state, apps]);-- useEffect(() => {- Promise.all([- api.getApps().catch(() => []),- api.getProviders().catch(() => ({ providers: [] })),- api.getAllowedCommands().catch(() => [])- ]).then(([appsData, providersRes, cmds]) => {- // Filter out PortOS Autofixer (it's part of PortOS project)- const filteredApps = appsData.filter(a => a.id !== 'portos-autofixer');- setApps(filteredApps);- // Set PortOS as default workspace (exact name match)- const portosApp = filteredApps.find(a => a.name === 'PortOS');- if (portosApp) {- setSelectedAppId(portosApp.id);- } else if (filteredApps.length > 0) {- setSelectedAppId(filteredApps[0].id);- }- const allProviders = providersRes.providers || [];- const enabledProviders = allProviders.filter(p => p.enabled);- setProviders(enabledProviders);- if (enabledProviders.length > 0) {- const active = enabledProviders.find(p => p.id === providersRes.activeProvider) || enabledProviders[0];- setSelectedProvider(active.id);- setSelectedModel(active.defaultModel || '');- }- setAllowedCommands(cmds);- });- }, []);-- // Subscribe to run output- useEffect(() => {- if (!runId) return;-- const handleData = (data) => {- setOutput(prev => prev + data);- if (outputRef.current) {- outputRef.current.scrollTop = outputRef.current.scrollHeight;- }- };-- const handleComplete = (metadata) => {- setRunning(false);- setRunId(null);- const status = metadata.success ? '✓ Completed' : `✗ Failed (${metadata.error || 'unknown error'})`;- setOutput(prev => prev + `\n\n--- ${status} (${Math.round(metadata.duration / 1000)}s) ---\n`);- };-- socket.on(`run:${runId}:data`, handleData);- socket.on(`run:${runId}:complete`, handleComplete);-- return () => {- socket.off(`run:${runId}:data`, handleData);- socket.off(`run:${runId}:complete`, handleComplete);- };- }, [runId]);-- // Subscribe to command output- useEffect(() => {- if (!commandId) return;-- const handleData = ({ data }) => {- setOutput(prev => prev + data);- if (outputRef.current) {- outputRef.current.scrollTop = outputRef.current.scrollHeight;- }- };-- const handleComplete = (result) => {- setRunning(false);- setCommandId(null);- setOutput(prev => prev + `\n--- Command finished (exit code: ${result.exitCode}) ---\n`);- };-- socket.on(`command:${commandId}:data`, handleData);- socket.on(`command:${commandId}:complete`, handleComplete);-- return () => {- socket.off(`command:${commandId}:data`, handleData);- socket.off(`command:${commandId}:complete`, handleComplete);- };- }, [commandId]);-- const handleRunAI = async () => {- if (!prompt.trim() || !selectedProvider) return;-- // Build final prompt, merging with continuation context if present- let finalPrompt = prompt.trim();- if (continueContext) {- if (continueContext.success === false) {- // Resuming a failed run - include error context- finalPrompt = `RESUMING FAILED RUN:----- PREVIOUS PROMPT ----${continueContext.prompt}-${continueContext.output ? `---- PREVIOUS OUTPUT (BEFORE FAILURE) ----${continueContext.output}-` : ''}---- ERROR ----${continueContext.error || 'Unknown error'}-${continueContext.suggestedFix ? `---- SUGGESTED FIX ----${continueContext.suggestedFix}-` : ''}---- NEW INSTRUCTIONS ----${prompt.trim()}`;- } else {- // Continuing a successful conversation- finalPrompt = `CONTINUATION OF PREVIOUS CONVERSATION:----- PREVIOUS PROMPT ----${continueContext.prompt}----- PREVIOUS OUTPUT ----${continueContext.output}----- NEW INSTRUCTIONS ----${prompt.trim()}`;- }- }-- setOutput('');- setRunning(true);-- const result = await api.createRun({- providerId: selectedProvider,- model: selectedModel || undefined,- prompt: finalPrompt,- workspacePath: workspacePath || undefined,- workspaceName: apps.find(a => a.repoPath === workspacePath)?.name,- timeout: timeout * 60 * 1000, // Convert minutes to milliseconds- screenshots: screenshots.map(s => s.path) // Include screenshot paths- }).catch(err => ({ error: err.message }));-- if (result.error) {- setOutput(`Error: ${result.error}`);- setRunning(false);- return;- }-- // Clear continuation context after running- setContinueContext(null);- setRunId(result.runId);- };-- const handleRunCommand = async () => {- if (!command.trim()) return;-- setOutput('');- setRunning(true);-- const result = await api.executeCommand(command, workspacePath || undefined)- .catch(err => ({ error: err.message }));-- if (result.error) {- setOutput(`Error: ${result.error}`);- setRunning(false);- return;- }-- setCommandId(result.commandId);- };-- const handleStop = async () => {- if (runId) {- await api.stopRun(runId);- setRunning(false);- setRunId(null);- }- if (commandId) {- await api.stopCommand(commandId);- setRunning(false);- setCommandId(null);- }- };-- const handleFileSelect = async (e) => {- await processScreenshotUploads(e.target.files, {- onSuccess: (fileInfo) => setScreenshots(prev => [...prev, fileInfo]),- onError: (msg) => toast.error(msg)- });- e.target.value = '';- };-- const removeScreenshot = (id) => {- setScreenshots(prev => prev.filter(s => s.id !== id));- };-- const currentProvider = providers.find(p => p.id === selectedProvider);-- return (- <div className="space-y-6">- <h1 className="text-2xl font-bold text-white">Code</h1>-- {/* Continuation Context Banner */}- {continueContext && (- <div className={`${continueContext.success === false ? 'bg-port-warning/10 border-port-warning/30' : 'bg-port-success/10 border-port-success/30'} border rounded-xl p-4`} data-testid="continuation-banner">- <div className="flex items-start justify-between mb-3">- <div className="flex items-center gap-2">- <Info size={18} className={continueContext.success === false ? 'text-port-warning' : 'text-port-success'} />- <span className={`font-medium ${continueContext.success === false ? 'text-port-warning' : 'text-port-success'}`}>- {continueContext.success === false ? 'Resuming Failed Run' : 'Continuing Previous Conversation'}- </span>- {continueContext.providerName && (- <span className="text-xs text-gray-400 bg-port-card px-2 py-0.5 rounded">- {continueContext.providerName}- </span>- )}- </div>- <button- onClick={() => setContinueContext(null)}- className="p-1 text-gray-400 hover:text-white"- title="Dismiss context"- >- <X size={16} />- </button>- </div>- <div className="space-y-2 text-sm">- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Previous Prompt</div>- <div className="text-gray-300 bg-port-card/50 rounded px-2 py-1 font-mono text-xs max-h-20 overflow-auto">- {continueContext.prompt?.substring(0, 500)}{continueContext.prompt?.length > 500 ? '...' : ''}- </div>- </div>- {continueContext.success === false && continueContext.error && (- <div>- <div className="text-xs text-port-error uppercase tracking-wide mb-1">Error</div>- <div className="text-port-error/80 bg-port-error/10 rounded px-2 py-1 font-mono text-xs max-h-20 overflow-auto">- {continueContext.error}- </div>- </div>- )}- {continueContext.success === false && continueContext.suggestedFix && (- <div>- <div className="text-xs text-port-warning uppercase tracking-wide mb-1">Suggested Fix</div>- <div className="text-gray-300 bg-port-warning/10 rounded px-2 py-1 text-xs max-h-20 overflow-auto">- {continueContext.suggestedFix}- </div>- </div>- )}- {continueContext.output && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Previous Output</div>- <div className="text-gray-300 bg-port-card/50 rounded px-2 py-1 font-mono text-xs max-h-24 overflow-auto">- {continueContext.output?.substring(0, 800)}{continueContext.output?.length > 800 ? '...' : ''}- </div>- </div>- )}- </div>- <div className="text-xs text-gray-500 mt-3 italic">- {continueContext.success === false- ? 'Enter instructions to retry the task. The previous context and error will be included automatically.'- : 'Enter your follow-up instructions below. The previous context will be included automatically.'}- </div>- </div>- )}-- {/* Mode Toggle */}- <div className="flex gap-2">- <button- onClick={() => setMode('ai')}- className={`px-4 py-2 rounded-lg transition-colors ${- mode === 'ai' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'- }`}- >- AI Assistant- </button>- <button- onClick={() => setMode('command')}- className={`px-4 py-2 rounded-lg transition-colors ${- mode === 'command' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'- }`}- >- Shell Command- </button>- </div>-- {/* Configuration Row */}- <div className="flex flex-wrap gap-3">- {/* Workspace */}- <select- value={selectedAppId}- onChange={(e) => setSelectedAppId(e.target.value)}- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- >- {apps.map(app => (- <option key={app.id} value={app.id}>{app.name}</option>- ))}- </select>-- {mode === 'ai' && (- <>- {/* Provider */}- <select- value={selectedProvider}- onChange={(e) => {- setSelectedProvider(e.target.value);- const p = providers.find(p => p.id === e.target.value);- setSelectedModel(p?.defaultModel || '');- }}- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- >- {providers.map(p => (- <option key={p.id} value={p.id}>{p.name}</option>- ))}- </select>-- {/* Model */}- {currentProvider?.models?.length > 0 && (- <select- value={selectedModel}- onChange={(e) => setSelectedModel(e.target.value)}- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- >- {currentProvider.models.map(m => (- <option key={m} value={m}>{m}</option>- ))}- </select>- )}-- {/* Timeout */}- <div className="flex items-center gap-2">- <Clock size={16} className="text-gray-400" />- <select- value={timeout}- onChange={(e) => setTimeout(Number(e.target.value))}- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- >- <option value={5}>5 min</option>- <option value={15}>15 min</option>- <option value={30}>30 min</option>- <option value={60}>60 min</option>- </select>- </div>-- {/* Screenshot Upload */}- <button- onClick={() => fileInputRef.current?.click()}- className="flex items-center gap-2 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-gray-400 hover:text-white text-sm"- >- <Image size={16} />- Add Screenshot- </button>- <input- ref={fileInputRef}- type="file"- accept="image/*"- multiple- onChange={handleFileSelect}- className="sr-only"- tabIndex={-1}- aria-hidden="true"- />- </>- )}- </div>-- {/* Screenshot Previews */}- {mode === 'ai' && screenshots.length > 0 && (- <div className="flex gap-2 flex-wrap">- {screenshots.map(s => (- <div key={s.id} className="relative group">- <img- src={s.preview}- alt={s.filename}- className="w-20 h-20 object-cover rounded-lg border border-port-border"- />- <button- onClick={() => removeScreenshot(s.id)}- className="absolute -top-2 -right-2 w-5 h-5 bg-port-error rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"- >- <X size={12} />- </button>- </div>- ))}- </div>- )}-- {/* Input Area */}- {mode === 'ai' ? (- <div className="flex flex-col sm:flex-row gap-2">- <textarea- value={prompt}- onChange={(e) => setPrompt(e.target.value)}- placeholder="Describe what you want the AI to do..."- rows={3}- className="flex-1 px-3 sm:px-4 py-3 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden resize-none text-sm sm:text-base"- />- {running ? (- <button- onClick={handleStop}- className="px-6 py-3 bg-port-error hover:bg-port-error/80 text-white rounded-lg transition-colors"- >- Stop- </button>- ) : (- <button- onClick={handleRunAI}- disabled={!prompt.trim() || !selectedProvider}- className="px-6 py-3 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors disabled:opacity-50"- >- Run- </button>- )}- </div>- ) : (- <>- <div className="flex flex-col sm:flex-row gap-2">- <input- type="text"- value={command}- onChange={(e) => setCommand(e.target.value)}- onKeyDown={(e) => e.key === 'Enter' && !running && handleRunCommand()}- placeholder="Enter command (e.g., npm run build)"- className="flex-1 px-3 sm:px-4 py-3 bg-port-bg border border-port-border rounded-lg text-white font-mono focus:border-port-accent focus:outline-hidden text-sm sm:text-base"- />- {running ? (- <button- onClick={handleStop}- className="px-6 py-3 bg-port-error hover:bg-port-error/80 text-white rounded-lg transition-colors"- >- Stop- </button>- ) : (- <button- onClick={handleRunCommand}- disabled={!command.trim()}- className="px-6 py-3 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors disabled:opacity-50"- >- Run- </button>- )}- </div>- <div className="text-xs text-gray-500 break-words">- Allowed: {allowedCommands.slice(0, 10).join(', ')}{allowedCommands.length > 10 ? `, +${allowedCommands.length - 10} more` : ''}- </div>- </>- )}-- {/* Output */}- <div className="space-y-1">- <div className="text-xs text-gray-500">Output:</div>- <div- ref={outputRef}- className="bg-port-bg border border-port-border rounded-lg p-3 sm:p-4 h-64 sm:h-80 overflow-auto font-mono text-xs sm:text-sm"- >- {output ? (- <pre className="text-gray-300 whitespace-pre-wrap">{output}</pre>- ) : (- <div className="text-gray-500">Output will appear here...</div>- )}- </div>- </div>- </div>- );-}--export function ProcessesPage() {- const [managedProcessNames, setManagedProcessNames] = useState(new Set());- const [saving, setSaving] = useState(false);-- useEffect(() => {- const loadManagedProcessNames = async () => {- const apps = await api.getApps().catch(() => []);- const names = new Set();- apps.forEach(app => {- (app.pm2ProcessNames || []).forEach(name => names.add(name));- });- setManagedProcessNames(names);- };- loadManagedProcessNames();- }, []);-- const isPortOSManaged = (procName) => {- if (procName.startsWith('portos-')) return true;- return managedProcessNames.has(procName);- };-- const handlePm2Save = async () => {- setSaving(true);- const result = await fetch('/api/commands/execute', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ command: 'pm2 save' })- }).then(r => r.json()).catch(() => ({ success: false }));- setSaving(false);- if (result.success) {- toast.success('PM2 process list saved to startup');- } else {- toast.error('Failed to save PM2 process list');- }- };-- return (- <div className="space-y-6">- <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">- <h1 className="text-2xl font-bold text-white">PM2 Processes</h1>- <button- onClick={handlePm2Save}- disabled={saving}- className="px-3 sm:px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50 text-sm sm:text-base"- >- <Save size={16} className={saving ? 'animate-pulse' : ''} />- <span className="hidden sm:inline">{saving ? 'Saving...' : 'PM2 Save'}</span>- <span className="sm:hidden">{saving ? '...' : 'Save'}</span>- </button>- </div>-- <ProcessesTab filterFn={isPortOSManaged} />- </div>- );-}--export function UsagePage() {- const [usage, setUsage] = useState(null);- const [loading, setLoading] = useState(true);-- useEffect(() => {- loadUsage();- }, []);-- const loadUsage = async () => {- setLoading(true);- const data = await api.getUsage().catch(() => null);- setUsage(data);- setLoading(false);- };-- const formatNumber = (num) => {- if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`;- if (num >= 1000) return `${(num / 1000).toFixed(1)}K`;- return String(num);- };-- if (loading) {- return <div className="text-center py-8"><BrailleSpinner text="Loading usage data" /></div>;- }-- if (!usage) {- return <div className="text-center py-8 text-gray-500">No usage data available</div>;- }-- const maxActivity = Math.max(...(usage.last7Days?.map(d => d.sessions) || [1]));-- return (- <div className="space-y-6">- <h1 className="text-2xl font-bold text-white">Usage Metrics</h1>-- {/* Summary Stats */}- <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4">- <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 text-center">- <div className="text-xl sm:text-2xl font-bold text-white">{formatNumber(usage.totalSessions)}</div>- <div className="text-xs sm:text-sm text-gray-400">Sessions</div>- </div>- <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 text-center">- <div className="text-xl sm:text-2xl font-bold text-white">{formatNumber(usage.totalMessages)}</div>- <div className="text-xs sm:text-sm text-gray-400">Messages</div>- </div>- <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 text-center">- <div className="text-xl sm:text-2xl font-bold text-white">{formatNumber(usage.totalToolCalls)}</div>- <div className="text-xs sm:text-sm text-gray-400">Tool Calls</div>- </div>- <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 text-center">- <div className="text-xl sm:text-2xl font-bold text-white">{formatNumber(usage.totalTokens?.input + usage.totalTokens?.output)}</div>- <div className="text-xs sm:text-sm text-gray-400">Tokens</div>- </div>- <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 text-center col-span-2 sm:col-span-1">- <div className="text-xl sm:text-2xl font-bold text-port-success">${usage.estimatedCost?.toFixed(2)}</div>- <div className="text-xs sm:text-sm text-gray-400">Est. Cost</div>- </div>- </div>-- <div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6">- {/* 7-Day Activity */}- <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4">- <h3 className="text-sm font-medium text-gray-400 mb-3 sm:mb-4">Last 7 Days</h3>- <div className="flex items-end gap-1 sm:gap-2 h-24 sm:h-32">- {usage.last7Days?.map((day, i) => (- <div key={i} className="flex-1 flex flex-col items-center">- <div- className="w-full bg-port-accent/60 rounded-t"- style={{ height: `${(day.sessions / maxActivity) * 100}%`, minHeight: day.sessions > 0 ? 4 : 0 }}- />- <div className="text-[10px] sm:text-xs text-gray-500 mt-1 sm:mt-2">{day.label}</div>- <div className="text-[10px] sm:text-xs text-gray-400">{day.sessions}</div>- </div>- ))}- </div>- </div>-- {/* Hourly Distribution */}- <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4">- <h3 className="text-sm font-medium text-gray-400 mb-3 sm:mb-4">Hourly Distribution</h3>- <div className="flex items-end gap-0.5 h-24 sm:h-32">- {usage.hourlyActivity?.map((count, hour) => {- const maxHour = Math.max(...usage.hourlyActivity);- return (- <div key={hour} className="flex-1 flex flex-col items-center">- <div- className="w-full bg-port-accent/40 rounded-t"- style={{ height: `${(count / (maxHour || 1)) * 100}%`, minHeight: count > 0 ? 2 : 0 }}- title={`${hour}:00 - ${count} sessions`}- />- </div>- );- })}- </div>- <div className="flex justify-between text-[10px] sm:text-xs text-gray-500 mt-1 sm:mt-2">- <span>12am</span>- <span>6am</span>- <span>12pm</span>- <span>6pm</span>- <span>12am</span>- </div>- </div>- </div>-- <div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6">- {/* Top Providers */}- <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4">- <h3 className="text-sm font-medium text-gray-400 mb-2 sm:mb-3">Top Providers</h3>- <div className="space-y-1 sm:space-y-2">- {usage.topProviders?.map((provider, i) => (- <div key={i} className="flex flex-col sm:flex-row sm:items-center sm:justify-between py-2 border-b border-port-border last:border-0 gap-1 sm:gap-0">- <span className="text-white text-sm sm:text-base">{provider.name}</span>- <div className="text-xs sm:text-sm text-gray-400">- <span>{provider.sessions} sessions</span>- <span className="mx-1 sm:mx-2">•</span>- <span>{formatNumber(provider.tokens)} tokens</span>- </div>- </div>- ))}- {(!usage.topProviders || usage.topProviders.length === 0) && (- <div className="text-gray-500 text-sm">No provider data</div>- )}- </div>- </div>-- {/* Top Models */}- <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4">- <h3 className="text-sm font-medium text-gray-400 mb-2 sm:mb-3">Top Models</h3>- <div className="space-y-1 sm:space-y-2">- {usage.topModels?.map((model, i) => (- <div key={i} className="flex flex-col sm:flex-row sm:items-center sm:justify-between py-2 border-b border-port-border last:border-0 gap-1 sm:gap-0">- <span className="text-white font-mono text-xs sm:text-sm truncate max-w-[200px] sm:max-w-none">{model.model}</span>- <div className="text-xs sm:text-sm text-gray-400">- <span>{model.sessions} sessions</span>- <span className="mx-1 sm:mx-2">•</span>- <span>{formatNumber(model.tokens)} tokens</span>- </div>- </div>- ))}- {(!usage.topModels || usage.topModels.length === 0) && (- <div className="text-gray-500 text-sm">No model data</div>- )}- </div>- </div>- </div>-- {/* Refresh button */}- <div className="flex justify-end">- <button- onClick={loadUsage}- className="flex items-center gap-2 px-4 py-2 text-gray-400 hover:text-white"- >- <RefreshCw size={16} /> Refresh- </button>- </div>- </div>- );-}--export function AgentsPage() {- const [agents, setAgents] = useState([]);- const [loading, setLoading] = useState(true);- const [killing, setKilling] = useState({});- const [expandedPid, setExpandedPid] = useState(null);- const REFRESH_INTERVAL = 3;-- useEffect(() => {- loadAgents();- const interval = setInterval(loadAgents, REFRESH_INTERVAL * 1000);- return () => clearInterval(interval);- }, []);-- const loadAgents = async () => {- const data = await api.getAgents().catch(() => []);- setAgents(data);- setLoading(false);- };-- const handleKill = async (pid) => {- setKilling(prev => ({ ...prev, [pid]: true }));- await api.killAgent(pid).catch(() => null);- setTimeout(() => {- setKilling(prev => ({ ...prev, [pid]: false }));- loadAgents();- }, 1000);- };-- const toggleExpand = (pid) => {- setExpandedPid(prev => prev === pid ? null : pid);- };-- const formatStartTime = (timestamp) => {- return new Date(timestamp).toLocaleString();- };-- const totalCpu = agents.reduce((sum, a) => sum + (a.cpu || 0), 0);- const totalMemory = agents.reduce((sum, a) => sum + (a.memory || 0), 0);-- if (loading) {- return <div className="text-center py-8 text-gray-400">Scanning for AI agents...</div>;- }-- return (- <div className="space-y-4 lg:space-y-6">- {/* Header */}- <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">- <div className="flex items-center gap-2 sm:gap-3">- <Activity size={24} className="sm:w-7 sm:h-7 text-purple-400" />- <h1 className="text-lg sm:text-2xl font-bold text-white font-mono">AI Agent Processes</h1>- <span className="hidden sm:inline text-gray-500 text-sm">({REFRESH_INTERVAL}s)</span>- </div>- <button- onClick={loadAgents}- className="flex items-center justify-center gap-2 px-3 py-1.5 sm:px-4 sm:py-2 bg-port-card border border-port-border hover:border-gray-500 text-white text-sm rounded-lg transition-colors"- >- <RefreshCw size={14} className="sm:w-4 sm:h-4" />- <span className="sm:inline">Refresh</span>- </button>- </div>-- {/* Summary Cards */}- <div className="grid grid-cols-3 gap-2 sm:gap-4">- <div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl p-2 sm:p-5 flex items-center justify-between">- <div>- <div className="text-gray-400 text-[10px] sm:text-sm mb-0.5 sm:mb-1">Processes</div>- <div className="text-lg sm:text-3xl font-bold text-white font-mono">{agents.length}</div>- </div>- <Terminal size={20} className="sm:w-8 sm:h-8 text-purple-400" />- </div>- <div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl p-2 sm:p-5 flex items-center justify-between">- <div>- <div className="text-gray-400 text-[10px] sm:text-sm mb-0.5 sm:mb-1">CPU</div>- <div className="text-lg sm:text-3xl font-bold text-white font-mono">{totalCpu.toFixed(1)}%</div>- </div>- <Cpu size={20} className="sm:w-8 sm:h-8 text-blue-400" />- </div>- <div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl p-2 sm:p-5 flex items-center justify-between">- <div>- <div className="text-gray-400 text-[10px] sm:text-sm mb-0.5 sm:mb-1">Memory</div>- <div className="text-lg sm:text-3xl font-bold text-white font-mono">{totalMemory.toFixed(1)}%</div>- </div>- <MemoryStick size={20} className="sm:w-8 sm:h-8 text-green-400" />- </div>- </div>-- {/* Running Processes */}- <div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl">- <div className="px-3 sm:px-6 py-3 sm:py-4 border-b border-port-border">- <h2 className="text-base sm:text-lg font-semibold text-white">Running Processes</h2>- </div>-- {/* Mobile Card View */}- <div className="sm:hidden divide-y divide-port-border">- {agents.map(agent => (- <div key={agent.pid} className="p-3">- {/* Top row: Name, PID, Runtime, Kill button */}- <div className="flex items-center justify-between gap-2 mb-2">- <div className="flex items-center gap-2 min-w-0 flex-1">- <span className="font-mono text-white text-sm truncate">{agent.agentName.toLowerCase()}</span>- {agent.source === 'cos' && (- <span className="px-1.5 py-0.5 text-[10px] bg-purple-500/20 text-purple-400 rounded shrink-0">CoS</span>- )}- <span className="text-gray-500 text-xs shrink-0">#{agent.pid}</span>- <span className="font-mono text-cyan-400 text-xs shrink-0 whitespace-nowrap">{agent.runtimeFormatted}</span>- </div>- <button- onClick={() => handleKill(agent.pid)}- disabled={killing[agent.pid]}- className="shrink-0 px-2 py-1 bg-red-500/20 text-red-400 hover:bg-red-500/30 hover:text-red-300 disabled:opacity-50 rounded text-xs font-medium flex items-center gap-1"- >- <XCircle size={14} className={killing[agent.pid] ? 'animate-pulse' : ''} />- Kill- </button>- </div>- {/* Stats row: CPU & Memory */}- <div className="flex items-center gap-4 text-xs">- <div className="flex items-center gap-1">- <span className="text-gray-500">CPU</span>- <span className="font-mono text-green-400">{agent.cpu?.toFixed(1)}%</span>- </div>- <div className="flex items-center gap-1">- <span className="text-gray-500">Mem</span>- <span className="font-mono text-blue-400">{agent.memory?.toFixed(1)}%</span>- </div>- </div>- <button- onClick={() => toggleExpand(agent.pid)}- className="mt-2 text-xs text-gray-500 hover:text-white flex items-center gap-1"- >- <span className={`inline-block transition-transform ${expandedPid === agent.pid ? 'rotate-90' : ''}`}>▶</span>- {expandedPid === agent.pid ? 'Hide details' : 'Show details'}- </button>- {expandedPid === agent.pid && (- <div className="mt-3 pt-3 border-t border-port-border space-y-3">- <div className="grid grid-cols-2 gap-3 text-xs">- <div>- <div className="text-gray-500 uppercase tracking-wide mb-0.5">Agent Type</div>- <div className="text-purple-400">{agent.agentName}</div>- </div>- <div>- <div className="text-gray-500 uppercase tracking-wide mb-0.5">Parent PID</div>- <div className="text-gray-300 font-mono">{agent.ppid}</div>- </div>- {agent.model && (- <div>- <div className="text-gray-500 uppercase tracking-wide mb-0.5">Model</div>- <div className="text-yellow-400 font-mono">{agent.model}</div>- </div>- )}- {agent.taskId && (- <div>- <div className="text-gray-500 uppercase tracking-wide mb-0.5">Task ID</div>- <div className="text-gray-300 font-mono truncate">{agent.taskId}</div>- </div>- )}- </div>- {agent.prompt && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Task</div>- <div className="bg-port-bg border border-port-border rounded p-2 text-xs text-gray-300 line-clamp-3">- {agent.prompt}- </div>- </div>- )}- </div>- )}- </div>- ))}- {agents.length === 0 && (- <div className="px-3 py-8 text-center text-gray-500 text-sm">- No AI agents currently running- </div>- )}- </div>-- {/* Desktop Table View */}- <div className="hidden sm:block overflow-x-auto">- <table className="w-full min-w-[600px]">- <thead>- <tr className="border-b border-port-border">- <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400 w-8"></th>- <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400">PID</th>- <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400">Runtime</th>- <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400">CPU %</th>- <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400">Memory %</th>- <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400">Command</th>- <th className="px-4 py-4 text-center text-sm font-semibold text-gray-400">Actions</th>- </tr>- </thead>- <tbody>- {agents.map(agent => (- <Fragment key={agent.pid}>- <tr className="border-b border-port-border/50 hover:bg-port-border/20">- <td className="px-4 py-4">- <button- onClick={() => toggleExpand(agent.pid)}- className="text-gray-400 hover:text-white transition-transform"- >- <span className={`inline-block transition-transform ${expandedPid === agent.pid ? 'rotate-90' : ''}`}>▶</span>- </button>- </td>- <td className="px-4 py-4 font-mono text-white">{agent.pid}</td>- <td className="px-4 py-4 font-mono text-cyan-400">{agent.runtimeFormatted}</td>- <td className="px-4 py-4 font-mono text-green-400">{agent.cpu?.toFixed(1)}%</td>- <td className="px-4 py-4 font-mono text-blue-400">{agent.memory?.toFixed(1)}%</td>- <td className="px-4 py-4 font-mono text-gray-300">- {agent.agentName.toLowerCase()}- {agent.source === 'cos' && (- <span className="ml-2 px-1.5 py-0.5 text-[10px] bg-purple-500/20 text-purple-400 rounded">CoS</span>- )}- </td>- <td className="px-4 py-4 text-center">- <button- onClick={() => handleKill(agent.pid)}- disabled={killing[agent.pid]}- className="px-3 py-1.5 bg-red-500/20 text-red-400 hover:bg-red-500/30 hover:text-red-300 disabled:opacity-50 rounded text-sm font-medium inline-flex items-center gap-1.5 transition-colors"- title="Kill process"- >- <XCircle size={16} className={killing[agent.pid] ? 'animate-pulse' : ''} />- Kill- </button>- </td>- </tr>- {expandedPid === agent.pid && (- <tr>- <td colSpan={7} className="p-0">- <div className="bg-port-bg border-t border-port-border">- <div className="px-3 sm:px-6 py-4 space-y-4">- {/* Process Details Grid */}- <div className="grid grid-cols-2 md:grid-cols-4 gap-4">- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Agent Type</div>- <div className="text-sm text-purple-400 font-medium">- {agent.agentName}- {agent.source === 'cos' && <span className="ml-1 text-xs text-purple-300">(CoS)</span>}- </div>- </div>- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Parent PID</div>- <div className="text-sm text-gray-300 font-mono">{agent.ppid}</div>- </div>- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Started At</div>- <div className="text-sm text-gray-300">{formatStartTime(agent.startTime)}</div>- </div>- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Runtime (ms)</div>- <div className="text-sm text-gray-300 font-mono">{agent.runtime?.toLocaleString()}</div>- </div>- {agent.model && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Model</div>- <div className="text-sm text-yellow-400 font-mono">{agent.model}</div>- </div>- )}- {agent.agentId && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Agent ID</div>- <div className="text-sm text-gray-300 font-mono">{agent.agentId}</div>- </div>- )}- {agent.taskId && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Task ID</div>- <div className="text-sm text-gray-300 font-mono">{agent.taskId}</div>- </div>- )}- {agent.workspacePath && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Workspace</div>- <div className="text-sm text-gray-300 font-mono truncate" title={agent.workspacePath}>- {agent.workspacePath.split('/').pop()}- </div>- </div>- )}- </div>-- {/* Full Command */}- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Full Command</div>- <div className="bg-port-card border border-port-border rounded-lg p-3 overflow-x-auto">- <code className="text-sm text-cyan-300 font-mono whitespace-pre-wrap break-all">- {agent.command}- </code>- </div>- </div>-- {/* Task Prompt (for CoS agents) */}- {agent.prompt && (- <div>- <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Task Prompt</div>- <div className="bg-port-card border border-port-border rounded-lg p-3 overflow-x-auto max-h-48 overflow-y-auto">- <p className="text-sm text-gray-300 whitespace-pre-wrap">- {agent.prompt}- </p>- </div>- </div>- )}-- {/* Resource Usage Bar */}- <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">- <div>- <div className="flex items-center justify-between text-xs mb-1">- <span className="text-gray-500 uppercase tracking-wide">CPU Usage</span>- <span className="text-green-400 font-mono">{agent.cpu?.toFixed(1)}%</span>- </div>- <div className="h-2 bg-port-border rounded-full overflow-hidden">- <div- className="h-full bg-green-500 rounded-full transition-all"- style={{ width: `${Math.min(agent.cpu || 0, 100)}%` }}- />- </div>- </div>- <div>- <div className="flex items-center justify-between text-xs mb-1">- <span className="text-gray-500 uppercase tracking-wide">Memory Usage</span>- <span className="text-blue-400 font-mono">{agent.memory?.toFixed(1)}%</span>- </div>- <div className="h-2 bg-port-border rounded-full overflow-hidden">- <div- className="h-full bg-blue-500 rounded-full transition-all"- style={{ width: `${Math.min(agent.memory || 0, 100)}%` }}- />- </div>- </div>- </div>- </div>- </div>- </td>- </tr>- )}- </Fragment>- ))}- {agents.length === 0 && (- <tr>- <td colSpan={7} className="px-6 py-12 text-center text-gray-500">- No AI agents currently running- </td>- </tr>- )}- </tbody>- </table>- </div>- </div>- </div>- );-}+// Barrel file — each page component lives in its own file+export { HistoryPage } from './HistoryPage';+export { RunsHistoryPage } from './RunsHistoryPage';+export { RunnerPage } from './RunnerPage';+export { ProcessesPage } from './ProcessesPage';+export { UsagePage } from './UsagePage';+export { AgentsPage } from './AgentsPage';diff --git a/client/src/pages/HistoryPage.jsx b/client/src/pages/HistoryPage.jsxnew file mode 100644index 0000000000..a70f1f08c2--- /dev/null+++ b/client/src/pages/HistoryPage.jsx@@ -0,0 +1,304 @@+import { useState, useEffect, useCallback } from 'react';+import { Trash2 } from 'lucide-react';+import * as api from '../services/api';+import { formatTime, formatRuntime } from '../utils/formatters';+import BrailleSpinner from '../components/BrailleSpinner';++export function HistoryPage() {+ const [history, setHistory] = useState([]);+ const [stats, setStats] = useState(null);+ const [loading, setLoading] = useState(true);+ const [filter, setFilter] = useState({ action: '', success: '' });+ const [actions, setActions] = useState([]);+ const [confirmingClear, setConfirmingClear] = useState(false);+ const [expandedId, setExpandedId] = useState(null);++ const loadData = useCallback(async () => {+ setLoading(true);+ const [historyData, statsData, actionsData] = await Promise.all([+ api.getHistory({+ limit: 100,+ action: filter.action || undefined,+ success: filter.success !== '' ? filter.success === 'true' : undefined+ }).catch(() => ({ entries: [] })),+ api.getHistoryStats().catch(() => null),+ api.getHistoryActions().catch(() => [])+ ]);+ setHistory(historyData.entries || []);+ setStats(statsData);+ setActions(actionsData);+ setLoading(false);+ }, [filter]);++ useEffect(() => {+ loadData();+ }, [loadData]);++ const handleClear = async () => {+ await api.clearHistory();+ setConfirmingClear(false);+ loadData();+ };++ const handleDelete = async (id, e) => {+ e.stopPropagation();+ await api.deleteHistoryEntry(id);+ setHistory(prev => prev.filter(entry => entry.id !== id));+ if (expandedId === id) setExpandedId(null);+ };++ const getActionIcon = (action) => {+ const icons = {+ start: '▶️',+ stop: '⏹️',+ restart: '🔄',+ command: '💻',+ scaffold: '🏗️',+ 'ai-run': '🤖'+ };+ return icons[action] || '📋';+ };++ const toggleExpand = (id) => {+ setExpandedId(prev => prev === id ? null : id);+ };++ if (loading) {+ return <div className="text-center py-8"><BrailleSpinner text="Loading history" /></div>;+ }++ return (+ <div className="space-y-6">+ <h1 className="text-2xl font-bold text-white">Action History</h1>++ {/* Stats */}+ {stats && (+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">+ <div className="bg-port-card border border-port-border rounded-lg p-4 text-center">+ <div className="text-2xl font-bold text-white">{stats.total}</div>+ <div className="text-sm text-gray-400">Total Actions</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-lg p-4 text-center">+ <div className="text-2xl font-bold text-port-success">{stats.successRate}%</div>+ <div className="text-sm text-gray-400">Success Rate</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-lg p-4 text-center">+ <div className="text-2xl font-bold text-white">{stats.last24h}</div>+ <div className="text-sm text-gray-400">Last 24h</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-lg p-4 text-center">+ <div className="text-2xl font-bold text-white">{Object.keys(stats.byAction).length}</div>+ <div className="text-sm text-gray-400">Action Types</div>+ </div>+ </div>+ )}++ {/* Filters */}+ <div className="flex flex-col sm:flex-row gap-3 sm:gap-4 sm:items-center">+ <div className="flex flex-wrap gap-2 sm:gap-4">+ <select+ value={filter.action}+ onChange={(e) => setFilter(prev => ({ ...prev, action: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:outline-hidden focus:ring-2 focus:ring-port-accent"+ aria-label="Filter by action type"+ >+ <option value="">All Actions</option>+ {actions.map(action => (+ <option key={action} value={action}>{action}</option>+ ))}+ </select>++ <select+ value={filter.success}+ onChange={(e) => setFilter(prev => ({ ...prev, success: e.target.value }))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:outline-hidden focus:ring-2 focus:ring-port-accent"+ aria-label="Filter by result status"+ >+ <option value="">All Results</option>+ <option value="true">Success</option>+ <option value="false">Failed</option>+ </select>+ </div>++ <div className="flex-1" />++ {confirmingClear ? (+ <div className="flex items-center gap-2">+ <span className="text-sm text-gray-400">Clear all?</span>+ <button+ onClick={handleClear}+ className="px-3 py-1.5 bg-port-error/20 text-port-error hover:bg-port-error/30 rounded-lg transition-colors"+ >+ Yes+ </button>+ <button+ onClick={() => setConfirmingClear(false)}+ className="px-3 py-1.5 text-gray-400 hover:text-white"+ >+ No+ </button>+ </div>+ ) : (+ <button+ onClick={() => setConfirmingClear(true)}+ className="px-4 py-2 bg-port-error/20 text-port-error hover:bg-port-error/30 rounded-lg transition-colors"+ >+ Clear History+ </button>+ )}+ </div>++ {/* History List */}+ <div className="bg-port-card border border-port-border rounded-xl overflow-hidden">+ {history.length === 0 ? (+ <div className="text-center py-12 text-gray-500">No history entries</div>+ ) : (+ <div className="divide-y divide-port-border">+ {history.map(entry => (+ <div key={entry.id}>+ <div+ className="p-3 sm:p-4 hover:bg-port-border/20 cursor-pointer group"+ onClick={() => toggleExpand(entry.id)}+ >+ <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4">+ <div className="flex items-center gap-3 flex-1 min-w-0">+ <button+ className="text-gray-400 hover:text-white shrink-0 focus:outline-hidden focus:ring-2 focus:ring-port-accent rounded"+ aria-expanded={expandedId === entry.id}+ aria-label={`${expandedId === entry.id ? 'Collapse' : 'Expand'} ${entry.action} details`}+ >+ <span className={`inline-block transition-transform ${expandedId === entry.id ? 'rotate-90' : ''}`} aria-hidden="true">▶</span>+ </button>+ <span className="text-xl shrink-0">{getActionIcon(entry.action)}</span>+ <div className="flex-1 min-w-0">+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">+ <span className="font-medium text-white">{entry.action}</span>+ {entry.targetName && (+ <span className="text-gray-400 text-sm sm:text-base">→ {entry.targetName}</span>+ )}+ {entry.details?.runtime && (+ <span className="text-xs text-cyan-400 font-mono">{formatRuntime(entry.details.runtime)}</span>+ )}+ </div>+ {entry.details?.command && (+ <code className="text-xs text-gray-500 font-mono truncate block mt-1">{entry.details.command}</code>+ )}+ </div>+ </div>+ <div className="flex items-center gap-3 pl-8 sm:pl-0">+ <span+ className={`w-2 h-2 rounded-full shrink-0 ${entry.success ? 'bg-port-success' : 'bg-port-error'}`}+ role="img"+ aria-label={entry.success ? 'Success' : 'Failed'}+ />+ <span className="text-sm text-gray-500 shrink-0">{formatTime(entry.timestamp)}</span>+ <button+ onClick={(e) => handleDelete(entry.id, e)}+ className="p-1 text-gray-500 hover:text-port-error transition-colors sm:opacity-0 sm:group-hover:opacity-100 focus:opacity-100 focus:outline-hidden focus:ring-2 focus:ring-port-accent rounded"+ title="Delete entry"+ aria-label={`Delete ${entry.action} entry from ${formatTime(entry.timestamp)}`}+ >+ <Trash2 size={14} aria-hidden="true" />+ </button>+ </div>+ </div>+ </div>++ {/* Expanded Details */}+ {expandedId === entry.id && (+ <div className="px-4 pb-4 bg-port-bg border-t border-port-border">+ <div className="pt-4 space-y-4">+ {/* Metadata Grid */}+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 text-sm">+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Timestamp</div>+ <div className="text-gray-300">{new Date(entry.timestamp).toLocaleString()}</div>+ </div>+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Status</div>+ <div className={entry.success ? 'text-port-success' : 'text-port-error'}>+ {entry.success ? 'Success' : 'Failed'}+ </div>+ </div>+ {entry.details?.runtime && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Runtime</div>+ <div className="text-cyan-400 font-mono">{formatRuntime(entry.details.runtime)}</div>+ </div>+ )}+ {entry.details?.exitCode !== undefined && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Exit Code</div>+ <div className={`font-mono ${entry.details.exitCode === 0 ? 'text-port-success' : 'text-port-error'}`}>+ {entry.details.exitCode}+ </div>+ </div>+ )}+ </div>++ {/* Command */}+ {entry.details?.command && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Command</div>+ <div className="bg-port-card border border-port-border rounded-lg p-3">+ <code className="text-sm text-cyan-300 font-mono whitespace-pre-wrap break-all">+ {entry.details.command}+ </code>+ </div>+ </div>+ )}++ {/* Output */}+ {entry.details?.output && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Output</div>+ <div className="bg-port-card border border-port-border rounded-lg p-3 max-h-64 overflow-auto">+ <pre className="text-xs text-gray-300 font-mono whitespace-pre-wrap break-all">+ {entry.details.output}+ </pre>+ </div>+ </div>+ )}++ {/* Error */}+ {entry.error && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Error</div>+ <div className="bg-port-error/10 border border-port-error/30 rounded-lg p-3">+ <pre className="text-sm text-port-error font-mono whitespace-pre-wrap">+ {entry.error}+ </pre>+ </div>+ </div>+ )}++ {/* Other Details */}+ {entry.details && Object.keys(entry.details).filter(k => !['command', 'output', 'runtime', 'exitCode'].includes(k)).length > 0 && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Additional Details</div>+ <div className="bg-port-card border border-port-border rounded-lg p-3">+ <pre className="text-xs text-gray-400 font-mono whitespace-pre-wrap">+ {JSON.stringify(+ Object.fromEntries(+ Object.entries(entry.details).filter(([k]) => !['command', 'output', 'runtime', 'exitCode'].includes(k))+ ),+ null,+ 2+ )}+ </pre>+ </div>+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ );+}++export default HistoryPage;diff --git a/client/src/pages/ProcessesPage.jsx b/client/src/pages/ProcessesPage.jsxnew file mode 100644index 0000000000..3788452223--- /dev/null+++ b/client/src/pages/ProcessesPage.jsx@@ -0,0 +1,63 @@+import { useState, useEffect } from 'react';+import { Save } from 'lucide-react';+import ProcessesTab from '../components/apps/tabs/ProcessesTab';+import toast from '../components/ui/Toast';+import * as api from '../services/api';++export function ProcessesPage() {+ const [managedProcessNames, setManagedProcessNames] = useState(new Set());+ const [saving, setSaving] = useState(false);++ useEffect(() => {+ const loadManagedProcessNames = async () => {+ const apps = await api.getApps().catch(() => []);+ const names = new Set();+ apps.forEach(app => {+ (app.pm2ProcessNames || []).forEach(name => names.add(name));+ });+ setManagedProcessNames(names);+ };+ loadManagedProcessNames();+ }, []);++ const isPortOSManaged = (procName) => {+ if (procName.startsWith('portos-')) return true;+ return managedProcessNames.has(procName);+ };++ const handlePm2Save = async () => {+ setSaving(true);+ const result = await fetch('/api/commands/execute', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ command: 'pm2 save' })+ }).then(r => r.json()).catch(() => ({ success: false }));+ setSaving(false);+ if (result.success) {+ toast.success('PM2 process list saved to startup');+ } else {+ toast.error('Failed to save PM2 process list');+ }+ };++ return (+ <div className="space-y-6">+ <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">+ <h1 className="text-2xl font-bold text-white">PM2 Processes</h1>+ <button+ onClick={handlePm2Save}+ disabled={saving}+ className="px-3 sm:px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50 text-sm sm:text-base"+ >+ <Save size={16} className={saving ? 'animate-pulse' : ''} />+ <span className="hidden sm:inline">{saving ? 'Saving...' : 'PM2 Save'}</span>+ <span className="sm:hidden">{saving ? '...' : 'Save'}</span>+ </button>+ </div>++ <ProcessesTab filterFn={isPortOSManaged} />+ </div>+ );+}++export default ProcessesPage;diff --git a/client/src/pages/RunnerPage.jsx b/client/src/pages/RunnerPage.jsxnew file mode 100644index 0000000000..6db8cde26c--- /dev/null+++ b/client/src/pages/RunnerPage.jsx@@ -0,0 +1,515 @@+import { useState, useEffect, useRef } from 'react';+import { useLocation } from 'react-router-dom';+import { Clock, Image, X, Info } from 'lucide-react';+import toast from '../components/ui/Toast';+import * as api from '../services/api';+import socket from '../services/socket';+import { processScreenshotUploads } from '../utils/fileUpload';+import BrailleSpinner from '../components/BrailleSpinner';++export function RunnerPage() {+ const location = useLocation();+ const [mode, setMode] = useState('ai'); // 'ai' or 'command'+ const [prompt, setPrompt] = useState('');+ const [command, setCommand] = useState('');+ const [selectedAppId, setSelectedAppId] = useState('');+ const [output, setOutput] = useState('');+ const [running, setRunning] = useState(false);+ const [runId, setRunId] = useState(null);+ const [commandId, setCommandId] = useState(null);+ const [apps, setApps] = useState([]);+ const [providers, setProviders] = useState([]);+ const [selectedProvider, setSelectedProvider] = useState('');+ const [selectedModel, setSelectedModel] = useState('');+ const [timeout, setTimeout] = useState(30);+ const [allowedCommands, setAllowedCommands] = useState([]);+ const [screenshots, setScreenshots] = useState([]);+ const [continueContext, setContinueContext] = useState(null);+ const fileInputRef = useRef(null);+ const outputRef = useRef(null);++ // Get the selected app's repoPath+ const selectedApp = apps.find(a => a.id === selectedAppId);+ const workspacePath = selectedApp?.repoPath || '';++ // Handle continuation context from navigation+ useEffect(() => {+ const continueFrom = location.state?.continueFrom;+ if (continueFrom) {+ setContinueContext(continueFrom);+ // Set provider and model from previous run if available+ if (continueFrom.providerId) {+ setSelectedProvider(continueFrom.providerId);+ }+ if (continueFrom.model) {+ setSelectedModel(continueFrom.model);+ }+ // Set workspace from previous run if available+ if (continueFrom.workspacePath) {+ const app = apps.find(a => a.repoPath === continueFrom.workspacePath);+ if (app) {+ setSelectedAppId(app.id);+ }+ }+ // Clear location state to prevent re-triggering on refresh+ window.history.replaceState({}, document.title);+ }+ }, [location.state, apps]);++ useEffect(() => {+ Promise.all([+ api.getApps().catch(() => []),+ api.getProviders().catch(() => ({ providers: [] })),+ api.getAllowedCommands().catch(() => [])+ ]).then(([appsData, providersRes, cmds]) => {+ // Filter out PortOS Autofixer (it's part of PortOS project)+ const filteredApps = appsData.filter(a => a.id !== 'portos-autofixer');+ setApps(filteredApps);+ // Set PortOS as default workspace (exact name match)+ const portosApp = filteredApps.find(a => a.name === 'PortOS');+ if (portosApp) {+ setSelectedAppId(portosApp.id);+ } else if (filteredApps.length > 0) {+ setSelectedAppId(filteredApps[0].id);+ }+ const allProviders = providersRes.providers || [];+ const enabledProviders = allProviders.filter(p => p.enabled);+ setProviders(enabledProviders);+ if (enabledProviders.length > 0) {+ const active = enabledProviders.find(p => p.id === providersRes.activeProvider) || enabledProviders[0];+ setSelectedProvider(active.id);+ setSelectedModel(active.defaultModel || '');+ }+ setAllowedCommands(cmds);+ });+ }, []);++ // Subscribe to run output+ useEffect(() => {+ if (!runId) return;++ const handleData = (data) => {+ setOutput(prev => prev + data);+ if (outputRef.current) {+ outputRef.current.scrollTop = outputRef.current.scrollHeight;+ }+ };++ const handleComplete = (metadata) => {+ setRunning(false);+ setRunId(null);+ const status = metadata.success ? '✓ Completed' : `✗ Failed (${metadata.error || 'unknown error'})`;+ setOutput(prev => prev + `\n\n--- ${status} (${Math.round(metadata.duration / 1000)}s) ---\n`);+ };++ socket.on(`run:${runId}:data`, handleData);+ socket.on(`run:${runId}:complete`, handleComplete);++ return () => {+ socket.off(`run:${runId}:data`, handleData);+ socket.off(`run:${runId}:complete`, handleComplete);+ };+ }, [runId]);++ // Subscribe to command output+ useEffect(() => {+ if (!commandId) return;++ const handleData = ({ data }) => {+ setOutput(prev => prev + data);+ if (outputRef.current) {+ outputRef.current.scrollTop = outputRef.current.scrollHeight;+ }+ };++ const handleComplete = (result) => {+ setRunning(false);+ setCommandId(null);+ setOutput(prev => prev + `\n--- Command finished (exit code: ${result.exitCode}) ---\n`);+ };++ socket.on(`command:${commandId}:data`, handleData);+ socket.on(`command:${commandId}:complete`, handleComplete);++ return () => {+ socket.off(`command:${commandId}:data`, handleData);+ socket.off(`command:${commandId}:complete`, handleComplete);+ };+ }, [commandId]);++ const handleRunAI = async () => {+ if (!prompt.trim() || !selectedProvider) return;++ // Build final prompt, merging with continuation context if present+ let finalPrompt = prompt.trim();+ if (continueContext) {+ if (continueContext.success === false) {+ // Resuming a failed run - include error context+ finalPrompt = `RESUMING FAILED RUN:++--- PREVIOUS PROMPT ---+${continueContext.prompt}+${continueContext.output ? `+--- PREVIOUS OUTPUT (BEFORE FAILURE) ---+${continueContext.output}+` : ''}+--- ERROR ---+${continueContext.error || 'Unknown error'}+${continueContext.suggestedFix ? `+--- SUGGESTED FIX ---+${continueContext.suggestedFix}+` : ''}+--- NEW INSTRUCTIONS ---+${prompt.trim()}`;+ } else {+ // Continuing a successful conversation+ finalPrompt = `CONTINUATION OF PREVIOUS CONVERSATION:++--- PREVIOUS PROMPT ---+${continueContext.prompt}++--- PREVIOUS OUTPUT ---+${continueContext.output}++--- NEW INSTRUCTIONS ---+${prompt.trim()}`;+ }+ }++ setOutput('');+ setRunning(true);++ const result = await api.createRun({+ providerId: selectedProvider,+ model: selectedModel || undefined,+ prompt: finalPrompt,+ workspacePath: workspacePath || undefined,+ workspaceName: apps.find(a => a.repoPath === workspacePath)?.name,+ timeout: timeout * 60 * 1000, // Convert minutes to milliseconds+ screenshots: screenshots.map(s => s.path) // Include screenshot paths+ }).catch(err => ({ error: err.message }));++ if (result.error) {+ setOutput(`Error: ${result.error}`);+ setRunning(false);+ return;+ }++ // Clear continuation context after running+ setContinueContext(null);+ setRunId(result.runId);+ };++ const handleRunCommand = async () => {+ if (!command.trim()) return;++ setOutput('');+ setRunning(true);++ const result = await api.executeCommand(command, workspacePath || undefined)+ .catch(err => ({ error: err.message }));++ if (result.error) {+ setOutput(`Error: ${result.error}`);+ setRunning(false);+ return;+ }++ setCommandId(result.commandId);+ };++ const handleStop = async () => {+ if (runId) {+ await api.stopRun(runId);+ setRunning(false);+ setRunId(null);+ }+ if (commandId) {+ await api.stopCommand(commandId);+ setRunning(false);+ setCommandId(null);+ }+ };++ const handleFileSelect = async (e) => {+ await processScreenshotUploads(e.target.files, {+ onSuccess: (fileInfo) => setScreenshots(prev => [...prev, fileInfo]),+ onError: (msg) => toast.error(msg)+ });+ e.target.value = '';+ };++ const removeScreenshot = (id) => {+ setScreenshots(prev => prev.filter(s => s.id !== id));+ };++ const currentProvider = providers.find(p => p.id === selectedProvider);++ return (+ <div className="space-y-6">+ <h1 className="text-2xl font-bold text-white">Code</h1>++ {/* Continuation Context Banner */}+ {continueContext && (+ <div className={`${continueContext.success === false ? 'bg-port-warning/10 border-port-warning/30' : 'bg-port-success/10 border-port-success/30'} border rounded-xl p-4`} data-testid="continuation-banner">+ <div className="flex items-start justify-between mb-3">+ <div className="flex items-center gap-2">+ <Info size={18} className={continueContext.success === false ? 'text-port-warning' : 'text-port-success'} />+ <span className={`font-medium ${continueContext.success === false ? 'text-port-warning' : 'text-port-success'}`}>+ {continueContext.success === false ? 'Resuming Failed Run' : 'Continuing Previous Conversation'}+ </span>+ {continueContext.providerName && (+ <span className="text-xs text-gray-400 bg-port-card px-2 py-0.5 rounded">+ {continueContext.providerName}+ </span>+ )}+ </div>+ <button+ onClick={() => setContinueContext(null)}+ className="p-1 text-gray-400 hover:text-white"+ title="Dismiss context"+ >+ <X size={16} />+ </button>+ </div>+ <div className="space-y-2 text-sm">+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Previous Prompt</div>+ <div className="text-gray-300 bg-port-card/50 rounded px-2 py-1 font-mono text-xs max-h-20 overflow-auto">+ {continueContext.prompt?.substring(0, 500)}{continueContext.prompt?.length > 500 ? '...' : ''}+ </div>+ </div>+ {continueContext.success === false && continueContext.error && (+ <div>+ <div className="text-xs text-port-error uppercase tracking-wide mb-1">Error</div>+ <div className="text-port-error/80 bg-port-error/10 rounded px-2 py-1 font-mono text-xs max-h-20 overflow-auto">+ {continueContext.error}+ </div>+ </div>+ )}+ {continueContext.success === false && continueContext.suggestedFix && (+ <div>+ <div className="text-xs text-port-warning uppercase tracking-wide mb-1">Suggested Fix</div>+ <div className="text-gray-300 bg-port-warning/10 rounded px-2 py-1 text-xs max-h-20 overflow-auto">+ {continueContext.suggestedFix}+ </div>+ </div>+ )}+ {continueContext.output && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Previous Output</div>+ <div className="text-gray-300 bg-port-card/50 rounded px-2 py-1 font-mono text-xs max-h-24 overflow-auto">+ {continueContext.output?.substring(0, 800)}{continueContext.output?.length > 800 ? '...' : ''}+ </div>+ </div>+ )}+ </div>+ <div className="text-xs text-gray-500 mt-3 italic">+ {continueContext.success === false+ ? 'Enter instructions to retry the task. The previous context and error will be included automatically.'+ : 'Enter your follow-up instructions below. The previous context will be included automatically.'}+ </div>+ </div>+ )}++ {/* Mode Toggle */}+ <div className="flex gap-2">+ <button+ onClick={() => setMode('ai')}+ className={`px-4 py-2 rounded-lg transition-colors ${+ mode === 'ai' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'+ }`}+ >+ AI Assistant+ </button>+ <button+ onClick={() => setMode('command')}+ className={`px-4 py-2 rounded-lg transition-colors ${+ mode === 'command' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'+ }`}+ >+ Shell Command+ </button>+ </div>++ {/* Configuration Row */}+ <div className="flex flex-wrap gap-3">+ {/* Workspace */}+ <select+ value={selectedAppId}+ onChange={(e) => setSelectedAppId(e.target.value)}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ {apps.map(app => (+ <option key={app.id} value={app.id}>{app.name}</option>+ ))}+ </select>++ {mode === 'ai' && (+ <>+ {/* Provider */}+ <select+ value={selectedProvider}+ onChange={(e) => {+ setSelectedProvider(e.target.value);+ const p = providers.find(p => p.id === e.target.value);+ setSelectedModel(p?.defaultModel || '');+ }}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ {providers.map(p => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>++ {/* Model */}+ {currentProvider?.models?.length > 0 && (+ <select+ value={selectedModel}+ onChange={(e) => setSelectedModel(e.target.value)}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ {currentProvider.models.map(m => (+ <option key={m} value={m}>{m}</option>+ ))}+ </select>+ )}++ {/* Timeout */}+ <div className="flex items-center gap-2">+ <Clock size={16} className="text-gray-400" />+ <select+ value={timeout}+ onChange={(e) => setTimeout(Number(e.target.value))}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ >+ <option value={5}>5 min</option>+ <option value={15}>15 min</option>+ <option value={30}>30 min</option>+ <option value={60}>60 min</option>+ </select>+ </div>++ {/* Screenshot Upload */}+ <button+ onClick={() => fileInputRef.current?.click()}+ className="flex items-center gap-2 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-gray-400 hover:text-white text-sm"+ >+ <Image size={16} />+ Add Screenshot+ </button>+ <input+ ref={fileInputRef}+ type="file"+ accept="image/*"+ multiple+ onChange={handleFileSelect}+ className="sr-only"+ tabIndex={-1}+ aria-hidden="true"+ />+ </>+ )}+ </div>++ {/* Screenshot Previews */}+ {mode === 'ai' && screenshots.length > 0 && (+ <div className="flex gap-2 flex-wrap">+ {screenshots.map(s => (+ <div key={s.id} className="relative group">+ <img+ src={s.preview}+ alt={s.filename}+ className="w-20 h-20 object-cover rounded-lg border border-port-border"+ />+ <button+ onClick={() => removeScreenshot(s.id)}+ className="absolute -top-2 -right-2 w-5 h-5 bg-port-error rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"+ >+ <X size={12} />+ </button>+ </div>+ ))}+ </div>+ )}++ {/* Input Area */}+ {mode === 'ai' ? (+ <div className="flex flex-col sm:flex-row gap-2">+ <textarea+ value={prompt}+ onChange={(e) => setPrompt(e.target.value)}+ placeholder="Describe what you want the AI to do..."+ rows={3}+ className="flex-1 px-3 sm:px-4 py-3 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden resize-none text-sm sm:text-base"+ />+ {running ? (+ <button+ onClick={handleStop}+ className="px-6 py-3 bg-port-error hover:bg-port-error/80 text-white rounded-lg transition-colors"+ >+ Stop+ </button>+ ) : (+ <button+ onClick={handleRunAI}+ disabled={!prompt.trim() || !selectedProvider}+ className="px-6 py-3 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors disabled:opacity-50"+ >+ Run+ </button>+ )}+ </div>+ ) : (+ <>+ <div className="flex flex-col sm:flex-row gap-2">+ <input+ type="text"+ value={command}+ onChange={(e) => setCommand(e.target.value)}+ onKeyDown={(e) => e.key === 'Enter' && !running && handleRunCommand()}+ placeholder="Enter command (e.g., npm run build)"+ className="flex-1 px-3 sm:px-4 py-3 bg-port-bg border border-port-border rounded-lg text-white font-mono focus:border-port-accent focus:outline-hidden text-sm sm:text-base"+ />+ {running ? (+ <button+ onClick={handleStop}+ className="px-6 py-3 bg-port-error hover:bg-port-error/80 text-white rounded-lg transition-colors"+ >+ Stop+ </button>+ ) : (+ <button+ onClick={handleRunCommand}+ disabled={!command.trim()}+ className="px-6 py-3 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors disabled:opacity-50"+ >+ Run+ </button>+ )}+ </div>+ <div className="text-xs text-gray-500 break-words">+ Allowed: {allowedCommands.slice(0, 10).join(', ')}{allowedCommands.length > 10 ? `, +${allowedCommands.length - 10} more` : ''}+ </div>+ </>+ )}++ {/* Output */}+ <div className="space-y-1">+ <div className="text-xs text-gray-500">Output:</div>+ <div+ ref={outputRef}+ className="bg-port-bg border border-port-border rounded-lg p-3 sm:p-4 h-64 sm:h-80 overflow-auto font-mono text-xs sm:text-sm"+ >+ {output ? (+ <pre className="text-gray-300 whitespace-pre-wrap">{output}</pre>+ ) : (+ <div className="text-gray-500">Output will appear here...</div>+ )}+ </div>+ </div>+ </div>+ );+}++export default RunnerPage;diff --git a/client/src/pages/RunsHistoryPage.jsx b/client/src/pages/RunsHistoryPage.jsxnew file mode 100644index 0000000000..70c899ec50--- /dev/null+++ b/client/src/pages/RunsHistoryPage.jsx@@ -0,0 +1,440 @@+import { useState, useEffect, useCallback } from 'react';+import { useNavigate } from 'react-router-dom';+import { Trash2, RotateCcw, MessageSquarePlus } from 'lucide-react';+import * as api from '../services/api';+import { formatTime, formatRuntime } from '../utils/formatters';+import BrailleSpinner from '../components/BrailleSpinner';++export function RunsHistoryPage() {+ const navigate = useNavigate();+ const [runs, setRuns] = useState([]);+ const [loading, setLoading] = useState(true);+ const [expandedId, setExpandedId] = useState(null);+ const [expandedDetails, setExpandedDetails] = useState({});+ const [sourceFilter, setSourceFilter] = useState('all');+ const [statusFilter, setStatusFilter] = useState('all');++ const loadRuns = useCallback(async () => {+ setLoading(true);+ const data = await api.getRuns(100, 0, sourceFilter).catch(() => ({ runs: [] }));+ setRuns(data.runs || []);+ setLoading(false);+ }, [sourceFilter]);++ useEffect(() => {+ loadRuns();+ }, [loadRuns]);++ // Filter runs by source and status+ const filteredRuns = runs.filter(run => {+ // Source filter (already applied via API, but kept for client-side consistency)+ const matchesSource = sourceFilter === 'all' || run.source === sourceFilter;++ // Status filter+ let matchesStatus = true;+ if (statusFilter === 'success') matchesStatus = run.success === true;+ else if (statusFilter === 'running') matchesStatus = run.success === null;+ else if (statusFilter === 'failed') matchesStatus = run.success === false;++ return matchesSource && matchesStatus;+ });++ const handleDelete = async (id, e) => {+ e.stopPropagation();+ await api.deleteRun(id);+ setRuns(prev => prev.filter(run => run.id !== id));+ if (expandedId === id) setExpandedId(null);+ };++ const toggleExpand = async (id) => {+ if (expandedId === id) {+ setExpandedId(null);+ return;+ }++ setExpandedId(id);++ // Load full prompt and output if not already loaded+ if (!expandedDetails[id]) {+ const [prompt, output] = await Promise.all([+ api.getRunPrompt(id).catch(() => ''),+ api.getRunOutput(id).catch(() => '')+ ]);+ setExpandedDetails(prev => ({+ ...prev,+ [id]: { prompt, output }+ }));+ }+ };++ const handleContinue = (run) => {+ const details = expandedDetails[run.id] || {};+ navigate('/devtools/runner', {+ state: {+ continueFrom: {+ prompt: details.prompt || run.prompt,+ output: details.output || '',+ runId: run.id,+ providerId: run.providerId,+ providerName: run.providerName,+ model: run.model,+ workspacePath: run.workspacePath,+ workspaceName: run.workspaceName+ }+ }+ });+ };++ const handleResume = async (run, e) => {+ e.stopPropagation();+ // Fetch details if not already loaded+ let details = expandedDetails[run.id];+ if (!details) {+ const [prompt, output] = await Promise.all([+ api.getRunPrompt(run.id).catch(() => ''),+ api.getRunOutput(run.id).catch(() => '')+ ]);+ details = { prompt, output };+ }+ navigate('/devtools/runner', {+ state: {+ continueFrom: {+ prompt: details.prompt || run.prompt,+ output: details.output || '',+ runId: run.id,+ providerId: run.providerId,+ providerName: run.providerName,+ model: run.model,+ workspacePath: run.workspacePath,+ workspaceName: run.workspaceName,+ error: run.error,+ errorCategory: run.errorCategory,+ suggestedFix: run.suggestedFix,+ success: run.success+ }+ }+ });+ };++ const getExitCodeInfo = (exitCode) => {+ const codeInfo = {+ 1: { label: 'Error', description: 'Generic error - check the output for details' },+ 2: { label: 'Misuse', description: 'Incorrect command usage or invalid arguments' },+ 126: { label: 'Not Executable', description: 'Command found but not executable' },+ 127: { label: 'Not Found', description: 'Command not found - check if CLI is installed' },+ 128: { label: 'Invalid Exit', description: 'Invalid exit argument' },+ 130: { label: 'Interrupted', description: 'Process interrupted (Ctrl+C / SIGINT)' },+ 137: { label: 'Killed', description: 'Process killed (SIGKILL) - likely out of memory' },+ 143: { label: 'Terminated', description: 'Process terminated (SIGTERM) - likely hit timeout' }+ };+ return codeInfo[exitCode] || { label: 'Unknown', description: `Exit code ${exitCode}` };+ };++ if (loading) {+ return <div className="text-center py-8"><BrailleSpinner text="Loading runs history" /></div>;+ }++ const failedCount = runs.filter(r => r.success === false).length;++ const handleClearFailed = async () => {+ const result = await api.deleteFailedRuns().catch(() => null);+ if (result) {+ setRuns(prev => prev.filter(r => r.success !== false));+ }+ };++ return (+ <div className="space-y-4 lg:space-y-6">+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">+ <h1 className="text-lg sm:text-2xl font-bold text-white">AI Runs History</h1>+ {failedCount > 0 && (+ <button+ onClick={handleClearFailed}+ className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-error/20 hover:bg-port-error/30 text-port-error rounded-lg transition-colors self-end sm:self-auto"+ >+ <Trash2 size={14} />+ Clear Failed ({failedCount})+ </button>+ )}+ </div>++ {/* Source Filter */}+ <div className="flex flex-wrap gap-1.5 sm:gap-2">+ {[+ { value: 'all', label: 'All' },+ { value: 'devtools', label: 'DevTools' },+ { value: 'cos-agent', label: 'CoS' }+ ].map(filter => (+ <button+ key={filter.value}+ onClick={() => setSourceFilter(filter.value)}+ className={`px-3 py-1.5 sm:px-4 sm:py-2 rounded-lg text-xs sm:text-sm font-medium transition-colors ${+ sourceFilter === filter.value+ ? 'bg-port-accent text-white'+ : 'bg-port-card text-gray-400 hover:text-white border border-port-border'+ }`}+ >+ {filter.label}+ </button>+ ))}+ </div>++ {/* Status Filter */}+ <div className="flex flex-wrap gap-1.5 sm:gap-2">+ {[+ { value: 'all', label: 'All Status' },+ { value: 'success', label: 'Success' },+ { value: 'running', label: 'Running' },+ { value: 'failed', label: 'Failed' }+ ].map(filter => (+ <button+ key={filter.value}+ onClick={() => setStatusFilter(filter.value)}+ className={`px-3 py-1.5 sm:px-4 sm:py-2 rounded-lg text-xs sm:text-sm font-medium transition-colors ${+ statusFilter === filter.value+ ? 'bg-port-accent text-white'+ : 'bg-port-card text-gray-400 hover:text-white border border-port-border'+ }`}+ >+ {filter.label}+ </button>+ ))}+ </div>++ {/* Runs List */}+ <div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl overflow-hidden">+ {filteredRuns.length === 0 ? (+ <div className="text-center py-12 text-gray-500">+ {runs.length === 0 ? 'No AI runs yet' : 'No runs match the selected filters'}+ </div>+ ) : (+ <div className="divide-y divide-port-border">+ {filteredRuns.map(run => (+ <div key={run.id}>+ <div+ className="p-3 sm:p-4 hover:bg-port-border/20 cursor-pointer group"+ onClick={() => toggleExpand(run.id)}+ data-testid={`run-row-${run.id}`}+ >+ <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4">+ <div className="flex items-center gap-3 flex-1 min-w-0">+ <button className="text-gray-400 hover:text-white shrink-0">+ <span className={`inline-block transition-transform ${expandedId === run.id ? 'rotate-90' : ''}`}>▶</span>+ </button>+ <span className="text-xl shrink-0">🤖</span>+ <div className="flex-1 min-w-0">+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">+ <span className="font-medium text-white">{run.providerName}</span>+ <span className="text-gray-500 text-sm">{run.model}</span>+ {run.source === 'cos-agent' && (+ <span className="text-xs text-purple-400 bg-purple-500/10 px-2 py-0.5 rounded">+ CoS+ </span>+ )}+ {run.workspaceName && (+ <span className="text-xs text-port-accent bg-port-accent/10 px-2 py-0.5 rounded">+ {run.workspaceName}+ </span>+ )}+ {run.duration && (+ <span className="text-xs text-cyan-400 font-mono">{formatRuntime(run.duration)}</span>+ )}+ </div>+ <div className="text-xs text-gray-500 font-mono truncate mt-1">+ {run.prompt?.substring(0, 100)}{run.prompt?.length > 100 ? '...' : ''}+ </div>+ {/* Show error preview for failed runs in collapsed view */}+ {run.success === false && expandedId !== run.id && (+ <div className="text-xs text-port-error/80 font-mono truncate mt-1">+ ⚠ {run.error+ ? (() => {+ const firstLine = run.error.split('\n')[0] || '';+ return `${firstLine.substring(0, 80)}${firstLine.length > 80 ? '...' : ''}`;+ })()+ : run.errorCategory && run.errorCategory !== 'unknown'+ ? `${run.errorCategory}: ${run.suggestedFix || 'See details'}`+ : `${getExitCodeInfo(run.exitCode).label}: ${getExitCodeInfo(run.exitCode).description}`}+ </div>+ )}+ </div>+ </div>+ <div className="flex items-center gap-3 pl-8 sm:pl-0">+ <span className={`w-2 h-2 rounded-full shrink-0 ${run.success ? 'bg-port-success' : run.success === false ? 'bg-port-error' : 'bg-port-warning'}`} />+ <span className="text-sm text-gray-500 shrink-0">{formatTime(run.startTime)}</span>+ {run.success !== null && (+ <button+ onClick={(e) => handleResume(run, e)}+ className="p-1 text-gray-500 hover:text-port-accent transition-colors sm:opacity-0 sm:group-hover:opacity-100"+ title="Resume run"+ data-testid={`resume-run-${run.id}`}+ >+ <RotateCcw size={14} />+ </button>+ )}+ <button+ onClick={(e) => handleDelete(run.id, e)}+ className="p-1 text-gray-500 hover:text-port-error transition-colors sm:opacity-0 sm:group-hover:opacity-100"+ title="Delete run"+ data-testid={`delete-run-${run.id}`}+ >+ <Trash2 size={14} />+ </button>+ </div>+ </div>+ </div>++ {/* Expanded Details */}+ {expandedId === run.id && (+ <div className="px-4 pb-4 bg-port-bg border-t border-port-border">+ <div className="pt-4 space-y-4">+ {/* Execution ID */}+ <div className="mb-4">+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Execution ID</div>+ <div className="flex items-center gap-2">+ <code className="text-xs text-gray-400 font-mono select-all">{run.id}</code>+ <button+ onClick={(e) => {+ e.stopPropagation();+ navigator.clipboard.writeText(run.id);+ }}+ className="p-1 text-gray-500 hover:text-white transition-colors"+ title="Copy execution ID"+ >+ <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />+ </svg>+ </button>+ </div>+ </div>++ {/* Metadata Grid */}+ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4 text-sm">+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Started</div>+ <div className="text-gray-300">{new Date(run.startTime).toLocaleString()}</div>+ </div>+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Status</div>+ <div className={run.success ? 'text-port-success' : run.success === false ? 'text-port-error' : 'text-port-warning'}>+ {run.success ? 'Success' : run.success === false ? 'Failed' : 'Running'}+ </div>+ </div>+ {run.duration && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Duration</div>+ <div className="text-cyan-400 font-mono">{formatRuntime(run.duration)}</div>+ </div>+ )}+ {run.exitCode !== undefined && run.exitCode !== null && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Exit Code</div>+ <div className={`font-mono ${run.exitCode === 0 ? 'text-port-success' : 'text-port-error'}`}>+ {run.exitCode}+ </div>+ </div>+ )}+ {run.outputSize && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Output Size</div>+ <div className="text-gray-300 font-mono">{(run.outputSize / 1024).toFixed(1)} KB</div>+ </div>+ )}+ </div>++ {/* Prompt */}+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Prompt</div>+ <div className="bg-port-card border border-port-border rounded-lg p-3 max-h-48 overflow-auto">+ <pre className="text-sm text-gray-300 font-mono whitespace-pre-wrap break-all">+ {expandedDetails[run.id]?.prompt || run.prompt || 'Loading...'}+ </pre>+ </div>+ </div>++ {/* Output - show for all completed runs */}+ {run.success !== null && (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Output</div>+ <div className="bg-port-card border border-port-border rounded-lg p-3 max-h-64 overflow-auto">+ <pre className="text-xs text-gray-300 font-mono whitespace-pre-wrap break-all">+ {expandedDetails[run.id]?.output !== undefined+ ? (expandedDetails[run.id].output || '(no output)')+ : 'Loading output...'}+ </pre>+ </div>+ </div>+ )}++ {/* Error - show for failed runs with error message OR exit code */}+ {(run.error || (run.success === false && run.exitCode !== 0)) && (() => {+ const exitInfo = getExitCodeInfo(run.exitCode);+ return (+ <div>+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2 flex items-center gap-2">+ Error+ {run.exitCode !== undefined && run.exitCode !== null && run.exitCode !== 0 && (+ <span className="text-port-error/70">(exit code: {run.exitCode})</span>+ )}+ {run.errorCategory && run.errorCategory !== 'unknown' ? (+ <span className="px-1.5 py-0.5 bg-port-error/20 text-port-error/80 rounded text-xs">+ {run.errorCategory}+ </span>+ ) : run.exitCode !== 0 && exitInfo.label !== 'Unknown' && (+ <span className="px-1.5 py-0.5 bg-port-error/20 text-port-error/80 rounded text-xs">+ {exitInfo.label}+ </span>+ )}+ </div>+ <div className="bg-port-error/10 border border-port-error/30 rounded-lg p-3">+ <pre className="text-sm text-port-error font-mono whitespace-pre-wrap break-all">+ {run.error || exitInfo.description}+ </pre>+ </div>+ {/* Show additional error details if available and different from error */}+ {run.errorDetails && run.errorDetails !== run.error && (+ <div className="mt-2 bg-port-error/5 border border-port-error/20 rounded-lg p-3">+ <div className="text-xs text-gray-500 mb-1">Additional Details</div>+ <pre className="text-xs text-port-error/80 font-mono whitespace-pre-wrap break-all">+ {run.errorDetails}+ </pre>+ </div>+ )}+ {/* Show suggested fix if available, or fallback to exit code info */}+ {(run.suggestedFix || (!run.error && exitInfo.description)) && (+ <div className="mt-2 bg-port-warning/10 border border-port-warning/30 rounded-lg p-3">+ <div className="text-xs text-port-warning mb-1 font-medium">Suggested Fix</div>+ <div className="text-sm text-gray-300">+ {run.suggestedFix || 'Check the output above for specific error details. If the output is empty, the process may have been terminated before producing output.'}+ </div>+ </div>+ )}+ </div>+ );+ })()}++ {/* Continue Button */}+ {run.success && expandedDetails[run.id]?.output && (+ <div className="flex justify-end pt-2">+ <button+ onClick={() => handleContinue(run)}+ className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"+ data-testid="continue-conversation-btn"+ >+ <MessageSquarePlus size={16} />+ Continue Conversation+ </button>+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ );+}++export default RunsHistoryPage;diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsxindex 249efe5c1f..2fdc552d2b 100644--- a/client/src/pages/Settings.jsx+++ b/client/src/pages/Settings.jsx@@ -1,1011 +1,9 @@-import { useState, useEffect, useCallback, useRef, useMemo } from 'react';import { useParams, useNavigate } from 'react-router-dom';-import { Save, Plus, X, Eye, EyeOff, Trash2, Send, Container, HardDrive, Download, ArrowRightLeft, Wrench, RefreshCw, Square, RotateCw, Play, Image, Zap } from 'lucide-react';-import toast from '../components/ui/Toast';-import BrailleSpinner from '../components/BrailleSpinner';-import { formatBytes } from '../utils/formatters';-import {- getSettings, updateSettings, getTelegramStatus, updateTelegramConfig,- deleteTelegramConfig, testTelegram, updateTelegramForwardTypes, updateTelegramMethod,- getDatabaseStatus, switchDatabase, setupNativeDatabase, exportDatabase, fixDatabase,- syncDatabase, startDatabase, stopDatabase, destroyDatabase,- getImageGenStatus, registerTool, updateTool, getToolsList-} from '../services/api';-import socket from '../services/socket';--const NOTIFICATION_TYPES = [- { key: 'memory_approval', label: 'Memory Approvals' },- { key: 'task_approval', label: 'Task Approvals' },- { key: 'code_review', label: 'Code Reviews' },- { key: 'health_issue', label: 'Health Issues' },- { key: 'briefing_ready', label: 'Briefings' },- { key: 'autobiography_prompt', label: 'Autobiography Prompts' },- { key: 'plan_question', label: 'Plan Questions' }-];--function BackupTab() {- const [loading, setLoading] = useState(true);- const [saving, setSaving] = useState(false);- const [destPath, setDestPath] = useState('');- const [enabled, setEnabled] = useState(false);- const [cronExpression, setCronExpression] = useState('0 2 * * *');- const [excludePaths, setExcludePaths] = useState([]);- const [newExclude, setNewExclude] = useState('');-- useEffect(() => {- getSettings()- .then(settings => {- const backup = settings?.backup || {};- setDestPath(backup.destPath || '');- setEnabled(backup.enabled ?? false);- setCronExpression(backup.cronExpression || '0 2 * * *');- setExcludePaths(backup.excludePaths || []);- })- .catch(() => toast.error('Failed to load settings'))- .finally(() => setLoading(false));- }, []);-- const handleSave = async () => {- setSaving(true);- await updateSettings({ backup: { destPath, enabled, cronExpression, excludePaths } })- .then(() => toast.success('Settings saved'))- .catch(() => toast.error('Failed to save settings'))- .finally(() => setSaving(false));- };-- const addExclude = () => {- const trimmed = newExclude.trim();- if (!trimmed || excludePaths.includes(trimmed)) return;- setExcludePaths([...excludePaths, trimmed]);- setNewExclude('');- };-- const removeExclude = (index) => {- setExcludePaths(excludePaths.filter((_, i) => i !== index));- };-- if (loading) {- return <BrailleSpinner text="Loading backup settings" />;- }-- return (- <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-5">- <div className="space-y-1">- <label className="block text-sm text-gray-400">Destination Path</label>- <input- type="text"- value={destPath}- onChange={e => setDestPath(e.target.value)}- className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"- placeholder="/path/to/backups"- />- </div>-- <div className="flex items-center gap-3">- <label className="text-sm text-gray-400">Enabled</label>- <button- onClick={() => setEnabled(!enabled)}- className={`relative w-10 h-5 rounded-full transition-colors ${enabled ? 'bg-port-accent' : 'bg-port-border'}`}- >- <span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${enabled ? 'translate-x-5' : ''}`} />- </button>- </div>-- <div className="space-y-1">- <label className="block text-sm text-gray-400">Schedule (cron)</label>- <input- type="text"- value={cronExpression}- onChange={e => setCronExpression(e.target.value)}- className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"- placeholder="0 2 * * *"- />- <p className="text-xs text-gray-500">Default: 2:00 AM daily</p>- </div>-- <div className="space-y-2">- <label className="block text-sm text-gray-400">Exclude Paths</label>- <p className="text-xs text-gray-500">Directories/patterns to skip during backup (relative to data/)</p>- <div className="flex gap-2">- <input- type="text"- value={newExclude}- onChange={e => setNewExclude(e.target.value)}- onKeyDown={e => e.key === 'Enter' && addExclude()}- className="flex-1 bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"- placeholder="repos/"- />- <button- onClick={addExclude}- disabled={!newExclude.trim()}- className="px-3 py-2 bg-port-border hover:bg-port-border/70 text-white rounded-lg transition-colors disabled:opacity-50"- >- <Plus size={16} />- </button>- </div>- {excludePaths.length > 0 && (- <div className="flex flex-wrap gap-2 mt-2">- {excludePaths.map((path, i) => (- <span key={i} className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-port-bg border border-port-border rounded-lg text-sm text-gray-300">- <code className="text-xs">{path}</code>- <button onClick={() => removeExclude(i)} className="text-gray-500 hover:text-port-error transition-colors">- <X size={14} />- </button>- </span>- ))}- </div>- )}- </div>-- <button- onClick={handleSave}- disabled={saving}- className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"- >- {saving ? <BrailleSpinner /> : <Save size={16} />}- Save- </button>- </div>- );-}--function BackendCard({ label, icon: Icon, backend, isActive, dbStatus, runAction, setConfirmAction, actionInProgress, busy, exportDatabase }) {- const data = dbStatus?.[backend];- const isRunning = backend === 'docker' ? data?.containerRunning : data?.running;- const canStart = backend === 'docker'- ? data?.installed && data?.daemonRunning && !data?.containerRunning- : data?.configured && !data?.running;- const canDestroy = !isActive && !isRunning && (backend === 'docker' ? data?.installed : data?.configured);- const statusLabel = isRunning ? 'Running'- : (backend === 'docker' ? (data?.installed ? 'Stopped' : 'Not installed')- : (data?.configured ? 'Stopped' : data?.installed ? 'Not configured' : 'Not installed'));- const statusColor = isRunning ? 'bg-port-success' : (data?.installed || data?.configured) ? 'bg-port-warning' : 'bg-gray-600';- const displayLabel = backend === 'docker' ? 'Docker' : 'Native';- const activeLabel = backend === 'docker' ? 'Native' : 'Docker';-- const btnClass = 'flex items-center gap-1.5 px-2 py-1 text-xs font-medium rounded transition-colors disabled:opacity-50';-- return (- <div className="bg-port-bg border border-port-border rounded-lg p-3 space-y-2">- <div className="flex items-center justify-between">- <div className="flex items-center gap-2 text-sm text-gray-400">- <Icon size={14} />- {label}- </div>- <div className="flex items-center gap-1.5">- {isActive && (- <span className="text-xs px-1.5 py-0.5 bg-port-accent/20 text-port-accent rounded">Active</span>- )}- <span className={`w-2 h-2 rounded-full ${statusColor}`} />- </div>- </div>-- <div className="text-sm text-white">{statusLabel}</div>-- {/* Resource stats */}- {data?.stats && (- <div className="grid grid-cols-2 gap-x-4 gap-y-0.5 text-xs text-gray-400 pt-1 border-t border-port-border/50">- <span>CPU: <span className="text-gray-300">{data.stats.cpu}</span></span>- <span>Memory: <span className="text-gray-300">{data.stats.memUsage}</span></span>- <span>Mem%: <span className="text-gray-300">{data.stats.memPercent}</span></span>- <span>PIDs: <span className="text-gray-300">{data.stats.pids}</span></span>- {data.stats.netIO && <span>Net I/O: <span className="text-gray-300">{data.stats.netIO}</span></span>}- {data.stats.blockIO && <span>Block I/O: <span className="text-gray-300">{data.stats.blockIO}</span></span>}- </div>- )}- {data?.diskUsage && (- <div className="text-xs text-gray-400">- Disk: <span className="text-gray-300">{data.diskUsage}</span>- </div>- )}-- {/* Card actions */}- <div className="flex flex-wrap gap-1.5 pt-1 border-t border-port-border/50">- {/* Start / Stop */}- {isRunning && !isActive && (- <button- onClick={() => runAction(`stop-${backend}`, () => stopDatabase(backend), `${displayLabel} stopped`)}- disabled={busy}- className={`${btnClass} bg-port-border hover:bg-port-border/70 text-white`}- >- {actionInProgress === `stop-${backend}` ? <BrailleSpinner /> : <Square size={12} />}- Stop- </button>- )}- {canStart && (- <button- onClick={() => runAction(`start-${backend}`, () => startDatabase(backend), `${displayLabel} started`)}- disabled={busy}- className={`${btnClass} bg-port-success/20 hover:bg-port-success/30 text-port-success`}- >- {actionInProgress === `start-${backend}` ? <BrailleSpinner /> : <Play size={12} />}- Start- </button>- )}-- {/* Export/Backup from this backend */}- {isRunning && (- <button- onClick={() => runAction(`export-${backend}`, () => exportDatabase(backend), (r) => `Backed up to ${r.dumpFile}`)}- disabled={busy}- className={`${btnClass} bg-port-border hover:bg-port-border/70 text-white`}- title={`Export ${displayLabel} database to SQL dump`}- >- {actionInProgress === `export-${backend}` ? <BrailleSpinner /> : <Download size={12} />}- Backup- </button>- )}-- {/* Non-active backend actions */}- {!isActive && (data?.installed || data?.configured) && (- <>- {/* Migrate & switch to this backend */}- <button- onClick={() => setConfirmAction({- type: 'migrate',- label: `Migrate to ${displayLabel} and switch?`,- detail: `Exports data from ${activeLabel}, imports into ${displayLabel}, and makes ${displayLabel} the active backend.`,- action: () => runAction(`migrate-${backend}`, () => switchDatabase(backend, true), `Migrated to ${displayLabel}`)- })}- disabled={busy}- className={`${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent`}- >- <ArrowRightLeft size={12} />- Migrate to {displayLabel}- </button>-- {/* Switch without migration */}- <button- onClick={() => setConfirmAction({- type: 'switch',- label: `Switch to ${displayLabel} without migrating data?`,- action: () => runAction(`switch-${backend}`, () => switchDatabase(backend, false), `Switched to ${displayLabel}`)- })}- disabled={busy}- className={`${btnClass} bg-port-border hover:bg-port-border/70 text-white`}- >- <ArrowRightLeft size={12} />- Switch- </button>-- {/* Sync data from active into this backend */}- <button- onClick={() => setConfirmAction({- type: 'sync',- label: `Sync from ${activeLabel} to ${displayLabel}?`,- detail: `Copies data from the active ${activeLabel} database into ${displayLabel}. ${displayLabel} will be left in its current state (running or stopped).`,- action: () => runAction(`sync-${backend}`, syncDatabase, `Data synced from ${activeLabel} to ${displayLabel}`)- })}- disabled={busy}- className={`${btnClass} bg-port-border hover:bg-port-border/70 text-white`}- >- <RotateCw size={12} />- Sync from {activeLabel}- </button>-- {/* Destroy */}- {canDestroy && (- <button- onClick={() => setConfirmAction({- type: 'destroy',- label: `Destroy ${displayLabel} database and all its data?`,- detail: 'This permanently removes the database files. You can set it up again later.',- action: () => runAction(`destroy-${backend}`, () => destroyDatabase(backend), `${displayLabel} database destroyed`)- })}- disabled={busy}- className={`${btnClass} bg-port-error/20 hover:bg-port-error/30 text-port-error`}- >- <Trash2 size={12} />- Destroy- </button>- )}- </>- )}-- {/* Setup native (when not configured) */}- {backend === 'native' && !data?.configured && (- <button- onClick={() => runAction('setup', setupNativeDatabase, 'Native PostgreSQL installed and configured')}- disabled={busy}- className={`${btnClass} bg-port-border hover:bg-port-border/70 text-white`}- >- {actionInProgress === 'setup' ? <BrailleSpinner /> : <HardDrive size={12} />}- {data?.installed ? 'Setup' : 'Install'}- </button>- )}- </div>- </div>- );-}--function DatabaseTab() {- const [dbStatus, setDbStatus] = useState(null);- const [dbLoading, setDbLoading] = useState(true);- const [actionInProgress, setActionInProgress] = useState(null);- const [progressMsg, setProgressMsg] = useState('');- const [confirmAction, setConfirmAction] = useState(null);- const progressTimer = useRef(null);-- const loadStatus = useCallback(() => {- setDbLoading(true);- getDatabaseStatus()- .then(setDbStatus)- .catch(() => toast.error('Failed to load database status'))- .finally(() => setDbLoading(false));- }, []);-- useEffect(() => {- loadStatus();-- const handleProgress = (data) => {- clearTimeout(progressTimer.current);- setProgressMsg(data.message || '');- if (data.event === 'complete') {- progressTimer.current = setTimeout(() => setProgressMsg(''), 3000);- loadStatus();- }- if (data.event === 'error') {- progressTimer.current = setTimeout(() => setProgressMsg(''), 5000);- }- };-- socket.on('database:progress', handleProgress);- return () => {- socket.off('database:progress', handleProgress);- clearTimeout(progressTimer.current);- };- }, [loadStatus]);-- const runAction = useCallback((key, fn, successMsg) => {- setConfirmAction(null);- setActionInProgress(key);- fn()- .then((result) => {- if (successMsg) toast.success(typeof successMsg === 'function' ? successMsg(result) : successMsg);- loadStatus();- })- .catch(() => {})- .finally(() => setActionInProgress(null));- }, [loadStatus]);-- const busy = actionInProgress != null;-- return (- <div className="space-y-4">- <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-5">- {/* Connection summary */}- <div className="flex items-center justify-between">- <div className="flex items-center gap-3">- <span className={`w-2 h-2 rounded-full ${dbStatus?.connected ? 'bg-port-success' : 'bg-port-error'}`} />- <span className="text-sm text-gray-300">- {dbStatus?.connected ? 'Connected' : dbStatus ? 'Disconnected' : ''}- {dbStatus?.memoryCount != null && ` \u2014 ${dbStatus.memoryCount.toLocaleString()} memories`}- {dbStatus?.dbBytes != null && ` \u2014 ${formatBytes(dbStatus.dbBytes)}`}- {dbStatus?.tableCount != null && ` (${dbStatus.tableCount} tables)`}- </span>- </div>- <button- onClick={loadStatus}- disabled={dbLoading}- className="p-1.5 text-gray-400 hover:text-white transition-colors"- title="Refresh status"- >- <RefreshCw size={14} className={dbLoading ? 'animate-spin' : ''} />- </button>- </div>-- {dbLoading && !dbStatus ? (- <BrailleSpinner text="Loading database status" />- ) : dbStatus ? (- <>- {/* Backend cards with inline actions */}- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">- <BackendCard- label="Docker" icon={Container} backend="docker"- isActive={dbStatus.mode === 'docker'} dbStatus={dbStatus}- runAction={runAction} setConfirmAction={setConfirmAction}- actionInProgress={actionInProgress} busy={busy}- exportDatabase={exportDatabase}- />- <BackendCard- label="Native" icon={HardDrive} backend="native"- isActive={dbStatus.mode === 'native'} dbStatus={dbStatus}- runAction={runAction} setConfirmAction={setConfirmAction}- actionInProgress={actionInProgress} busy={busy}- exportDatabase={exportDatabase}- />- </div>-- {/* Progress indicator */}- {progressMsg && (- <div className="flex items-center gap-2 text-sm text-port-accent bg-port-accent/10 border border-port-accent/20 rounded-lg px-3 py-2">- <BrailleSpinner />- {progressMsg}- </div>- )}-- {/* Confirmation dialog */}- {confirmAction && (- <div className={`bg-port-bg border rounded-lg p-4 space-y-3 ${- confirmAction.type === 'destroy' ? 'border-port-error/30' : 'border-port-warning/30'- }`}>- <p className="text-sm text-white">{confirmAction.label}</p>- {confirmAction.detail && (- <p className="text-xs text-gray-400">{confirmAction.detail}</p>- )}- <div className="flex items-center gap-2">- <button- onClick={confirmAction.action}- disabled={busy}- className={`flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-lg transition-colors disabled:opacity-50 ${- confirmAction.type === 'destroy'- ? 'bg-port-error/20 hover:bg-port-error/30 text-port-error'- : 'bg-port-warning/20 hover:bg-port-warning/30 text-port-warning'- }`}- >- {busy ? <BrailleSpinner /> : <ArrowRightLeft size={14} />}- Confirm- </button>- <button- onClick={() => setConfirmAction(null)}- className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors"- >- Cancel- </button>- </div>- </div>- )}-- {/* Global actions */}- {!dbStatus.connected && (- <div className="flex flex-wrap items-center gap-2">- <button- onClick={() => runAction('fix', fixDatabase, 'Database fixed')}- disabled={busy}- className="flex items-center gap-2 px-3 py-1.5 bg-port-error/20 hover:bg-port-error/30 text-port-error text-sm font-medium rounded-lg transition-colors disabled:opacity-50"- title="Fix stale PID files and other issues"- >- {actionInProgress === 'fix' ? <BrailleSpinner /> : <Wrench size={14} />}- Fix- </button>- </div>- )}- </>- ) : (- <p className="text-sm text-gray-500">Unable to load database status</p>- )}- </div>- </div>- );-}--function TelegramTab() {- const [loading, setLoading] = useState(true);- const [method, setMethod] = useState('manual');- const [switching, setSwitching] = useState(false);- const [tgToken, setTgToken] = useState('');- const [tgChatId, setTgChatId] = useState('');- const [tgShowToken, setTgShowToken] = useState(false);- const [tgStatus, setTgStatus] = useState(null);- const [tgSaving, setTgSaving] = useState(false);- const [tgTesting, setTgTesting] = useState(false);- const [tgDisconnecting, setTgDisconnecting] = useState(false);- const [tgForwardTypes, setTgForwardTypes] = useState([]);-- useEffect(() => {- Promise.all([- getSettings(),- getTelegramStatus().catch(() => null)- ]).then(([settings, status]) => {- if (status) {- setTgStatus(status);- setMethod(status.method || 'manual');- setTgChatId(settings?.telegram?.chatId || '');- setTgForwardTypes(status.forwardTypes || []);- }- }).catch(() => toast.error('Failed to load Telegram settings'))- .finally(() => setLoading(false));- }, []);-- const handleMethodChange = (newMethod) => {- setSwitching(true);- updateTelegramMethod(newMethod)- .then(status => {- setMethod(newMethod);- setTgStatus(status);- toast.success(newMethod === 'mcp-bridge'- ? 'Switched to Claude MCP Bridge'- : 'Switched to Manual Bot');- })- .catch(() => toast.error('Failed to switch method'))- .finally(() => setSwitching(false));- };-- const handleTelegramSave = () => {- if (!tgToken && !tgStatus?.hasToken) {- toast.error('Bot token is required');- return;- }- setTgSaving(true);- updateTelegramConfig({ token: tgToken, chatId: tgChatId })- .then(status => {- setTgStatus(status);- toast.success(tgChatId- ? 'Telegram connected — check your chat for a test message'- : 'Bot connected — now message your bot /start to get your Chat ID');- })- .catch(() => toast.error('Failed to configure Telegram'))- .finally(() => setTgSaving(false));- };-- const handleTelegramTest = () => {- setTgTesting(true);- testTelegram()- .then(() => toast.success('Test message sent'))- .catch(() => toast.error('Failed to send test message'))- .finally(() => setTgTesting(false));- };-- const handleTelegramDisconnect = () => {- setTgDisconnecting(true);- deleteTelegramConfig()- .then(() => {- setTgStatus(null);- setTgToken('');- setTgChatId('');- setTgForwardTypes([]);- toast.success('Telegram disconnected');- })- .catch(() => toast.error('Failed to disconnect'))- .finally(() => setTgDisconnecting(false));- };-- const toggleForwardType = (type) => {- const updated = tgForwardTypes.includes(type)- ? tgForwardTypes.filter(t => t !== type)- : [...tgForwardTypes, type];- setTgForwardTypes(updated);- updateTelegramForwardTypes(updated).catch(() => toast.error('Failed to update forward types'));- };-- if (loading) {- return <BrailleSpinner text="Loading Telegram settings" />;- }-- return (- <div className="space-y-4">- {/* Method Selector */}- <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4">- <label className="block text-sm text-gray-400">Integration Method</label>- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">- <button- onClick={() => method !== 'manual' && handleMethodChange('manual')}- disabled={switching}- className={`p-4 rounded-lg border text-left transition-colors ${- method === 'manual'- ? 'border-port-accent bg-port-accent/10'- : 'border-port-border bg-port-bg hover:border-port-accent/50'- }`}- >- <div className="text-sm font-medium text-white">Manual Bot</div>- <div className="text-xs text-gray-500 mt-1">- Self-hosted polling bot with /status, /goals, /checkin commands. Requires bot token and chat ID.- </div>- </button>- <button- onClick={() => method !== 'mcp-bridge' && handleMethodChange('mcp-bridge')}- disabled={switching}- className={`p-4 rounded-lg border text-left transition-colors ${- method === 'mcp-bridge'- ? 'border-port-accent bg-port-accent/10'- : 'border-port-border bg-port-bg hover:border-port-accent/50'- }`}- >- <div className="text-sm font-medium text-white">Claude MCP Bridge</div>- <div className="text-xs text-gray-500 mt-1">- Uses Claude Code's Telegram plugin. Natural language inbound, PortOS notifications outbound.- </div>- </button>- </div>- {switching && <BrailleSpinner text="Switching..." />}- </div>-- {/* Method-specific config */}- {method === 'manual' ? (- <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-5">- <div className="flex items-center justify-between">- <div className="text-sm">- {tgStatus?.connected && (- <span className="flex items-center gap-2 text-port-success">- <span className="w-2 h-2 rounded-full bg-port-success" />- @{tgStatus.botUsername}- </span>- )}- {tgStatus && !tgStatus.connected && tgStatus.hasToken && (- <span className="flex items-center gap-2 text-port-error">- <span className="w-2 h-2 rounded-full bg-port-error" />- Disconnected- </span>- )}- </div>- </div>-- <div className="space-y-1">- <label className="block text-sm text-gray-400">Bot Token</label>- <div className="flex gap-2">- <input- type={tgShowToken ? 'text' : 'password'}- value={tgToken}- onChange={e => setTgToken(e.target.value)}- className="flex-1 bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"- placeholder={tgStatus?.hasToken ? '••••••••••• (configured)' : 'Paste bot token from @BotFather'}- />- <button- onClick={() => setTgShowToken(!tgShowToken)}- className="px-3 py-2 bg-port-border hover:bg-port-border/70 text-white rounded-lg transition-colors"- >- {tgShowToken ? <EyeOff size={16} /> : <Eye size={16} />}- </button>- </div>- </div>-- <div className="space-y-1">- <label className="block text-sm text-gray-400">Chat ID</label>- <input- type="text"- value={tgChatId}- onChange={e => setTgChatId(e.target.value)}- className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"- placeholder="Message your bot /start to get your chat ID"- />- </div>-- <p className="text-xs text-gray-500">- 1. Message <code>@BotFather</code> on Telegram, send <code>/newbot</code>, copy the token, paste above, click Save.- 2. Message your bot <code>/start</code> — it will reply with your Chat ID.- 3. Paste the Chat ID above and click Save & Test.- </p>-- <div className="flex items-center gap-3">- <button- onClick={handleTelegramSave}- disabled={tgSaving || (!tgToken && !tgStatus?.hasToken)}- className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"- >- {tgSaving ? <BrailleSpinner /> : <Save size={16} />}- {tgStatus?.connected && tgChatId ? 'Save & Test' : 'Save'}- </button>- {tgStatus?.connected && (- <button- onClick={handleTelegramTest}- disabled={tgTesting}- className="flex items-center gap-2 px-4 py-2 bg-port-border hover:bg-port-border/70 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"- >- {tgTesting ? <BrailleSpinner /> : <Send size={16} />}- Send Test- </button>- )}- {(tgStatus?.hasToken || tgStatus?.hasChatId) && (- <button- onClick={handleTelegramDisconnect}- disabled={tgDisconnecting}- className="flex items-center gap-2 px-4 py-2 bg-port-error/20 hover:bg-port-error/30 text-port-error text-sm font-medium rounded-lg transition-colors disabled:opacity-50"- >- {tgDisconnecting ? <BrailleSpinner /> : <Trash2 size={16} />}- Disconnect- </button>- )}- </div>- </div>- ) : (- <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-5">- <div className="flex items-center justify-between">- <div className="text-sm">- {tgStatus?.connected ? (- <span className="flex items-center gap-2 text-port-success">- <span className="w-2 h-2 rounded-full bg-port-success" />- @{tgStatus.botUsername} → {tgStatus.chatId}- </span>- ) : (- <span className="flex items-center gap-2 text-port-warning">- <span className="w-2 h-2 rounded-full bg-port-warning" />- Not connected- </span>- )}- </div>- </div>-- <div className="text-xs text-gray-500 space-y-2">- <p>- The MCP Bridge reads config from Claude Code's Telegram plugin at <code>~/.claude/channels/telegram/</code>.- Bot token comes from <code>.env</code>, chat ID from the first entry in <code>access.json</code> allowlist.- </p>- <p>- <b>Outbound:</b> PortOS sends notifications via direct Telegram Bot API calls (no polling conflict).- </p>- <p>- <b>Inbound:</b> Messages are handled by Claude Code via the MCP plugin — natural language instead of rigid commands.- </p>- {!tgStatus?.connected && (- <p className="text-port-warning">- Set up the Claude Code Telegram plugin first: run <code>/telegram:configure</code> in Claude Code, then <code>/telegram:access pair <code></code> to approve your chat.- </p>- )}- </div>-- {tgStatus?.connected && (- <div className="flex items-center gap-3">- <button- onClick={handleTelegramTest}- disabled={tgTesting}- className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"- >- {tgTesting ? <BrailleSpinner /> : <Send size={16} />}- Send Test- </button>- </div>- )}- </div>- )}-- {/* Forward types (shared between both methods) */}- {tgStatus?.connected && (- <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-2">- <label className="block text-sm text-gray-400">Forward Notification Types</label>- <p className="text-xs text-gray-500">When all are unchecked, all types are forwarded</p>- <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">- {NOTIFICATION_TYPES.map(({ key, label }) => (- <label key={key} className="flex items-center gap-2 text-sm text-gray-300 cursor-pointer">- <input- type="checkbox"- checked={tgForwardTypes.includes(key)}- onChange={() => toggleForwardType(key)}- className="rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"- />- {label}- </label>- ))}- </div>- </div>- )}- </div>- );-}--function GeneralTab() {- const [loading, setLoading] = useState(true);- const [timezone, setTimezone] = useState('');- const [saving, setSaving] = useState(false);- const detectedTz = Intl.DateTimeFormat().resolvedOptions().timeZone;- const allTimezones = useMemo(() => Intl.supportedValuesOf?.('timeZone') ?? [], []);-- useEffect(() => {- getSettings()- .then(settings => setTimezone(settings?.timezone || ''))- .catch(() => toast.error('Failed to load settings'))- .finally(() => setLoading(false));- }, []);-- const handleSave = async (tz) => {- const tzToSave = tz || detectedTz;- if (!tzToSave) {- toast.error('Timezone is required.');- return;- }-- // Validate timezone string- let isValid = false;- if (allTimezones.length > 0) {- isValid = allTimezones.includes(tzToSave);- } else {- try {- new Intl.DateTimeFormat('en-US', { timeZone: tzToSave });- isValid = true;- } catch { isValid = false; }- }- if (!isValid) {- toast.error('Invalid timezone. Please select a valid IANA timezone.');- return;- }-- setSaving(true);- await updateSettings({ timezone: tzToSave })- .then(() => {- setTimezone(tzToSave);- toast.success(`Timezone set to ${tzToSave}`);- })- .catch(() => toast.error('Failed to save timezone'))- .finally(() => setSaving(false));- };-- if (loading) return <BrailleSpinner />;-- return (- <div className="space-y-6">- <div className="bg-port-card border border-port-border rounded-lg p-6">- <h3 className="text-lg font-semibold text-white mb-4">Timezone</h3>- <p className="text-sm text-gray-400 mb-4">- Used for job scheduling (cron expressions & scheduled times) and briefing dates.- </p>- <div className="flex items-center gap-3">- <input- type="text"- value={timezone}- onChange={e => setTimezone(e.target.value)}- placeholder={detectedTz}- className="flex-1 max-w-xs px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"- list="tz-list"- />- <button- onClick={() => handleSave(timezone)}- disabled={saving}- className="px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-50"- >- <Save size={14} className="inline mr-1" />- {saving ? 'Saving...' : 'Save'}- </button>- {!timezone && (- <button- onClick={() => handleSave(detectedTz)}- disabled={saving}- className="px-3 py-2 text-sm text-gray-400 hover:text-white transition-colors"- >- Use detected: {detectedTz}- </button>- )}- </div>- {timezone && timezone !== detectedTz && (- <p className="text-xs text-gray-500 mt-2">- Browser detected: {detectedTz}- </p>- )}- <datalist id="tz-list">- {allTimezones.map(tz => (- <option key={tz} value={tz} />- ))}- </datalist>- </div>- </div>- );-}--const SDAPI_TOOL_ID = 'sdapi';--function ImageGenTab() {- const [loading, setLoading] = useState(true);- const [saving, setSaving] = useState(false);- const [sdapiUrl, setSdapiUrl] = useState('');- const [savedUrl, setSavedUrl] = useState('');- const [status, setStatus] = useState(null);- const [checking, setChecking] = useState(false);- const [toolRegistered, setToolRegistered] = useState(false);-- useEffect(() => {- Promise.all([getSettings(), getToolsList()])- .then(([settings, tools]) => {- const rawUrl = settings?.imageGen?.sdapiUrl || '';- const normalizedUrl = rawUrl.trim().replace(/\/+$/, '');- setSdapiUrl(normalizedUrl);- setSavedUrl(normalizedUrl);- setToolRegistered(tools.some(t => t.id === SDAPI_TOOL_ID));- })- .catch(() => toast.error('Failed to load image gen settings'))- .finally(() => setLoading(false));- }, []);-- const checkStatus = useCallback(() => {- setChecking(true);- getImageGenStatus()- .then(setStatus)- .catch(() => setStatus({ connected: false, reason: 'Check failed' }))- .finally(() => setChecking(false));- }, []);-- const handleSave = async () => {- setSaving(true);- const url = sdapiUrl.trim().replace(/\/+$/, '') || undefined;-- let settingsSaved = false;- await updateSettings({ imageGen: { sdapiUrl: url } })- .then(() => { settingsSaved = true; setSavedUrl(url || ''); toast.success('Image gen settings saved'); })- .catch(() => toast.error('Failed to save settings'));-- if (!settingsSaved) {- setSaving(false);- return;- }-- // Register or update the tool in the CoS tools registry- const toolData = {- name: 'Stable Diffusion',- category: 'image-generation',- description: 'Generate images via Stable Diffusion API (AUTOMATIC1111 / Forge WebUI)',- enabled: !!url,- config: { sdapiUrl: url },- promptHints: 'Use POST /api/image-gen/generate with { prompt, negativePrompt, width, height, steps, cfgScale }. Use POST /api/image-gen/avatar for character portraits.'- };- if (toolRegistered) {- await updateTool(SDAPI_TOOL_ID, toolData).catch(() => {- toast.error('Failed to update CoS tools registry');- });- } else if (url) {- await registerTool({ id: SDAPI_TOOL_ID, ...toolData })- .then(() => setToolRegistered(true))- .catch(() => {- toast.error('Failed to register in CoS tools registry');- });- }-- setSaving(false);- };-- if (loading) return <BrailleSpinner text="Loading image gen settings" />;-- return (- <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-5">- <div className="flex items-center gap-2 text-white">- <Image size={18} />- <h2 className="text-lg font-semibold">Stable Diffusion API</h2>- </div>-- <div className="space-y-1">- <label className="block text-sm text-gray-400">API URL</label>- <p className="text-xs text-gray-500 mb-1">- Base URL for AUTOMATIC1111 / Forge WebUI (e.g. http://localhost:7860)- </p>- <input- type="text"- value={sdapiUrl}- onChange={e => setSdapiUrl(e.target.value)}- className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"- placeholder="http://localhost:7860"- />- </div>-- <div className="flex items-center gap-3">- <button- onClick={handleSave}- disabled={saving}- className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white text-sm rounded-lg transition-colors disabled:opacity-50"- >- {saving ? <BrailleSpinner /> : <Save size={14} />}- Save- </button>-- <button- onClick={checkStatus}- disabled={checking || !sdapiUrl.trim() || sdapiUrl.trim().replace(/\/+$/, '') !== savedUrl}- className="flex items-center gap-2 px-4 py-2 bg-port-border hover:bg-port-border/70 text-white text-sm rounded-lg transition-colors disabled:opacity-50"- title={sdapiUrl.trim().replace(/\/+$/, '') !== savedUrl ? 'Save settings first to test' : 'Test connection to SD API'}- >- {checking ? <BrailleSpinner /> : <Zap size={14} />}- Test Connection- </button>- </div>-- {status && (- <div className={`flex items-center gap-2 text-sm ${status.connected ? 'text-port-success' : 'text-port-error'}`}>- <span className={`w-2 h-2 rounded-full ${status.connected ? 'bg-port-success' : 'bg-port-error'}`} />- {status.connected ? `Connected — model: ${status.model}` : status.reason || 'Not connected'}- </div>- )}-- <div className="border-t border-port-border pt-4 space-y-2">- <h3 className="text-sm font-medium text-gray-300">CoS Integration</h3>- <p className="text-xs text-gray-500">- When configured, this tool is registered with the CoS tools registry. Agents can use it to generate- images for briefings, character avatars, and other visual content. Images are stored in <code className="text-gray-400">./data/images/</code>.- </p>- {toolRegistered && (- <div className="flex items-center gap-2 text-xs text-port-success">- <Wrench size={12} />- Registered as CoS tool- </div>- )}- </div>- </div>- );-}+import { BackupTab } from '../components/settings/BackupTab';+import { DatabaseTab } from '../components/settings/DatabaseTab';+import { TelegramTab } from '../components/settings/TelegramTab';+import { GeneralTab } from '../components/settings/GeneralTab';+import { ImageGenTab } from '../components/settings/ImageGenTab';const TABS = [{ id: 'general', label: 'General' },diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsxnew file mode 100644index 0000000000..60ed1b786d--- /dev/null+++ b/client/src/pages/UsagePage.jsx@@ -0,0 +1,165 @@+import { useState, useEffect } from 'react';+import { RefreshCw } from 'lucide-react';+import * as api from '../services/api';+import BrailleSpinner from '../components/BrailleSpinner';++export function UsagePage() {+ const [usage, setUsage] = useState(null);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ loadUsage();+ }, []);++ const loadUsage = async () => {+ setLoading(true);+ const data = await api.getUsage().catch(() => null);+ setUsage(data);+ setLoading(false);+ };++ const formatNumber = (num) => {+ if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`;+ if (num >= 1000) return `${(num / 1000).toFixed(1)}K`;+ return String(num);+ };++ if (loading) {+ return <div className="text-center py-8"><BrailleSpinner text="Loading usage data" /></div>;+ }++ if (!usage) {+ return <div className="text-center py-8 text-gray-500">No usage data available</div>;+ }++ const maxActivity = Math.max(...(usage.last7Days?.map(d => d.sessions) || [1]));++ return (+ <div className="space-y-6">+ <h1 className="text-2xl font-bold text-white">Usage Metrics</h1>++ {/* Summary Stats */}+ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4">+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 text-center">+ <div className="text-xl sm:text-2xl font-bold text-white">{formatNumber(usage.totalSessions)}</div>+ <div className="text-xs sm:text-sm text-gray-400">Sessions</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 text-center">+ <div className="text-xl sm:text-2xl font-bold text-white">{formatNumber(usage.totalMessages)}</div>+ <div className="text-xs sm:text-sm text-gray-400">Messages</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 text-center">+ <div className="text-xl sm:text-2xl font-bold text-white">{formatNumber(usage.totalToolCalls)}</div>+ <div className="text-xs sm:text-sm text-gray-400">Tool Calls</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 text-center">+ <div className="text-xl sm:text-2xl font-bold text-white">{formatNumber(usage.totalTokens?.input + usage.totalTokens?.output)}</div>+ <div className="text-xs sm:text-sm text-gray-400">Tokens</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4 text-center col-span-2 sm:col-span-1">+ <div className="text-xl sm:text-2xl font-bold text-port-success">${usage.estimatedCost?.toFixed(2)}</div>+ <div className="text-xs sm:text-sm text-gray-400">Est. Cost</div>+ </div>+ </div>++ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6">+ {/* 7-Day Activity */}+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4">+ <h3 className="text-sm font-medium text-gray-400 mb-3 sm:mb-4">Last 7 Days</h3>+ <div className="flex items-end gap-1 sm:gap-2 h-24 sm:h-32">+ {usage.last7Days?.map((day, i) => (+ <div key={i} className="flex-1 flex flex-col items-center">+ <div+ className="w-full bg-port-accent/60 rounded-t"+ style={{ height: `${(day.sessions / maxActivity) * 100}%`, minHeight: day.sessions > 0 ? 4 : 0 }}+ />+ <div className="text-[10px] sm:text-xs text-gray-500 mt-1 sm:mt-2">{day.label}</div>+ <div className="text-[10px] sm:text-xs text-gray-400">{day.sessions}</div>+ </div>+ ))}+ </div>+ </div>++ {/* Hourly Distribution */}+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4">+ <h3 className="text-sm font-medium text-gray-400 mb-3 sm:mb-4">Hourly Distribution</h3>+ <div className="flex items-end gap-0.5 h-24 sm:h-32">+ {usage.hourlyActivity?.map((count, hour) => {+ const maxHour = Math.max(...usage.hourlyActivity);+ return (+ <div key={hour} className="flex-1 flex flex-col items-center">+ <div+ className="w-full bg-port-accent/40 rounded-t"+ style={{ height: `${(count / (maxHour || 1)) * 100}%`, minHeight: count > 0 ? 2 : 0 }}+ title={`${hour}:00 - ${count} sessions`}+ />+ </div>+ );+ })}+ </div>+ <div className="flex justify-between text-[10px] sm:text-xs text-gray-500 mt-1 sm:mt-2">+ <span>12am</span>+ <span>6am</span>+ <span>12pm</span>+ <span>6pm</span>+ <span>12am</span>+ </div>+ </div>+ </div>++ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6">+ {/* Top Providers */}+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4">+ <h3 className="text-sm font-medium text-gray-400 mb-2 sm:mb-3">Top Providers</h3>+ <div className="space-y-1 sm:space-y-2">+ {usage.topProviders?.map((provider, i) => (+ <div key={i} className="flex flex-col sm:flex-row sm:items-center sm:justify-between py-2 border-b border-port-border last:border-0 gap-1 sm:gap-0">+ <span className="text-white text-sm sm:text-base">{provider.name}</span>+ <div className="text-xs sm:text-sm text-gray-400">+ <span>{provider.sessions} sessions</span>+ <span className="mx-1 sm:mx-2">•</span>+ <span>{formatNumber(provider.tokens)} tokens</span>+ </div>+ </div>+ ))}+ {(!usage.topProviders || usage.topProviders.length === 0) && (+ <div className="text-gray-500 text-sm">No provider data</div>+ )}+ </div>+ </div>++ {/* Top Models */}+ <div className="bg-port-card border border-port-border rounded-xl p-3 sm:p-4">+ <h3 className="text-sm font-medium text-gray-400 mb-2 sm:mb-3">Top Models</h3>+ <div className="space-y-1 sm:space-y-2">+ {usage.topModels?.map((model, i) => (+ <div key={i} className="flex flex-col sm:flex-row sm:items-center sm:justify-between py-2 border-b border-port-border last:border-0 gap-1 sm:gap-0">+ <span className="text-white font-mono text-xs sm:text-sm truncate max-w-[200px] sm:max-w-none">{model.model}</span>+ <div className="text-xs sm:text-sm text-gray-400">+ <span>{model.sessions} sessions</span>+ <span className="mx-1 sm:mx-2">•</span>+ <span>{formatNumber(model.tokens)} tokens</span>+ </div>+ </div>+ ))}+ {(!usage.topModels || usage.topModels.length === 0) && (+ <div className="text-gray-500 text-sm">No model data</div>+ )}+ </div>+ </div>+ </div>++ {/* Refresh button */}+ <div className="flex justify-end">+ <button+ onClick={loadUsage}+ className="flex items-center gap-2 px-4 py-2 text-gray-400 hover:text-white"+ >+ <RefreshCw size={16} /> Refresh+ </button>+ </div>+ </div>+ );+}++export default UsagePage;diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 83d2c0ebf5..e08d1c9402 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -527,7 +527,7 @@ export async function spawnAgentForTask(task) {// Use CoS Runner if available, otherwise spawn directlyif (useRunner) {- return spawnViaRunner(agentId, task, prompt, workspacePath, selectedModel, provider, runId, cliConfig, toolExecution.id, laneName);+ return spawnViaRunner(agentId, task, { prompt, workspacePath, model: selectedModel, provider, runId, cliConfig, executionId: toolExecution.id, laneName });}// Direct spawn mode (fallback)@@ -571,7 +571,8 @@ export async function waitForRunnerStability() {/*** Spawn agent via CoS Runner (isolated PM2 process).*/-export async function spawnViaRunner(agentId, task, prompt, workspacePath, model, provider, runId, cliConfig, executionId, laneName) {+export async function spawnViaRunner(agentId, task, opts) {+ const { prompt, workspacePath, model, provider, runId, cliConfig, executionId, laneName } = opts;// Wait for runner to be stable to prevent orphaned agents during rolling restartsawait waitForRunnerStability();diff --git a/server/services/cos.js b/server/services/cos.jsindex b64514a8f6..48702df2f1 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -997,7 +997,7 @@ async function queueEligibleImprovementTasks(state, cosTaskData) {}// Generate task description- const taskDesc = getAppImprovementTaskDescription(nextType, app);+ const taskDesc = getTaskDescription(nextType, app.name);if (!taskDesc) continue;// Add to COS-TASKS.md@@ -1025,9 +1025,31 @@ async function queueEligibleImprovementTasks(state, cosTaskData) {}/**- * Get task description for a self-improvement type+ * Get task description for a self-improvement or app improvement type.+ * When appName is provided, returns app-scoped descriptions; otherwise returns PortOS self-improvement descriptions.*/-function getSelfImprovementTaskDescription(taskType) {+function getTaskDescription(taskType, appName) {+ if (appName) {+ const descriptions = {+ 'security': `Security audit for ${appName}: check for vulnerabilities`,+ 'code-quality': `Code quality review for ${appName}: DRY violations, dead code`,+ 'test-coverage': `Add missing tests for ${appName}`,+ 'performance': `Performance optimization for ${appName}`,+ 'accessibility': `Accessibility audit for ${appName}`,+ 'console-errors': `Fix console errors in ${appName}`,+ 'dependency-updates': `Update dependencies for ${appName}`,+ 'documentation': `Update documentation for ${appName}`,+ 'error-handling': `Improve error handling in ${appName}`,+ 'typing': `Add/fix TypeScript types in ${appName}`,+ 'ui-bugs': `Review UI for visual bugs in ${appName}`,+ 'mobile-responsive': `Check mobile responsiveness of ${appName}`,+ 'feature-ideas': `Implement a feature idea for ${appName} aligned with GOALS.md and PLAN.md (worktree+PR)`,+ 'release-check': `Verify release readiness for ${appName}`,+ 'jira-sprint-manager': `Triage and implement JIRA sprint tickets for ${appName} (worktree+PR)`,+ 'jira-status-report': `Generate JIRA weekly status report for ${appName}`+ };+ return descriptions[taskType] ?? null;+ }const descriptions = {'ui-bugs': 'Review UI for visual bugs, layout issues, and UX improvements','mobile-responsive': 'Check mobile responsiveness and fix layout issues on smaller screens',@@ -1046,32 +1068,7 @@ function getSelfImprovementTaskDescription(taskType) {'jira-sprint-manager': 'Triage and implement JIRA sprint tickets (worktree+PR)','jira-status-report': 'Generate JIRA weekly status report'};- return descriptions[taskType] || null;-}--/**- * Get task description for an app improvement type- */-function getAppImprovementTaskDescription(taskType, app) {- const descriptions = {- 'security': `Security audit for ${app.name}: check for vulnerabilities`,- 'code-quality': `Code quality review for ${app.name}: DRY violations, dead code`,- 'test-coverage': `Add missing tests for ${app.name}`,- 'performance': `Performance optimization for ${app.name}`,- 'accessibility': `Accessibility audit for ${app.name}`,- 'console-errors': `Fix console errors in ${app.name}`,- 'dependency-updates': `Update dependencies for ${app.name}`,- 'documentation': `Update documentation for ${app.name}`,- 'error-handling': `Improve error handling in ${app.name}`,- 'typing': `Add/fix TypeScript types in ${app.name}`,- 'ui-bugs': `Review UI for visual bugs in ${app.name}`,- 'mobile-responsive': `Check mobile responsiveness of ${app.name}`,- 'feature-ideas': `Implement a feature idea for ${app.name} aligned with GOALS.md and PLAN.md (worktree+PR)`,- 'release-check': `Verify release readiness for ${app.name}`,- 'jira-sprint-manager': `Triage and implement JIRA sprint tickets for ${app.name} (worktree+PR)`,- 'jira-status-report': `Generate JIRA weekly status report for ${app.name}`- };- return descriptions[taskType] || null;+ return descriptions[taskType] ?? null;}// Unified improvement task types (rotates through these)@@ -2995,15 +2992,21 @@ async function init() {// Autonomous job lifecycle → re-register/cancel individual job timerscosEvents.on('jobs:toggled', async ({ id }) => {- if (isDaemonRunning()) await registerSingleJobSchedule(id);+ if (isDaemonRunning()) await registerSingleJobSchedule(id).catch(err =>+ console.error(`❌ Failed to register job schedule on toggle for ${id}: ${err.message}`)+ );});cosEvents.on('jobs:updated', async ({ id }) => {- if (isDaemonRunning()) await registerSingleJobSchedule(id);+ if (isDaemonRunning()) await registerSingleJobSchedule(id).catch(err =>+ console.error(`❌ Failed to register job schedule on update for ${id}: ${err.message}`)+ );});cosEvents.on('jobs:created', async ({ id }) => {- if (isDaemonRunning()) await registerSingleJobSchedule(id);+ if (isDaemonRunning()) await registerSingleJobSchedule(id).catch(err =>+ console.error(`❌ Failed to register job schedule on create for ${id}: ${err.message}`)+ );});cosEvents.on('jobs:deleted', async ({ id }) => {@@ -3012,7 +3015,9 @@ async function init() {// Schedule changes → re-compute next improvement checkcosEvents.on('schedule:changed', async () => {- if (isDaemonRunning()) await scheduleNextImprovementCheck();+ if (isDaemonRunning()) await scheduleNextImprovementCheck().catch(err =>+ console.error(`❌ Failed to schedule next improvement check: ${err.message}`)+ );});const state = await loadState();diff --git a/server/services/memory.js b/server/services/memory.jsindex dfc0bfc7f9..636c2389a0 100644--- a/server/services/memory.js+++ b/server/services/memory.js@@ -9,7 +9,7 @@ import { writeFile, readdir, rm } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';-import { cosEvents } from './cos.js';+import { cosEvents } from './cosEvents.js';import { findTopK, findAboveThreshold, clusterBySimilarity } from '../lib/vectorMath.js';import * as notifications from './notifications.js';import { ensureDir, ensureDirs, readJSONFile, PATHS } from '../lib/fileUtils.js';diff --git a/server/services/memory.test.js b/server/services/memory.test.jsindex 8f664ee68f..e9c3e339c6 100644--- a/server/services/memory.test.js+++ b/server/services/memory.test.js@@ -18,7 +18,10 @@ vi.mock('../lib/uuid.js', () => ({v4: vi.fn().mockReturnValue('test-uuid-1234')}));-// Mock cosEvents+// Mock cosEvents (memory.js imports from cosEvents.js directly)+vi.mock('./cosEvents.js', () => ({+ cosEvents: new EventEmitter()+}));vi.mock('./cos.js', () => ({cosEvents: new EventEmitter()}));@@ -79,7 +82,7 @@ import * as memoryBM25 from './memoryBM25.js';import * as notifications from './notifications.js';import { findTopK, findAboveThreshold, clusterBySimilarity } from '../lib/vectorMath.js';import { generateSummary, decrementAgentPendingApproval } from './memoryConfig.js';-import { cosEvents } from './cos.js';+import { cosEvents } from './cosEvents.js';import {createMemory,getMemory,diff --git a/server/services/memoryDB.js b/server/services/memoryDB.jsindex 9812faad3f..fbda43e872 100644--- a/server/services/memoryDB.js+++ b/server/services/memoryDB.js@@ -9,7 +9,7 @@import { v4 as uuidv4 } from '../lib/uuid.js';import { query, withTransaction, pgvectorToArray, arrayToPgvector } from '../lib/db.js';-import { cosEvents } from './cos.js';+import { cosEvents } from './cosEvents.js';import * as notifications from './notifications.js';import { DEFAULT_MEMORY_CONFIG, generateSummary, decrementAgentPendingApproval } from './memoryConfig.js';import { getInstanceId } from './instances.js';diff --git a/server/services/socket.js b/server/services/socket.jsindex add7212325..2d4f664771 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -61,14 +61,20 @@ export function initSocket(io) {// Handle streaming app detectionsocket.on('detect:start', async (rawData) => {- const data = validateSocketData(detectStartSchema, rawData, socket, 'detect:start');- if (!data) return;- console.log(`🔍 Starting detection: ${data.path}`);- await streamDetection(socket, data.path);+ try {+ const data = validateSocketData(detectStartSchema, rawData, socket, 'detect:start');+ if (!data) return;+ console.log(`🔍 Starting detection: ${data.path}`);+ await streamDetection(socket, data.path);+ } catch (err) {+ console.error(`❌ Socket handler error [detect:start]: ${err.message}`);+ socket.emit('error:server', { message: err.message });+ }});// Handle PM2 standardizationsocket.on('standardize:start', async (rawData) => {+ try {const data = validateSocketData(standardizeStartSchema, rawData, socket, 'standardize:start');if (!data) return;const { repoPath, providerId } = data;@@ -142,6 +148,10 @@ export function initSocket(io) {});console.log(`✅ Standardization complete: ${result.filesModified.length} files modified`);+ } catch (err) {+ console.error(`❌ Socket handler error [standardize:start]: ${err.message}`);+ socket.emit('error:server', { message: err.message });+ }});// Handle log streaming requests@@ -280,116 +290,131 @@ export function initSocket(io) {// Handle error recovery requests (can trigger auto-fix agents)socket.on('error:recover', async (rawData) => {- const data = validateSocketData(errorRecoverSchema, rawData, socket, 'error:recover');- if (!data) return;- const { code, context } = data;- console.log(`🔧 Error recovery requested: ${code}`);-- // Create auto-fix task- const task = await handleErrorRecovery(code, context);-- // Broadcast recovery task created- io.emit('error:recover:requested', {- code,- context,- taskId: task.id,- timestamp: Date.now()- });+ try {+ const data = validateSocketData(errorRecoverSchema, rawData, socket, 'error:recover');+ if (!data) return;+ const { code, context } = data;+ console.log(`🔧 Error recovery requested: ${code}`);++ // Create auto-fix task+ const task = await handleErrorRecovery(code, context);++ // Broadcast recovery task created+ io.emit('error:recover:requested', {+ code,+ context,+ taskId: task.id,+ timestamp: Date.now()+ });+ } catch (err) {+ console.error(`❌ Socket handler error [error:recover]: ${err.message}`);+ socket.emit('error:server', { message: err.message });+ }});// App update handler — streams progress via socketsocket.on('app:update', async (rawData) => {- const data = validateSocketData(appUpdateSchema, rawData, socket, 'app:update');- if (!data) return;+ try {+ const data = validateSocketData(appUpdateSchema, rawData, socket, 'app:update');+ if (!data) return;- const app = await appsService.getAppById(data.appId);- if (!app) {- socket.emit('app:update:error', { message: 'App not found' });- return;- }+ const app = await appsService.getAppById(data.appId);+ if (!app) {+ socket.emit('app:update:error', { message: 'App not found' });+ return;+ }- console.log(`⬇️ Socket update started for ${app.name}`);- const emit = (step, status, message) => {- socket.emit('app:update:step', { step, status, message, timestamp: Date.now() });- };+ console.log(`⬇️ Socket update started for ${app.name}`);+ const emit = (step, status, message) => {+ socket.emit('app:update:step', { step, status, message, timestamp: Date.now() });+ };- const result = await appUpdater.updateApp(app, emit).catch(err => {- socket.emit('app:update:error', { message: err.message });- return null;- });+ const result = await appUpdater.updateApp(app, emit).catch(err => {+ socket.emit('app:update:error', { message: err.message });+ return null;+ });- if (result) {- socket.emit('app:update:complete', { success: result.success, steps: result.steps });- console.log(`✅ Socket update complete for ${app.name}`);+ if (result) {+ socket.emit('app:update:complete', { success: result.success, steps: result.steps });+ console.log(`✅ Socket update complete for ${app.name}`);+ }+ } catch (err) {+ console.error(`❌ Socket handler error [app:update]: ${err.message}`);+ socket.emit('error:server', { message: err.message });}});// App standardize handler — streams progress via socketsocket.on('app:standardize', async (rawData) => {- const data = validateSocketData(appStandardizeSchema, rawData, socket, 'app:standardize');- if (!data) return;-- const app = await appsService.getAppById(data.appId);- if (!app) {- socket.emit('app:standardize:error', { message: 'App not found' });- return;- }+ try {+ const data = validateSocketData(appStandardizeSchema, rawData, socket, 'app:standardize');+ if (!data) return;- console.log(`🔧 Socket standardize started for ${app.name}`);- const emit = (step, status, message) => {- socket.emit('app:standardize:step', { step, status, message, timestamp: Date.now() });- };+ const app = await appsService.getAppById(data.appId);+ if (!app) {+ socket.emit('app:standardize:error', { message: 'App not found' });+ return;+ }- // Step 1: Analyze- emit('analyze', 'running', 'Analyzing project configuration...');- const analysis = await pm2Standardizer.analyzeApp(app.repoPath)- .catch(err => ({ success: false, error: err.message }));+ console.log(`🔧 Socket standardize started for ${app.name}`);+ const emit = (step, status, message) => {+ socket.emit('app:standardize:step', { step, status, message, timestamp: Date.now() });+ };- if (!analysis.success) {- emit('analyze', 'error', analysis.error);- socket.emit('app:standardize:error', { message: analysis.error });- return;- }- emit('analyze', 'done', `Found ${analysis.proposedChanges.processes?.length || 0} processes`);+ // Step 1: Analyze+ emit('analyze', 'running', 'Analyzing project configuration...');+ const analysis = await pm2Standardizer.analyzeApp(app.repoPath)+ .catch(err => ({ success: false, error: err.message }));- // Step 2: Backup- emit('backup', 'running', 'Creating git backup...');- const backup = await pm2Standardizer.createGitBackup(app.repoPath)- .catch(err => ({ success: false, reason: err.message }));+ if (!analysis.success) {+ emit('analyze', 'error', analysis.error);+ socket.emit('app:standardize:error', { message: analysis.error });+ return;+ }+ emit('analyze', 'done', `Found ${analysis.proposedChanges.processes?.length || 0} processes`);- if (backup.success) {- emit('backup', 'done', `Backup branch: ${backup.branch}`);- } else {- emit('backup', 'skipped', backup.reason || 'No git repository');- }+ // Step 2: Backup+ emit('backup', 'running', 'Creating git backup...');+ const backup = await pm2Standardizer.createGitBackup(app.repoPath)+ .catch(err => ({ success: false, reason: err.message }));- // Step 3: Apply- emit('apply', 'running', 'Writing ecosystem.config.cjs...');- const result = await pm2Standardizer.applyStandardization(app.repoPath, analysis)- .catch(err => ({ success: false, errors: [err.message] }));+ if (backup.success) {+ emit('backup', 'done', `Backup branch: ${backup.branch}`);+ } else {+ emit('backup', 'skipped', backup.reason || 'No git repository');+ }- if (result.errors?.length > 0) {- emit('apply', 'error', result.errors.join(', '));- socket.emit('app:standardize:error', { message: result.errors.join(', ') });- return;- }- emit('apply', 'done', `Modified ${result.filesModified.length} files`);+ // Step 3: Apply+ emit('apply', 'running', 'Writing ecosystem.config.cjs...');+ const result = await pm2Standardizer.applyStandardization(app.repoPath, analysis)+ .catch(err => ({ success: false, errors: [err.message] }));- // Update app with new PM2 process names- if (analysis.proposedChanges?.processes) {- const pm2ProcessNames = analysis.proposedChanges.processes.map(p => p.name);- await appsService.updateApp(data.appId, { pm2ProcessNames });- }+ if (result.errors?.length > 0) {+ emit('apply', 'error', result.errors.join(', '));+ socket.emit('app:standardize:error', { message: result.errors.join(', ') });+ return;+ }+ emit('apply', 'done', `Modified ${result.filesModified.length} files`);- socket.emit('app:standardize:complete', {- success: true,- result: {- backupBranch: result.backupBranch,- filesModified: result.filesModified,- processes: analysis.proposedChanges.processes+ // Update app with new PM2 process names+ if (analysis.proposedChanges?.processes) {+ const pm2ProcessNames = analysis.proposedChanges.processes.map(p => p.name);+ await appsService.updateApp(data.appId, { pm2ProcessNames });}- });- console.log(`✅ Socket standardize complete for ${app.name}`);++ socket.emit('app:standardize:complete', {+ success: true,+ result: {+ backupBranch: result.backupBranch,+ filesModified: result.filesModified,+ processes: analysis.proposedChanges.processes+ }+ });+ console.log(`✅ Socket standardize complete for ${app.name}`);+ } catch (err) {+ console.error(`❌ Socket handler error [app:standardize]: ${err.message}`);+ socket.emit('error:server', { message: err.message });+ }});// App deploy handler — streams real-time output from deploy.shdiff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex fc4525b076..75b413181f 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -2199,62 +2199,3 @@ function getTaskTypeDescription(taskType) {return descriptions[taskType] || taskType.replace(/-/g, ' ');}-// ============================================================-// Backward-compatible exports (delegate to unified functions)-// ============================================================--export async function getSelfImprovementInterval(taskType) {- return getTaskInterval(taskType);-}--export async function getAppImprovementInterval(taskType) {- return getTaskInterval(taskType);-}--export async function updateSelfImprovementInterval(taskType, settings) {- return updateTaskInterval(taskType, settings);-}--export async function updateAppImprovementInterval(taskType, settings) {- return updateTaskInterval(taskType, settings);-}--export async function shouldRunSelfImprovementTask(taskType) {- return shouldRunTask(taskType);-}--export async function shouldRunAppImprovementTask(taskType, appId) {- return shouldRunTask(taskType, appId);-}--export async function getDueSelfImprovementTasks() {- return getDueTasks();-}--export async function getDueAppImprovementTasks(appId) {- return getDueTasks(appId);-}--export async function getNextSelfImprovementTaskType(lastType) {- return getNextTaskType(null, lastType);-}--export async function getNextAppImprovementTaskType(appId, lastType) {- return getNextTaskType(appId, lastType);-}--export function getDefaultSelfImprovementPrompt(taskType) {- return getDefaultPrompt(taskType);-}--export function getDefaultAppImprovementPrompt(taskType) {- return getDefaultPrompt(taskType);-}--export async function getSelfImprovementPrompt(taskType) {- return getTaskPrompt(taskType);-}--export async function getAppImprovementPrompt(taskType) {- return getTaskPrompt(taskType);-}