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: OpenClaw operator chat MVP — streaming, attachments, simplify pass [skip ci]

[._.]/ Adam Eivy9b1e148cf66c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ecfffd84f9..7409246f4f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -54,3 +54,29 @@
## Fixed
- JIRA report provider discovery now tries all available API providers instead of failing on first unreachable one
- `agentCliSpawning.js` imported `completeExecution`/`errorExecution` from `executionLanes.js` (wrong module); corrected to import from `toolStateMachine.js`, fixing server crash on startup
+- OpenClaw stream route now calls `res.flushHeaders()` before proxying SSE so headers reach the client immediately
+- OpenClaw stream reader loop wrapped in try/catch to handle AbortError on client disconnect without unhandled rejection
+- Orphaned `htmlFor="compact-task-app"` sr-only label in `TaskAddForm` compact mode removed (referenced select id that no longer exists after AppContextPicker refactor)
+
+## Added
+- `AppContextPicker` component — reusable app selector with repo path display; replaces inline `<select>` in `TaskAddForm` (compact and full modes)
+- OpenClaw operator chat: SSE streaming with optimistic UI (user + streaming assistant placeholder appear immediately)
+- OpenClaw: file/image attachment support — drag & drop, paste screenshots, file picker
+- OpenClaw: app context, directory context, and extra instructions fields sent with messages
+- OpenClaw: Stop/Cancel button aborts in-flight stream via AbortController
+- OpenClaw: Cmd/Ctrl+Enter keyboard shortcut submits the composer
+- OpenClaw: auto-scroll to latest message during streaming
+- OpenClaw: collapsible "older chats" section for sessions beyond the top 6 non-empty ones
+- OpenClaw: synthetic default session injected when `defaultSession` config key has no matching session
+- `formatDateTime` added to `client/src/utils/formatters.js` (medium date + short time via `Intl.DateTimeFormat`)
+- `readFileAsBase64` exported from `client/src/utils/fileUpload.js` for reuse across components
+
+## Changed
+- OpenClaw integration rewritten to use OpenResponses `/v1/responses` API and `/tools/invoke` for session discovery
+- `normalizeAttachment` builds OpenAI-compatible `input_image`/`input_file` blocks from base64 or URL sources
+- `streamSessionMessage` proxies upstream SSE with `timeoutMs: 0` for long-running streaming responses
+- `fetchWithTimeout` accepts `timeoutMs: 0` to opt out of the timeout (needed for streaming)
+- `loadRuntime` stabilized via `selectedSessionIdRef` — session switches no longer trigger a full runtime reload
+- After send, session `lastMessageAt` updated locally instead of triggering a full `loadRuntime()` reload
+- `context` state in OpenClaw simplified — removed derived `appName`/`repoPath`; computed at send time
+- Duplicate `setMessages` update pattern in `handleSend` extracted into `updateAssistant(updater)` helper
diff --git a/client/src/components/AppContextPicker.jsx b/client/src/components/AppContextPicker.jsx
new file mode 100644
index 0000000000..44abf91047
--- /dev/null
+++ b/client/src/components/AppContextPicker.jsx
@@ -0,0 +1,66 @@
+import AppIcon from './AppIcon';
+
+export default function AppContextPicker({
+ apps = [],
+ value = '',
+ onChange,
+ label = 'App context',
+ placeholder = 'PortOS (default)',
+ includeDefaultOption = true,
+ className = '',
+ selectClassName = 'w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm min-h-[44px]',
+ showRepoPath = true,
+ repoLabel = 'Repository'
+}) {
+ const selectedApp = apps.find(app => app.id === value);
+
+ const content = (
+ <div className="space-y-2">
+ <select
+ value={value}
+ onChange={(event) => onChange?.(event.target.value)}
+ className={selectClassName}
+ >
+ {includeDefaultOption && <option value="">{placeholder}</option>}
+ {apps.map(app => (
+ <option key={app.id} value={app.id}>{app.name}</option>
+ ))}
+ </select>
+
+ {showRepoPath && (
+ <div className="rounded-lg border border-port-border bg-port-bg/50 px-3 py-2 text-xs text-gray-400">
+ {selectedApp ? (
+ <div className="flex items-start gap-2">
+ <AppIcon
+ icon={selectedApp.icon || 'package'}
+ appId={selectedApp.id}
+ hasAppIcon={!!selectedApp.appIconPath}
+ size={14}
+ className="mt-0.5 shrink-0 text-gray-400"
+ />
+ <div className="min-w-0">
+ <div className="font-medium text-gray-200">{selectedApp.name}</div>
+ <div className="truncate text-gray-500" title={selectedApp.repoPath || ''}>
+ {repoLabel}: {selectedApp.repoPath || 'No repo path'}
+ </div>
+ </div>
+ </div>
+ ) : (
+ <div>{repoLabel}: using default PortOS context</div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+
+ return (
+ <div className={className}>
+ {label ? (
+ <label className="block text-xs text-gray-400">
+ {label}
+ <div className="mt-1">{content}</div>
+ </label>
+ ) : content}
+ </div>
+ );
+}
diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsx
index b9a1d7d0b1..a9919c032c 100644
--- a/client/src/components/cos/TaskAddForm.jsx
+++ b/client/src/components/cos/TaskAddForm.jsx
@@ -1,6 +1,7 @@
import { useState, useEffect, useRef, useMemo, useCallback } from 'react';
import { Plus, Image, X, ChevronDown, ChevronRight, Sparkles, Loader2, Paperclip, FileText, Zap, Bookmark, Ticket, GitBranch, GitPullRequest, Wand2, RefreshCw } from 'lucide-react';
import toast from '../ui/Toast';
+import AppContextPicker from '../AppContextPicker';
import * as api from '../../services/api';
import { processScreenshotUploads, processAttachmentUploads } from '../../utils/fileUpload';
import { formatBytes } from '../../utils/formatters';
@@ -233,18 +234,17 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
aria-required="true"
/>
<div className="flex gap-2">
- <label htmlFor="compact-task-app" className="sr-only">Target application</label>
- <select
- id="compact-task-app"
- value={newTask.app}
- onChange={e => setNewTask(t => ({ ...t, app: e.target.value }))}
- className="flex-1 sm:w-32 sm:flex-none px-2 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm min-h-[44px]"
- >
- <option value="">PortOS</option>
- {apps?.map(app => (
- <option key={app.id} value={app.id}>{app.name}</option>
- ))}
- </select>
+ <div className="flex-1 sm:w-40 sm:flex-none">
+ <AppContextPicker
+ apps={apps}
+ value={newTask.app}
+ onChange={(appId) => setNewTask(t => ({ ...t, app: appId }))}
+ label=""
+ placeholder="PortOS"
+ showRepoPath={false}
+ selectClassName="w-full px-2 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm min-h-[44px]"
+ />
+ </div>
<button
onClick={handleAddTask}
disabled={isSubmitting || isEnhancing}
@@ -343,20 +343,14 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
return (
<>
{!compact && (
- <div>
- <label htmlFor="task-app" className="sr-only">Target application</label>
- <select
- id="task-app"
- value={newTask.app}
- onChange={e => setNewTask(t => ({ ...t, app: e.target.value }))}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm min-h-[44px]"
- >
- <option value="">PortOS (default)</option>
- {apps?.map(app => (
- <option key={app.id} value={app.id}>{app.name}</option>
- ))}
- </select>
- </div>
+ <AppContextPicker
+ apps={apps}
+ value={newTask.app}
+ onChange={(appId) => setNewTask(t => ({ ...t, app: appId }))}
+ label="Target application"
+ placeholder="PortOS (default)"
+ showRepoPath
+ />
)}
<div className="grid grid-cols-2 sm:flex sm:items-center gap-x-4 gap-y-2 sm:gap-4 sm:flex-wrap">
<label className="flex items-center gap-2 cursor-pointer select-none min-h-[44px]">
diff --git a/client/src/pages/OpenClaw.jsx b/client/src/pages/OpenClaw.jsx
index a2641f8d8c..aef2de79cb 100644
--- a/client/src/pages/OpenClaw.jsx
+++ b/client/src/pages/OpenClaw.jsx
@@ -1,18 +1,23 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
-import { Bot, RefreshCw, Send, AlertCircle, MessageSquareText, PlugZap } from 'lucide-react';
-import * as api from '../services/api';
-
-function formatTimestamp(value) {
- if (!value) return 'Unknown time';
-
- const date = new Date(value);
- if (Number.isNaN(date.getTime())) return String(value);
-
- return new Intl.DateTimeFormat(undefined, {
- dateStyle: 'medium',
- timeStyle: 'short'
- }).format(date);
-}
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import {
+ Bot,
+ RefreshCw,
+ Send,
+ Square,
+ AlertCircle,
+ MessageSquareText,
+ PlugZap,
+ Paperclip,
+ Image as ImageIcon,
+ X,
+ Upload,
+ ClipboardPaste
+} from 'lucide-react';
+import AppContextPicker from '../components/AppContextPicker';
+import * as api from '../services/apiOpenClaw';
+import * as coreApi from '../services/api';
+import { formatDateTime } from '../utils/formatters';
+import { readFileAsBase64 } from '../utils/fileUpload';
function getRuntimeState(status) {
if (!status?.configured) {
@@ -35,20 +40,124 @@ function getRuntimeState(status) {
};
}
+function ensureDefaultSession(sessions, status) {
+ const nextSessions = Array.isArray(sessions) ? [...sessions] : [];
+ const defaultSessionId = status?.defaultSession;
+ if (!defaultSessionId) return nextSessions;
+ if (nextSessions.some(session => session.id === defaultSessionId)) return nextSessions;
+
+ return [
+ {
+ id: defaultSessionId,
+ title: status?.label ? `${status.label} (default)` : 'Default PortOS session',
+ label: 'Default PortOS session',
+ status: 'default',
+ messageCount: null,
+ lastMessageAt: null,
+ synthetic: true
+ },
+ ...nextSessions
+ ];
+}
+
+function getSessionSortTime(session) {
+ const value = session?.lastMessageAt;
+ const timestamp = value ? new Date(value).getTime() : 0;
+ return Number.isFinite(timestamp) ? timestamp : 0;
+}
+
+function isSessionEmpty(session) {
+ return !session?.synthetic && !session?.lastMessageAt && Number(session?.messageCount || 0) === 0;
+}
+
+function partitionSessions(sessions = [], selectedSessionId = '', defaultSessionId = '') {
+ const sorted = [...sessions].sort((left, right) => {
+ const leftPinned = left.id === selectedSessionId || left.id === defaultSessionId;
+ const rightPinned = right.id === selectedSessionId || right.id === defaultSessionId;
+ if (leftPinned !== rightPinned) return leftPinned ? -1 : 1;
+ return getSessionSortTime(right) - getSessionSortTime(left);
+ });
+
+ const primary = [];
+ const older = [];
+
+ for (const session of sorted) {
+ const pinned = session.id === selectedSessionId || session.id === defaultSessionId;
+ const empty = isSessionEmpty(session);
+ if (pinned || (!empty && primary.length < 6)) {
+ primary.push(session);
+ } else {
+ older.push(session);
+ }
+ }
+
+ return { primary, older };
+}
+
+function getAttachmentKind(file) {
+ return file.type.startsWith('image/') ? 'image' : 'file';
+}
+
+function normalizeContent(content) {
+ if (typeof content === 'string') return content;
+ if (!content) return '';
+ if (Array.isArray(content)) return content.map(normalizeContent).filter(Boolean).join('\n\n');
+ if (typeof content === 'object') {
+ if (typeof content.text === 'string') return content.text;
+ if (typeof content.content === 'string') return content.content;
+ }
+ return '';
+}
+
+async function filesToAttachments(files) {
+ return Promise.all(files.map(async (file) => {
+ const kind = getAttachmentKind(file);
+ const mediaType = file.type || 'application/octet-stream';
+ const base64 = await readFileAsBase64(file);
+ return {
+ id: `attachment-${file.name}-${file.lastModified}-${Math.random().toString(36).slice(2, 8)}`,
+ name: file.name,
+ filename: file.name,
+ mediaType,
+ kind,
+ size: file.size,
+ data: base64,
+ previewUrl: kind === 'image' ? `data:${mediaType};base64,${base64}` : ''
+ };
+ }));
+}
+
export default function OpenClaw() {
const [status, setStatus] = useState(null);
const [sessions, setSessions] = useState([]);
+ const [apps, setApps] = useState([]);
const [selectedSessionId, setSelectedSessionId] = useState('');
const [messages, setMessages] = useState([]);
const [composer, setComposer] = useState('');
+ const [context, setContext] = useState({
+ appId: '',
+ directoryPath: '',
+ extraInstructions: ''
+ });
+ const [attachments, setAttachments] = useState([]);
const [statusLoading, setStatusLoading] = useState(true);
const [sessionsLoading, setSessionsLoading] = useState(false);
const [messagesLoading, setMessagesLoading] = useState(false);
const [sending, setSending] = useState(false);
+ const [activityLabel, setActivityLabel] = useState('');
const [pageError, setPageError] = useState('');
const [messagesError, setMessagesError] = useState('');
-
+ const [isDragActive, setIsDragActive] = useState(false);
+ const [showOlderChats, setShowOlderChats] = useState(false);
+ const fileInputRef = useRef(null);
+ const messagesEndRef = useRef(null);
+ const abortControllerRef = useRef(null);
+ const selectedSessionIdRef = useRef(selectedSessionId);
const runtimeState = useMemo(() => getRuntimeState(status), [status]);
+ const visibleSessions = useMemo(
+ () => partitionSessions(sessions, selectedSessionId, status?.defaultSession),
+ [sessions, selectedSessionId, status?.defaultSession]
+ );
const loadMessages = useCallback(async (sessionId) => {
if (!sessionId) {
@@ -89,18 +198,17 @@ export default function OpenClaw() {
}
const sessionsData = await api.getOpenClawSessions();
- const nextSessions = sessionsData?.sessions || [];
+ const nextSessions = ensureDefaultSession(sessionsData?.sessions || [], statusData);
setSessions(nextSessions);
const validIds = new Set(nextSessions.map(session => session.id).filter(Boolean));
const preferredSessionId = [
- selectedSessionId,
+ selectedSessionIdRef.current,
statusData.defaultSession,
nextSessions[0]?.id
].find(id => id && (validIds.size === 0 || validIds.has(id)));
- const fallbackSessionId = preferredSessionId || statusData.defaultSession || '';
- setSelectedSessionId(fallbackSessionId);
+ setSelectedSessionId(preferredSessionId || statusData.defaultSession || '');
} catch (err) {
setStatus(null);
setSessions([]);
@@ -111,12 +219,17 @@ export default function OpenClaw() {
setStatusLoading(false);
setSessionsLoading(false);
}
- }, [selectedSessionId]);
+ }, []);
useEffect(() => {
loadRuntime();
+ coreApi.getApps().then(data => setApps((data || []).filter(app => !app.archived))).catch(() => setApps([]));
}, [loadRuntime]);
+ useEffect(() => {
+ selectedSessionIdRef.current = selectedSessionId;
+ }, [selectedSessionId]);
+
useEffect(() => {
if (!status?.configured || !selectedSessionId) {
setMessages([]);
@@ -127,24 +240,191 @@ export default function OpenClaw() {
loadMessages(selectedSessionId);
}, [loadMessages, selectedSessionId, status?.configured]);
- const handleSend = async (event) => {
+ useEffect(() => {
+ messagesEndRef.current?.scrollIntoView({ behavior: 'smooth', block: 'end' });
+ }, [messages]);
+
+ useEffect(() => () => abortControllerRef.current?.abort(), []);
+
+ const appendFiles = useCallback(async (files) => {
+ if (!files || files.length === 0) return;
+
+ try {
+ const next = await filesToAttachments(files);
+ setAttachments(current => [...current, ...next]);
+ setMessagesError('');
+ } catch (err) {
+ setMessagesError(err.message || 'Failed to prepare attachment');
+ }
+ }, []);
+
+ const handleAttachmentSelect = async (event) => {
+ const files = Array.from(event.target.files || []);
+ await appendFiles(files);
+ event.target.value = '';
+ };
+
+ const handlePaste = async (event) => {
+ const items = Array.from(event.clipboardData?.items || []);
+ const files = items
+ .map(item => item.getAsFile())
+ .filter(Boolean);
+
+ if (files.length === 0) return;
event.preventDefault();
+ await appendFiles(files);
+ };
+
+ const handleDragEnter = (event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ if (event.dataTransfer?.types?.includes('Files')) setIsDragActive(true);
+ };
+
+ const handleDragOver = (event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
+ if (event.dataTransfer?.types?.includes('Files')) setIsDragActive(true);
+ };
+
+ const handleDragLeave = (event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ const relatedTarget = event.relatedTarget;
+ if (!event.currentTarget.contains(relatedTarget)) {
+ setIsDragActive(false);
+ }
+ };
+
+ const handleDrop = async (event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ setIsDragActive(false);
+ const files = Array.from(event.dataTransfer?.files || []);
+ await appendFiles(files);
+ };
+
+ const removeAttachment = (attachmentId) => {
+ setAttachments(current => current.filter(item => item.id !== attachmentId));
+ };
+
+ const handleSend = async (event) => {
+ event?.preventDefault();
const message = composer.trim();
- if (!message || !selectedSessionId || sending) return;
+ if ((!message && attachments.length === 0) || !selectedSessionId || sending) return;
+
+ const userMessageId = `local-user-${Date.now()}`;
+ const assistantMessageId = `local-assistant-${Date.now()}`;
+ const selectedApp = apps.find(app => app.id === context.appId);
+ const payloadContext = Object.fromEntries(
+ Object.entries({
+ appName: selectedApp?.name || '',
+ repoPath: selectedApp?.repoPath || '',
+ directoryPath: context.directoryPath,
+ extraInstructions: context.extraInstructions
+ }).filter(([, value]) => String(value || '').trim())
+ );
+ const payloadAttachments = attachments.map(({ id, size, previewUrl, ...attachment }) => attachment);
setSending(true);
+ setActivityLabel('Connecting…');
setMessagesError('');
+ const userMessage = {
+ id: userMessageId,
+ role: 'user',
+ content: message || `[Sent ${attachments.length} attachment${attachments.length === 1 ? '' : 's'}]`,
+ createdAt: new Date().toISOString(),
+ status: 'completed',
+ attachments: attachments.map(({ id, data, ...attachment }) => ({ id, ...attachment }))
+ };
+
+ setMessages(current => [...current, userMessage, {
+ id: assistantMessageId,
+ role: 'assistant',
+ content: '',
+ createdAt: new Date().toISOString(),
+ status: 'streaming'
+ }]);
+
+ const abortController = new AbortController();
+ abortControllerRef.current = abortController;
+
+ const updateAssistant = (updater) =>
+ setMessages(current => current.map(item =>
+ item.id === assistantMessageId
+ ? { ...item, ...(typeof updater === 'function' ? updater(item) : updater) }
+ : item
+ ));
+
try {
- await api.sendOpenClawMessage(selectedSessionId, message);
+ await api.streamOpenClawMessage(selectedSessionId, {
+ message: message || 'Please inspect the attached context and respond.',
+ context: payloadContext,
+ attachments: payloadAttachments,
+ signal: abortController.signal,
+ onEvent: ({ event: eventName, data }) => {
+ if (eventName === 'response.created' || eventName === 'response.in_progress') {
+ setActivityLabel('Thinking…');
+ return;
+ }
+
+ if (eventName === 'response.output_item.added' || eventName === 'response.content_part.added') {
+ setActivityLabel('Working…');
+ return;
+ }
+
+ if (eventName === 'response.output_text.delta') {
+ const delta = typeof data === 'string' ? data : (data?.delta || data?.text || '');
+ setActivityLabel('Responding…');
+ updateAssistant(item => ({ content: `${item.content || ''}${delta}`, status: 'streaming' }));
+ return;
+ }
+
+ if (eventName === 'response.output_text.done') {
+ const finalText = normalizeContent(data?.text || data?.output_text || data);
+ if (finalText) updateAssistant({ content: finalText, status: 'streaming' });
+ return;
+ }
+
+ if (eventName === 'response.failed' || eventName === 'error') {
+ throw new Error(data?.error?.message || data?.message || data?.error || 'OpenClaw stream failed');
+ }
+
+ if (eventName === 'done' || eventName === 'response.completed') {
+ setActivityLabel('');
+ updateAssistant({ status: 'completed', createdAt: new Date().toISOString() });
+ }
+ }
+ });
+
setComposer('');
- await loadMessages(selectedSessionId);
- await loadRuntime();
+ setAttachments([]);
+ updateAssistant(item => ({ status: 'completed', content: item.content || '[No text response]' }));
+ const now = new Date().toISOString();
+ setSessions(prev => prev.map(s =>
+ s.id === selectedSessionId ? { ...s, lastMessageAt: now } : s
+ ));
} catch (err) {
+ setMessages(current => current.filter(item => item.id !== assistantMessageId));
setMessagesError(err.message || 'Failed to send message');
} finally {
+ abortControllerRef.current = null;
setSending(false);
+ setActivityLabel('');
+ }
+ };
+
+ const handleStop = () => {
+ abortControllerRef.current?.abort();
+ };
+
+ const handleComposerKeyDown = (event) => {
+ if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {
+ event.preventDefault();
+ handleSend();
}
};
@@ -157,7 +437,7 @@ export default function OpenClaw() {
<Bot className="h-8 w-8 text-port-accent" />
<div>
<h1 className="text-xl font-bold text-white">OpenClaw</h1>
- <p className="text-sm text-gray-500">Operator chat surface for an optional runtime.</p>
+ <p className="text-sm text-gray-500">Operator chat surface with streaming, context, and attachments.</p>
</div>
</div>
@@ -241,25 +521,60 @@ export default function OpenClaw() {
No sessions available.
</div>
) : (
- sessions.map((session) => {
- const isActive = session.id === selectedSessionId;
- return (
- <button
- key={session.id}
- type="button"
- onClick={() => setSelectedSessionId(session.id)}
- className={`block w-full border-b border-port-border px-4 py-3 text-left transition-colors last:border-b-0 ${
- isActive ? 'bg-port-accent/10 text-white' : 'text-gray-300 hover:bg-port-border/20 hover:text-white'
- }`}
- >
- <div className="truncate text-sm font-medium">{session.title || session.label || session.id}</div>
- <div className="mt-1 flex items-center justify-between gap-3 text-xs text-gray-500">
- <span className="truncate">{session.id}</span>
- <span>{session.messageCount ?? 0} msgs</span>
- </div>
- </button>
- );
- })
+ <>
+ {visibleSessions.primary.map((session) => {
+ const isActive = session.id === selectedSessionId;
+ return (
+ <button
+ key={session.id}
+ type="button"
+ onClick={() => setSelectedSessionId(session.id)}
+ className={`block w-full border-b border-port-border px-4 py-3 text-left transition-colors last:border-b-0 ${
+ isActive ? 'bg-port-accent/10 text-white' : 'text-gray-300 hover:bg-port-border/20 hover:text-white'
+ }`}
+ >
+ <div className="truncate text-sm font-medium">{session.title || session.label || session.id}</div>
+ <div className="mt-1 flex items-center justify-between gap-3 text-xs text-gray-500">
+ <span className="truncate">{session.id}</span>
+ <span>{session.messageCount ?? 0} msgs</span>
+ </div>
+ </button>
+ );
+ })}
+
+ {visibleSessions.older.length > 0 && (
+ <div className="border-t border-port-border">
+ <button
+ type="button"
+ onClick={() => setShowOlderChats(current => !current)}
+ className="flex w-full items-center justify-between px-4 py-3 text-left text-sm text-gray-400 transition-colors hover:bg-port-border/20 hover:text-white"
+ >
+ <span>{showOlderChats ? 'Hide older chats' : `Show older chats (${visibleSessions.older.length})`}</span>
+ <span className="text-xs text-gray-500">{showOlderChats ? 'expanded' : 'collapsed'}</span>
+ </button>
+
+ {showOlderChats && visibleSessions.older.map((session) => {
+ const isActive = session.id === selectedSessionId;
+ return (
+ <button
+ key={session.id}
+ type="button"
+ onClick={() => setSelectedSessionId(session.id)}
+ className={`block w-full border-t border-port-border/60 px-4 py-3 text-left transition-colors ${
+ isActive ? 'bg-port-accent/10 text-white' : 'text-gray-400 hover:bg-port-border/20 hover:text-white'
+ }`}
+ >
+ <div className="truncate text-sm font-medium">{session.title || session.label || session.id}</div>
+ <div className="mt-1 flex items-center justify-between gap-3 text-xs text-gray-500">
+ <span className="truncate">{session.id}</span>
+ <span>{session.messageCount ?? 0} msgs</span>
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </>
)}
</div>
</section>
@@ -276,11 +591,10 @@ export default function OpenClaw() {
{selectedSessionId ? `Session ID: ${selectedSessionId}` : 'Choose a session to load recent messages.'}
</p>
</div>
- {selectedSession?.lastMessageAt && (
- <div className="text-xs text-gray-500">
- Last activity {formatTimestamp(selectedSession.lastMessageAt)}
- </div>
- )}
+ <div className="text-right text-xs text-gray-500">
+ {selectedSession?.lastMessageAt && <div>Last activity {formatDateTime(selectedSession.lastMessageAt)}</div>}
+ {activityLabel && <div className="mt-1 text-port-accent">{activityLabel}</div>}
+ </div>
</div>
</div>
@@ -322,6 +636,7 @@ export default function OpenClaw() {
const role = message.role || 'assistant';
const isUser = role === 'user';
const key = message.id || `${message.createdAt || 'message'}-${index}`;
+ const messageAttachments = Array.isArray(message.attachments) ? message.attachments : [];
return (
<div
@@ -334,44 +649,182 @@ export default function OpenClaw() {
>
<div className="mb-2 flex items-center justify-between gap-3 text-xs uppercase tracking-wide">
<span className={isUser ? 'text-port-accent' : 'text-gray-400'}>{role}</span>
- <span className="text-gray-500">{formatTimestamp(message.createdAt)}</span>
+ <span className="text-gray-500">{formatDateTime(message.createdAt)}</span>
</div>
<div className="whitespace-pre-wrap text-sm leading-6 text-gray-100">
- {message.content || '[Empty message]'}
+ {message.content || (message.status === 'streaming' ? '…' : '[Empty message]')}
</div>
+ {messageAttachments.length > 0 && (
+ <div className="mt-3 flex flex-wrap gap-2">
+ {messageAttachments.map((attachment) => (
+ <div key={attachment.id || attachment.name} className="rounded-lg border border-port-border bg-port-card px-3 py-2 text-xs text-gray-300">
+ {attachment.kind === 'image' ? <ImageIcon size={12} className="mr-1 inline" /> : <Paperclip size={12} className="mr-1 inline" />}
+ {attachment.name || attachment.filename}
+ </div>
+ ))}
+ </div>
+ )}
</div>
);
})}
+ <div ref={messagesEndRef} />
</div>
)}
</div>
<form onSubmit={handleSend} className="border-t border-port-border p-4">
- <label className="mb-2 block text-sm font-medium text-white" htmlFor="openclaw-composer">
- Send message
- </label>
- <textarea
- id="openclaw-composer"
- value={composer}
- onChange={(event) => setComposer(event.target.value)}
- rows={4}
- placeholder={status?.configured ? 'Send a message to the selected session…' : 'OpenClaw is not configured'}
- disabled={!status?.configured || !selectedSessionId || sending}
- className="w-full resize-none rounded-lg border border-port-border bg-port-bg px-3 py-3 text-sm text-white focus:border-port-accent focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-60"
- />
- <div className="mt-3 flex items-center justify-between gap-3">
- <span className="text-xs text-gray-500">
- {status?.configured && selectedSessionId ? 'Messages are proxied through PortOS.' : 'Select a configured session to send.'}
- </span>
- <button
- type="submit"
- disabled={!composer.trim() || !status?.configured || !selectedSessionId || sending}
- className="inline-flex items-center gap-2 rounded-lg bg-port-accent px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-port-accent/80 disabled:cursor-not-allowed disabled:opacity-60"
- >
- {sending ? <RefreshCw size={16} className="animate-spin" /> : <Send size={16} />}
- {sending ? 'Sending…' : 'Send'}
- </button>
+ <div className="mb-3 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
+ <AppContextPicker
+ apps={apps}
+ value={context.appId}
+ onChange={(appId) => setContext(current => ({ ...current, appId }))}
+ label="App context"
+ placeholder="PortOS (default)"
+ showRepoPath
+ />
+ <label className="block text-xs text-gray-400">
+ Directory context
+ <input
+ value={context.directoryPath}
+ onChange={(event) => setContext(current => ({ ...current, directoryPath: event.target.value }))}
+ placeholder="client/src/pages"
+ className="mt-1 w-full rounded-lg border border-port-border bg-port-bg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-hidden"
+ />
+ </label>
+ <label className="block text-xs text-gray-400">
+ Extra context
+ <input
+ value={context.extraInstructions}
+ onChange={(event) => setContext(current => ({ ...current, extraInstructions: event.target.value }))}
+ placeholder="What to pay attention to"
+ className="mt-1 w-full rounded-lg border border-port-border bg-port-bg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-hidden"
+ />
+ </label>
</div>
+
+ <div
+ onDragEnter={handleDragEnter}
+ onDragOver={handleDragOver}
+ onDragLeave={handleDragLeave}
+ onDrop={handleDrop}
+ className={`rounded-xl border p-3 transition-colors ${
+ isDragActive
+ ? 'border-port-accent bg-port-accent/10'
+ : 'border-port-border bg-port-bg/20'
+ }`}
+ >
+ <label className="mb-2 block text-sm font-medium text-white" htmlFor="openclaw-composer">
+ Send message
+ </label>
+ <textarea
+ id="openclaw-composer"
+ value={composer}
+ onChange={(event) => setComposer(event.target.value)}
+ onPaste={handlePaste}
+ onKeyDown={handleComposerKeyDown}
+ rows={4}
+ placeholder={status?.configured ? 'Send a message, paste an image, or drop files here…' : 'OpenClaw is not configured'}
+ disabled={!status?.configured || !selectedSessionId || sending}
+ className="w-full resize-none rounded-lg border border-port-border bg-port-bg px-3 py-3 text-sm text-white focus:border-port-accent focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-60"
+ />
+
+ <div className="mt-2 flex flex-wrap items-center gap-3 text-xs text-gray-400">
+ <span className="inline-flex items-center gap-1">
+ <Upload size={12} />
+ drag & drop
+ </span>
+ <span className="inline-flex items-center gap-1">
+ <ClipboardPaste size={12} />
+ paste screenshots
+ </span>
+ <span className="inline-flex items-center gap-1">
+ <Paperclip size={12} />
+ files + images
+ </span>
+ </div>
+ </div>
+
+ {attachments.length > 0 && (
+ <div className="mt-3 grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
+ {attachments.map((attachment) => (
+ <div key={attachment.id} className="rounded-xl border border-port-border bg-port-bg/40 p-3">
+ <div className="mb-2 flex items-start justify-between gap-2">
+ <div className="min-w-0 text-xs text-gray-300">
+ <div className="truncate font-medium text-white">{attachment.name}</div>
+ <div className="truncate text-gray-500">{attachment.mediaType}</div>
+ </div>
+ <button
+ type="button"
+ onClick={() => removeAttachment(attachment.id)}
+ className="text-gray-400 hover:text-white"
+ aria-label={`Remove ${attachment.name}`}
+ >
+ <X size={14} />
+ </button>
+ </div>
+
+ {attachment.kind === 'image' && attachment.previewUrl ? (
+ <img
+ src={attachment.previewUrl}
+ alt={attachment.name}
+ className="h-32 w-full rounded-lg border border-port-border object-cover"
+ />
+ ) : (
+ <div className="flex h-32 items-center justify-center rounded-lg border border-port-border bg-port-card text-xs text-gray-400">
+ <Paperclip size={16} className="mr-2" />
+ File attached
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+
+ <div className="mt-3 flex flex-wrap items-center justify-between gap-3">
+ <div className="flex flex-wrap items-center gap-2 text-xs text-gray-500">
+ <span>
+ {status?.configured && selectedSessionId ? 'Stream via PortOS · ⌘↵ to send' : 'Select a configured session to send.'}
+ </span>
+ <button
+ type="button"
+ onClick={() => fileInputRef.current?.click()}
+ disabled={!status?.configured || !selectedSessionId || sending}
+ className="inline-flex items-center gap-2 rounded-lg border border-port-border bg-port-card px-3 py-2 text-xs text-gray-200 hover:border-gray-500 hover:text-white disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ <Paperclip size={14} />
+ Add file/image
+ </button>
+ </div>
+ <div className="flex items-center gap-2">
+ {sending && (
+ <button
+ type="button"
+ onClick={handleStop}
+ className="inline-flex items-center gap-2 rounded-lg border border-port-border bg-port-card px-4 py-2 text-sm font-medium text-gray-200 transition-colors hover:border-red-500/50 hover:text-red-300"
+ >
+ <Square size={14} />
+ Stop
+ </button>
+ )}
+ <button
+ type="submit"
+ disabled={(!composer.trim() && attachments.length === 0) || !status?.configured || !selectedSessionId || sending}
+ className="inline-flex items-center gap-2 rounded-lg bg-port-accent px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-port-accent/80 disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ {sending ? <RefreshCw size={16} className="animate-spin" /> : <Send size={16} />}
+ {sending ? (activityLabel || 'Working…') : 'Send'}
+ </button>
+ </div>
+ </div>
+
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ accept="image/*,.txt,.md,.json,.csv,.pdf"
+ className="hidden"
+ onChange={handleAttachmentSelect}
+ />
</form>
</section>
</div>
diff --git a/client/src/services/apiOpenClaw.js b/client/src/services/apiOpenClaw.js
index e9665e6c02..b091aadb39 100644
--- a/client/src/services/apiOpenClaw.js
+++ b/client/src/services/apiOpenClaw.js
@@ -1,4 +1,4 @@
-import { request } from './apiCore.js';
+import { API_BASE, request } from './apiCore.js';
export const getOpenClawStatus = () => request('/openclaw/status', { silent: true });
export const getOpenClawSessions = () => request('/openclaw/sessions', { silent: true });
@@ -8,8 +8,80 @@ export const getOpenClawMessages = (sessionId, options = {}) => {
const query = params.toString();
return request(`/openclaw/sessions/${encodeURIComponent(sessionId)}/messages${query ? `?${query}` : ''}`, { silent: true });
};
-export const sendOpenClawMessage = (sessionId, message, context) => request(`/openclaw/sessions/${encodeURIComponent(sessionId)}/messages`, {
+
+export const sendOpenClawMessage = (sessionId, message, context, attachments) => request(`/openclaw/sessions/${encodeURIComponent(sessionId)}/messages`, {
method: 'POST',
- body: JSON.stringify({ message, context }),
+ body: JSON.stringify({ message, context, attachments }),
silent: true
});
+
+export async function streamOpenClawMessage(sessionId, { message, context, attachments, signal, onEvent }) {
+ const response = await fetch(`${API_BASE}/openclaw/sessions/${encodeURIComponent(sessionId)}/messages/stream`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({ message, context, attachments }),
+ signal
+ }).catch(() => null);
+
+ if (!response) {
+ throw new Error('Server unreachable — check your connection and try again');
+ }
+
+ if (!response.ok) {
+ const error = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));
+ throw new Error(error.error || `HTTP ${response.status}`);
+ }
+
+ if (!response.body) {
+ throw new Error('Streaming is unavailable for this response');
+ }
+
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = '';
+
+ const emit = (eventName, data) => {
+ if (typeof onEvent === 'function') onEvent({ event: eventName, data });
+ };
+
+ const flushEventBlock = (block) => {
+ const lines = block.split('\n');
+ let eventName = 'message';
+ const dataLines = [];
+
+ for (const line of lines) {
+ if (line.startsWith('event:')) eventName = line.slice(6).trim() || 'message';
+ if (line.startsWith('data:')) dataLines.push(line.slice(5).trimStart());
+ }
+
+ if (dataLines.length === 0) return;
+ const rawData = dataLines.join('\n');
+ if (rawData === '[DONE]') {
+ emit('done', '[DONE]');
+ return;
+ }
+
+ let data = rawData;
+ try {
+ data = JSON.parse(rawData);
+ } catch {
+ // keep raw string
+ }
+ emit(eventName, data);
+ };
+
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+
+ const parts = buffer.split('\n\n');
+ buffer = parts.pop() || '';
+ for (const part of parts) flushEventBlock(part);
+ }
+
+ buffer += decoder.decode();
+ if (buffer.trim()) flushEventBlock(buffer);
+}
diff --git a/client/src/utils/fileUpload.js b/client/src/utils/fileUpload.js
index b973518409..1f1ca24446 100644
--- a/client/src/utils/fileUpload.js
+++ b/client/src/utils/fileUpload.js
@@ -17,6 +17,23 @@ const ALLOWED_ATTACHMENT_EXTENSIONS = [
// Default max file size: 10MB
const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024;
+/**
+ * Read a File as a base64 string (without the data URL prefix)
+ * @param {File} file - File to read
+ * @returns {Promise<string>} Base64-encoded file contents
+ */
+export function readFileAsBase64(file) {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => {
+ const result = typeof reader.result === 'string' ? reader.result : '';
+ resolve(result.includes(',') ? result.split(',').pop() : result);
+ };
+ reader.onerror = () => reject(new Error(`Failed to read ${file.name}`));
+ reader.readAsDataURL(file);
+ });
+}
+
/**
* Process and upload image files as screenshots
*
diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.js
index b881b0ff1f..37bbf689eb 100644
--- a/client/src/utils/formatters.js
+++ b/client/src/utils/formatters.js
@@ -109,6 +109,18 @@ export function formatBytes(bytes, decimals = 1) {
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`;
}
+/**
+ * Format a timestamp as a localized date+time string (e.g., "Apr 1, 2026, 1:30 PM")
+ * @param {string|Date|null} value - ISO timestamp or Date object
+ * @returns {string} Formatted date and time, or 'Unknown time' for invalid input
+ */
+export function formatDateTime(value) {
+ if (!value) return 'Unknown time';
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) return String(value);
+ return new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date);
+}
+
/**
* Get app name from app ID by looking up in apps array
* @param {string|null} appId - The app ID to look up
diff --git a/server/integrations/openclaw/api.js b/server/integrations/openclaw/api.js
index 9419836ece..1e047a0f8b 100644
--- a/server/integrations/openclaw/api.js
+++ b/server/integrations/openclaw/api.js
@@ -6,10 +6,8 @@ import { ServerError } from '../../lib/errorHandler.js';
const CONFIG_FILE = join(PATHS.data, 'openclaw', 'config.json');
const DEFAULT_TIMEOUT_MS = 15000;
const DEFAULT_PATHS = {
- status: '/status',
- sessions: '/sessions',
- sessionMessages: '/sessions/:sessionId/messages',
- sendMessage: '/sessions/:sessionId/messages'
+ toolsInvoke: '/tools/invoke',
+ responses: '/v1/responses'
};
function parseBoolean(value) {
@@ -38,22 +36,6 @@ function joinUrl(baseUrl, path) {
return new URL(withLeadingSlash(path), baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`).toString();
}
-function buildPath(template, params = {}) {
- return Object.entries(params).reduce(
- (path, [key, value]) => path.replaceAll(`:${key}`, encodeURIComponent(String(value))),
- template
- );
-}
-
-function toArray(value) {
- if (Array.isArray(value)) return value;
- if (Array.isArray(value?.items)) return value.items;
- if (Array.isArray(value?.sessions)) return value.sessions;
- if (Array.isArray(value?.messages)) return value.messages;
- if (Array.isArray(value?.data)) return value.data;
- return [];
-}
-
function parseUpstreamBody(text) {
if (!text) return null;
@@ -77,8 +59,11 @@ function extractMessageContent(value) {
if (typeof value.content === 'string') return value.content;
if (typeof value.body === 'string') return value.body;
if (typeof value.message === 'string') return value.message;
+ if (typeof value.output_text === 'string') return value.output_text;
if (value.parts) return extractMessageContent(value.parts);
if (value.content?.parts) return extractMessageContent(value.content.parts);
+ if (Array.isArray(value.content)) return extractMessageContent(value.content);
+ if (Array.isArray(value.output)) return extractMessageContent(value.output);
}
return '';
@@ -93,13 +78,13 @@ function normalizeRole(input) {
}
function normalizeSession(session) {
- const id = pickFirst(session?.id, session?.sessionId, session?.slug, session?.name, session?.title);
+ const id = pickFirst(session?.key, session?.id, session?.sessionId, session?.slug, session?.name, session?.title);
if (!id) return null;
return {
id: String(id),
- title: pickFirst(session?.title, session?.label, session?.name, session?.sessionId, id),
- label: pickFirst(session?.label, session?.name, session?.title, id),
+ title: pickFirst(session?.title, session?.displayName, session?.label, session?.name, session?.sessionId, id),
+ label: pickFirst(session?.label, session?.displayName, session?.name, session?.title, id),
status: pickFirst(session?.status, session?.state, null) || null,
messageCount: pickFirst(session?.messageCount, session?.messagesCount, session?.count, null),
lastMessageAt: pickFirst(session?.lastMessageAt, session?.updatedAt, session?.lastActivityAt, session?.createdAt, null),
@@ -147,6 +132,7 @@ async function loadConfig() {
authScheme: pickFirst(process.env.OPENCLAW_AUTH_SCHEME, fileConfig.authScheme, 'Bearer'),
label: pickFirst(process.env.OPENCLAW_LABEL, fileConfig.label, 'OpenClaw Runtime'),
defaultSession: pickFirst(process.env.OPENCLAW_DEFAULT_SESSION, fileConfig.defaultSession, null),
+ defaultAgentId: pickFirst(process.env.OPENCLAW_DEFAULT_AGENT_ID, fileConfig.defaultAgentId, 'main'),
timeoutMs: Number.parseInt(String(pickFirst(process.env.OPENCLAW_TIMEOUT_MS, fileConfig.timeoutMs, DEFAULT_TIMEOUT_MS)), 10) || DEFAULT_TIMEOUT_MS,
paths: {
...DEFAULT_PATHS,
@@ -165,7 +151,7 @@ function getAuthHeaders(config) {
};
}
-async function openClawRequest(config, path, { method = 'GET', query, body } = {}) {
+async function openClawFetch(config, path, { method = 'GET', headers = {}, body, accept = 'application/json', timeoutMs } = {}) {
if (!config.configured) {
throw new ServerError('OpenClaw is not configured', {
status: 503,
@@ -173,26 +159,17 @@ async function openClawRequest(config, path, { method = 'GET', query, body } = {
});
}
- const url = new URL(joinUrl(config.baseUrl, path));
- if (query) {
- for (const [key, value] of Object.entries(query)) {
- if (value !== undefined && value !== null && value !== '') {
- url.searchParams.set(key, String(value));
- }
- }
- }
-
- let response;
try {
- response = await fetchWithTimeout(url.toString(), {
+ return await fetchWithTimeout(joinUrl(config.baseUrl, path), {
method,
headers: {
- Accept: 'application/json',
+ Accept: accept,
...getAuthHeaders(config),
+ ...headers,
...(body ? { 'Content-Type': 'application/json' } : {})
},
...(body ? { body: JSON.stringify(body) } : {})
- }, config.timeoutMs);
+ }, timeoutMs ?? config.timeoutMs);
} catch (err) {
if (err?.name === 'AbortError') {
throw new ServerError('OpenClaw request timed out', {
@@ -206,35 +183,144 @@ async function openClawRequest(config, path, { method = 'GET', query, body } = {
code: 'OPENCLAW_UNREACHABLE'
});
}
+}
+async function parseOpenClawError(response) {
let payload = null;
if (response.status !== 204) {
const text = await response.text();
payload = parseUpstreamBody(text);
}
+ const upstreamMessage = pickFirst(payload?.error?.message, payload?.error, payload?.message, null);
+ let code = 'OPENCLAW_REQUEST_FAILED';
+ let message = upstreamMessage || `OpenClaw request failed with HTTP ${response.status}`;
+ let status = 502;
+
+ if (response.status === 401 || response.status === 403) {
+ code = 'OPENCLAW_UNAUTHORIZED';
+ message = upstreamMessage || 'OpenClaw rejected the configured credentials';
+ } else if (response.status === 404) {
+ code = 'OPENCLAW_NOT_FOUND';
+ message = upstreamMessage || 'OpenClaw endpoint is not available';
+ } else if (response.status >= 500) {
+ code = 'OPENCLAW_UPSTREAM_ERROR';
+ message = upstreamMessage || 'OpenClaw runtime failed to process the request';
+ status = 503;
+ }
+
+ throw new ServerError(message, { status, code });
+}
+
+async function openClawRequest(config, path, options = {}) {
+ const response = await openClawFetch(config, path, options);
if (!response.ok) {
- const upstreamMessage = pickFirst(payload?.error, payload?.message, null);
- let code = 'OPENCLAW_REQUEST_FAILED';
- let message = upstreamMessage || `OpenClaw request failed with HTTP ${response.status}`;
- let status = 502;
-
- if (response.status === 401 || response.status === 403) {
- code = 'OPENCLAW_UNAUTHORIZED';
- message = upstreamMessage || 'OpenClaw rejected the configured credentials';
- } else if (response.status === 404) {
- code = 'OPENCLAW_NOT_FOUND';
- message = upstreamMessage || 'OpenClaw endpoint is not available';
- } else if (response.status >= 500) {
- code = 'OPENCLAW_UPSTREAM_ERROR';
- message = upstreamMessage || 'OpenClaw runtime failed to process the request';
- status = 503;
+ await parseOpenClawError(response);
+ }
+
+ if (response.status === 204) return null;
+ const text = await response.text();
+ return parseUpstreamBody(text);
+}
+
+function normalizeAttachment(attachment = {}) {
+ const mediaType = attachment.mediaType || attachment.mimeType || 'application/octet-stream';
+ const sourceType = attachment.sourceType || (attachment.url ? 'url' : 'base64');
+ const filename = attachment.filename || attachment.name || 'attachment';
+ const kind = attachment.kind || (String(mediaType).startsWith('image/') ? 'image' : 'file');
+
+ if (sourceType === 'url' && attachment.url) {
+ return kind === 'image'
+ ? {
+ type: 'input_image',
+ source: {
+ type: 'url',
+ url: attachment.url
+ }
+ }
+ : {
+ type: 'input_file',
+ source: {
+ type: 'url',
+ url: attachment.url,
+ filename
+ }
+ };
+ }
+
+ if (!attachment.data) return null;
+
+ return kind === 'image'
+ ? {
+ type: 'input_image',
+ source: {
+ type: 'base64',
+ media_type: mediaType,
+ data: attachment.data
+ }
+ }
+ : {
+ type: 'input_file',
+ source: {
+ type: 'base64',
+ media_type: mediaType,
+ data: attachment.data,
+ filename
+ }
+ };
+}
+
+function buildContextText(context = {}) {
+ const lines = [];
+ if (context.appName) lines.push(`App context: ${context.appName}`);
+ if (context.repoPath) lines.push(`Repository context: ${context.repoPath}`);
+ if (context.directoryPath) lines.push(`Directory context: ${context.directoryPath}`);
+ if (context.extraInstructions) lines.push(`Extra context: ${context.extraInstructions}`);
+ if (lines.length === 0) return '';
+ return `PortOS operator context:\n${lines.join('\n')}`;
+}
+
+function buildInput(message, context = {}, attachments = []) {
+ const input = [];
+ const contextText = buildContextText(context);
+ const text = [contextText, message].filter(Boolean).join('\n\n');
+ if (text) {
+ input.push({
+ type: 'message',
+ role: 'user',
+ content: [{
+ type: 'input_text',
+ text
+ }]
+ });
+ }
+
+ for (const attachment of attachments) {
+ const normalized = normalizeAttachment(attachment);
+ if (normalized) input.push(normalized);
+ }
+
+ return input.length === 1 ? text : input;
+}
+
+async function invokeTool(config, tool, args = {}, sessionKey = 'main') {
+ const payload = await openClawRequest(config, config.paths.toolsInvoke, {
+ method: 'POST',
+ body: {
+ tool,
+ args,
+ sessionKey
}
+ });
- throw new ServerError(message, { status, code });
+ if (!payload?.ok) {
+ throw new ServerError(pickFirst(payload?.error?.message, payload?.message, `OpenClaw tool failed: ${tool}`), {
+ status: 502,
+ code: 'OPENCLAW_TOOL_FAILED'
+ });
}
- return payload;
+ return pickFirst(payload?.result?.details, payload?.result, payload?.details, payload);
}
export async function getRuntimeStatus() {
@@ -244,26 +330,20 @@ export async function getRuntimeStatus() {
}
try {
- const payload = await openClawRequest(config, config.paths.status);
- return normalizeStatusPayload(payload, config, true, null);
+ const sessions = await invokeTool(config, 'sessions_list', {});
+ return normalizeStatusPayload({
+ defaultSession: config.defaultSession,
+ sessionsCount: Array.isArray(sessions?.sessions) ? sessions.sessions.length : null
+ }, config, true, null);
} catch (err) {
- if (err.code === 'OPENCLAW_NOT_FOUND') {
- try {
- await openClawRequest(config, config.paths.sessions);
- return normalizeStatusPayload(null, config, true, null);
- } catch (fallbackErr) {
- return normalizeStatusPayload(null, config, false, fallbackErr.message);
- }
- }
-
return normalizeStatusPayload(null, config, false, err.message);
}
}
export async function listSessions() {
const config = await loadConfig();
- const payload = await openClawRequest(config, config.paths.sessions);
- const sessions = toArray(payload)
+ const payload = await invokeTool(config, 'sessions_list', {});
+ const sessions = (payload?.sessions || [])
.map(normalizeSession)
.filter(Boolean);
@@ -278,9 +358,12 @@ export async function listSessions() {
export async function getSessionMessages(sessionId, { limit = 50 } = {}) {
const config = await loadConfig();
- const path = buildPath(config.paths.sessionMessages, { sessionId });
- const payload = await openClawRequest(config, path, { query: { limit } });
- const messages = toArray(payload)
+ const payload = await invokeTool(config, 'sessions_history', {
+ sessionKey: sessionId,
+ limit,
+ includeTools: false
+ });
+ const messages = (payload?.messages || [])
.map((message, index) => normalizeMessage(message, index))
.filter(message => message.content || message.role || message.createdAt);
@@ -292,22 +375,28 @@ export async function getSessionMessages(sessionId, { limit = 50 } = {}) {
};
}
-export async function sendSessionMessage(sessionId, { message, context } = {}) {
+export async function sendSessionMessage(sessionId, { message, context, attachments } = {}) {
const config = await loadConfig();
- const path = buildPath(config.paths.sendMessage, { sessionId });
- const payload = await openClawRequest(config, path, {
+ const payload = await openClawRequest(config, config.paths.responses, {
method: 'POST',
+ headers: {
+ 'x-openclaw-session-key': sessionId
+ },
body: {
- sessionId,
- message,
- text: message,
- content: message,
- role: 'user',
- ...(context !== undefined ? { context } : {})
+ model: `openclaw:${config.defaultAgentId}`,
+ user: sessionId,
+ input: buildInput(message, context, attachments)
}
});
- const normalizedReply = payload ? normalizeMessage(payload) : null;
+ const normalizedReply = {
+ id: payload?.id || `response-${Date.now()}`,
+ role: 'assistant',
+ content: extractMessageContent(payload),
+ createdAt: new Date().toISOString(),
+ status: payload?.status || 'completed',
+ raw: payload
+ };
return {
ok: true,
@@ -317,3 +406,33 @@ export async function sendSessionMessage(sessionId, { message, context } = {}) {
message: normalizedReply
};
}
+
+export async function streamSessionMessage(sessionId, { message, context, attachments } = {}, handlers = {}) {
+ const config = await loadConfig();
+ const response = await openClawFetch(config, config.paths.responses, {
+ method: 'POST',
+ accept: 'text/event-stream',
+ headers: {
+ 'x-openclaw-session-key': sessionId
+ },
+ timeoutMs: 0,
+ body: {
+ model: `openclaw:${config.defaultAgentId}`,
+ user: sessionId,
+ stream: true,
+ input: buildInput(message, context, attachments)
+ }
+ });
+
+ if (!response.ok) {
+ await parseOpenClawError(response);
+ }
+
+ return {
+ config,
+ response,
+ stream: response.body,
+ contentType: response.headers.get('content-type') || '',
+ handlers
+ };
+}
diff --git a/server/lib/fetchWithTimeout.js b/server/lib/fetchWithTimeout.js
index 85f4c2877f..be9708787f 100644
--- a/server/lib/fetchWithTimeout.js
+++ b/server/lib/fetchWithTimeout.js
@@ -8,7 +8,8 @@
*/
export async function fetchWithTimeout(url, options = {}, timeoutMs = 15000) {
const controller = new AbortController();
- const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
+ const hasTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0;
+ const timeoutId = hasTimeout ? setTimeout(() => controller.abort(), timeoutMs) : null;
let signal = controller.signal;
let abortHandler;
@@ -29,7 +30,7 @@ export async function fetchWithTimeout(url, options = {}, timeoutMs = 15000) {
const response = await fetch(url, { ...options, signal });
return response;
} finally {
- clearTimeout(timeoutId);
+ if (timeoutId) clearTimeout(timeoutId);
if (options.signal && abortHandler) {
options.signal.removeEventListener('abort', abortHandler);
}
diff --git a/server/routes/openclaw.js b/server/routes/openclaw.js
index ff03ce20c8..3318e757ce 100644
--- a/server/routes/openclaw.js
+++ b/server/routes/openclaw.js
@@ -6,14 +6,34 @@ import {
getRuntimeStatus,
listSessions,
getSessionMessages,
- sendSessionMessage
+ sendSessionMessage,
+ streamSessionMessage
} from '../integrations/openclaw/api.js';
const router = express.Router();
+const attachmentSchema = z.object({
+ kind: z.enum(['image', 'file']).optional(),
+ sourceType: z.enum(['base64', 'url']).optional(),
+ name: z.string().trim().min(1).optional(),
+ filename: z.string().trim().min(1).optional(),
+ mediaType: z.string().trim().min(1).optional(),
+ mimeType: z.string().trim().min(1).optional(),
+ data: z.string().trim().min(1).optional(),
+ url: z.string().trim().url().optional()
+});
+
+const contextSchema = z.object({
+ appName: z.string().trim().min(1).optional(),
+ repoPath: z.string().trim().min(1).optional(),
+ directoryPath: z.string().trim().min(1).optional(),
+ extraInstructions: z.string().trim().min(1).optional()
+}).optional();
+
const sendMessageSchema = z.object({
message: z.string().trim().min(1),
- context: z.unknown().optional()
+ context: contextSchema,
+ attachments: z.array(attachmentSchema).max(8).optional()
});
router.get('/status', asyncHandler(async (req, res) => {
@@ -80,4 +100,56 @@ router.post('/sessions/:id/messages', asyncHandler(async (req, res) => {
res.json(result);
}));
+router.post('/sessions/:id/messages/stream', asyncHandler(async (req, res) => {
+ const sessionId = req.params.id?.trim();
+ if (!sessionId) {
+ throw new ServerError('Session ID is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+
+ const payload = validateRequest(sendMessageSchema, req.body);
+ const status = await getRuntimeStatus();
+ if (!status.configured) {
+ throw new ServerError('OpenClaw is not configured for this PortOS instance', {
+ status: 503,
+ code: 'OPENCLAW_UNCONFIGURED'
+ });
+ }
+
+ const { response } = await streamSessionMessage(sessionId, payload);
+
+ res.setHeader('Content-Type', 'text/event-stream');
+ res.setHeader('Cache-Control', 'no-cache');
+ res.setHeader('Connection', 'keep-alive');
+ res.setHeader('X-Accel-Buffering', 'no');
+ res.flushHeaders();
+
+ const upstream = response.body;
+ if (!upstream) {
+ res.write('event: error\ndata: {"error":"No upstream stream body"}\n\n');
+ return res.end();
+ }
+
+ const reader = upstream.getReader();
+ const decoder = new TextDecoder();
+
+ req.on('close', async () => {
+ try { await reader.cancel(); } catch { /* no-op */ }
+ });
+
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (value) res.write(decoder.decode(value, { stream: true }));
+ }
+ const tail = decoder.decode();
+ if (tail) res.write(tail);
+ } catch (err) {
+ if (err?.name !== 'AbortError') {
+ console.error(`❌ OpenClaw stream error: ${err.message}`);
+ }
+ }
+ res.end();
+}));
+
export default router;