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

feat(M9): streaming import detection with websocket

Adam Eivy3d31a5fc3a80
diff --git a/client/src/pages/CreateApp.jsx b/client/src/pages/CreateApp.jsx
index f048b1fd0f..2d220374df 100644
--- a/client/src/pages/CreateApp.jsx
+++ b/client/src/pages/CreateApp.jsx
@@ -1,105 +1,95 @@
-import { useState, useEffect } from 'react';
+import { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
+import { io } from 'socket.io-client';
+import { CheckCircle, Circle, Loader, AlertCircle, Play } from 'lucide-react';
import * as api from '../services/api';
+const DETECTION_STEPS = [
+ { id: 'validate', label: 'Validating path' },
+ { id: 'files', label: 'Scanning files' },
+ { id: 'package', label: 'Reading package.json' },
+ { id: 'config', label: 'Checking configs' },
+ { id: 'pm2', label: 'Checking PM2' },
+ { id: 'ai', label: 'AI analysis' }
+];
+
export default function CreateApp() {
const navigate = useNavigate();
+ const socketRef = useRef(null);
// Path input
const [repoPath, setRepoPath] = useState('');
- const [pathValid, setPathValid] = useState(null);
// Detection state
const [detecting, setDetecting] = useState(false);
- const [aiDetecting, setAiDetecting] = useState(false);
- const [detected, setDetected] = useState(null);
- const [hasAiProvider, setHasAiProvider] = useState(false);
+ const [steps, setSteps] = useState({});
+ const [detectionLog, setDetectionLog] = useState([]);
+ const [showLog, setShowLog] = useState(false);
- // Form fields (populated by detection or manual entry)
+ // Form fields
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [uiPort, setUiPort] = useState('');
const [apiPort, setApiPort] = useState('');
- const [startCommands, setStartCommands] = useState('npm run dev');
+ const [startCommands, setStartCommands] = useState('');
const [pm2Names, setPm2Names] = useState('');
+ const [pm2Status, setPm2Status] = useState(null);
// Submit state
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState(null);
+ const [detected, setDetected] = useState(false);
- // Check if AI provider is available
+ // Initialize socket
useEffect(() => {
- api.getActiveProvider().then(p => setHasAiProvider(!!p)).catch(() => {});
- }, []);
+ socketRef.current = io({ path: '/socket.io' });
+
+ socketRef.current.on('detect:step', ({ step, status, data }) => {
+ setSteps(prev => ({ ...prev, [step]: { status, data } }));
+ setDetectionLog(prev => [...prev, { step, status, ...data }]);
+
+ // Update form fields as data comes in
+ if (data.name) setName(data.name);
+ if (data.description) setDescription(data.description);
+ if (data.uiPort) setUiPort(String(data.uiPort));
+ if (data.apiPort) setApiPort(String(data.apiPort));
+ if (data.startCommands?.length) setStartCommands(data.startCommands.join('\n'));
+ if (data.pm2ProcessNames?.length) setPm2Names(data.pm2ProcessNames.join(', '));
+ if (data.pm2Status) setPm2Status(data.pm2Status);
+ });
- // AI-powered detection
- const handleAiDetect = async () => {
- if (!repoPath) return;
+ socketRef.current.on('detect:complete', ({ success, result, error: err }) => {
+ setDetecting(false);
+ if (success && result) {
+ setDetected(true);
+ if (result.name) setName(result.name);
+ if (result.description) setDescription(result.description);
+ if (result.uiPort) setUiPort(String(result.uiPort));
+ if (result.apiPort) setApiPort(String(result.apiPort));
+ if (result.startCommands?.length) setStartCommands(result.startCommands.join('\n'));
+ if (result.pm2ProcessNames?.length) setPm2Names(result.pm2ProcessNames.join(', '));
+ } else if (err) {
+ setError(err);
+ }
+ });
- setError(null);
- setAiDetecting(true);
-
- const result = await api.detectWithAi(repoPath).catch(err => ({
- success: false,
- error: err.message
- }));
-
- setAiDetecting(false);
-
- if (!result.success) {
- setError(result.error || 'AI detection failed');
- return;
- }
-
- setDetected(result);
-
- // Apply AI-detected values
- const d = result.detected;
- if (d.name) setName(d.name);
- if (d.description) setDescription(d.description);
- if (d.uiPort) setUiPort(String(d.uiPort));
- if (d.apiPort) setApiPort(String(d.apiPort));
- if (d.startCommands?.length > 0) setStartCommands(d.startCommands.join('\n'));
- if (d.pm2ProcessNames?.length > 0) setPm2Names(d.pm2ProcessNames.join(', '));
- };
+ return () => {
+ socketRef.current?.disconnect();
+ };
+ }, []);
- // Import button handler - validates path, then runs AI detection if available
- const handleImport = async () => {
- if (!repoPath) return;
+ // Start streaming detection
+ const handleImport = () => {
+ if (!repoPath || detecting) return;
setError(null);
+ setDetecting(true);
+ setSteps({});
+ setDetectionLog([]);
+ setDetected(false);
+ setPm2Status(null);
- // First validate the path
- if (pathValid === null) {
- setDetecting(true);
- const result = await api.detectRepo(repoPath).catch(() => ({ valid: false }));
- setPathValid(result.valid);
- setDetecting(false);
-
- if (!result.valid) {
- setError('Invalid directory path');
- return;
- }
-
- // Apply basic detection
- if (result.packageJson?.name && !name) {
- setName(result.packageJson.name);
- }
- if (result.startCommands?.length > 0 && startCommands === 'npm run dev') {
- setStartCommands(result.startCommands.join('\n'));
- }
- if (result.detectedPorts?.vite && !uiPort) {
- setUiPort(String(result.detectedPorts.vite));
- }
- if (result.detectedPorts?.main && !apiPort) {
- setApiPort(String(result.detectedPorts.main));
- }
- }
-
- // Then run AI detection if provider is available
- if (hasAiProvider) {
- await handleAiDetect();
- }
+ socketRef.current.emit('detect:start', { path: repoPath });
};
// Submit form
@@ -125,10 +115,31 @@ export default function CreateApp() {
});
setSubmitting(false);
+ if (result) navigate('/apps');
+ };
- if (result) {
- navigate('/apps');
- }
+ const reset = () => {
+ setDetected(false);
+ setSteps({});
+ setDetectionLog([]);
+ setName('');
+ setDescription('');
+ setUiPort('');
+ setApiPort('');
+ setStartCommands('');
+ setPm2Names('');
+ setPm2Status(null);
+ setError(null);
+ };
+
+ const getStepIcon = (stepId) => {
+ const step = steps[stepId];
+ if (!step) return <Circle size={16} className="text-gray-600" />;
+ if (step.status === 'running') return <Loader size={16} className="text-port-accent animate-spin" />;
+ if (step.status === 'done') return <CheckCircle size={16} className="text-port-success" />;
+ if (step.status === 'error') return <AlertCircle size={16} className="text-port-error" />;
+ if (step.status === 'skipped') return <Circle size={16} className="text-gray-500" />;
+ return <Circle size={16} className="text-gray-600" />;
};
return (
@@ -145,7 +156,7 @@ export default function CreateApp() {
<input
type="text"
value={repoPath}
- onChange={(e) => { setRepoPath(e.target.value); setPathValid(null); setDetected(null); }}
+ onChange={(e) => { setRepoPath(e.target.value); reset(); }}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
@@ -156,38 +167,63 @@ export default function CreateApp() {
className="w-full px-4 py-3 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none font-mono"
/>
+ {/* Detection Progress */}
{detecting && (
- <p className="mt-2 text-sm text-gray-500">Validating path...</p>
- )}
-
- {aiDetecting && (
- <p className="mt-2 text-sm text-port-accent">Detecting project configuration with AI...</p>
+ <div className="mt-4 space-y-2">
+ {DETECTION_STEPS.map(({ id, label }) => (
+ <div key={id} className="flex items-center gap-2 text-sm">
+ {getStepIcon(id)}
+ <span className={steps[id]?.status === 'running' ? 'text-port-accent' :
+ steps[id]?.status === 'done' ? 'text-white' : 'text-gray-500'}>
+ {label}
+ </span>
+ {steps[id]?.data?.message && (
+ <span className="text-gray-500 text-xs ml-2">
+ {steps[id].data.message}
+ </span>
+ )}
+ </div>
+ ))}
+ </div>
)}
- {pathValid === false && (
- <p className="mt-2 text-sm text-port-error">Invalid directory path</p>
+ {/* PM2 Running Status */}
+ {pm2Status && pm2Status.length > 0 && (
+ <div className="mt-3 p-3 bg-port-warning/10 border border-port-warning/30 rounded-lg">
+ <p className="text-sm text-port-warning font-medium flex items-center gap-2">
+ <Play size={14} /> Already running in PM2
+ </p>
+ <p className="text-xs text-gray-400 mt-1">
+ {pm2Status.map(p => `${p.name} (${p.status})`).join(', ')}
+ </p>
+ </div>
)}
- {pathValid === true && !detected && !aiDetecting && (
- <p className="mt-2 text-sm text-port-success">
- Valid project directory
- </p>
+ {/* Detection Log Toggle */}
+ {detectionLog.length > 0 && (
+ <button
+ type="button"
+ onClick={() => setShowLog(!showLog)}
+ className="mt-3 text-xs text-gray-500 hover:text-gray-400"
+ >
+ {showLog ? 'Hide' : 'Show'} detection log ({detectionLog.length} entries)
+ </button>
)}
- {detected && (
- <div className="mt-3 p-3 bg-port-success/10 border border-port-success/30 rounded-lg">
- <p className="text-sm text-port-success font-medium">
- AI Detection Complete ({detected.provider})
- </p>
- <p className="text-xs text-gray-400 mt-1">
- {detected.context?.configFiles?.length > 0 && (
- <>Config files found: {detected.context.configFiles.join(', ')}</>
- )}
- </p>
+ {showLog && (
+ <div className="mt-2 p-2 bg-port-bg rounded text-xs font-mono text-gray-400 max-h-40 overflow-auto">
+ {detectionLog.map((log, i) => (
+ <div key={i} className="py-0.5">
+ <span className={log.status === 'done' ? 'text-port-success' :
+ log.status === 'error' ? 'text-port-error' : 'text-gray-500'}>
+ [{log.step}]
+ </span> {log.message}
+ </div>
+ ))}
</div>
)}
- {/* Action Buttons - Always visible */}
+ {/* Action Buttons */}
<div className="flex gap-3 mt-4">
<button
type="button"
@@ -199,17 +235,17 @@ export default function CreateApp() {
<button
type="button"
onClick={handleImport}
- disabled={!repoPath || detecting || aiDetecting}
+ disabled={!repoPath || detecting}
className="flex-1 px-6 py-3 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors disabled:opacity-50"
>
- {detecting ? 'Validating...' : aiDetecting ? 'Detecting...' : 'Import'}
+ {detecting ? 'Detecting...' : 'Import'}
</button>
</div>
</div>
- {/* App Details */}
- {pathValid && (
- <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4">
+ {/* App Configuration - shown after detection */}
+ {detected && (
+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4 animate-in fade-in slide-in-from-bottom-2 duration-300">
<h3 className="text-lg font-semibold text-white mb-4">App Configuration</h3>
<div>
@@ -246,7 +282,6 @@ export default function CreateApp() {
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
/>
</div>
-
<div>
<label className="block text-sm text-gray-400 mb-1">API/Backend Port</label>
<input
@@ -296,21 +331,12 @@ export default function CreateApp() {
</div>
)}
- {/* Submit - only shown after detection */}
- {pathValid && (
+ {/* Submit */}
+ {detected && (
<div className="flex justify-between items-center">
<button
type="button"
- onClick={() => {
- setPathValid(null);
- setDetected(null);
- setName('');
- setDescription('');
- setUiPort('');
- setApiPort('');
- setStartCommands('npm run dev');
- setPm2Names('');
- }}
+ onClick={reset}
className="px-4 py-2 text-gray-400 hover:text-white"
>
Reset
@@ -325,17 +351,6 @@ export default function CreateApp() {
</div>
)}
</form>
-
- {/* No AI Provider Notice */}
- {pathValid && !hasAiProvider && (
- <div className="mt-6 p-4 bg-port-border/50 rounded-lg">
- <p className="text-sm text-gray-400">
- <strong className="text-white">Tip:</strong> Configure an AI provider in{' '}
- <a href="/ai" className="text-port-accent hover:underline">AI Providers</a>{' '}
- to enable smart auto-detection of app configuration.
- </p>
- </div>
- )}
</div>
);
}
diff --git a/server/services/socket.js b/server/services/socket.js
index 5ba27ec396..9675d3c03b 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -1,4 +1,5 @@
import { spawn } from 'child_process';
+import { streamDetection } from './streamingDetect.js';
// Store active log streams per socket
const activeStreams = new Map();
@@ -7,6 +8,12 @@ export function initSocket(io) {
io.on('connection', (socket) => {
console.log(`🔌 Client connected: ${socket.id}`);
+ // Handle streaming app detection
+ socket.on('detect:start', async ({ path, providerId }) => {
+ console.log(`🔍 Starting detection: ${path}`);
+ await streamDetection(socket, path, providerId);
+ });
+
// Handle log streaming requests
socket.on('logs:subscribe', ({ processName, lines = 100 }) => {
// Clean up any existing stream for this socket
diff --git a/server/services/streamingDetect.js b/server/services/streamingDetect.js
new file mode 100644
index 0000000000..388804327d
--- /dev/null
+++ b/server/services/streamingDetect.js
@@ -0,0 +1,279 @@
+import { readFile, readdir, stat } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join, basename } from 'path';
+import { exec } from 'child_process';
+import { promisify } from 'util';
+import { getActiveProvider, getProviderById } from './providers.js';
+import { spawn } from 'child_process';
+
+const execAsync = promisify(exec);
+
+/**
+ * Stream detection results to a socket as each step completes
+ */
+export async function streamDetection(socket, dirPath, providerId = null) {
+ const emit = (step, status, data = {}) => {
+ socket.emit('detect:step', { step, status, data, timestamp: Date.now() });
+ };
+
+ const result = {
+ name: '',
+ description: '',
+ uiPort: null,
+ apiPort: null,
+ startCommands: [],
+ pm2ProcessNames: [],
+ pm2Status: null,
+ type: 'unknown'
+ };
+
+ // Step 1: Validate path
+ emit('validate', 'running', { message: 'Validating directory path...' });
+
+ if (!existsSync(dirPath)) {
+ emit('validate', 'error', { message: 'Directory does not exist' });
+ socket.emit('detect:complete', { success: false, error: 'Directory does not exist' });
+ return;
+ }
+
+ const stats = await stat(dirPath);
+ if (!stats.isDirectory()) {
+ emit('validate', 'error', { message: 'Path is not a directory' });
+ socket.emit('detect:complete', { success: false, error: 'Path is not a directory' });
+ return;
+ }
+
+ emit('validate', 'done', { message: 'Valid directory' });
+ result.name = basename(dirPath);
+
+ // Step 2: Read directory contents
+ emit('files', 'running', { message: 'Scanning directory...' });
+ const entries = await readdir(dirPath, { withFileTypes: true }).catch(() => []);
+ const files = entries.map(e => e.name);
+ emit('files', 'done', { message: `Found ${files.length} files`, files: files.slice(0, 20) });
+
+ // Step 3: Read package.json
+ emit('package', 'running', { message: 'Reading package.json...' });
+ const pkgPath = join(dirPath, 'package.json');
+ let pkg = null;
+
+ if (existsSync(pkgPath)) {
+ const content = await readFile(pkgPath, 'utf-8').catch(() => null);
+ if (content) {
+ pkg = JSON.parse(content);
+ result.name = pkg.name || result.name;
+ result.description = pkg.description || '';
+
+ // Detect project type
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
+ if (deps.vite && deps.express) result.type = 'vite+express';
+ else if (deps.vite || deps.react || deps.vue) result.type = 'vite';
+ else if (deps.express || deps.fastify || deps.koa) result.type = 'single-node-server';
+ else if (deps.next) result.type = 'nextjs';
+
+ // Get start commands
+ const scripts = pkg.scripts || {};
+ if (scripts.dev) result.startCommands.push('npm run dev');
+ if (scripts.start && !scripts.dev) result.startCommands.push('npm start');
+
+ emit('package', 'done', {
+ message: `Found: ${result.name}`,
+ name: result.name,
+ description: result.description,
+ type: result.type,
+ startCommands: result.startCommands
+ });
+ }
+ } else {
+ emit('package', 'done', { message: 'No package.json found' });
+ }
+
+ // Step 4: Check config files for ports
+ emit('config', 'running', { message: 'Checking configuration files...' });
+ const configFiles = [];
+
+ // Check .env
+ const envPath = join(dirPath, '.env');
+ if (existsSync(envPath)) {
+ const content = await readFile(envPath, 'utf-8').catch(() => '');
+ const portMatch = content.match(/PORT\s*=\s*(\d+)/i);
+ if (portMatch) result.apiPort = parseInt(portMatch[1]);
+ const viteMatch = content.match(/VITE_PORT\s*=\s*(\d+)/i);
+ if (viteMatch) result.uiPort = parseInt(viteMatch[1]);
+ configFiles.push('.env');
+ }
+
+ // Check vite.config
+ for (const viteConfig of ['vite.config.js', 'vite.config.ts']) {
+ const configPath = join(dirPath, viteConfig);
+ if (existsSync(configPath)) {
+ const content = await readFile(configPath, 'utf-8').catch(() => '');
+ const portMatch = content.match(/port\s*:\s*(\d+)/);
+ if (portMatch) result.uiPort = parseInt(portMatch[1]);
+ configFiles.push(viteConfig);
+ }
+ }
+
+ emit('config', 'done', {
+ message: configFiles.length ? `Found: ${configFiles.join(', ')}` : 'No config files found',
+ uiPort: result.uiPort,
+ apiPort: result.apiPort,
+ configFiles
+ });
+
+ // Step 5: Check PM2 status
+ emit('pm2', 'running', { message: 'Checking PM2 processes...' });
+ const { stdout } = await execAsync('pm2 jlist').catch(() => ({ stdout: '[]' }));
+ const pm2Processes = JSON.parse(stdout);
+
+ // Look for processes that might be this app
+ const possibleNames = [
+ result.name,
+ result.name.toLowerCase(),
+ result.name.toLowerCase().replace(/[^a-z0-9]/g, '-'),
+ `${result.name}-ui`,
+ `${result.name}-api`
+ ];
+
+ const matchingProcesses = pm2Processes.filter(p =>
+ possibleNames.some(name => p.name.includes(name) || name.includes(p.name))
+ );
+
+ if (matchingProcesses.length > 0) {
+ result.pm2Status = matchingProcesses.map(p => ({
+ name: p.name,
+ status: p.pm2_env?.status,
+ pid: p.pid
+ }));
+ emit('pm2', 'done', {
+ message: `Found ${matchingProcesses.length} running process(es)`,
+ pm2Status: result.pm2Status
+ });
+ } else {
+ emit('pm2', 'done', { message: 'No matching PM2 processes found' });
+ }
+
+ // Generate PM2 process names
+ const baseName = result.name.toLowerCase().replace(/[^a-z0-9]/g, '-');
+ if (result.type === 'vite+express') {
+ result.pm2ProcessNames = [`${baseName}-ui`, `${baseName}-api`];
+ } else {
+ result.pm2ProcessNames = [baseName];
+ }
+
+ // Step 6: AI-powered analysis (if provider available)
+ const provider = providerId
+ ? await getProviderById(providerId)
+ : await getActiveProvider();
+
+ if (provider?.enabled) {
+ emit('ai', 'running', { message: `Analyzing with ${provider.name}...` });
+
+ const aiResult = await runAiAnalysis(dirPath, provider, { pkg, files }).catch(err => {
+ console.log(`⚠️ AI analysis failed: ${err.message}`);
+ return null;
+ });
+
+ if (aiResult) {
+ // Merge AI results (AI takes precedence for name/description)
+ if (aiResult.name) result.name = aiResult.name;
+ if (aiResult.description) result.description = aiResult.description;
+ if (aiResult.uiPort && !result.uiPort) result.uiPort = aiResult.uiPort;
+ if (aiResult.apiPort && !result.apiPort) result.apiPort = aiResult.apiPort;
+ if (aiResult.startCommands?.length) result.startCommands = aiResult.startCommands;
+ if (aiResult.pm2ProcessNames?.length) result.pm2ProcessNames = aiResult.pm2ProcessNames;
+
+ emit('ai', 'done', {
+ message: 'AI analysis complete',
+ name: result.name,
+ description: result.description
+ });
+ } else {
+ emit('ai', 'skipped', { message: 'AI analysis unavailable' });
+ }
+ } else {
+ emit('ai', 'skipped', { message: 'No AI provider configured' });
+ }
+
+ // Complete
+ socket.emit('detect:complete', {
+ success: true,
+ result,
+ provider: provider?.name || null
+ });
+}
+
+/**
+ * Run AI analysis on project
+ */
+async function runAiAnalysis(dirPath, provider, context) {
+ const prompt = buildPrompt(dirPath, context);
+
+ let response;
+ if (provider.type === 'cli') {
+ response = await executeCliPrompt(provider, prompt, dirPath);
+ } else if (provider.type === 'api') {
+ response = await executeApiPrompt(provider, prompt);
+ } else {
+ throw new Error('Unknown provider type');
+ }
+
+ return parseResponse(response);
+}
+
+function buildPrompt(dirPath, { pkg, files }) {
+ return `Analyze this project and return JSON configuration.
+
+Directory: ${basename(dirPath)}
+Files: ${files.slice(0, 30).join(', ')}
+${pkg ? `package.json name: ${pkg.name}, scripts: ${Object.keys(pkg.scripts || {}).join(', ')}` : 'No package.json'}
+
+Return ONLY valid JSON:
+{
+ "name": "Human readable app name",
+ "description": "One sentence description",
+ "uiPort": null or number,
+ "apiPort": null or number,
+ "startCommands": ["npm run dev"],
+ "pm2ProcessNames": ["app-name"]
+}`;
+}
+
+async function executeCliPrompt(provider, prompt, cwd) {
+ return new Promise((resolve, reject) => {
+ const args = [...(provider.args || []), prompt];
+ let output = '';
+ const child = spawn(provider.command, args, { cwd, env: process.env, shell: false });
+ child.stdout.on('data', d => output += d.toString());
+ child.stderr.on('data', d => output += d.toString());
+ child.on('close', code => code === 0 ? resolve(output) : reject(new Error(`Exit ${code}`)));
+ child.on('error', reject);
+ setTimeout(() => { child.kill(); reject(new Error('Timeout')); }, provider.timeout || 60000);
+ });
+}
+
+async function executeApiPrompt(provider, prompt) {
+ const headers = { 'Content-Type': 'application/json' };
+ if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;
+
+ const res = await fetch(`${provider.endpoint}/chat/completions`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ model: provider.defaultModel,
+ messages: [{ role: 'user', content: prompt }],
+ temperature: 0.1
+ })
+ });
+
+ if (!res.ok) throw new Error(`API ${res.status}`);
+ const data = await res.json();
+ return data.choices?.[0]?.message?.content || '';
+}
+
+function parseResponse(response) {
+ let str = response.trim();
+ const match = str.match(/```(?:json)?\s*([\s\S]*?)```/) || str.match(/\{[\s\S]*\}/);
+ if (match) str = match[1] || match[0];
+ return JSON.parse(str);
+}