Skip to content

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

fix: brain inbox classification no longer hangs on capture

Adam Eivyefb226c3bd80
diff --git a/.changelog/v0.11.x.md b/.changelog/v0.11.x.md
index 1708e43a62..c4b27ccc9a 100644
--- a/.changelog/v0.11.x.md
+++ b/.changelog/v0.11.x.md
@@ -29,6 +29,15 @@ This release focuses on security improvements, bug fixes for the AI runner syste
- `portos-ai-toolkit/src/server/providers.js` - Universal refresh implementation
- `client/src/pages/AIProviders.jsx` - UI updates with toast notifications
+### Digital Twin AI Interview Chat
+- New "Interview" tab in Digital Twin for building personality profiles via external AI conversation loops
+- Paste personality data from ChatGPT/other AIs for automated analysis and twin record updates
+- AI-powered follow-up question generation to deepen profile coverage
+- Persistent chat sessions with session management (create, rename, delete)
+- Automatically maps traits to Big Five, values, and communication dimensions
+- Creates new documents for trait categories not yet captured (Cognitive, Creative, Technical, etc.)
+- Linkable sessions via URL query params (`/digital-twin/interview?session=<uuid>`)
+
## 🐛 Bug Fixes
### CLI Runner Security & Reliability
@@ -46,3 +55,17 @@ This release focuses on security improvements, bug fixes for the AI runner syste
**Files Modified**:
- `server/services/runner.js` - New secure CLI execution implementation
- `server/index.js` - Runtime patching to override toolkit's runner
+
+### Brain Inbox Classification Hang on Capture
+- **Background Classification**: Brain inbox thought capture now returns immediately instead of blocking the UI while waiting for AI classification
+- **Real-time Updates**: Classification results are pushed to the client via Socket.IO events (`brain:classified`), with toast notifications showing the result
+- **New "Classifying" Status**: Added `classifying` status with animated UI indicator so users can see thoughts being processed in real time
+- **No More Hangs**: Previously, submitting a thought would hang the UI spinner indefinitely if the AI provider was slow or unresponsive. Now the thought is saved instantly and classified in the background
+
+**Files Modified**:
+- `server/services/brain.js` - Split `captureThought` into immediate return + background `classifyInBackground`
+- `server/services/socket.js` - Added brain event forwarding via `setupBrainEventForwarding`
+- `server/lib/brainValidation.js` - Added `classifying` to inbox status enum
+- `server/services/brainStorage.js` - Added `classifying` to inbox log counts
+- `client/src/components/brain/tabs/InboxTab.jsx` - Socket.IO listener for classification results, classifying section UI
+- `client/src/components/brain/constants.js` - Added `classifying` status color
diff --git a/client/src/components/brain/constants.js b/client/src/components/brain/constants.js
index 66b31b4fc2..b76f3616c8 100644
--- a/client/src/components/brain/constants.js
+++ b/client/src/components/brain/constants.js
@@ -49,6 +49,7 @@ export const DESTINATIONS = {
// Inbox status colors
export const STATUS_COLORS = {
+ classifying: 'bg-port-accent/20 text-port-accent border-port-accent/30',
filed: 'bg-port-success/20 text-port-success border-port-success/30',
needs_review: 'bg-port-warning/20 text-port-warning border-port-warning/30',
corrected: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
diff --git a/client/src/components/brain/tabs/InboxTab.jsx b/client/src/components/brain/tabs/InboxTab.jsx
index 40f9f859b0..5214bce142 100644
--- a/client/src/components/brain/tabs/InboxTab.jsx
+++ b/client/src/components/brain/tabs/InboxTab.jsx
@@ -1,5 +1,6 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import * as api from '../../../services/api';
+import socket from '../../../services/socket';
import {
Send,
RefreshCw,
@@ -11,7 +12,8 @@ import {
ExternalLink,
Trash2,
Save,
- X
+ X,
+ Brain
} from 'lucide-react';
import toast from 'react-hot-toast';
@@ -48,6 +50,24 @@ export default function InboxTab({ onRefresh, settings }) {
fetchInbox();
}, [fetchInbox]);
+ // Listen for background classification results
+ useEffect(() => {
+ const handleClassified = (data) => {
+ if (data.status === 'filed') {
+ toast.success(`Classified as ${data.destination}: ${data.title}`);
+ } else if (data.error) {
+ toast.error(`Classification failed: ${data.error}`);
+ } else {
+ toast(`Low confidence (${Math.round((data.confidence || 0) * 100)}%) — needs review`, { icon: '🤔' });
+ }
+ fetchInbox();
+ onRefresh?.();
+ };
+
+ socket.on('brain:classified', handleClassified);
+ return () => socket.off('brain:classified', handleClassified);
+ }, [fetchInbox, onRefresh]);
+
const handleSubmit = async (e) => {
e.preventDefault();
if (!inputText.trim() || sending) return;
@@ -155,6 +175,7 @@ export default function InboxTab({ onRefresh, settings }) {
onRefresh?.();
};
+ const classifyingEntries = entries.filter(e => e.status === 'classifying');
const needsReviewEntries = entries.filter(e => e.status === 'needs_review');
const filedEntries = entries.filter(e => e.status === 'filed' || e.status === 'corrected');
const errorEntries = entries.filter(e => e.status === 'error');
@@ -202,6 +223,35 @@ export default function InboxTab({ onRefresh, settings }) {
</p>
</form>
+ {/* Classifying section */}
+ {classifyingEntries.length > 0 && (
+ <div className="mb-4">
+ <div className="flex items-center gap-2 text-port-accent font-medium mb-2">
+ <Brain size={16} className="animate-pulse" />
+ Classifying ({classifyingEntries.length})
+ </div>
+ <div className="space-y-2">
+ {classifyingEntries.map(entry => (
+ <div
+ key={entry.id}
+ className="p-3 bg-port-card border border-port-accent/30 rounded-lg"
+ >
+ <div className="flex items-start justify-between gap-2">
+ <p className="text-white flex-1">{entry.capturedText}</p>
+ <div className="flex items-center gap-2">
+ <RefreshCw className="w-4 h-4 text-port-accent animate-spin" />
+ <span className="text-xs text-gray-500 whitespace-nowrap">
+ {formatRelativeTime(entry.capturedAt)}
+ </span>
+ </div>
+ </div>
+ <p className="text-xs text-port-accent mt-1">AI is classifying this thought...</p>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
{/* Needs Review section */}
{needsReviewEntries.length > 0 && (
<div className="mb-4">
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.js
index 915665c48c..630ee405b1 100644
--- a/server/lib/brainValidation.js
+++ b/server/lib/brainValidation.js
@@ -10,7 +10,7 @@ export const projectStatusEnum = z.enum(['active', 'waiting', 'blocked', 'someda
export const adminStatusEnum = z.enum(['open', 'waiting', 'done']);
// Inbox log status enum
-export const inboxStatusEnum = z.enum(['filed', 'needs_review', 'corrected', 'error']);
+export const inboxStatusEnum = z.enum(['classifying', 'filed', 'needs_review', 'corrected', 'error']);
// AI configuration schema
export const aiConfigSchema = z.object({
diff --git a/server/services/brain.js b/server/services/brain.js
index 5fa505bf1a..878e0c12ae 100644
--- a/server/services/brain.js
+++ b/server/services/brain.js
@@ -10,9 +10,11 @@
import { spawn } from 'child_process';
import * as storage from './brainStorage.js';
+import { brainEvents } from './brainStorage.js';
import { getActiveProvider, getProviderById } from './providers.js';
import { buildPrompt } from './promptService.js';
import { validate } from '../lib/validation.js';
+import { safeJSONParse } from '../lib/fileUtils.js';
import {
classifierOutputSchema,
digestOutputSchema,
@@ -135,8 +137,32 @@ function parseJsonResponse(content) {
return JSON.parse(jsonStr);
}
+/**
+ * Safe version of parseJsonResponse that returns null instead of throwing.
+ * Used in background classification where errors can't bubble to middleware.
+ */
+function safeParseJsonResponse(content) {
+ if (!content || typeof content !== 'string') return null;
+
+ let jsonStr = content.trim();
+
+ const jsonMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/);
+ if (jsonMatch) {
+ jsonStr = jsonMatch[1].trim();
+ }
+
+ const objectMatch = jsonStr.match(/\{[\s\S]*\}/);
+ if (objectMatch) {
+ jsonStr = objectMatch[0];
+ }
+
+ return safeJSONParse(jsonStr, null, { logError: true, context: 'brain-classifier' });
+}
+
/**
* Capture a thought and classify it
+ * Returns immediately after creating the inbox entry.
+ * AI classification runs in the background and emits a socket event on completion.
*/
export async function captureThought(text, providerOverride, modelOverride) {
const meta = await storage.loadMeta();
@@ -152,10 +178,25 @@ export async function captureThought(text, providerOverride, modelOverride) {
modelId: model,
promptTemplateId: 'brain-classifier'
},
- status: 'needs_review'
+ status: 'classifying'
});
- // Attempt AI classification
+ console.log(`🧠 Thought captured, classifying in background: ${inboxEntry.id}`);
+
+ // Run AI classification in background (don't await)
+ classifyInBackground(inboxEntry.id, text, meta, providerOverride, modelOverride);
+
+ return {
+ inboxLog: inboxEntry,
+ message: 'Thought captured! AI is classifying...'
+ };
+}
+
+/**
+ * Background AI classification for a captured thought.
+ * Updates the inbox entry and emits a brain:classified event when done.
+ */
+async function classifyInBackground(entryId, text, meta, providerOverride, modelOverride) {
let classification = null;
let aiError = null;
@@ -170,21 +211,24 @@ export async function captureThought(text, providerOverride, modelOverride) {
});
if (aiResponse) {
- const parsed = parseJsonResponse(aiResponse);
- const validationResult = classifierOutputSchema.safeParse(parsed);
-
- if (validationResult.success) {
- classification = validationResult.data;
+ const parsed = safeParseJsonResponse(aiResponse);
+ if (parsed) {
+ const validationResult = classifierOutputSchema.safeParse(parsed);
+ if (validationResult.success) {
+ classification = validationResult.data;
+ } else {
+ console.error(`🧠 Classification validation failed: ${JSON.stringify(validationResult.error.errors)}`);
+ aiError = new Error('Invalid classification output from AI');
+ }
} else {
- console.error(`🧠 Classification validation failed: ${JSON.stringify(validationResult.error.errors)}`);
- aiError = new Error('Invalid classification output from AI');
+ aiError = new Error('Could not parse AI response as JSON');
}
}
- // If AI failed, return entry as needs_review
+ // If AI failed, mark as needs_review
if (!classification) {
const errorMessage = aiError?.message || 'AI classification failed';
- await storage.updateInboxLog(inboxEntry.id, {
+ await storage.updateInboxLog(entryId, {
classification: {
destination: 'unknown',
confidence: 0,
@@ -196,31 +240,27 @@ export async function captureThought(text, providerOverride, modelOverride) {
error: { message: errorMessage }
});
- console.log(`🧠 Capture queued for review (AI unavailable): ${inboxEntry.id}`);
- return {
- inboxLog: await storage.getInboxLogById(inboxEntry.id),
- message: `Thought captured but AI unavailable. Queued for manual review.`
- };
+ console.log(`🧠 Classification failed for ${entryId}: ${errorMessage}`);
+ brainEvents.emit('classified', { entryId, status: 'needs_review', error: errorMessage });
+ return;
}
// Check confidence threshold
if (classification.confidence < meta.confidenceThreshold || classification.destination === 'unknown') {
- await storage.updateInboxLog(inboxEntry.id, {
+ await storage.updateInboxLog(entryId, {
classification,
status: 'needs_review'
});
- console.log(`🧠 Capture needs review (low confidence ${classification.confidence}): ${inboxEntry.id}`);
- return {
- inboxLog: await storage.getInboxLogById(inboxEntry.id),
- message: `Thought captured but needs review. Confidence: ${Math.round(classification.confidence * 100)}%`
- };
+ console.log(`🧠 Low confidence (${classification.confidence}) for ${entryId}`);
+ brainEvents.emit('classified', { entryId, status: 'needs_review', confidence: classification.confidence });
+ return;
}
// File to appropriate destination
const filedRecord = await fileToDestination(classification.destination, classification.extracted, classification.title);
- await storage.updateInboxLog(inboxEntry.id, {
+ await storage.updateInboxLog(entryId, {
classification,
status: 'filed',
filed: {
@@ -229,12 +269,13 @@ export async function captureThought(text, providerOverride, modelOverride) {
}
});
- console.log(`🧠 Captured and filed to ${classification.destination}: ${filedRecord.id}`);
- return {
- inboxLog: await storage.getInboxLogById(inboxEntry.id),
- filedRecord,
- message: `Filed to ${classification.destination}: ${classification.title}`
- };
+ console.log(`🧠 Classified and filed to ${classification.destination}: ${filedRecord.id}`);
+ brainEvents.emit('classified', {
+ entryId,
+ status: 'filed',
+ destination: classification.destination,
+ title: classification.title
+ });
}
/**
diff --git a/server/services/brainStorage.js b/server/services/brainStorage.js
index 8b81c15efe..0160cdd0b1 100644
--- a/server/services/brainStorage.js
+++ b/server/services/brainStorage.js
@@ -402,6 +402,7 @@ export async function getInboxLogCounts() {
const counts = {
total: records.length,
+ classifying: 0,
filed: 0,
needs_review: 0,
corrected: 0,
diff --git a/server/services/socket.js b/server/services/socket.js
index 56517cee36..136d4badc1 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -11,6 +11,7 @@ import { agentPersonalityEvents } from './agentPersonalities.js';
import { platformAccountEvents } from './platformAccounts.js';
import { scheduleEvents } from './automationScheduler.js';
import { activityEvents } from './agentActivity.js';
+import { brainEvents } from './brainStorage.js';
import * as shellService from './shell.js';
// Store active log streams per socket
@@ -292,6 +293,9 @@ export function initSocket(io) {
// Set up agent event forwarding
setupAgentEventForwarding();
+
+ // Set up brain event forwarding
+ setupBrainEventForwarding();
}
function cleanupStream(socketId) {
@@ -433,3 +437,12 @@ function setupAgentEventForwarding() {
activityEvents.on('activity', (data) => broadcastToAgents('agents:activity', data));
activityEvents.on('activity:updated', (data) => broadcastToAgents('agents:activity:updated', data));
}
+
+// Set up brain event forwarding - broadcast to all clients
+function setupBrainEventForwarding() {
+ brainEvents.on('classified', (data) => {
+ if (ioInstance) {
+ ioInstance.emit('brain:classified', data);
+ }
+ });
+}