Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(brain): add Open button to reveal cloned repo folders in file manager
Adam Eivy5e1463a40a53
diff --git a/.changelog/v0.10.x.md b/.changelog/v0.10.x.mdindex ac97ef5521..36d33211f5 100644--- a/.changelog/v0.10.x.md+++ b/.changelog/v0.10.x.md@@ -113,6 +113,21 @@ This release introduces a structured changelog documentation system for creating- **Validation Schemas**: New Zod schemas for import sources and analysis results- **API Endpoints**: New `/api/digital-twin/import/sources`, `/api/digital-twin/import/analyze`, and `/api/digital-twin/import/save` endpoints+### AI Agent Personalities & Platform Automation+- **Agent Personalities Page**: New `/agents` page for managing AI agent personalities with custom communication styles, tones, topics, and quirks+- **Personality Configuration**: Define agent style (professional, casual, witty, academic, creative), tone, expertise topics, unique quirks, and custom prompt prefixes+- **AI-Powered Personality Generation**: "Generate with AI" button on the new agent form auto-generates personality description, style, tone, topics, quirks, prompt prefix, and avatar based on agent name - select from any configured AI provider/model+- **Multi-User Support**: Agents support `userId` field for future multi-tenant scenarios+- **Platform Accounts**: Link agents to social platforms (starting with Moltbook) with credential management and status tracking+- **Moltbook Integration**: Isolated `server/integrations/moltbook/` module with REST API client for posts, comments, votes, follows, and heartbeat actions - designed for easy extraction to standalone app+- **Automation Scheduling**: Create schedules with cron, interval, or random timing to automate platform actions with per-schedule rate limiting+- **Action Types**: Supports post, comment, vote, and heartbeat (browse & engage naturally) action types+- **Rate Limit Enforcement**: Moltbook rate limits (30min posts, 20sec comments, 50/day comments) automatically enforced+- **Activity Logging**: All agent actions logged per-agent per-day for monitoring and analytics+- **Real-Time Updates**: Socket.IO events for personality changes, account updates, schedule triggers, and activity logs+- **Tab Navigation**: Five tabs - Personalities, Accounts, Schedules, Activity, and Config with URL-based deep linking+- **Quick Actions**: Run schedules immediately with "Run Now" button, toggle schedules on/off, test platform connections+### AI Provider Usage Limit Handling & Fallback- **Usage Limit Detection**: Agents now detect provider usage limit errors (e.g., "You've hit your usage limit. Upgrade to Pro or try again in 1 day 1 hour 33 minutes") and mark providers as temporarily unavailable- **Provider Status Tracking**: New `providerStatus.js` service tracks provider availability, usage limits, and estimated recovery times with persistence across server restarts@@ -146,6 +161,20 @@ This release introduces a structured changelog documentation system for creating- **Visual Feedback**: Loading spinner and "Enhancing..." state during prompt processing, with clear success/error toasts- **API Endpoint**: New `POST /api/cos/tasks/enhance` endpoint for programmatic access to prompt enhancement+### Brain Links - Quick URL Capture with GitHub Clone+- **Links Tab in Brain**: New "Links" tab in the Brain feature for quickly saving URLs for later reference+- **Quick-Add Form**: Paste any URL and it's automatically saved - GitHub repos are detected and tagged automatically+- **GitHub Auto-Clone**: When pasting a GitHub repository URL, the repo is automatically cloned to `data/repos/` for local reference+- **Clone Status Tracking**: Real-time clone progress display with pending, cloning, cloned, and failed states+- **Pull Updates**: One-click "Pull" button to fetch latest changes for cloned repositories+- **Open Folder**: One-click "Open" button to reveal cloned repositories in the system file manager (Finder on macOS, Explorer on Windows, xdg-open on Linux)+- **Link Types**: Links are categorized as github, article, documentation, tool, reference, or other with color-coded badges+- **Tag Support**: Add custom tags to organize and filter links+- **Filter Views**: Toggle between All, GitHub Repos, and Other Links views+- **Edit/Delete**: Full CRUD operations with inline editing for title, description, type, and tags+- **API Endpoints**: New `/api/brain/links` CRUD endpoints plus `/api/brain/links/:id/clone` and `/api/brain/links/:id/pull` for repo management+- **GitHub URL Parsing**: Supports HTTPS and SSH GitHub URL formats+## 🔧 Improvements### Prompt Manager UX@@ -222,6 +251,21 @@ This release introduces a structured changelog documentation system for creating### Brain Memory Delete Handler- **Fixed Delete Success Detection**: The MemoryTab delete handler was checking `result !== null` to determine success, but successful API responses might not return a value. Changed to track failures explicitly with a boolean flag, fixing false-positive "Deleted" toasts when delete operations failed+### Task Enhancement Empty Response Handling+- **Fixed "Description is required" Error**: When task enhancement returned an empty response from the AI provider, the client would proceed to submit the task with an empty description, triggering a validation error. Now both client and server validate that the enhanced description is non-empty before proceeding+- **Graceful Fallback on Enhancement Failure**: Task enhancement failures (empty result or AI error) now fall back to using the original task description instead of aborting - shows a warning toast and continues adding the task++### CLI Provider Support for AI Services+- **Fixed "API error: 0" Failures**: Services like `agentPersonalityGenerator.js` and `taskEnhancer.js` were using `executeApiRun()` for all providers, but CLI providers (claude-code, codex) have no API endpoint, causing immediate failures with status 0+- **Provider Type Detection**: Added `provider.type` check to determine whether to use `executeApiRun()` (for API providers) or `executeCliRun()` (for CLI providers)+- **Impact**: Agent personality generation and task prompt enhancement now work correctly with CLI-based AI providers like Claude Code CLI++### Reasoning Model Support (AI Toolkit)+- **Fixed Empty Responses from Reasoning Models**: LM Studio 0.4.0+ and reasoning models like DeepSeek-R1 and gpt-oss-20b use a separate `reasoning` field for chain-of-thought, leaving `content` empty until reasoning completes. The AI toolkit now captures both fields.+- **Automatic Fallback**: If a model returns empty `content` but has `reasoning`, the toolkit falls back to using the reasoning output rather than returning empty results+- **Metadata Tracking**: Run metadata now includes `hadReasoning` and `usedReasoningAsFallback` flags for debugging+- **Impact**: Task enhancement and other AI services now work correctly with reasoning-based local models+### Critical: Fixed "Unexpected end of JSON input" Errors- **Safe JSON Parsing**: Added comprehensive JSON parsing utilities to `server/lib/fileUtils.js`:- `isValidJSON(str)` - Pre-validates JSON structure before parsing (supports both objects and arrays)diff --git a/client/src/components/brain/tabs/LinksTab.jsx b/client/src/components/brain/tabs/LinksTab.jsxnew file mode 100644index 0000000000..ad98af5b3a--- /dev/null+++ b/client/src/components/brain/tabs/LinksTab.jsx@@ -0,0 +1,510 @@+import { useState, useEffect, useCallback, useRef } from 'react';+import * as api from '../../../services/api';+import {+ Link2,+ Send,+ RefreshCw,+ ExternalLink,+ Trash2,+ Edit2,+ Save,+ X,+ GitBranch,+ Download,+ Check,+ AlertCircle,+ FolderOpen,+ Tag+} from 'lucide-react';+import toast from 'react-hot-toast';+import { formatRelativeTime } from '../constants';++const LINK_TYPE_COLORS = {+ github: 'bg-purple-500/20 text-purple-400 border-purple-500/30',+ article: 'bg-blue-500/20 text-blue-400 border-blue-500/30',+ documentation: 'bg-green-500/20 text-green-400 border-green-500/30',+ tool: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30',+ reference: 'bg-cyan-500/20 text-cyan-400 border-cyan-500/30',+ other: 'bg-gray-500/20 text-gray-400 border-gray-500/30'+};++const CLONE_STATUS_STYLES = {+ none: '',+ pending: 'text-yellow-400',+ cloning: 'text-blue-400 animate-pulse',+ cloned: 'text-green-400',+ failed: 'text-red-400'+};++export default function LinksTab({ onRefresh }) {+ const [inputUrl, setInputUrl] = useState('');+ const [sending, setSending] = useState(false);+ const [links, setLinks] = useState([]);+ const [total, setTotal] = useState(0);+ const [loading, setLoading] = useState(true);+ const [filter, setFilter] = useState('all'); // all, github, other+ const [editingId, setEditingId] = useState(null);+ const [editForm, setEditForm] = useState({});+ const [confirmingDeleteId, setConfirmingDeleteId] = useState(null);+ const inputRef = useRef(null);++ const fetchLinks = useCallback(async () => {+ const options = {};+ if (filter === 'github') {+ options.isGitHubRepo = true;+ } else if (filter === 'other') {+ options.isGitHubRepo = false;+ }++ const data = await api.getBrainLinks(options).catch(() => ({ links: [], total: 0 }));+ setLinks(data.links || []);+ setTotal(data.total || 0);+ setLoading(false);+ }, [filter]);++ useEffect(() => {+ fetchLinks();+ }, [fetchLinks]);++ // Poll for clone status updates+ useEffect(() => {+ const cloningLinks = links.filter(l => l.cloneStatus === 'cloning' || l.cloneStatus === 'pending');+ if (cloningLinks.length === 0) return;++ const interval = setInterval(fetchLinks, 3000);+ return () => clearInterval(interval);+ }, [links, fetchLinks]);++ const handleSubmit = async (e) => {+ e.preventDefault();+ if (!inputUrl.trim() || sending) return;++ // Basic URL validation+ let url = inputUrl.trim();+ if (!url.startsWith('http://') && !url.startsWith('https://') && !url.startsWith('git@')) {+ // Try adding https://+ if (url.includes('github.com') || url.includes('.')) {+ url = 'https://' + url;+ } else {+ toast.error('Please enter a valid URL');+ return;+ }+ }++ setSending(true);+ const result = await api.createBrainLink({ url }).catch(err => {+ if (err.message?.includes('already exists')) {+ toast.error('This URL is already saved');+ } else {+ toast.error(err.message || 'Failed to save link');+ }+ return null;+ });+ setSending(false);++ if (result) {+ const isGitHub = result.isGitHubRepo;+ toast.success(isGitHub ? 'GitHub repo added - cloning in background' : 'Link saved');+ setInputUrl('');+ fetchLinks();+ onRefresh?.();+ }+ };++ const handleEdit = (link) => {+ setEditingId(link.id);+ setEditForm({+ title: link.title,+ description: link.description || '',+ linkType: link.linkType,+ tags: link.tags?.join(', ') || ''+ });+ };++ const handleSaveEdit = async (linkId) => {+ const updates = {+ title: editForm.title,+ description: editForm.description,+ linkType: editForm.linkType,+ tags: editForm.tags ? editForm.tags.split(',').map(t => t.trim()).filter(Boolean) : []+ };++ const result = await api.updateBrainLink(linkId, updates).catch(err => {+ toast.error(err.message || 'Failed to update');+ return null;+ });++ if (result) {+ toast.success('Link updated');+ setEditingId(null);+ setEditForm({});+ fetchLinks();+ }+ };++ const handleCancelEdit = () => {+ setEditingId(null);+ setEditForm({});+ };++ const handleDelete = async (linkId) => {+ await api.deleteBrainLink(linkId).catch(err => {+ toast.error(err.message || 'Failed to delete');+ return null;+ });++ toast.success('Link deleted');+ setConfirmingDeleteId(null);+ fetchLinks();+ onRefresh?.();+ };++ const handleClone = async (linkId) => {+ const result = await api.cloneBrainLink(linkId).catch(err => {+ toast.error(err.message || 'Failed to start clone');+ return null;+ });++ if (result) {+ toast.success('Clone started');+ fetchLinks();+ }+ };++ const handlePull = async (linkId) => {+ const result = await api.pullBrainLink(linkId).catch(err => {+ toast.error(err.message || 'Failed to pull');+ return null;+ });++ if (result) {+ toast.success('Pulled latest changes');+ }+ };++ const handleOpenFolder = async (linkId) => {+ await api.openBrainLinkFolder(linkId).catch(err => {+ toast.error(err.message || 'Failed to open folder');+ });+ };++ if (loading) {+ return (+ <div className="flex items-center justify-center h-64">+ <RefreshCw className="w-6 h-6 text-port-accent animate-spin" />+ </div>+ );+ }++ return (+ <div className="flex flex-col h-full max-w-4xl mx-auto">+ {/* Quick-add input */}+ <form onSubmit={handleSubmit} className="mb-6">+ <div className="flex gap-2">+ <input+ ref={inputRef}+ type="text"+ value={inputUrl}+ onChange={(e) => setInputUrl(e.target.value)}+ placeholder="Paste a URL (GitHub repos auto-clone)..."+ className="flex-1 px-4 py-3 bg-port-card border border-port-border rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"+ disabled={sending}+ />+ <button+ type="submit"+ disabled={sending || !inputUrl.trim()}+ className="px-4 py-3 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 min-h-[48px]"+ title={sending ? 'Saving...' : 'Save link'}+ >+ {sending ? (+ <RefreshCw className="w-5 h-5 animate-spin" />+ ) : (+ <Send className="w-5 h-5" />+ )}+ </button>+ </div>+ <p className="mt-2 text-xs text-gray-500">+ Paste any URL. GitHub repos will be automatically cloned for local reference.+ </p>+ </form>++ {/* Filter tabs */}+ <div className="flex gap-2 mb-4">+ {[+ { id: 'all', label: 'All', count: total },+ { id: 'github', label: 'GitHub Repos', icon: GitBranch },+ { id: 'other', label: 'Other Links', icon: Link2 }+ ].map(tab => {+ const Icon = tab.icon;+ const isActive = filter === tab.id;+ return (+ <button+ key={tab.id}+ onClick={() => setFilter(tab.id)}+ className={`flex items-center gap-2 px-3 py-2 text-sm rounded-lg transition-colors min-h-[40px] ${+ isActive+ ? 'bg-port-accent/20 text-port-accent border border-port-accent/30'+ : 'bg-port-card text-gray-400 hover:text-white border border-port-border'+ }`}+ >+ {Icon && <Icon size={14} />}+ {tab.label}+ {tab.count !== undefined && (+ <span className="text-xs opacity-60">({tab.count})</span>+ )}+ </button>+ );+ })}+ </div>++ {/* Links list */}+ <div className="space-y-3">+ {links.map(link => (+ <div+ key={link.id}+ className="p-4 bg-port-card border border-port-border rounded-lg"+ >+ {/* Header row */}+ <div className="flex items-start justify-between gap-3 mb-2">+ {editingId === link.id ? (+ <div className="flex-1 space-y-2">+ <input+ type="text"+ value={editForm.title}+ onChange={(e) => setEditForm({ ...editForm, title: e.target.value })}+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"+ placeholder="Title"+ autoFocus+ />+ <textarea+ value={editForm.description}+ onChange={(e) => setEditForm({ ...editForm, description: e.target.value })}+ className="w-full px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm resize-none"+ placeholder="Description (optional)"+ rows={2}+ />+ <div className="flex gap-2">+ <select+ value={editForm.linkType}+ onChange={(e) => setEditForm({ ...editForm, linkType: e.target.value })}+ className="px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"+ >+ <option value="github">GitHub</option>+ <option value="article">Article</option>+ <option value="documentation">Documentation</option>+ <option value="tool">Tool</option>+ <option value="reference">Reference</option>+ <option value="other">Other</option>+ </select>+ <input+ type="text"+ value={editForm.tags}+ onChange={(e) => setEditForm({ ...editForm, tags: e.target.value })}+ className="flex-1 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"+ placeholder="Tags (comma-separated)"+ />+ </div>+ <div className="flex gap-2">+ <button+ onClick={() => handleSaveEdit(link.id)}+ className="flex items-center gap-1 px-2 py-1 text-xs bg-port-success/20 text-port-success rounded hover:bg-port-success/30 transition-colors"+ >+ <Save size={12} />+ Save+ </button>+ <button+ onClick={handleCancelEdit}+ className="flex items-center gap-1 px-2 py-1 text-xs text-gray-400 hover:text-white transition-colors"+ >+ <X size={12} />+ Cancel+ </button>+ </div>+ </div>+ ) : (+ <>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 mb-1">+ {link.isGitHubRepo ? (+ <GitBranch size={16} className="text-purple-400 flex-shrink-0" />+ ) : (+ <Link2 size={16} className="text-gray-400 flex-shrink-0" />+ )}+ <h3 className="font-medium text-white truncate">{link.title}</h3>+ </div>+ <a+ href={link.url}+ target="_blank"+ rel="noopener noreferrer"+ className="text-sm text-gray-400 hover:text-port-accent truncate block"+ >+ {link.url}+ </a>+ {link.description && (+ <p className="text-sm text-gray-500 mt-1">{link.description}</p>+ )}+ </div>++ <div className="flex items-center gap-1 flex-shrink-0">+ <button+ onClick={() => handleEdit(link)}+ className="p-1.5 text-gray-400 hover:text-white transition-colors"+ title="Edit"+ >+ <Edit2 size={14} />+ </button>+ <button+ onClick={() => setConfirmingDeleteId(link.id)}+ className="p-1.5 text-gray-400 hover:text-port-error transition-colors"+ title="Delete"+ >+ <Trash2 size={14} />+ </button>+ <a+ href={link.url}+ target="_blank"+ rel="noopener noreferrer"+ className="p-1.5 text-gray-400 hover:text-port-accent transition-colors"+ title="Open in new tab"+ >+ <ExternalLink size={14} />+ </a>+ </div>+ </>+ )}++ <span className="text-xs text-gray-500 whitespace-nowrap">+ {formatRelativeTime(link.createdAt)}+ </span>+ </div>++ {/* Delete confirmation */}+ {confirmingDeleteId === link.id && (+ <div className="flex items-center gap-2 p-2 bg-port-error/10 border border-port-error/30 rounded mb-2">+ <span className="text-xs text-white flex-1">Delete this link? This cannot be undone.</span>+ <button+ onClick={() => handleDelete(link.id)}+ className="px-2 py-1 text-xs bg-port-error text-white rounded hover:bg-port-error/80 transition-colors"+ >+ Delete+ </button>+ <button+ onClick={() => setConfirmingDeleteId(null)}+ className="px-2 py-1 text-xs text-gray-400 hover:text-white transition-colors"+ >+ Cancel+ </button>+ </div>+ )}++ {/* Footer row */}+ {editingId !== link.id && (+ <div className="flex items-center gap-2 flex-wrap mt-2">+ {/* Link type badge */}+ <span className={`px-2 py-1 text-xs rounded border ${LINK_TYPE_COLORS[link.linkType] || LINK_TYPE_COLORS.other}`}>+ {link.linkType}+ </span>++ {/* Tags */}+ {link.tags?.length > 0 && (+ <div className="flex items-center gap-1">+ <Tag size={12} className="text-gray-500" />+ {link.tags.map((tag, i) => (+ <span key={i} className="px-1.5 py-0.5 text-xs bg-port-border/50 text-gray-400 rounded">+ {tag}+ </span>+ ))}+ </div>+ )}++ {/* GitHub-specific controls */}+ {link.isGitHubRepo && (+ <>+ {/* Clone status */}+ <span className={`flex items-center gap-1 text-xs ${CLONE_STATUS_STYLES[link.cloneStatus]}`}>+ {link.cloneStatus === 'cloned' && <Check size={12} />}+ {link.cloneStatus === 'cloning' && <RefreshCw size={12} className="animate-spin" />}+ {link.cloneStatus === 'pending' && <Download size={12} />}+ {link.cloneStatus === 'failed' && <AlertCircle size={12} />}+ {link.cloneStatus === 'cloned' && 'Cloned'}+ {link.cloneStatus === 'cloning' && 'Cloning...'}+ {link.cloneStatus === 'pending' && 'Pending clone'}+ {link.cloneStatus === 'failed' && 'Clone failed'}+ </span>++ {/* Clone error */}+ {link.cloneError && (+ <span className="text-xs text-port-error truncate max-w-[200px]" title={link.cloneError}>+ {link.cloneError}+ </span>+ )}++ {/* Local path */}+ {link.localPath && (+ <span className="flex items-center gap-1 text-xs text-gray-500 truncate max-w-[200px]" title={link.localPath}>+ <FolderOpen size={12} />+ {link.localPath.split('/').slice(-2).join('/')}+ </span>+ )}++ {/* Action buttons */}+ {link.cloneStatus === 'none' && (+ <button+ onClick={() => handleClone(link.id)}+ className="flex items-center gap-1 px-2 py-1 text-xs rounded border border-port-border text-gray-400 hover:text-white transition-colors"+ title="Clone repository"+ >+ <Download size={12} />+ Clone+ </button>+ )}++ {link.cloneStatus === 'failed' && (+ <button+ onClick={() => handleClone(link.id)}+ className="flex items-center gap-1 px-2 py-1 text-xs rounded border border-port-border text-gray-400 hover:text-white transition-colors"+ title="Retry clone"+ >+ <RefreshCw size={12} />+ Retry+ </button>+ )}++ {link.cloneStatus === 'cloned' && (+ <>+ <button+ onClick={() => handleOpenFolder(link.id)}+ className="flex items-center gap-1 px-2 py-1 text-xs rounded border border-port-border text-gray-400 hover:text-white transition-colors"+ title="Open folder in file manager"+ >+ <FolderOpen size={12} />+ Open+ </button>+ <button+ onClick={() => handlePull(link.id)}+ className="flex items-center gap-1 px-2 py-1 text-xs rounded border border-port-border text-gray-400 hover:text-white transition-colors"+ title="Pull latest changes"+ >+ <RefreshCw size={12} />+ Pull+ </button>+ </>+ )}+ </>+ )}+ </div>+ )}+ </div>+ ))}++ {links.length === 0 && (+ <div className="text-center py-12 text-gray-500">+ <Link2 className="w-12 h-12 mx-auto mb-3 opacity-30" />+ <p>No links saved yet.</p>+ <p className="text-sm mt-1">Paste a URL above to get started.</p>+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 0da2e75a8e..8270533a2f 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -215,10 +215,110 @@ export const uploadScreenshot = (base64Data, filename, mimeType) => request('/scbody: JSON.stringify({ data: base64Data, filename, mimeType })});-// Agents-export const getAgents = () => request('/agents');-export const getAgentInfo = (pid) => request(`/agents/${pid}`);-export const killAgent = (pid) => request(`/agents/${pid}`, { method: 'DELETE' });+// Running Agents (Process Management)+export const getRunningAgents = () => request('/agents');+export const getRunningAgentInfo = (pid) => request(`/agents/${pid}`);+export const killRunningAgent = (pid) => request(`/agents/${pid}`, { method: 'DELETE' });+// Legacy aliases+export const getAgents = getRunningAgents;+export const getAgentInfo = getRunningAgentInfo;+export const killAgent = killRunningAgent;++// Agent Personalities+export const getAgentPersonalities = (userId = null) => {+ const params = userId ? `?userId=${encodeURIComponent(userId)}` : '';+ return request(`/agents/personalities${params}`);+};+export const getAgentPersonality = (id) => request(`/agents/personalities/${id}`);+export const createAgentPersonality = (data) => request('/agents/personalities', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const updateAgentPersonality = (id, data) => request(`/agents/personalities/${id}`, {+ method: 'PUT',+ body: JSON.stringify(data)+});+export const deleteAgentPersonality = (id) => request(`/agents/personalities/${id}`, { method: 'DELETE' });+export const toggleAgentPersonality = (id, enabled) => request(`/agents/personalities/${id}/toggle`, {+ method: 'POST',+ body: JSON.stringify({ enabled })+});+export const generateAgentPersonality = (seedData, providerId, model) => request('/agents/personalities/generate', {+ method: 'POST',+ body: JSON.stringify({ seed: seedData, providerId, model })+});++// Platform Accounts+export const getPlatformAccounts = (agentId = null, platform = null) => {+ const params = new URLSearchParams();+ if (agentId) params.set('agentId', agentId);+ if (platform) params.set('platform', platform);+ const query = params.toString();+ return request(`/agents/accounts${query ? `?${query}` : ''}`);+};+export const getPlatformAccount = (id) => request(`/agents/accounts/${id}`);+export const createPlatformAccount = (data) => request('/agents/accounts', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const registerPlatformAccount = (agentId, platform, name, description) => request('/agents/accounts', {+ method: 'POST',+ body: JSON.stringify({ agentId, platform, name, description })+});+export const deletePlatformAccount = (id) => request(`/agents/accounts/${id}`, { method: 'DELETE' });+export const testPlatformAccount = (id) => request(`/agents/accounts/${id}/test`, { method: 'POST' });+export const claimPlatformAccount = (id) => request(`/agents/accounts/${id}/claim`, { method: 'POST' });++// Automation Schedules+export const getAutomationSchedules = (agentId = null, accountId = null) => {+ const params = new URLSearchParams();+ if (agentId) params.set('agentId', agentId);+ if (accountId) params.set('accountId', accountId);+ const query = params.toString();+ return request(`/agents/schedules${query ? `?${query}` : ''}`);+};+export const getAutomationSchedule = (id) => request(`/agents/schedules/${id}`);+export const getScheduleStats = () => request('/agents/schedules/stats');+export const createAutomationSchedule = (data) => request('/agents/schedules', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const updateAutomationSchedule = (id, data) => request(`/agents/schedules/${id}`, {+ method: 'PUT',+ body: JSON.stringify(data)+});+export const deleteAutomationSchedule = (id) => request(`/agents/schedules/${id}`, { method: 'DELETE' });+export const toggleAutomationSchedule = (id, enabled) => request(`/agents/schedules/${id}/toggle`, {+ method: 'POST',+ body: JSON.stringify({ enabled })+});+export const runAutomationScheduleNow = (id) => request(`/agents/schedules/${id}/run`, { method: 'POST' });++// Agent Activity+export const getAgentActivities = (limit = 50, agentIds = null, action = null) => {+ const params = new URLSearchParams();+ params.set('limit', limit);+ if (agentIds) params.set('agentIds', agentIds.join(','));+ if (action) params.set('action', action);+ return request(`/agents/activity?${params}`);+};+export const getAgentActivityTimeline = (limit = 50, agentIds = null, before = null) => {+ const params = new URLSearchParams();+ params.set('limit', limit);+ if (agentIds) params.set('agentIds', agentIds.join(','));+ if (before) params.set('before', before);+ return request(`/agents/activity/timeline?${params}`);+};+export const getAgentActivityByAgent = (agentId, options = {}) => {+ const params = new URLSearchParams();+ if (options.date) params.set('date', options.date);+ if (options.limit) params.set('limit', options.limit);+ if (options.offset) params.set('offset', options.offset);+ if (options.action) params.set('action', options.action);+ return request(`/agents/activity/agent/${agentId}?${params}`);+};+export const getAgentActivityStats = (agentId, days = 7) =>+ request(`/agents/activity/agent/${agentId}/stats?days=${days}`);// Chief of Staffexport const getCosStatus = () => request('/cos');@@ -543,6 +643,29 @@ export const runBrainReview = (providerOverride, modelOverride) => request('/brabody: JSON.stringify({ providerOverride, modelOverride })});+// Brain - Links+export const getBrainLinks = (options = {}) => {+ const params = new URLSearchParams();+ if (options.linkType) params.set('linkType', options.linkType);+ if (options.isGitHubRepo !== undefined) params.set('isGitHubRepo', options.isGitHubRepo);+ if (options.limit) params.set('limit', options.limit);+ if (options.offset) params.set('offset', options.offset);+ return request(`/brain/links?${params}`);+};+export const getBrainLink = (id) => request(`/brain/links/${id}`);+export const createBrainLink = (data) => request('/brain/links', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const updateBrainLink = (id, data) => request(`/brain/links/${id}`, {+ method: 'PUT',+ body: JSON.stringify(data)+});+export const deleteBrainLink = (id) => request(`/brain/links/${id}`, { method: 'DELETE' });+export const cloneBrainLink = (id) => request(`/brain/links/${id}/clone`, { method: 'POST' });+export const pullBrainLink = (id) => request(`/brain/links/${id}/pull`, { method: 'POST' });+export const openBrainLinkFolder = (id) => request(`/brain/links/${id}/open-folder`, { method: 'POST' });+// Media - Server media devicesexport const getMediaDevices = () => request('/media/devices');export const getMediaStatus = () => request('/media/status');diff --git a/server/routes/brain.js b/server/routes/brain.jsindex 36d67991f8..2526303551 100644--- a/server/routes/brain.js+++ b/server/routes/brain.js@@ -9,6 +9,8 @@*/import { Router } from 'express';+import { spawn } from 'child_process';+import { existsSync } from 'fs';import * as brainService from '../services/brain.js';import { getProviderById } from '../services/providers.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';@@ -23,8 +25,12 @@ import {projectInputSchema,ideaInputSchema,adminInputSchema,- settingsUpdateInputSchema+ settingsUpdateInputSchema,+ linkInputSchema,+ linkUpdateInputSchema,+ linksQuerySchema} from '../lib/brainValidation.js';+import * as githubCloner from '../services/githubCloner.js';const router = Router();@@ -521,4 +527,265 @@ router.get('/summary', asyncHandler(async (req, res) => {res.json(summary);}));+// =============================================================================+// LINKS CRUD+// =============================================================================++/**+ * GET /api/brain/links+ * Get all links with optional filters+ */+router.get('/links', asyncHandler(async (req, res) => {+ const validation = validate(linksQuerySchema, req.query);+ if (!validation.success) {+ throw new ServerError('Validation failed', {+ status: 400,+ code: 'VALIDATION_ERROR',+ context: { details: validation.errors }+ });+ }++ const { linkType, isGitHubRepo, limit, offset } = validation.data;+ let links = await brainService.getLinks();++ // Apply filters+ if (linkType) {+ links = links.filter(l => l.linkType === linkType);+ }+ if (isGitHubRepo !== undefined) {+ links = links.filter(l => l.isGitHubRepo === isGitHubRepo);+ }++ // Sort by createdAt descending+ links.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));++ // Apply pagination+ const total = links.length;+ links = links.slice(offset, offset + limit);++ res.json({ links, total, limit, offset });+}));++/**+ * GET /api/brain/links/:id+ * Get a single link by ID+ */+router.get('/links/:id', asyncHandler(async (req, res) => {+ const link = await brainService.getLinkById(req.params.id);+ if (!link) {+ throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(link);+}));++/**+ * POST /api/brain/links+ * Create a new link (quick-add with URL)+ */+router.post('/links', asyncHandler(async (req, res) => {+ const validation = validate(linkInputSchema, req.body);+ if (!validation.success) {+ throw new ServerError('Validation failed', {+ status: 400,+ code: 'VALIDATION_ERROR',+ context: { details: validation.errors }+ });+ }++ const { url, title, description, linkType, tags, autoClone } = validation.data;++ // Check if URL already exists+ const existing = await brainService.getLinkByUrl(url);+ if (existing) {+ throw new ServerError('Link with this URL already exists', {+ status: 409,+ code: 'DUPLICATE_URL',+ context: { existingId: existing.id }+ });+ }++ // Parse GitHub URL if applicable+ const parsed = githubCloner.parseGitHubUrl(url);+ const isGitHubRepo = !!parsed;++ // Create initial link record+ const linkData = {+ url,+ title: title || (parsed ? `${parsed.owner}/${parsed.repo}` : url),+ description: description || '',+ linkType: linkType || (isGitHubRepo ? 'github' : 'other'),+ tags: tags || [],+ isGitHubRepo,+ gitHubOwner: parsed?.owner,+ gitHubRepo: parsed?.repo,+ localPath: null,+ cloneStatus: isGitHubRepo && autoClone !== false ? 'pending' : 'none',+ cloneError: null+ };++ const link = await brainService.createLink(linkData);+ console.log(`🔗 Created link: ${link.id} (${isGitHubRepo ? 'GitHub repo' : 'regular URL'})`);++ // If GitHub repo and auto-clone enabled, start clone in background+ if (isGitHubRepo && autoClone !== false) {+ cloneRepoInBackground(link.id, url);+ }++ res.status(201).json(link);+}));++/**+ * Clone repo in background and update link record+ */+async function cloneRepoInBackground(linkId, url) {+ // Update status to cloning+ await brainService.updateLink(linkId, { cloneStatus: 'cloning' });++ githubCloner.cloneRepo(url)+ .then(async (result) => {+ await brainService.updateLink(linkId, {+ localPath: result.localPath,+ cloneStatus: 'cloned',+ cloneError: null+ });+ console.log(`✅ Background clone complete: ${linkId}`);+ })+ .catch(async (err) => {+ await brainService.updateLink(linkId, {+ cloneStatus: 'failed',+ cloneError: err.message+ });+ console.error(`❌ Background clone failed: ${linkId} - ${err.message}`);+ });+}++/**+ * PUT /api/brain/links/:id+ * Update a link+ */+router.put('/links/:id', asyncHandler(async (req, res) => {+ const validation = validate(linkUpdateInputSchema, req.body);+ if (!validation.success) {+ throw new ServerError('Validation failed', {+ status: 400,+ code: 'VALIDATION_ERROR',+ context: { details: validation.errors }+ });+ }++ const link = await brainService.updateLink(req.params.id, validation.data);+ if (!link) {+ throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(link);+}));++/**+ * DELETE /api/brain/links/:id+ * Delete a link+ */+router.delete('/links/:id', asyncHandler(async (req, res) => {+ const deleted = await brainService.deleteLink(req.params.id);+ if (!deleted) {+ throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.status(204).send();+}));++/**+ * POST /api/brain/links/:id/clone+ * Manually trigger clone for a GitHub repo link+ */+router.post('/links/:id/clone', asyncHandler(async (req, res) => {+ const link = await brainService.getLinkById(req.params.id);+ if (!link) {+ throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });+ }++ if (!link.isGitHubRepo) {+ throw new ServerError('Link is not a GitHub repository', {+ status: 400,+ code: 'NOT_GITHUB_REPO'+ });+ }++ if (link.cloneStatus === 'cloning') {+ throw new ServerError('Clone already in progress', {+ status: 409,+ code: 'CLONE_IN_PROGRESS'+ });+ }++ // Start clone in background+ cloneRepoInBackground(link.id, link.url);++ res.json({ message: 'Clone started', linkId: link.id });+}));++/**+ * POST /api/brain/links/:id/pull+ * Pull latest changes for a cloned repo+ */+router.post('/links/:id/pull', asyncHandler(async (req, res) => {+ const link = await brainService.getLinkById(req.params.id);+ if (!link) {+ throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });+ }++ if (!link.isGitHubRepo || !link.localPath) {+ throw new ServerError('Link is not a cloned GitHub repository', {+ status: 400,+ code: 'NOT_CLONED'+ });+ }++ const result = await githubCloner.pullRepo(link.localPath);+ res.json({ message: 'Pull complete', ...result });+}));++/**+ * POST /api/brain/links/:id/open-folder+ * Open the cloned repo folder in the system file manager+ */+router.post('/links/:id/open-folder', asyncHandler(async (req, res) => {+ const link = await brainService.getLinkById(req.params.id);+ if (!link) {+ throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });+ }++ if (!link.localPath) {+ throw new ServerError('Link has no local folder', {+ status: 400,+ code: 'NO_LOCAL_PATH'+ });+ }++ if (!existsSync(link.localPath)) {+ throw new ServerError('Local folder does not exist', {+ status: 400,+ code: 'PATH_NOT_FOUND'+ });+ }++ // Cross-platform folder open command+ const platform = process.platform;+ let cmd, args;++ if (platform === 'darwin') {+ cmd = 'open';+ args = [link.localPath];+ } else if (platform === 'win32') {+ cmd = 'explorer';+ args = [link.localPath];+ } else {+ cmd = 'xdg-open';+ args = [link.localPath];+ }++ spawn(cmd, args, { detached: true, stdio: 'ignore' }).unref();+ console.log(`📂 Opened folder: ${link.localPath}`);++ res.json({ message: 'Folder opened', path: link.localPath });+}));+export default router;