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(agents): add cooldown countdown timer and sync rate limits from Moltbook 429
Adam Eivy4c68d4959eae
diff --git a/.changelog/v0.12.x.md b/.changelog/v0.12.x.mdindex 672253ed7f..2941ee6a50 100644--- a/.changelog/v0.12.x.md+++ b/.changelog/v0.12.x.md@@ -527,3 +527,17 @@ This release adds branch management and automated release workflow capabilities- `client/src/components/city/cityConstants.js` — Added `BOROUGH_PARAMS` and `PROCESS_BUILDING_PARAMS`, increased spacing to 12.0- `client/src/components/city/CityScene.jsx` — Adjusted camera position, fog distance, and orbit controls for larger city- `client/src/components/city/CityRoads.jsx` — Wider road surfaces, edge lines, and padding for larger grid spacing++### Agents — Moltbook Rate Limit Cooldown Timer & 429 Sync+- **Cooldown countdown timer**: Rate limit pills in ToolsTab and OverviewTab now show a live mm:ss countdown when a cooldown is active (e.g., `post: 24:35`), pulsing with `animate-pulse` for visibility. Timer auto-refreshes rate limits from the server when it reaches zero.+- **Publish button cooldown**: The Publish button disables during post cooldown and shows "Wait mm:ss" instead of "Publish", preventing wasted API calls+- **429 rate limit sync**: When Moltbook returns HTTP 429 (e.g., "You can only post once every 30 minutes"), the server now syncs local in-memory rate limit state to match platform enforcement — fixing the desync that occurs after PM2 restarts when in-memory counters reset to zero+- **Publish error recovery**: Fixed stuck "Publishing..." button state when API calls fail — publish handlers now catch errors gracefully and reset loading state++**Server changes**:+- `server/integrations/moltbook/rateLimits.js` — Added `syncFromExternal()` to update lastAction from external 429 responses+- `server/integrations/moltbook/api.js` — Added `inferActionFromEndpoint()` and 429 detection in `request()` that auto-syncs rate limit state++**Client changes**:+- `client/src/components/agents/tabs/ToolsTab.jsx` — Cooldown timer state, interval tick, formatted countdown in rate limit pills and Publish button, `.catch()` on publish handlers+- `client/src/components/agents/tabs/OverviewTab.jsx` — Matching cooldown timer state and countdown display in Quick Actions rate limit pillsdiff --git a/client/src/components/agents/tabs/OverviewTab.jsx b/client/src/components/agents/tabs/OverviewTab.jsxindex 31b9d83018..e0454715b5 100644--- a/client/src/components/agents/tabs/OverviewTab.jsx+++ b/client/src/components/agents/tabs/OverviewTab.jsx@@ -1,20 +1,20 @@import { useState, useEffect, useCallback } from 'react';-import { Sparkles, Cpu } from 'lucide-react';+import { useNavigate } from 'react-router-dom';+import { Cpu, Zap, MessageSquare, Eye } from 'lucide-react';import toast from 'react-hot-toast';import * as api from '../../../services/api';import { PERSONALITY_STYLES, DEFAULT_PERSONALITY, DEFAULT_AVATAR, PLATFORM_TYPES, ACCOUNT_STATUSES } from '../constants';export default function OverviewTab({ agentId, agent, onAgentUpdate }) {+ const navigate = useNavigate();+// Personality form stateconst [formData, setFormData] = useState(null);const [topicsText, setTopicsText] = useState('');const [quirksText, setQuirksText] = useState('');- // AI generation state+ // Providers state (for AI config section)const [providers, setProviders] = useState([]);- const [selectedProviderId, setSelectedProviderId] = useState('');- const [selectedModel, setSelectedModel] = useState('');- const [generating, setGenerating] = useState(false);// Accounts stateconst [accounts, setAccounts] = useState([]);@@ -31,6 +31,16 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {// Stats stateconst [activityStats, setActivityStats] = useState(null);+ // Quick action state+ const [quickAccountId, setQuickAccountId] = useState('');+ const [engaging, setEngaging] = useState(false);+ const [checking, setChecking] = useState(false);+ const [rateLimits, setRateLimits] = useState(null);++ // Cooldown timer state+ const [cooldownEnds, setCooldownEnds] = useState({});+ const [, setTick] = useState(0);+// Initialize form from agentuseEffect(() => {if (!agent) return;@@ -74,51 +84,58 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {fetchStats();}, [fetchAccounts, fetchProviders, fetchStats]);- const selectedProvider = providers.find(p => p.id === selectedProviderId);- const availableModels = selectedProvider?.models || [];- const getModelsForProvider = (providerId) => {- const p = providers.find(pr => pr.id === providerId);- return p?.models || [];- };+ // Auto-select first active account for quick actions+ useEffect(() => {+ if (quickAccountId) return;+ const active = accounts.filter(a => a.status === 'active');+ if (active.length >= 1) {+ setQuickAccountId(active[0].id);+ }+ }, [accounts, quickAccountId]);- const handleGenerate = async () => {- setGenerating(true);- const seedData = {- name: formData.name.trim(),- description: formData.description.trim(),- personality: {- style: formData.personality.style,- tone: formData.personality.tone,- topics: topicsText.split(',').map(t => t.trim()).filter(Boolean),- quirks: quirksText.split(',').map(t => t.trim()).filter(Boolean),- promptPrefix: formData.personality.promptPrefix.trim()- },- avatar: { emoji: formData.avatar.emoji, color: formData.avatar.color }- };- const generated = await api.generateAgentPersonality(- seedData, selectedProviderId || null, selectedModel || null- ).catch(() => null);- setGenerating(false);+ // Load rate limits when quick account changes+ useEffect(() => {+ if (!quickAccountId) {+ setRateLimits(null);+ return;+ }+ api.getAgentRateLimits(quickAccountId).then(setRateLimits).catch(() => {});+ }, [quickAccountId]);- if (!generated) return;+ // Calculate cooldown end timestamps from rate limit data+ useEffect(() => {+ if (!rateLimits) { setCooldownEnds({}); return; }+ const ends = {};+ const now = Date.now();+ for (const [action, rl] of Object.entries(rateLimits)) {+ if (rl.cooldownRemainingMs > 0) {+ ends[action] = now + rl.cooldownRemainingMs;+ }+ }+ setCooldownEnds(ends);+ }, [rateLimits]);- setFormData(prev => ({- ...prev,- name: generated.name || prev.name,- description: generated.description || prev.description,- personality: {- style: generated.personality?.style || prev.personality.style,- tone: generated.personality?.tone || prev.personality.tone,- topics: generated.personality?.topics || prev.personality.topics,- quirks: generated.personality?.quirks || prev.personality.quirks,- promptPrefix: generated.personality?.promptPrefix || prev.personality.promptPrefix- },- avatar: {- emoji: generated.avatar?.emoji || prev.avatar.emoji,- color: generated.avatar?.color || prev.avatar.color+ // Tick cooldown timer every second while any cooldown is active+ useEffect(() => {+ const hasActive = Object.values(cooldownEnds).some(end => end > Date.now());+ if (!hasActive) return;+ let refetched = false;+ const interval = setInterval(() => {+ const stillActive = Object.values(cooldownEnds).some(end => end > Date.now());+ setTick(t => t + 1);+ if (!stillActive && !refetched) {+ refetched = true;+ if (quickAccountId) {+ api.getAgentRateLimits(quickAccountId).then(setRateLimits).catch(() => {});+ }}- }));- toast.success(`Generated: ${generated.name || 'personality'}`);+ }, 1000);+ return () => clearInterval(interval);+ }, [cooldownEnds, quickAccountId]);++ const getModelsForProvider = (providerId) => {+ const p = providers.find(pr => pr.id === providerId);+ return p?.models || [];};const buildAiConfig = (config) => {@@ -160,6 +177,26 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {}));};+ // Quick action handlers+ const handleEngage = async () => {+ if (!agentId || !quickAccountId) return;+ setEngaging(true);+ const result = await api.engageAgent(agentId, quickAccountId, 1, 3);+ setEngaging(false);+ toast.success(`Engaged: ${result.votes?.length || 0} votes, ${result.comments?.length || 0} comments`);+ api.getAgentRateLimits(quickAccountId).then(setRateLimits).catch(() => {});+ };++ const handleCheckPosts = async () => {+ if (!agentId || !quickAccountId) return;+ setChecking(true);+ const result = await api.checkAgentPosts(agentId, quickAccountId, 7, 2, 10).catch(() => null);+ setChecking(false);+ if (!result) return;+ toast.success(`Checked ${result.postsChecked} posts: ${result.engagement?.upvoted?.length || 0} upvotes, ${result.engagement?.replied?.length || 0} replies`);+ api.getAgentRateLimits(quickAccountId).then(setRateLimits).catch(() => {});+ };+// Account handlersconst resetAccountForm = () => {setAccountForm({ platform: 'moltbook', name: '', description: '' });@@ -203,13 +240,27 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {setTestResult(null);};+ const getCooldownMs = (action) => {+ const end = cooldownEnds[action];+ return end ? Math.max(0, end - Date.now()) : 0;+ };++ const formatCooldown = (ms) => {+ const totalSeconds = Math.ceil(ms / 1000);+ const minutes = Math.floor(totalSeconds / 60);+ const seconds = totalSeconds % 60;+ return `${minutes}:${seconds.toString().padStart(2, '0')}`;+ };+if (!formData) {return <div className="p-4 text-gray-400">Loading...</div>;}+ const activeAccounts = accounts.filter(a => a.status === 'active');+return (<div className="p-4 space-y-6">- {/* Quick Stats */}+ {/* Quick Stats - Full Width */}{activityStats && (<div className="grid grid-cols-3 gap-4"><div className="p-3 bg-port-card border border-port-border rounded-lg text-center">@@ -227,392 +278,429 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {</div>)}- {/* Personality Section */}- <div className="bg-port-card border border-port-border rounded-lg p-4">- <h3 className="text-md font-semibold text-white mb-4">Personality</h3>-- {/* AI Generation */}- <div className="mb-4 p-3 bg-port-bg border border-port-accent/30 rounded-lg">- <div className="flex items-center gap-2 mb-3">- <Sparkles size={16} className="text-port-accent" />- <span className="text-sm font-medium text-white">Regenerate with AI</span>- </div>- <div className="flex items-end gap-3">- <div className="flex-1">- <label className="block text-xs text-gray-400 mb-1">Provider</label>- <select- value={selectedProviderId}- onChange={(e) => { setSelectedProviderId(e.target.value); setSelectedModel(''); }}- disabled={generating}- className="w-full px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"- >- <option value="">Default (active)</option>- {providers.map(p => (- <option key={p.id} value={p.id}>{p.name}</option>- ))}- </select>- </div>- <div className="flex-1">- <label className="block text-xs text-gray-400 mb-1">Model</label>- <select- value={selectedModel}- onChange={(e) => setSelectedModel(e.target.value)}- disabled={generating}- className="w-full px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"- >- <option value="">Default</option>- {availableModels.map(m => (- <option key={m} value={m}>{m}</option>- ))}- </select>- </div>- <button- type="button"- onClick={handleGenerate}- disabled={generating}- className="px-4 py-1.5 bg-port-accent text-white rounded hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"- >- {generating ? (- <><span className="animate-spin">⚡</span>Generating...</>- ) : (- <><Sparkles size={14} />Generate</>- )}- </button>- </div>- </div>-- <form onSubmit={handleSave}>- <div className="grid grid-cols-2 gap-4 mb-4">- <div>- <label className="block text-sm text-gray-400 mb-1">Name</label>- <input- type="text"- value={formData.name}- onChange={(e) => setFormData({ ...formData, name: e.target.value })}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"- required- />- </div>- <div>- <label className="block text-sm text-gray-400 mb-1">Style</label>- <select- value={formData.personality.style}- onChange={(e) => updatePersonality('style', e.target.value)}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"- >- {PERSONALITY_STYLES.map(style => (- <option key={style.value} value={style.value}>{style.label}</option>- ))}- </select>- </div>- </div>-- <div className="mb-4">- <label className="block text-sm text-gray-400 mb-1">Description</label>- <textarea- value={formData.description}- onChange={(e) => setFormData({ ...formData, description: e.target.value })}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white h-20"- placeholder="Brief description of this agent's purpose..."- />- </div>-- <div className="mb-4">- <label className="block text-sm text-gray-400 mb-1">Tone</label>- <input- type="text"- value={formData.personality.tone}- onChange={(e) => updatePersonality('tone', e.target.value)}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"- placeholder="e.g., friendly but informative"- />- </div>-- <div className="mb-4">- <label className="block text-sm text-gray-400 mb-1">Topics (comma-separated)</label>- <input- type="text"- value={topicsText}- onChange={(e) => setTopicsText(e.target.value)}- onBlur={() => updatePersonality('topics', topicsText.split(',').map(t => t.trim()).filter(Boolean))}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"- placeholder="e.g., technology, AI, philosophy"- />- </div>-- <div className="mb-4">- <label className="block text-sm text-gray-400 mb-1">Quirks (comma-separated)</label>- <input- type="text"- value={quirksText}- onChange={(e) => setQuirksText(e.target.value)}- onBlur={() => updatePersonality('quirks', quirksText.split(',').map(t => t.trim()).filter(Boolean))}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"- placeholder="e.g., uses metaphors, asks follow-up questions"- />- </div>-- <div className="mb-4">- <label className="block text-sm text-gray-400 mb-1">Prompt Prefix</label>- <textarea- value={formData.personality.promptPrefix}- onChange={(e) => updatePersonality('promptPrefix', e.target.value)}- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white h-24 font-mono text-sm"- placeholder="Custom instructions injected into AI prompts..."- />- </div>-- <div className="flex items-center gap-4 mb-4">- <label className="block text-sm text-gray-400">Avatar Emoji</label>- <input- type="text"- value={formData.avatar.emoji || ''}- onChange={(e) => setFormData({ ...formData, avatar: { ...formData.avatar, emoji: e.target.value } })}- className="w-16 px-3 py-2 bg-port-bg border border-port-border rounded text-white text-center"- maxLength={2}- />- <label className="block text-sm text-gray-400">Color</label>- <input- type="color"- value={formData.avatar.color || '#3b82f6'}- onChange={(e) => setFormData({ ...formData, avatar: { ...formData.avatar, color: e.target.value } })}- className="w-12 h-8 border border-port-border rounded cursor-pointer"- />- </div>-- <button- type="submit"- className="px-4 py-2 bg-port-success text-white rounded hover:bg-port-success/80"- >- Save Changes- </button>- </form>- </div>-- {/* Per-Function AI Provider Section */}- <div className="bg-port-card border border-port-border rounded-lg p-4">- <div className="flex items-center gap-2 mb-3">- <Cpu size={16} className="text-port-accent" />- <h3 className="text-md font-semibold text-white">AI Providers</h3>- </div>- <p className="text-xs text-gray-500 mb-3">- Choose AI providers for each function. "System Default" uses the globally active provider.- </p>- <div className="space-y-3">- {[- { key: 'content', label: 'Content Generation', desc: 'Posts, comments, replies' },- { key: 'engagement', label: 'Engagement', desc: 'Autonomous voting & commenting' },- { key: 'challenge', label: 'Challenge Solving', desc: 'Verification challenges' }- ].map(({ key, label, desc }) => {- const fnConfig = formData.aiConfig?.[key] || {};- const fnModels = getModelsForProvider(fnConfig.providerId);- return (- <div key={key} className="flex items-end gap-3">- <div className="w-40 shrink-0 pb-1">- <div className="text-sm text-white">{label}</div>- <div className="text-[10px] text-gray-500">{desc}</div>+ {/* Two-Column Layout */}+ <div className="grid grid-cols-1 lg:grid-cols-5 gap-6">+ {/* Left Column - Personality Form */}+ <div className="lg:col-span-3">+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="text-md font-semibold text-white mb-4">Personality</h3>++ <form onSubmit={handleSave}>+ {/* Name + Style */}+ <div className="grid grid-cols-2 gap-4 mb-4">+ <div>+ <label className="block text-sm text-gray-400 mb-1">Name</label>+ <input+ type="text"+ value={formData.name}+ onChange={(e) => setFormData({ ...formData, name: e.target.value })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ required+ /></div>- <div className="flex-1">- <label className="block text-xs text-gray-400 mb-1">Provider</label>+ <div>+ <label className="block text-sm text-gray-400 mb-1">Style</label><select- value={fnConfig.providerId || ''}- onChange={(e) => setFormData(prev => ({- ...prev,- aiConfig: {- ...prev.aiConfig,- [key]: { ...prev.aiConfig?.[key], providerId: e.target.value || undefined, model: undefined }- }- }))}- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"+ value={formData.personality.style}+ onChange={(e) => updatePersonality('style', e.target.value)}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white">- <option value="">System Default</option>- {providers.map(p => (- <option key={p.id} value={p.id}>{p.name}</option>+ {PERSONALITY_STYLES.map(style => (+ <option key={style.value} value={style.value}>{style.label}</option>))}</select></div>+ </div>++ {/* Description */}+ <div className="mb-4">+ <label className="block text-sm text-gray-400 mb-1">Description</label>+ <textarea+ value={formData.description}+ onChange={(e) => setFormData({ ...formData, description: e.target.value })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white h-20"+ placeholder="Brief description of this agent's purpose..."+ />+ </div>++ {/* Tone + Avatar (emoji + color) */}+ <div className="flex items-end gap-4 mb-4"><div className="flex-1">- <label className="block text-xs text-gray-400 mb-1">Model</label>- <select- value={fnConfig.model || ''}- onChange={(e) => setFormData(prev => ({- ...prev,- aiConfig: {- ...prev.aiConfig,- [key]: { ...prev.aiConfig?.[key], model: e.target.value || undefined }- }- }))}- disabled={!fnConfig.providerId}- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm disabled:opacity-50"- >- <option value="">Default</option>- {fnModels.map(m => (- <option key={m} value={m}>{m}</option>- ))}- </select>+ <label className="block text-sm text-gray-400 mb-1">Tone</label>+ <input+ type="text"+ value={formData.personality.tone}+ onChange={(e) => updatePersonality('tone', e.target.value)}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ placeholder="e.g., friendly but informative"+ />+ </div>+ <div className="flex items-center gap-2">+ <label className="text-sm text-gray-400">Emoji</label>+ <input+ type="text"+ value={formData.avatar.emoji || ''}+ onChange={(e) => setFormData({ ...formData, avatar: { ...formData.avatar, emoji: e.target.value } })}+ className="w-14 px-2 py-2 bg-port-bg border border-port-border rounded text-white text-center"+ maxLength={2}+ />+ </div>+ <div className="flex items-center gap-2">+ <label className="text-sm text-gray-400">Color</label>+ <input+ type="color"+ value={formData.avatar.color || '#3b82f6'}+ onChange={(e) => setFormData({ ...formData, avatar: { ...formData.avatar, color: e.target.value } })}+ className="w-12 h-9 border border-port-border rounded cursor-pointer"+ /></div></div>- );- })}- </div>- <button- type="button"- onClick={async () => {- const aiConfig = buildAiConfig(formData.aiConfig);- await api.updateAgentPersonality(agentId, { aiConfig });- toast.success(aiConfig ? 'AI providers saved' : 'Reset to system defaults');- onAgentUpdate?.();- }}- className="mt-3 px-4 py-1.5 bg-port-success text-white rounded hover:bg-port-success/80 text-sm"- >- Save AI Config- </button>- </div>-- {/* Accounts Section */}- <div className="bg-port-card border border-port-border rounded-lg p-4">- <div className="flex justify-between items-center mb-4">- <h3 className="text-md font-semibold text-white">Platform Accounts</h3>- <button- onClick={() => setShowAccountForm(!showAccountForm)}- className="px-3 py-1.5 text-sm bg-port-accent text-white rounded hover:bg-port-accent/80"- >- {showAccountForm ? 'Cancel' : '+ Link Account'}- </button>- </div>- {showAccountForm && (- <form onSubmit={handleAccountSubmit} className="mb-4 p-3 bg-port-bg border border-port-border rounded-lg">- <div className="grid grid-cols-2 gap-4 mb-3">- <div>- <label className="block text-sm text-gray-400 mb-1">Platform</label>- <select- value={accountForm.platform}- onChange={(e) => setAccountForm({ ...accountForm, platform: e.target.value })}- className="w-full px-3 py-2 bg-port-card border border-port-border rounded text-white"- >- {PLATFORM_TYPES.map(platform => (- <option key={platform.value} value={platform.value}>- {platform.icon} {platform.label}- </option>- ))}- </select>+ {/* Topics + Quirks */}+ <div className="grid grid-cols-2 gap-4 mb-4">+ <div>+ <label className="block text-sm text-gray-400 mb-1">Topics (comma-separated)</label>+ <input+ type="text"+ value={topicsText}+ onChange={(e) => setTopicsText(e.target.value)}+ onBlur={() => updatePersonality('topics', topicsText.split(',').map(t => t.trim()).filter(Boolean))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ placeholder="e.g., technology, AI"+ />+ </div>+ <div>+ <label className="block text-sm text-gray-400 mb-1">Quirks (comma-separated)</label>+ <input+ type="text"+ value={quirksText}+ onChange={(e) => setQuirksText(e.target.value)}+ onBlur={() => updatePersonality('quirks', quirksText.split(',').map(t => t.trim()).filter(Boolean))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ placeholder="e.g., uses metaphors"+ />+ </div></div>- <div>- <label className="block text-sm text-gray-400 mb-1">Account Name</label>- <input- type="text"- value={accountForm.name}- onChange={(e) => setAccountForm({ ...accountForm, name: e.target.value })}- className="w-full px-3 py-2 bg-port-card border border-port-border rounded text-white"- placeholder="Display name on platform"- required++ {/* Prompt Prefix */}+ <div className="mb-4">+ <label className="block text-sm text-gray-400 mb-1">Prompt Prefix</label>+ <textarea+ value={formData.personality.promptPrefix}+ onChange={(e) => updatePersonality('promptPrefix', e.target.value)}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white h-24 font-mono text-sm"+ placeholder="Custom instructions injected into AI prompts..."/></div>- </div>- <div className="mb-3">- <label className="block text-sm text-gray-400 mb-1">Bio/Description</label>- <textarea- value={accountForm.description}- onChange={(e) => setAccountForm({ ...accountForm, description: e.target.value })}- className="w-full px-3 py-2 bg-port-card border border-port-border rounded text-white h-16"- placeholder="Brief bio for the platform profile..."- />- </div>- <div className="flex gap-2">- <button type="submit" className="px-3 py-1.5 text-sm bg-port-success text-white rounded hover:bg-port-success/80">- Register Account- </button>- <button type="button" onClick={resetAccountForm} className="px-3 py-1.5 text-sm bg-port-border text-gray-300 rounded hover:bg-port-border/80">- Cancel++ <button+ type="submit"+ className="px-4 py-2 bg-port-success text-white rounded hover:bg-port-success/80"+ >+ Save Changes</button>- </div>- </form>- )}-- {testResult && (- <div className={`mb-4 p-3 rounded border ${- testResult.success- ? 'bg-port-success/20 border-port-success/50 text-port-success'- : 'bg-port-error/20 border-port-error/50 text-port-error'- }`}>- <p className="text-sm">{testResult.message}</p>- {testResult.claimUrl && (- <div className="mt-2">- <a href={testResult.claimUrl} target="_blank" rel="noopener noreferrer" className="text-port-accent underline text-sm">- {testResult.claimUrl}- </a>- <button- onClick={() => handleAccountClaim(testResult.accountId)}- className="ml-4 px-3 py-1 bg-port-accent text-white rounded text-sm"- >- I've claimed it- </button>- </div>+ </form>+ </div>+ </div>++ {/* Right Column - Quick Actions, AI Providers, Accounts */}+ <div className="lg:col-span-2 space-y-6">+ {/* Quick Actions */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="text-md font-semibold text-white mb-3">Quick Actions</h3>++ {activeAccounts.length === 0 ? (+ <p className="text-sm text-gray-500">No active accounts — link one below to enable actions</p>+ ) : (+ <>+ {activeAccounts.length > 1 && (+ <div className="mb-3">+ <label className="block text-xs text-gray-400 mb-1">Account</label>+ <select+ value={quickAccountId}+ onChange={(e) => setQuickAccountId(e.target.value)}+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"+ >+ {activeAccounts.map(a => (+ <option key={a.id} value={a.id}>{a.credentials.username}</option>+ ))}+ </select>+ </div>+ )}++ {rateLimits && (+ <div className="flex flex-wrap gap-2 mb-3">+ {Object.entries(rateLimits).map(([action, rl]) => {+ const cooldownMs = getCooldownMs(action);+ const isCooling = cooldownMs > 0;+ const pct = rl.remaining / rl.maxPerDay;+ const colorClass = isCooling+ ? 'bg-port-warning/20 text-port-warning animate-pulse'+ : pct === 0+ ? 'bg-port-error/20 text-port-error'+ : pct < 0.25+ ? 'bg-port-warning/20 text-port-warning'+ : 'bg-port-success/20 text-port-success';+ return (+ <span key={action} className={`text-xs px-2 py-0.5 rounded ${colorClass}`} title={isCooling ? `Cooldown: ${formatCooldown(cooldownMs)}` : `${rl.remaining} of ${rl.maxPerDay} remaining`}>+ {isCooling ? `${action}: ${formatCooldown(cooldownMs)}` : `${action}: ${rl.remaining}/${rl.maxPerDay}`}+ </span>+ );+ })}+ </div>+ )}++ <div className="flex flex-wrap gap-2">+ <button+ onClick={() => navigate(`/agents/${agentId}/tools`)}+ className="px-3 py-1.5 text-sm bg-port-accent text-white rounded hover:bg-port-accent/80 flex items-center gap-1.5"+ >+ <Zap size={14} />+ Generate Post+ </button>+ <button+ onClick={handleEngage}+ disabled={engaging || !quickAccountId}+ className="px-3 py-1.5 text-sm bg-port-success text-white rounded hover:bg-port-success/80 disabled:opacity-50 flex items-center gap-1.5"+ >+ <MessageSquare size={14} />+ {engaging ? 'Engaging...' : 'Engage Now'}+ </button>+ <button+ onClick={handleCheckPosts}+ disabled={checking || !quickAccountId}+ className="px-3 py-1.5 text-sm bg-purple-600 text-white rounded hover:bg-purple-500 disabled:opacity-50 flex items-center gap-1.5"+ >+ <Eye size={14} />+ {checking ? 'Checking...' : 'Check Posts'}+ </button>+ </div>+ </>)}</div>- )}-- {accountsLoading ? (- <p className="text-sm text-gray-400">Loading accounts...</p>- ) : accounts.length === 0 ? (- <p className="text-sm text-gray-500 text-center py-4">No platform accounts linked to this agent</p>- ) : (- <div className="space-y-3">- {accounts.map(account => {- const statusConfig = ACCOUNT_STATUSES[account.status] || ACCOUNT_STATUSES.error;- const platform = PLATFORM_TYPES.find(p => p.value === account.platform);-- return (- <div key={account.id} className="p-3 bg-port-bg border border-port-border rounded-lg">- <div className="flex items-start justify-between">++ {/* Per-Function AI Provider Section */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center gap-2 mb-3">+ <Cpu size={16} className="text-port-accent" />+ <h3 className="text-md font-semibold text-white">AI Providers</h3>+ </div>+ <p className="text-xs text-gray-500 mb-3">+ Choose AI providers for each function. "System Default" uses the globally active provider.+ </p>+ <div className="space-y-3">+ {[+ { key: 'content', label: 'Content Generation', desc: 'Posts, comments, replies' },+ { key: 'engagement', label: 'Engagement', desc: 'Autonomous voting & commenting' },+ { key: 'challenge', label: 'Challenge Solving', desc: 'Verification challenges' }+ ].map(({ key, label, desc }) => {+ const fnConfig = formData.aiConfig?.[key] || {};+ const fnModels = getModelsForProvider(fnConfig.providerId);+ return (+ <div key={key} className="space-y-1"><div>- <div className="flex items-center gap-2 mb-1">- <span>{platform?.icon || '🔗'}</span>- <span className="font-medium text-white">{account.credentials.username}</span>- <span className={`text-xs px-2 py-0.5 rounded ${statusConfig.bgColor} ${statusConfig.color}`}>- {statusConfig.label}- </span>- </div>- <p className="text-xs text-gray-500">- {platform?.label}- {account.lastActivity && ` • Last activity: ${new Date(account.lastActivity).toLocaleString()}`}- </p>- {account.platformData?.claimUrl && account.status === 'pending' && (- <a href={account.platformData.claimUrl} target="_blank" rel="noopener noreferrer" className="text-port-accent underline text-xs mt-1 inline-block">- Claim URL- </a>- )}+ <div className="text-sm text-white">{label}</div>+ <div className="text-[10px] text-gray-500">{desc}</div></div>- <div className="flex items-center gap-2">- <button- onClick={() => handleAccountTest(account.id)}- disabled={testingId === account.id}- className="px-2 py-1 text-xs bg-port-accent/20 text-port-accent rounded hover:bg-port-accent/30 disabled:opacity-50"+ <div className="flex gap-2">+ <select+ value={fnConfig.providerId || ''}+ onChange={(e) => setFormData(prev => ({+ ...prev,+ aiConfig: {+ ...prev.aiConfig,+ [key]: { ...prev.aiConfig?.[key], providerId: e.target.value || undefined, model: undefined }+ }+ }))}+ className="flex-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm">- {testingId === account.id ? 'Testing...' : 'Test'}- </button>- {account.status === 'pending' && (- <button- onClick={() => handleAccountClaim(account.id)}- className="px-2 py-1 text-xs bg-port-success/20 text-port-success rounded hover:bg-port-success/30"- >- Claimed- </button>- )}- <button- onClick={() => handleAccountDelete(account.id)}- className="px-2 py-1 text-xs bg-port-error/20 text-port-error rounded hover:bg-port-error/30"+ <option value="">System Default</option>+ {providers.map(p => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+ <select+ value={fnConfig.model || ''}+ onChange={(e) => setFormData(prev => ({+ ...prev,+ aiConfig: {+ ...prev.aiConfig,+ [key]: { ...prev.aiConfig?.[key], model: e.target.value || undefined }+ }+ }))}+ disabled={!fnConfig.providerId}+ className="flex-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm disabled:opacity-50">- Delete- </button>+ <option value="">Default</option>+ {fnModels.map(m => (+ <option key={m} value={m}>{m}</option>+ ))}+ </select></div></div>+ );+ })}+ </div>+ <button+ type="button"+ onClick={async () => {+ const aiConfig = buildAiConfig(formData.aiConfig);+ await api.updateAgentPersonality(agentId, { aiConfig });+ toast.success(aiConfig ? 'AI providers saved' : 'Reset to system defaults');+ onAgentUpdate?.();+ }}+ className="mt-3 px-4 py-1.5 bg-port-success text-white rounded hover:bg-port-success/80 text-sm"+ >+ Save AI Config+ </button>+ </div>++ {/* Accounts Section */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex justify-between items-center mb-4">+ <h3 className="text-md font-semibold text-white">Platform Accounts</h3>+ <button+ onClick={() => setShowAccountForm(!showAccountForm)}+ className="px-3 py-1.5 text-sm bg-port-accent text-white rounded hover:bg-port-accent/80"+ >+ {showAccountForm ? 'Cancel' : '+ Link Account'}+ </button>+ </div>++ {showAccountForm && (+ <form onSubmit={handleAccountSubmit} className="mb-4 p-3 bg-port-bg border border-port-border rounded-lg">+ <div className="grid grid-cols-2 gap-4 mb-3">+ <div>+ <label className="block text-sm text-gray-400 mb-1">Platform</label>+ <select+ value={accountForm.platform}+ onChange={(e) => setAccountForm({ ...accountForm, platform: e.target.value })}+ className="w-full px-3 py-2 bg-port-card border border-port-border rounded text-white"+ >+ {PLATFORM_TYPES.map(platform => (+ <option key={platform.value} value={platform.value}>+ {platform.icon} {platform.label}+ </option>+ ))}+ </select>+ </div>+ <div>+ <label className="block text-sm text-gray-400 mb-1">Account Name</label>+ <input+ type="text"+ value={accountForm.name}+ onChange={(e) => setAccountForm({ ...accountForm, name: e.target.value })}+ className="w-full px-3 py-2 bg-port-card border border-port-border rounded text-white"+ placeholder="Display name on platform"+ required+ />+ </div>+ </div>+ <div className="mb-3">+ <label className="block text-sm text-gray-400 mb-1">Bio/Description</label>+ <textarea+ value={accountForm.description}+ onChange={(e) => setAccountForm({ ...accountForm, description: e.target.value })}+ className="w-full px-3 py-2 bg-port-card border border-port-border rounded text-white h-16"+ placeholder="Brief bio for the platform profile..."+ /></div>- );- })}+ <div className="flex gap-2">+ <button type="submit" className="px-3 py-1.5 text-sm bg-port-success text-white rounded hover:bg-port-success/80">+ Register Account+ </button>+ <button type="button" onClick={resetAccountForm} className="px-3 py-1.5 text-sm bg-port-border text-gray-300 rounded hover:bg-port-border/80">+ Cancel+ </button>+ </div>+ </form>+ )}++ {testResult && (+ <div className={`mb-4 p-3 rounded border ${+ testResult.success+ ? 'bg-port-success/20 border-port-success/50 text-port-success'+ : 'bg-port-error/20 border-port-error/50 text-port-error'+ }`}>+ <p className="text-sm">{testResult.message}</p>+ {testResult.claimUrl && (+ <div className="mt-2">+ <a href={testResult.claimUrl} target="_blank" rel="noopener noreferrer" className="text-port-accent underline text-sm">+ {testResult.claimUrl}+ </a>+ <button+ onClick={() => handleAccountClaim(testResult.accountId)}+ className="ml-4 px-3 py-1 bg-port-accent text-white rounded text-sm"+ >+ I've claimed it+ </button>+ </div>+ )}+ </div>+ )}++ {accountsLoading ? (+ <p className="text-sm text-gray-400">Loading accounts...</p>+ ) : accounts.length === 0 ? (+ <p className="text-sm text-gray-500 text-center py-4">No platform accounts linked to this agent</p>+ ) : (+ <div className="space-y-3">+ {accounts.map(account => {+ const statusConfig = ACCOUNT_STATUSES[account.status] || ACCOUNT_STATUSES.error;+ const platform = PLATFORM_TYPES.find(p => p.value === account.platform);++ return (+ <div key={account.id} className="p-3 bg-port-bg border border-port-border rounded-lg">+ <div className="flex items-start justify-between">+ <div>+ <div className="flex items-center gap-2 mb-1">+ <span>{platform?.icon || '🔗'}</span>+ <span className="font-medium text-white">{account.credentials.username}</span>+ <span className={`text-xs px-2 py-0.5 rounded ${statusConfig.bgColor} ${statusConfig.color}`}>+ {statusConfig.label}+ </span>+ </div>+ <p className="text-xs text-gray-500">+ {platform?.label}+ {account.lastActivity && ` • Last activity: ${new Date(account.lastActivity).toLocaleString()}`}+ </p>+ {account.platformData?.claimUrl && account.status === 'pending' && (+ <a href={account.platformData.claimUrl} target="_blank" rel="noopener noreferrer" className="text-port-accent underline text-xs mt-1 inline-block">+ Claim URL+ </a>+ )}+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={() => handleAccountTest(account.id)}+ disabled={testingId === account.id}+ className="px-2 py-1 text-xs bg-port-accent/20 text-port-accent rounded hover:bg-port-accent/30 disabled:opacity-50"+ >+ {testingId === account.id ? 'Testing...' : 'Test'}+ </button>+ {account.status === 'pending' && (+ <button+ onClick={() => handleAccountClaim(account.id)}+ className="px-2 py-1 text-xs bg-port-success/20 text-port-success rounded hover:bg-port-success/30"+ >+ Claimed+ </button>+ )}+ <button+ onClick={() => handleAccountDelete(account.id)}+ className="px-2 py-1 text-xs bg-port-error/20 text-port-error rounded hover:bg-port-error/30"+ >+ Delete+ </button>+ </div>+ </div>+ </div>+ );+ })}+ </div>+ )}</div>- )}+ </div></div></div>);diff --git a/client/src/components/agents/tabs/ToolsTab.jsx b/client/src/components/agents/tabs/ToolsTab.jsxindex 63733b3da7..a57541fad2 100644--- a/client/src/components/agents/tabs/ToolsTab.jsx+++ b/client/src/components/agents/tabs/ToolsTab.jsx@@ -41,9 +41,17 @@ export default function ToolsTab({ agentId, agent }) {const [drafts, setDrafts] = useState([]);const [activeDraftId, setActiveDraftId] = useState(null);+ // Cooldown timer state+ const [cooldownEnds, setCooldownEnds] = useState({});+ const [, setTick] = useState(0);+const fetchInitial = useCallback(async () => {const accountsData = await api.getPlatformAccounts(agentId);- setAccounts(accountsData.filter(a => a.status === 'active'));+ const active = accountsData.filter(a => a.status === 'active');+ setAccounts(active);+ if (active.length === 1 && !selectedAccountId) {+ setSelectedAccountId(active[0].id);+ }setLoading(false);}, [agentId]);@@ -64,6 +72,37 @@ export default function ToolsTab({ agentId, agent }) {}).catch(() => {});}, [selectedAccountId]);+ // Calculate cooldown end timestamps from rate limit data+ useEffect(() => {+ if (!rateLimits) { setCooldownEnds({}); return; }+ const ends = {};+ const now = Date.now();+ for (const [action, rl] of Object.entries(rateLimits)) {+ if (rl.cooldownRemainingMs > 0) {+ ends[action] = now + rl.cooldownRemainingMs;+ }+ }+ setCooldownEnds(ends);+ }, [rateLimits]);++ // Tick cooldown timer every second while any cooldown is active+ useEffect(() => {+ const hasActive = Object.values(cooldownEnds).some(end => end > Date.now());+ if (!hasActive) return;+ let refetched = false;+ const interval = setInterval(() => {+ const stillActive = Object.values(cooldownEnds).some(end => end > Date.now());+ setTick(t => t + 1);+ if (!stillActive && !refetched) {+ refetched = true;+ if (selectedAccountId) {+ api.getAgentRateLimits(selectedAccountId).then(setRateLimits).catch(() => {});+ }+ }+ }, 1000);+ return () => clearInterval(interval);+ }, [cooldownEnds, selectedAccountId]);+const loadDrafts = useCallback(async () => {if (!agentId) return;const data = await api.getAgentDrafts(agentId);@@ -133,7 +172,13 @@ export default function ToolsTab({ agentId, agent }) {const handlePublishPost = async () => {if (!postTitle || !postContent) return;setPublishing(true);- const result = await api.publishAgentPost(agentId, selectedAccountId, selectedSubmolt, postTitle, postContent);+ const result = await api.publishAgentPost(agentId, selectedAccountId, selectedSubmolt, postTitle, postContent).catch(() => null);++ if (!result) {+ setPublishing(false);+ api.getAgentRateLimits(selectedAccountId).then(setRateLimits).catch(() => {});+ return;+ }if (activeDraftId) {if (result?.verificationFailed) {@@ -191,7 +236,13 @@ export default function ToolsTab({ agentId, agent }) {setPublishingComment(true);const result = await api.publishAgentComment(agentId, selectedAccountId, selectedPost.id, commentContent, replyToId || undefined- );+ ).catch(() => null);++ if (!result) {+ setPublishingComment(false);+ api.getAgentRateLimits(selectedAccountId).then(setRateLimits).catch(() => {});+ return;+ }if (activeDraftId) {if (result?.verificationFailed) {@@ -273,6 +324,18 @@ export default function ToolsTab({ agentId, agent }) {toast.success('Draft deleted');};+ const getCooldownMs = (action) => {+ const end = cooldownEnds[action];+ return end ? Math.max(0, end - Date.now()) : 0;+ };++ const formatCooldown = (ms) => {+ const totalSeconds = Math.ceil(ms / 1000);+ const minutes = Math.floor(totalSeconds / 60);+ const seconds = totalSeconds % 60;+ return `${minutes}:${seconds.toString().padStart(2, '0')}`;+ };+if (loading) {return <div className="p-4 text-gray-400">Loading tools...</div>;}@@ -301,15 +364,19 @@ export default function ToolsTab({ agentId, agent }) {{rateLimits && (<div className="flex gap-3 ml-auto">{Object.entries(rateLimits).map(([action, rl]) => {+ const cooldownMs = getCooldownMs(action);+ const isCooling = cooldownMs > 0;const pct = rl.remaining / rl.maxPerDay;- const colorClass = pct === 0- ? 'bg-port-error/20 text-port-error'- : pct < 0.25- ? 'bg-port-warning/20 text-port-warning'- : 'bg-port-success/20 text-port-success';+ const colorClass = isCooling+ ? 'bg-port-warning/20 text-port-warning animate-pulse'+ : pct === 0+ ? 'bg-port-error/20 text-port-error'+ : pct < 0.25+ ? 'bg-port-warning/20 text-port-warning'+ : 'bg-port-success/20 text-port-success';return (- <div key={action} className={`text-xs px-2 py-1 rounded ${colorClass}`} title={`${rl.remaining} of ${rl.maxPerDay} ${action}s remaining today`}>- {action}: {rl.remaining} left+ <div key={action} className={`text-xs px-2 py-1 rounded ${colorClass}`} title={`${rl.remaining} of ${rl.maxPerDay} ${action}s remaining today${isCooling ? ` — cooldown: ${formatCooldown(cooldownMs)}` : ''}`}>+ {isCooling ? `${action}: ${formatCooldown(cooldownMs)}` : `${action}: ${rl.remaining} left`}</div>);})}@@ -575,10 +642,11 @@ export default function ToolsTab({ agentId, agent }) {</button><buttononClick={handlePublishPost}- disabled={publishing}+ disabled={publishing || getCooldownMs('post') > 0}className="px-4 py-1 text-sm bg-port-success text-white rounded hover:bg-port-success/80 disabled:opacity-50"+ title={getCooldownMs('post') > 0 ? `Post cooldown: ${formatCooldown(getCooldownMs('post'))}` : ''}>- {publishing ? 'Publishing...' : 'Publish'}+ {publishing ? 'Publishing...' : getCooldownMs('post') > 0 ? `Wait ${formatCooldown(getCooldownMs('post'))}` : 'Publish'}</button></>)}diff --git a/server/integrations/moltbook/api.js b/server/integrations/moltbook/api.jsindex a2fa9da46c..76287ca2f2 100644--- a/server/integrations/moltbook/api.js+++ b/server/integrations/moltbook/api.js@@ -7,11 +7,24 @@* API Base: https://www.moltbook.com/api/v1*/-import { checkRateLimit, recordAction } from './rateLimits.js';+import { checkRateLimit, recordAction, syncFromExternal } from './rateLimits.js';import { solveChallenge } from './challengeSolver.js';const API_BASE = 'https://www.moltbook.com/api/v1';+/**+ * Infer the rate-limited action type from a Moltbook API endpoint+ */+function inferActionFromEndpoint(endpoint, method) {+ if (method !== 'POST') return null;+ if (endpoint === '/posts') return 'post';+ if (/^\/posts\/[^/]+\/comments$/.test(endpoint)) return 'comment';+ if (/^\/posts\/[^/]+\/vote$/.test(endpoint)) return 'vote';+ if (/^\/comments\/[^/]+\/upvote$/.test(endpoint)) return 'vote';+ if (/^\/agents\/[^/]+\/follow$/.test(endpoint)) return 'follow';+ return null;+}+/*** Handle a Moltbook verification challenge embedded in a response* Challenges are obfuscated math word problems that must be solved within 5 minutes.@@ -77,6 +90,16 @@ async function request(endpoint, options = {}, aiConfig) {} else {console.log(`📚 Moltbook API: 404 ${endpoint}`);}+ // Sync local rate limit state when platform enforces a cooldown+ if (response.status === 429) {+ const apiKey = config.headers?.['Authorization']?.replace('Bearer ', '');+ const action = inferActionFromEndpoint(endpoint, options.method);+ if (apiKey && action) {+ syncFromExternal(apiKey, action);+ console.log(`⏱️ Synced ${action} rate limit from 429 response`);+ }+ }+const err = new Error(message);err.status = response.status;err.suspended = response.status === 403 && message.toLowerCase().includes('suspended');diff --git a/server/integrations/moltbook/rateLimits.js b/server/integrations/moltbook/rateLimits.jsindex b6a6dce590..7cbefc030d 100644--- a/server/integrations/moltbook/rateLimits.js+++ b/server/integrations/moltbook/rateLimits.js@@ -134,6 +134,19 @@ export function getRateLimitStatus(apiKey) {return status;}+/**+ * Sync local rate limit state from a platform 429 response+ * Sets lastAction to now so cooldown timer reflects platform enforcement+ * @param {string} apiKey - The API key+ * @param {string} action - The action type+ */+export function syncFromExternal(apiKey, action) {+ const state = getState(apiKey);+ if (state[action]) {+ state[action].lastAction = Date.now();+ }+}+/*** Clear rate limit state for an API key (e.g., on account deletion)* @param {string} apiKey - The API key