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
import PageLayout from '../components/PageLayout';
import { useState, useEffect, useRef, useCallback } from 'react';
import { useLocation, useNavigate } from 'react-router';
import { Clock, Image, X, Info, Code2 } from 'lucide-react';
import toast from '../components/ui/Toast';
import FilePickerButton from '../components/ui/FilePickerButton';
import * as api from '../services/api';
import socket from '../services/socket';
import { useSocketSubscription } from '../hooks/useSocketSubscription';
import { processScreenshotUploads } from '../services/apiMedia';
import { filterSelectableModels } from '../utils/providers';
import ProviderModelSelector from '../components/ProviderModelSelector';
import PageHeader from '../components/PageHeader';
import useListResource from '../hooks/useListResource.js';
import ListLoadError from '../components/ui/ListLoadError';
export function RunnerPage() {
const location = useLocation();
const navigate = useNavigate();
const [mode, setMode] = useState('ai'); // 'ai' or 'command'
const [prompt, setPrompt] = useState('');
const [command, setCommand] = useState('');
const [selectedAppId, setSelectedAppId] = useState('');
const [output, setOutput] = useState('');
const [running, setRunning] = useState(false);
const [runId, setRunId] = useState(null);
const [commandId, setCommandId] = useState(null);
const [providers, setProviders] = useState([]);
const [selectedProvider, setSelectedProvider] = useState('');
const [selectedModel, setSelectedModel] = useState('');
const [timeoutMinutes, setTimeoutMinutes] = useState(30);
const [screenshots, setScreenshots] = useState([]);
const [continueContext, setContinueContext] = useState(null);
const outputRef = useRef(null);
const continueWorkspaceRef = useRef(location.state?.continueFrom?.workspacePath ?? null);
const fetchApps = useCallback(async () => {
const list = await api.getApps({ silent: true });
return (Array.isArray(list) ? list : []).filter(a => a.id !== 'portos-autofixer');
}, []);
const appsResource = useListResource(fetchApps);
const { items: apps, state: appsState, error: appsError, retry: retryApps } = appsResource;
const fetchAllowedCommands = useCallback(async () => {
const list = await api.getAllowedCommands({ silent: true });
return Array.isArray(list) ? list : [];
}, []);
const allowedCommandsResource = useListResource(fetchAllowedCommands);
const {
items: allowedCommands,
state: allowedCommandsState,
error: allowedCommandsError,
retry: retryAllowedCommands,
} = allowedCommandsResource;
// Get the selected app's repoPath
const selectedApp = apps.find(a => a.id === selectedAppId);
const workspacePath = selectedApp?.repoPath || '';
// Handle continuation context from navigation — store continueFrom and clear location state once
useEffect(() => {
const continueFrom = location.state?.continueFrom;
if (continueFrom) {
setContinueContext(continueFrom);
// Set provider and model from previous run if available
if (continueFrom.providerId) {
setSelectedProvider(continueFrom.providerId);
}
if (continueFrom.model) {
setSelectedModel(continueFrom.model);
}
// Clear location state to prevent re-triggering on refresh
navigate(location.pathname, { replace: true, state: null });
}
}, [location.state, navigate]);
useEffect(() => {
api.getProviders({ silent: true })
.then((providersRes) => {
const allProviders = providersRes?.providers || [];
const enabledProviders = allProviders.filter(p => p.enabled);
setProviders(enabledProviders);
if (enabledProviders.length > 0) {
const active = enabledProviders.find(p => p.id === providersRes.activeProvider) || enabledProviders[0];
setSelectedProvider(prev => prev || active.id);
setSelectedModel(prev => prev || active.defaultModel || '');
}
})
.catch((_err) => {});
}, []);
useEffect(() => {
if (appsState !== 'ready') return;
// Set workspace: prefer continuation context (stored in ref), then PortOS, then first app
setSelectedAppId(prev => {
if (prev) return prev;
if (continueWorkspaceRef.current) {
const continueApp = apps.find(a => a.repoPath === continueWorkspaceRef.current);
if (continueApp) return continueApp.id;
}
const portosApp = apps.find(a => a.name === 'PortOS');
if (portosApp) return portosApp.id;
return apps.length > 0 ? apps[0].id : prev;
});
}, [apps, appsState]);
// Subscribe to run output
useEffect(() => {
if (!runId) return;
const handleData = (data) => {
setOutput(prev => prev + data);
if (outputRef.current) {
outputRef.current.scrollTop = outputRef.current.scrollHeight;
}
};
const handleComplete = (metadata) => {
setRunning(false);
setRunId(null);
const status = metadata.success ? '✓ Completed' : `✗ Failed (${metadata.error || 'unknown error'})`;
setOutput(prev => prev + `\n\n--- ${status} (${Math.round(metadata.duration / 1000)}s) ---\n`);
};
socket.on(`run:${runId}:data`, handleData);
socket.on(`run:${runId}:complete`, handleComplete);
return () => {
socket.off(`run:${runId}:data`, handleData);
socket.off(`run:${runId}:complete`, handleComplete);
};
}, [runId]);
// Command output is only broadcast to subscribed sockets (#12019).
useSocketSubscription('command');
// Subscribe to command output
useEffect(() => {
if (!commandId) return;
const handleData = ({ data }) => {
setOutput(prev => prev + data);
if (outputRef.current) {
outputRef.current.scrollTop = outputRef.current.scrollHeight;
}
};
const handleComplete = (result) => {
setRunning(false);
setCommandId(null);
setOutput(prev => prev + `\n--- Command finished (exit code: ${result.exitCode}) ---\n`);
};
socket.on(`command:${commandId}:data`, handleData);
socket.on(`command:${commandId}:complete`, handleComplete);
return () => {
socket.off(`command:${commandId}:data`, handleData);
socket.off(`command:${commandId}:complete`, handleComplete);
};
}, [commandId]);
const handleRunAI = async () => {
if (!prompt.trim() || !selectedProvider) return;
// Build final prompt, merging with continuation context if present
let finalPrompt = prompt.trim();
if (continueContext) {
if (continueContext.success === false) {
// Resuming a failed run - include error context
finalPrompt = `RESUMING FAILED RUN:
--- PREVIOUS PROMPT ---
${continueContext.prompt}
${continueContext.output ? `
--- PREVIOUS OUTPUT (BEFORE FAILURE) ---
${continueContext.output}
` : ''}
--- ERROR ---
${continueContext.error || 'Unknown error'}
${continueContext.suggestedFix ? `
--- SUGGESTED FIX ---
${continueContext.suggestedFix}
` : ''}
--- NEW INSTRUCTIONS ---
${prompt.trim()}`;
} else {
// Continuing a successful conversation
finalPrompt = `CONTINUATION OF PREVIOUS CONVERSATION:
--- PREVIOUS PROMPT ---
${continueContext.prompt}
--- PREVIOUS OUTPUT ---
${continueContext.output}
--- NEW INSTRUCTIONS ---
${prompt.trim()}`;
}
}
setOutput('');
setRunning(true);
const result = await api.createRun({
providerId: selectedProvider,
model: selectedModel || undefined,
prompt: finalPrompt,
workspacePath: workspacePath || undefined,
// Take the name from the app that is actually selected, not from a
// reverse lookup by repoPath. When the selected app's Repository Path is
// unset, `workspacePath` is '' and the lookup matched some *other*
// pathless app (or nothing) — so the server saw no workspace at all and
// ran in the PortOS directory instead of rejecting the misconfigured app
// it was pointed at (#3180).
workspaceName: selectedApp?.name,
timeout: timeoutMinutes * 60 * 1000, // Convert minutes to milliseconds
screenshots: screenshots.map(s => s.path) // Include screenshot paths
}).catch(err => ({ error: err.message }));
if (result.error) {
setOutput(`Error: ${result.error}`);
setRunning(false);
return;
}
// Clear continuation context after running
setContinueContext(null);
setRunId(result.runId);
};
const handleRunCommand = async () => {
if (!command.trim()) return;
setOutput('');
setRunning(true);
const result = await api.executeCommand(command, workspacePath || undefined)
.catch(err => ({ error: err.message }));
if (result.error) {
setOutput(`Error: ${result.error}`);
setRunning(false);
return;
}
setCommandId(result.commandId);
};
const handleStop = async () => {
if (runId) {
await api.stopRun(runId);
setRunning(false);
setRunId(null);
}
if (commandId) {
await api.stopCommand(commandId);
setRunning(false);
setCommandId(null);
}
};
const handleFileSelect = async (e) => {
await processScreenshotUploads(e.target.files, {
onSuccess: (fileInfo) => setScreenshots(prev => [...prev, fileInfo]),
onError: (msg) => toast.error(msg)
});
};
const removeScreenshot = (id) => {
setScreenshots(prev => prev.filter(s => s.id !== id));
};
const currentProvider = providers.find(p => p.id === selectedProvider);
return (
<PageLayout header={<PageHeader
icon={Code2}
title="Code Runner"
subtitle="Execute AI assistant tasks and shell commands across workspaces"
/>}>
<div className="space-y-6">
{/* Continuation Context Banner */}
{continueContext && (
<div className={`${continueContext.success === false ? 'bg-port-warning/10 border-port-warning/30' : 'bg-port-success/10 border-port-success/30'} border rounded-xl p-4`} data-testid="continuation-banner">
<div className="flex items-start justify-between mb-3">
<div className="flex items-center gap-2">
<Info size={18} className={continueContext.success === false ? 'text-port-warning' : 'text-port-success'} />
<span className={`font-medium ${continueContext.success === false ? 'text-port-warning' : 'text-port-success'}`}>
{continueContext.success === false ? 'Resuming Failed Run' : 'Continuing Previous Conversation'}
</span>
{continueContext.providerName && (
<span className="text-xs text-gray-400 bg-port-card px-2 py-0.5 rounded">
{continueContext.providerName}
</span>
)}
</div>
<button
onClick={() => setContinueContext(null)}
className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-gray-400 hover:text-white"
title="Dismiss context"
aria-label="Dismiss context"
>
<X size={16} />
</button>
</div>
<div className="space-y-2 text-sm">
<div>
<div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Previous Prompt</div>
<div className="text-gray-300 bg-port-card/50 rounded px-2 py-1 font-mono text-xs max-h-20 overflow-auto">
{continueContext.prompt?.substring(0, 500)}{continueContext.prompt?.length > 500 ? '...' : ''}
</div>
</div>
{continueContext.success === false && continueContext.error && (
<div role="status">
<div className="text-xs text-port-error uppercase tracking-wide mb-1">Error</div>
<div className="text-port-error/80 bg-port-error/10 rounded px-2 py-1 font-mono text-xs max-h-20 overflow-auto">
{continueContext.error}
</div>
</div>
)}
{continueContext.success === false && continueContext.suggestedFix && (
<div>
<div className="text-xs text-port-warning uppercase tracking-wide mb-1">Suggested Fix</div>
<div className="text-gray-300 bg-port-warning/10 rounded px-2 py-1 text-xs max-h-20 overflow-auto">
{continueContext.suggestedFix}
</div>
</div>
)}
{continueContext.output && (
<div>
<div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Previous Output</div>
<div className="text-gray-300 bg-port-card/50 rounded px-2 py-1 font-mono text-xs max-h-24 overflow-auto">
{continueContext.output?.substring(0, 800)}{continueContext.output?.length > 800 ? '...' : ''}
</div>
</div>
)}
</div>
<div className="text-xs text-gray-500 mt-3 italic">
{continueContext.success === false
? 'Enter instructions to retry the task. The previous context and error will be included automatically.'
: 'Enter your follow-up instructions below. The previous context will be included automatically.'}
</div>
</div>
)}
{/* Mode Toggle */}
<div className="flex gap-2">
<button
onClick={() => setMode('ai')}
className={`px-4 py-2 rounded-lg transition-colors ${
mode === 'ai' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'
}`}
>
AI Assistant
</button>
<button
onClick={() => setMode('command')}
className={`px-4 py-2 rounded-lg transition-colors ${
mode === 'command' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'
}`}
>
Shell Command
</button>
</div>
{/* Configuration Row */}
<div className="flex flex-wrap gap-3">
{/* Workspace */}
{appsState === 'error' && (
<ListLoadError what="workspaces" error={appsError} onRetry={retryApps} />
)}
{appsState !== 'error' && (
<select
aria-label="Workspace"
value={selectedAppId}
onChange={(e) => setSelectedAppId(e.target.value)}
className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
>
{appsState === 'ready' && apps.length === 0 && (
<option value="">No workspaces found</option>
)}
{apps.map(app => (
<option key={app.id} value={app.id}>{app.name}</option>
))}
</select>
)}
{mode === 'ai' && (
<>
{/* Provider + model. A composed route (Custom combination…) is not in
`providers`, so `currentProvider` is undefined for it and the
selector offers the composite's own service catalog instead. */}
<ProviderModelSelector
compact
label="AI provider"
providers={providers}
selectedProviderId={selectedProvider}
selectedModel={selectedModel}
availableModels={filterSelectableModels(currentProvider?.models)}
onProviderChange={(id) => {
setSelectedProvider(id);
const p = providers.find(p => p.id === id);
setSelectedModel(p?.defaultModel || '');
}}
onModelChange={setSelectedModel}
/>
{/* Timeout */}
<div className="flex items-center gap-2">
<Clock size={16} className="text-gray-400" />
<select
aria-label="Timeout"
value={timeoutMinutes}
onChange={(e) => setTimeoutMinutes(Number(e.target.value))}
className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
>
<option value={5}>5 min</option>
<option value={15}>15 min</option>
<option value={30}>30 min</option>
<option value={60}>60 min</option>
</select>
</div>
{/* Screenshot Upload */}
<FilePickerButton
accept="image/*"
multiple
onChange={handleFileSelect}
ariaLabel="Add screenshots"
className="flex items-center gap-2 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-gray-400 hover:text-white text-sm"
>
<Image size={16} />
Add Screenshot
</FilePickerButton>
</>
)}
</div>
{/* Screenshot Previews */}
{mode === 'ai' && screenshots.length > 0 && (
<div className="flex gap-2 flex-wrap">
{screenshots.map(s => (
<div key={s.id} className="relative group">
<img
src={s.preview}
alt={s.filename}
className="w-20 h-20 object-cover rounded-lg border border-port-border"
/>
<button
aria-label="Remove screenshot"
onClick={() => removeScreenshot(s.id)}
className="absolute -top-2 -right-2 w-5 h-5 bg-port-error rounded-full flex items-center justify-center opacity-100 sm:opacity-0 sm:group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity"
>
<X size={12} />
</button>
</div>
))}
</div>
)}
{/* Input Area */}
{mode === 'ai' ? (
<div className="flex flex-col sm:flex-row gap-2">
<textarea
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
aria-label="AI prompt"
placeholder="Describe what you want the AI to do..."
rows={3}
className="flex-1 px-3 sm:px-4 py-3 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden resize-none text-sm sm:text-base"
/>
{running ? (
<button
onClick={handleStop}
className="px-6 py-3 bg-port-error hover:bg-port-error/80 text-white rounded-lg transition-colors"
>
Stop
</button>
) : (
<button
onClick={handleRunAI}
disabled={!prompt.trim() || !selectedProvider}
className="px-6 py-3 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors disabled:opacity-50"
>
Run
</button>
)}
</div>
) : (
<>
<div className="flex flex-col sm:flex-row gap-2">
<input
type="text"
value={command}
onChange={(e) => setCommand(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && !running && handleRunCommand()}
aria-label="Command to run"
placeholder="Enter command (e.g., npm run build)"
className="flex-1 px-3 sm:px-4 py-3 bg-port-bg border border-port-border rounded-lg text-white font-mono focus:border-port-accent focus:outline-hidden text-sm sm:text-base"
/>
{running ? (
<button
onClick={handleStop}
className="px-6 py-3 bg-port-error hover:bg-port-error/80 text-white rounded-lg transition-colors"
>
Stop
</button>
) : (
<button
onClick={handleRunCommand}
disabled={!command.trim()}
className="px-6 py-3 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors disabled:opacity-50"
>
Run
</button>
)}
</div>
{allowedCommandsState === 'error' && (
<ListLoadError what="allowed commands" error={allowedCommandsError} onRetry={retryAllowedCommands} />
)}
{allowedCommandsState === 'ready' && (
<div className="text-xs text-gray-500 break-words">
{allowedCommands.length === 0
? 'No allowed commands configured'
: `Allowed: ${allowedCommands.slice(0, 10).join(', ')}${allowedCommands.length > 10 ? `, +${allowedCommands.length - 10} more` : ''}`}
</div>
)}
</>
)}
{/* Output */}
<div className="space-y-1">
<div className="text-xs text-gray-500">Output:</div>
<div
ref={outputRef}
className="bg-port-bg border border-port-border rounded-lg p-3 sm:p-4 h-64 sm:h-80 overflow-auto font-mono text-xs sm:text-sm"
>
{output ? (
<pre className="text-gray-300 whitespace-pre-wrap break-all">{output}</pre>
) : (
<div className="text-gray-500">Output will appear here...</div>
)}
</div>
</div>
</div>
</PageLayout>
);
}
export default RunnerPage;