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 draft persistence for generated content
Adam Eivy858b89d45d42
diff --git a/.changelog/v0.12.x.md b/.changelog/v0.12.x.mdindex 5163a434c4..0599413b93 100644--- a/.changelog/v0.12.x.md+++ b/.changelog/v0.12.x.md@@ -75,10 +75,22 @@ This release adds branch management and automated release workflow capabilities- `server/lib/validation.js` — Added tool schemas and `engage` action type**Client changes**:-- `client/src/components/agents/tabs/ToolsTab.jsx` — Full-featured tools UI with feed browser, post/comment composers, and engage button-- `client/src/services/api.js` — Added 11 new API functions for agent tools+- `client/src/components/agents/tabs/ToolsTab.jsx` — Full-featured tools UI with feed browser, post/comment composers, drafts panel, and engage button+- `client/src/services/api.js` — Added 11 new API functions for agent tools plus 4 for draft management- `client/src/components/agents/constants.js` — Added Tools tab and Engage action type+### Agents — Draft Persistence for Generated Content+- **Auto-save drafts**: AI-generated posts and comments are automatically saved as drafts, so content isn't lost when navigating away+- **Drafts panel**: New section in the Tools tab listing all saved drafts per agent, sorted by newest first+- **Load into composer**: Click a draft to load it back into the post or comment composer for further editing+- **Auto-delete on publish**: Drafts are automatically removed when their content is published to Moltbook+- **Manual delete**: Remove unwanted drafts with the delete button++**Server changes**:+- `server/services/agentDrafts.js` — New service for draft CRUD operations, persisting to `data/agents/drafts/{agentId}.json`+- `server/routes/agentTools.js` — Added GET/POST/PUT/DELETE draft endpoints+- `server/lib/validation.js` — Added `createDraftSchema` and `updateDraftSchema`+### Dashboard — Archived App Styling- **Greyed-out cards**: Archived apps on the main dashboard now render with reduced opacity, dimmed icon/title colors, and a subtle "Archived" badge next to the app name- **Sorted to bottom**: Archived apps are sorted after active apps in the grid so they don't intermix with actively managed servicesdiff --git a/client/src/components/agents/tabs/ToolsTab.jsx b/client/src/components/agents/tabs/ToolsTab.jsxindex 3214c71187..4cf15ce4de 100644--- a/client/src/components/agents/tabs/ToolsTab.jsx+++ b/client/src/components/agents/tabs/ToolsTab.jsx@@ -35,6 +35,11 @@ export default function ToolsTab() {const [engaging, setEngaging] = useState(false);const [engageResult, setEngageResult] = useState(null);+ // Drafts state+ const [drafts, setDrafts] = useState([]);+ const [draftsLoading, setDraftsLoading] = useState(false);+ const [activeDraftId, setActiveDraftId] = useState(null);+const fetchInitial = useCallback(async () => {const [agentsData, accountsData] = await Promise.all([api.getAgentPersonalities(),@@ -66,6 +71,17 @@ export default function ToolsTab() {}).catch(() => {});}, [selectedAccountId]);+ const loadDrafts = useCallback(async (agentId) => {+ if (!agentId) {+ setDrafts([]);+ return;+ }+ setDraftsLoading(true);+ const data = await api.getAgentDrafts(agentId);+ setDrafts(data);+ setDraftsLoading(false);+ }, []);+const handleAgentChange = (agentId) => {setSelectedAgentId(agentId);setSelectedAccountId('');@@ -75,6 +91,8 @@ export default function ToolsTab() {setPostContent('');setCommentContent('');setEngageResult(null);+ setActiveDraftId(null);+ loadDrafts(agentId);};const handleBrowseFeed = async () => {@@ -112,7 +130,7 @@ export default function ToolsTab() {}};- // Post generation+ // Post generation (auto-saves as draft)const handleGeneratePost = async () => {if (!selectedAgentId || !selectedAccountId) return;setGenerating(true);@@ -120,13 +138,33 @@ export default function ToolsTab() {setPostTitle(generated.title);setPostContent(generated.content);setGenerating(false);- toast.success('Post generated');++ // Auto-save as draft+ const draft = await api.createAgentDraft({+ agentId: selectedAgentId,+ type: 'post',+ title: generated.title,+ content: generated.content,+ submolt: selectedSubmolt,+ accountId: selectedAccountId+ });+ setActiveDraftId(draft.id);+ loadDrafts(selectedAgentId);+ toast.success('Post generated and saved as draft');};const handlePublishPost = async () => {if (!postTitle || !postContent) return;setPublishing(true);await api.publishAgentPost(selectedAgentId, selectedAccountId, selectedSubmolt, postTitle, postContent);++ // Delete the draft after publishing+ if (activeDraftId) {+ await api.deleteAgentDraft(selectedAgentId, activeDraftId).catch(() => {});+ setActiveDraftId(null);+ loadDrafts(selectedAgentId);+ }+setPostTitle('');setPostContent('');setPublishing(false);@@ -134,7 +172,7 @@ export default function ToolsTab() {api.getAgentRateLimits(selectedAccountId).then(setRateLimits).catch(() => {});};- // Comment generation+ // Comment generation (auto-saves as draft)const handleGenerateComment = async () => {if (!selectedPost) return;setGeneratingComment(true);@@ -143,7 +181,20 @@ export default function ToolsTab() {);setCommentContent(generated.content);setGeneratingComment(false);- toast.success('Comment generated');++ // Auto-save as draft+ const draft = await api.createAgentDraft({+ agentId: selectedAgentId,+ type: 'comment',+ content: generated.content,+ postId: selectedPost.id,+ parentId: replyToId || null,+ postTitle: selectedPost.title,+ accountId: selectedAccountId+ });+ setActiveDraftId(draft.id);+ loadDrafts(selectedAgentId);+ toast.success('Comment generated and saved as draft');};const handlePublishComment = async () => {@@ -152,6 +203,14 @@ export default function ToolsTab() {await api.publishAgentComment(selectedAgentId, selectedAccountId, selectedPost.id, commentContent, replyToId || undefined);++ // Delete the draft after publishing+ if (activeDraftId) {+ await api.deleteAgentDraft(selectedAgentId, activeDraftId).catch(() => {});+ setActiveDraftId(null);+ loadDrafts(selectedAgentId);+ }+setCommentContent('');setReplyToId(null);setPublishingComment(false);@@ -173,6 +232,39 @@ export default function ToolsTab() {api.getAgentRateLimits(selectedAccountId).then(setRateLimits).catch(() => {});};+ const handleLoadDraft = (draft) => {+ setActiveDraftId(draft.id);+ if (draft.type === 'post') {+ setPostTitle(draft.title || '');+ setPostContent(draft.content || '');+ if (draft.submolt) setSelectedSubmolt(draft.submolt);+ if (draft.accountId) setSelectedAccountId(draft.accountId);+ setSelectedPost(null);+ setCommentContent('');+ } else {+ setCommentContent(draft.content || '');+ setReplyToId(draft.parentId || null);+ // If we have a postId, load the post for context+ if (draft.postId && draft.accountId) {+ setSelectedAccountId(draft.accountId);+ api.getAgentPost(draft.accountId, draft.postId).then(details => {+ setSelectedPost(details);+ setPostComments(details.comments || []);+ }).catch(() => {});+ }+ }+ toast.success(`Loaded ${draft.type} draft`);+ };++ const handleDeleteDraft = async (draftId) => {+ await api.deleteAgentDraft(selectedAgentId, draftId);+ if (activeDraftId === draftId) {+ setActiveDraftId(null);+ }+ loadDrafts(selectedAgentId);+ toast.success('Draft deleted');+ };+if (loading) {return <div className="p-4 text-gray-400">Loading tools...</div>;}@@ -439,6 +531,58 @@ export default function ToolsTab() {</div></div>+ {/* Drafts */}+ {drafts.length > 0 && (+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="font-semibold text-white mb-3">+ Drafts ({drafts.length})+ </h3>+ <div className="space-y-2 max-h-[300px] overflow-y-auto">+ {drafts.map(draft => (+ <div+ key={draft.id}+ className={`p-3 border rounded transition-colors ${+ activeDraftId === draft.id+ ? 'border-port-accent bg-port-accent/10'+ : 'border-port-border hover:border-port-border/80'+ }`}+ >+ <div className="flex items-start justify-between">+ <div className="flex-1 min-w-0 cursor-pointer" onClick={() => handleLoadDraft(draft)}>+ <div className="flex items-center gap-2">+ <span className="text-xs px-1.5 py-0.5 rounded bg-port-accent/20 text-port-accent">+ {draft.type}+ </span>+ {draft.submolt && (+ <span className="text-xs text-gray-500">/{draft.submolt}</span>+ )}+ </div>+ <p className="text-sm text-white mt-1 truncate">+ {draft.title || draft.content?.substring(0, 80)}+ </p>+ {draft.postTitle && (+ <p className="text-xs text-gray-500 mt-0.5">+ re: {draft.postTitle}+ </p>+ )}+ <p className="text-[10px] text-gray-600 mt-1">+ {new Date(draft.createdAt).toLocaleString()}+ </p>+ </div>+ <button+ onClick={() => handleDeleteDraft(draft.id)}+ className="text-gray-600 hover:text-port-error ml-2 shrink-0 text-sm"+ title="Delete draft"+ >+ x+ </button>+ </div>+ </div>+ ))}+ </div>+ </div>+ )}+{/* Comment Composer */}{selectedPost && (<div className="bg-port-card border border-port-border rounded-lg p-4">diff --git a/client/src/services/api.js b/client/src/services/api.jsindex e8bf943e30..dd986f9815 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -363,6 +363,20 @@ export const getAgentSubmolts = (accountId) => request(`/agents/tools/submolts?aexport const getAgentPost = (accountId, postId) => request(`/agents/tools/post/${postId}?accountId=${accountId}`);export const getAgentRateLimits = (accountId) => request(`/agents/tools/rate-limits?accountId=${accountId}`);+// Agent Drafts+export const getAgentDrafts = (agentId) => request(`/agents/tools/drafts?agentId=${agentId}`);+export const createAgentDraft = (data) => request('/agents/tools/drafts', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const updateAgentDraft = (agentId, draftId, data) => request(`/agents/tools/drafts/${draftId}?agentId=${agentId}`, {+ method: 'PUT',+ body: JSON.stringify(data)+});+export const deleteAgentDraft = (agentId, draftId) => request(`/agents/tools/drafts/${draftId}?agentId=${agentId}`, {+ method: 'DELETE'+});+// Agent Activityexport const getAgentActivities = (limit = 50, agentIds = null, action = null) => {const params = new URLSearchParams();diff --git a/server/lib/validation.js b/server/lib/validation.jsindex c81483024a..457540514e 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -244,6 +244,24 @@ export const engageSchema = z.object({maxVotes: z.number().int().min(0).max(10).optional().default(3)});+export const createDraftSchema = z.object({+ agentId: z.string().min(1),+ type: z.enum(['post', 'comment']),+ title: z.string().max(300).optional().nullable(),+ content: z.string().min(1).max(10000),+ submolt: z.string().max(100).optional().nullable(),+ postId: z.string().optional().nullable(),+ parentId: z.string().optional().nullable(),+ postTitle: z.string().max(300).optional().nullable(),+ accountId: z.string().optional().nullable()+});++export const updateDraftSchema = z.object({+ title: z.string().max(300).optional().nullable(),+ content: z.string().min(1).max(10000).optional(),+ submolt: z.string().max(100).optional().nullable()+});+/*** Validate data against a schema* Returns { success: true, data } or { success: false, errors }diff --git a/server/routes/agentTools.js b/server/routes/agentTools.jsindex dc23cf98ff..0b7e764304 100644--- a/server/routes/agentTools.js+++ b/server/routes/agentTools.js@@ -13,11 +13,14 @@ import {generateCommentSchema,publishPostSchema,publishCommentSchema,- engageSchema+ engageSchema,+ createDraftSchema,+ updateDraftSchema} from '../lib/validation.js';import * as platformAccounts from '../services/platformAccounts.js';import * as agentPersonalities from '../services/agentPersonalities.js';import * as agentActivity from '../services/agentActivity.js';+import * as agentDrafts from '../services/agentDrafts.js';import { generatePost, generateComment, generateReply } from '../services/agentContentGenerator.js';import { findRelevantPosts } from '../services/agentFeedFilter.js';import { MoltbookClient } from '../integrations/moltbook/index.js';@@ -328,4 +331,69 @@ router.get('/rate-limits', asyncHandler(async (req, res) => {res.json(rateLimits);}));+// =============================================================================+// DRAFTS+// =============================================================================++// GET /drafts - List drafts for an agent+router.get('/drafts', asyncHandler(async (req, res) => {+ const { agentId } = req.query;+ if (!agentId) {+ throw new ServerError('agentId required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ console.log(`🛠️ GET /api/agents/tools/drafts agent=${agentId}`);+ const drafts = await agentDrafts.listDrafts(agentId);+ res.json(drafts);+}));++// POST /drafts - Create a draft+router.post('/drafts', asyncHandler(async (req, res) => {+ const { success, data, errors } = validate(createDraftSchema, req.body);+ if (!success) {+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });+ }++ console.log(`🛠️ POST /api/agents/tools/drafts agent=${data.agentId} type=${data.type}`);+ const draft = await agentDrafts.createDraft(data.agentId, data);+ res.status(201).json(draft);+}));++// PUT /drafts/:draftId - Update a draft+router.put('/drafts/:draftId', asyncHandler(async (req, res) => {+ const { draftId } = req.params;+ const { agentId } = req.query;+ if (!agentId) {+ throw new ServerError('agentId required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ const { success, data, errors } = validate(updateDraftSchema, req.body);+ if (!success) {+ throw new ServerError('Validation failed', { status: 400, code: 'VALIDATION_ERROR', context: { errors } });+ }++ console.log(`🛠️ PUT /api/agents/tools/drafts/${draftId} agent=${agentId}`);+ const updated = await agentDrafts.updateDraft(agentId, draftId, data);+ if (!updated) {+ throw new ServerError('Draft not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(updated);+}));++// DELETE /drafts/:draftId - Delete a draft+router.delete('/drafts/:draftId', asyncHandler(async (req, res) => {+ const { draftId } = req.params;+ const { agentId } = req.query;+ if (!agentId) {+ throw new ServerError('agentId required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ console.log(`🛠️ DELETE /api/agents/tools/drafts/${draftId} agent=${agentId}`);+ const deleted = await agentDrafts.deleteDraft(agentId, draftId);+ if (!deleted) {+ throw new ServerError('Draft not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.status(204).send();+}));+export default router;diff --git a/server/services/agentDrafts.js b/server/services/agentDrafts.jsnew file mode 100644index 0000000000..f2d2122ac7--- /dev/null+++ b/server/services/agentDrafts.js@@ -0,0 +1,99 @@+/**+ * Agent Drafts Service+ *+ * Persists generated content as drafts per agent.+ * Drafts are stored as JSON files: data/agents/drafts/{agentId}.json+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { v4 as uuidv4 } from 'uuid';+import { ensureDir, PATHS } from '../lib/fileUtils.js';++const DRAFTS_DIR = join(PATHS.agentPersonalities, 'drafts');++async function getDraftsPath(agentId) {+ await ensureDir(DRAFTS_DIR);+ return join(DRAFTS_DIR, `${agentId}.json`);+}++async function loadDrafts(agentId) {+ const filePath = await getDraftsPath(agentId);+ const content = await readFile(filePath, 'utf-8').catch(() => null);+ if (!content) return [];+ return JSON.parse(content);+}++async function saveDrafts(agentId, drafts) {+ const filePath = await getDraftsPath(agentId);+ await writeFile(filePath, JSON.stringify(drafts, null, 2));+}++/**+ * List all drafts for an agent+ */+export async function listDrafts(agentId) {+ const drafts = await loadDrafts(agentId);+ return drafts.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));+}++/**+ * Get a single draft by ID+ */+export async function getDraft(agentId, draftId) {+ const drafts = await loadDrafts(agentId);+ return drafts.find(d => d.id === draftId) || null;+}++/**+ * Save a new draft+ */+export async function createDraft(agentId, draft) {+ const drafts = await loadDrafts(agentId);+ const entry = {+ id: uuidv4(),+ type: draft.type, // 'post' or 'comment'+ title: draft.title || null,+ content: draft.content,+ submolt: draft.submolt || null,+ postId: draft.postId || null,+ parentId: draft.parentId || null,+ postTitle: draft.postTitle || null,+ accountId: draft.accountId || null,+ createdAt: new Date().toISOString()+ };++ drafts.push(entry);+ await saveDrafts(agentId, drafts);+ console.log(`📋 Draft saved for agent ${agentId}: ${entry.type} "${entry.title || entry.content?.substring(0, 40)}..."`);+ return entry;+}++/**+ * Update an existing draft+ */+export async function updateDraft(agentId, draftId, updates) {+ const drafts = await loadDrafts(agentId);+ const idx = drafts.findIndex(d => d.id === draftId);+ if (idx === -1) return null;++ drafts[idx] = {+ ...drafts[idx],+ ...updates,+ updatedAt: new Date().toISOString()+ };+ await saveDrafts(agentId, drafts);+ return drafts[idx];+}++/**+ * Delete a draft+ */+export async function deleteDraft(agentId, draftId) {+ const drafts = await loadDrafts(agentId);+ const filtered = drafts.filter(d => d.id !== draftId);+ if (filtered.length === drafts.length) return false;+ await saveDrafts(agentId, filtered);+ console.log(`🗑️ Draft deleted for agent ${agentId}: ${draftId}`);+ return true;+}