Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 882f3def99 | |||
| 092f085254 | |||
| 21eac63723 | |||
| 06316da36f | |||
| 7927ad05ae | |||
| 5b2c552a88 | |||
| f51ad1547d | |||
| 2a2700907c | |||
| 93ecbf6c43 |
@@ -79,8 +79,8 @@ android {
|
||||
applicationId "com.ariacockpit"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 10905
|
||||
versionName "0.1.9.5"
|
||||
versionCode 10908
|
||||
versionName "0.1.9.8"
|
||||
// Fallback fuer Libraries mit Product Flavors
|
||||
missingDimensionStrategy 'react-native-camera', 'general'
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "aria-cockpit",
|
||||
"version": "0.1.9.5",
|
||||
"version": "0.1.9.8",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"android": "react-native run-android",
|
||||
|
||||
@@ -33,9 +33,12 @@ interface Props {
|
||||
/** Optional — wenn als Modal genutzt, sonst inline */
|
||||
visible?: boolean;
|
||||
onClose?: () => void;
|
||||
/** Wird gerufen wenn sich das aktive Projekt aendert — ChatScreen
|
||||
* refresht dann seinen Banner-State. */
|
||||
/** Wird gerufen wenn Stefan ein anderes Projekt fokussiert (App-lokale
|
||||
* UI-Entscheidung, wechselt den Chat-Focus). */
|
||||
onActiveChanged?: (project: Project | null) => void;
|
||||
/** Queue-Status pro Kontext (key "__main__" = Hauptchat, sonst project_id).
|
||||
* Wenn geliefert: Status-Dot pro Zeile gerendert. */
|
||||
queueStatus?: Record<string, { busy: boolean; queue_size: number }>;
|
||||
}
|
||||
|
||||
function _fmtRel(unixSec: number): string {
|
||||
@@ -48,7 +51,14 @@ function _fmtRel(unixSec: number): string {
|
||||
return new Date(unixSec * 1000).toLocaleDateString('de-DE');
|
||||
}
|
||||
|
||||
export const ProjectsBrowser: React.FC<Props> = ({ visible = true, onClose, onActiveChanged }) => {
|
||||
export const ProjectsBrowser: React.FC<Props> = ({ visible = true, onClose, onActiveChanged, queueStatus }) => {
|
||||
const _statusDot = (pid: string) => {
|
||||
const s = queueStatus?.[pid];
|
||||
if (!s) return { color: '#555570', label: '' };
|
||||
if (s.busy) return { color: '#FF6E6E', label: 'arbeitet' };
|
||||
if (s.queue_size > 0) return { color: '#FFD60A', label: `Queue: ${s.queue_size}` };
|
||||
return { color: '#34C759', label: 'idle' };
|
||||
};
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const [activeId, setActiveId] = useState<string>('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -88,13 +98,14 @@ export const ProjectsBrowser: React.FC<Props> = ({ visible = true, onClose, onAc
|
||||
}, [visible, load]);
|
||||
|
||||
const switchTo = useCallback((id: string) => {
|
||||
brainApi.switchProject(id)
|
||||
.then(status => {
|
||||
setActiveId(status.active_id || '');
|
||||
onActiveChangedRef.current?.(status.active);
|
||||
})
|
||||
.catch(e => Alert.alert('Fehler', String(e?.message || e)));
|
||||
}, []);
|
||||
// Multi-Threading: Focus-Wechsel ist reine App-lokale UI-Entscheidung.
|
||||
// Brain wird nicht mehr benachrichtigt (kein globaler active_project mehr).
|
||||
// Wir suchen das Projekt lokal aus der Liste, damit die App den Namen kennt.
|
||||
setActiveId(id);
|
||||
const p = id ? (projects.find(x => x.id === id) || null) : null;
|
||||
onActiveChangedRef.current?.(p);
|
||||
if (onClose) onClose();
|
||||
}, [projects, onClose]);
|
||||
|
||||
const createProject = useCallback(() => {
|
||||
const name = newName.trim();
|
||||
@@ -152,6 +163,7 @@ export const ProjectsBrowser: React.FC<Props> = ({ visible = true, onClose, onAc
|
||||
|
||||
const renderItem = ({ item }: { item: Project }) => {
|
||||
const isActive = item.id === activeId;
|
||||
const dot = _statusDot(item.id);
|
||||
return (
|
||||
<TouchableOpacity
|
||||
onPress={() => switchTo(item.id)}
|
||||
@@ -160,15 +172,19 @@ export const ProjectsBrowser: React.FC<Props> = ({ visible = true, onClose, onAc
|
||||
>
|
||||
<View style={{ flex: 1 }}>
|
||||
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
|
||||
{queueStatus && (
|
||||
<View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: dot.color }} />
|
||||
)}
|
||||
<Text style={[s.rowName, isActive && { color: '#34C759' }]}>{item.name}</Text>
|
||||
{item.status === 'ended' && <Text style={s.statusBadge}>beendet</Text>}
|
||||
{isActive && <Text style={s.activeBadge}>✓ AKTIV</Text>}
|
||||
{isActive && <Text style={s.activeBadge}>✓ FOCUS</Text>}
|
||||
</View>
|
||||
{item.description ? (
|
||||
<Text style={s.rowDesc} numberOfLines={2}>{item.description}</Text>
|
||||
) : null}
|
||||
<Text style={s.rowMeta}>
|
||||
{item.turn_count} Turns · zuletzt {_fmtRel(item.last_activity_at)}
|
||||
{dot.label ? ` · ${dot.label}` : ''}
|
||||
</Text>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
@@ -191,18 +207,29 @@ export const ProjectsBrowser: React.FC<Props> = ({ visible = true, onClose, onAc
|
||||
</View>
|
||||
|
||||
{/* Hauptchat-Eintrag (immer oben) */}
|
||||
<TouchableOpacity
|
||||
onPress={() => switchTo('')}
|
||||
style={[s.row, !activeId && s.rowActive]}
|
||||
>
|
||||
<View style={{ flex: 1 }}>
|
||||
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
|
||||
<Text style={[s.rowName, !activeId && { color: '#34C759' }]}>💬 Hauptchat</Text>
|
||||
{!activeId && <Text style={s.activeBadge}>✓ AKTIV</Text>}
|
||||
</View>
|
||||
<Text style={s.rowMeta}>Standard-Verlauf, keine Projekt-Zuordnung</Text>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
{(() => {
|
||||
const dot = _statusDot('__main__');
|
||||
return (
|
||||
<TouchableOpacity
|
||||
onPress={() => switchTo('')}
|
||||
style={[s.row, !activeId && s.rowActive]}
|
||||
>
|
||||
<View style={{ flex: 1 }}>
|
||||
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
|
||||
{queueStatus && (
|
||||
<View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: dot.color }} />
|
||||
)}
|
||||
<Text style={[s.rowName, !activeId && { color: '#34C759' }]}>💬 Hauptchat</Text>
|
||||
{!activeId && <Text style={s.activeBadge}>✓ FOCUS</Text>}
|
||||
</View>
|
||||
<Text style={s.rowMeta}>
|
||||
Standard-Verlauf, keine Projekt-Zuordnung
|
||||
{dot.label ? ` · ${dot.label}` : ''}
|
||||
</Text>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
);
|
||||
})()}
|
||||
|
||||
{loading ? (
|
||||
<View style={{ padding: 24, alignItems: 'center' }}>
|
||||
|
||||
+120
-165
@@ -286,9 +286,15 @@ const ChatScreen: React.FC = () => {
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [searchVisible, setSearchVisible] = useState(false);
|
||||
const [projectsVisible, setProjectsVisible] = useState(false);
|
||||
const [activeProject, setActiveProject] = useState<BrainProject | null>(null);
|
||||
// Lookup-Map id → Projekt — fuer Header-Names im Chat-Verlauf
|
||||
// Focus-One-View: welchen Chat sieht Stefan gerade?
|
||||
// Leer = Hauptchat, sonst die project_id. Multi-Threading:
|
||||
// Wechsel des Focus stoppt NICHT ARIAs Arbeit in anderen Projekten —
|
||||
// die laufen im Brain weiter, wir sehen sie hier nur nicht.
|
||||
const [focusedProjectId, setFocusedProjectId] = useState<string>('');
|
||||
// Lookup-Map id → Projekt (fuer Drawer + Referenzen)
|
||||
const [projectNameById, setProjectNameById] = useState<Record<string, string>>({});
|
||||
// Queue-Status pro Kontext — polled alle 2s, fuer Status-Dots im Drawer
|
||||
const [queueStatus, setQueueStatus] = useState<Record<string, { busy: boolean; queue_size: number }>>({});
|
||||
const [searchIndex, setSearchIndex] = useState(0); // welcher Treffer aktiv ist
|
||||
const [pendingAttachments, setPendingAttachments] = useState<{file: any, isPhoto: boolean}[]>([]);
|
||||
const [agentActivity, setAgentActivity] = useState<{activity: string, tool: string}>({activity: 'idle', tool: ''});
|
||||
@@ -465,27 +471,53 @@ const ChatScreen: React.FC = () => {
|
||||
}, [dispatchWithAck]);
|
||||
|
||||
// TTS- + GPS-Settings beim Mount + alle 2s neu laden (damit Settings-Toggle
|
||||
// sofort greift, ohne Context- oder Event-System)
|
||||
// Aktives Projekt initial laden + bei RVS-Reconnect refreshen.
|
||||
// Wird zusaetzlich nach jedem chat-Response refreshed (siehe handleAriaMessage).
|
||||
// Projekt-Namen laden (Lookup-Map) + focusedProjectId aus AsyncStorage
|
||||
// wiederherstellen (Default = Hauptchat wenn nichts gespeichert). Der
|
||||
// Brain hat mit Multi-Threading keinen global-aktiven Projekt-State mehr;
|
||||
// Focus ist reine App-lokale UI-Info.
|
||||
useEffect(() => {
|
||||
const loadProject = () => {
|
||||
brainApi.getProjectStatus()
|
||||
.then(s => {
|
||||
setActiveProject(s.active || null);
|
||||
// Lookup-Map fuellen damit der Chat-Verlauf Header mit Namen rendern kann
|
||||
const loadNames = () => {
|
||||
brainApi.listProjects(true)
|
||||
.then(list => {
|
||||
const map: Record<string, string> = {};
|
||||
for (const p of (s.projects || [])) map[p.id] = p.name;
|
||||
if (s.active) map[s.active.id] = s.active.name;
|
||||
for (const p of list) map[p.id] = p.name;
|
||||
setProjectNameById(prev => ({ ...prev, ...map }));
|
||||
})
|
||||
.catch(() => {});
|
||||
};
|
||||
loadProject();
|
||||
const unsub = rvs.onStateChange(state => { if (state === 'connected') loadProject(); });
|
||||
loadNames();
|
||||
// Letzten Focus aus Storage restoren
|
||||
AsyncStorage.getItem('aria_focused_project_id').then(v => {
|
||||
if (v && typeof v === 'string') setFocusedProjectId(v);
|
||||
}).catch(() => {});
|
||||
const unsub = rvs.onStateChange(state => { if (state === 'connected') loadNames(); });
|
||||
return () => unsub();
|
||||
}, []);
|
||||
|
||||
// Focus in Storage spiegeln damit der letzte Kontext nach Neustart wieder
|
||||
// da ist. Kein zwingender UX-Fix (Default = Hauptchat waere auch ok), aber
|
||||
// fuer den Auto-Fall angenehm.
|
||||
useEffect(() => {
|
||||
AsyncStorage.setItem('aria_focused_project_id', focusedProjectId).catch(() => {});
|
||||
}, [focusedProjectId]);
|
||||
|
||||
// Queue-Status alle 2s pollen — fuers Status-Dot im Focus-Header und
|
||||
// fuer die Drawer-Anzeige. Nur wenn RVS verbunden ist (sonst 30s Timeout).
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const poll = async () => {
|
||||
if (rvs.getState() !== 'connected') return;
|
||||
try {
|
||||
const s = await brainApi.getProjectQueueStatus();
|
||||
if (cancelled) return;
|
||||
setQueueStatus(s.contexts || {});
|
||||
} catch {}
|
||||
};
|
||||
poll();
|
||||
const iv = setInterval(poll, 2000);
|
||||
return () => { cancelled = true; clearInterval(iv); };
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const loadSettings = async () => {
|
||||
const enabled = await AsyncStorage.getItem('aria_tts_enabled');
|
||||
@@ -769,6 +801,7 @@ const ChatScreen: React.FC = () => {
|
||||
timestamp: m.ts || Date.now(),
|
||||
attachments: attachments.length ? attachments : undefined,
|
||||
backupTs: typeof m.ts === 'number' ? m.ts : undefined,
|
||||
projectId: typeof m.project_id === 'string' ? m.project_id : '',
|
||||
...(cmid && { clientMsgId: cmid }),
|
||||
// Server-Bubble = vom Brain verarbeitet → 'delivered' (✓✓)
|
||||
...(role === 'user' && cmid && { deliveryStatus: 'delivered' as const }),
|
||||
@@ -824,12 +857,20 @@ const ChatScreen: React.FC = () => {
|
||||
return;
|
||||
}
|
||||
|
||||
// project_changed: ARIA hat in einem Tool-Call ein Projekt erstellt /
|
||||
// betreten / verlassen / beendet. Banner refreshen.
|
||||
// project_changed: ARIA hat via Tool ein Projekt erstellt/betreten/exited/beendet.
|
||||
// App entscheidet ob sie den Focus wechselt basierend auf action + payload.
|
||||
if (message.type === 'project_changed') {
|
||||
brainApi.getProjectStatus()
|
||||
.then(s => setActiveProject(s.active || null))
|
||||
.catch(() => {});
|
||||
const p: any = message.payload || {};
|
||||
const action = p.action || '';
|
||||
// Neuer Projekt-Name in Lookup-Map merken
|
||||
if (p.id && p.name) {
|
||||
setProjectNameById(prev => ({ ...prev, [p.id]: p.name }));
|
||||
}
|
||||
if (action === 'entered' || action === 'created') {
|
||||
if (p.id) setFocusedProjectId(p.id);
|
||||
} else if (action === 'exited') {
|
||||
setFocusedProjectId('');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1628,84 +1669,14 @@ const ChatScreen: React.FC = () => {
|
||||
[messages],
|
||||
);
|
||||
|
||||
// Projekt-Bloecke: aufeinanderfolgende Nachrichten mit gleicher projectId
|
||||
// werden visuell gruppiert. Erstes Message-Item einer Gruppe bekommt einen
|
||||
// Header darueber (tappable für collapse). Collapsed → restliche Messages
|
||||
// der Gruppe werden ausgefiltert; nur Header bleibt sichtbar.
|
||||
// Hauptchat-Nachrichten (projectId leer) bleiben ungruppiert dazwischen.
|
||||
const [collapsedProjects, setCollapsedProjects] = useState<Set<string>>(new Set());
|
||||
|
||||
const projectMeta = useMemo(() => {
|
||||
// Pre-compute: welche Message ist Erst-Element ihrer Projekt-Gruppe?
|
||||
// Plus: wieviele Messages pro Projekt insgesamt (fuer Header-Count).
|
||||
const firstOfGroup = new Set<string>();
|
||||
const counts = new Map<string, number>();
|
||||
let lastPid: string | null = null;
|
||||
for (const m of chatVisibleMessages) {
|
||||
const pid = m.projectId || '';
|
||||
if (pid) counts.set(pid, (counts.get(pid) || 0) + 1);
|
||||
if (pid && pid !== lastPid) firstOfGroup.add(m.id);
|
||||
lastPid = pid || null;
|
||||
}
|
||||
return { firstOfGroup, counts };
|
||||
}, [chatVisibleMessages]);
|
||||
|
||||
// Render-Filter: bei collapsed Projekten zeigen wir NUR das erste Message-
|
||||
// Item der Gruppe (das traegt den Header). Restliche Messages werden ausge-
|
||||
// blendet — Header allein steht dann zwischen Hauptchat-Bubbles.
|
||||
// Focus-One-View (Multi-Threading, 06/2026): Chat zeigt NUR die Nachrichten
|
||||
// des gerade fokussierten Kontexts. Hauptchat (focusedProjectId leer) →
|
||||
// alle ungeтагtgeд Nachrichten. Projekt X aktiv → nur Nachrichten mit
|
||||
// projectId === X. ARIA arbeitet weiterhin in allen Kontexten parallel;
|
||||
// wir sehen nur den einen.
|
||||
const messagesForRender = useMemo(() => {
|
||||
return chatVisibleMessages.filter(m => {
|
||||
const pid = m.projectId || '';
|
||||
if (!pid) return true;
|
||||
if (!collapsedProjects.has(pid)) return true;
|
||||
return projectMeta.firstOfGroup.has(m.id);
|
||||
});
|
||||
}, [chatVisibleMessages, collapsedProjects, projectMeta]);
|
||||
|
||||
// Auto-Collapse beim Projekt-Wechsel: altes Projekt einklappen, neues aufklappen.
|
||||
const prevActiveIdRef = useRef<string>('');
|
||||
useEffect(() => {
|
||||
const newActive = activeProject?.id || '';
|
||||
const prevActive = prevActiveIdRef.current;
|
||||
if (newActive === prevActive) return;
|
||||
setCollapsedProjects(prev => {
|
||||
const next = new Set(prev);
|
||||
if (prevActive) next.add(prevActive);
|
||||
if (newActive) next.delete(newActive);
|
||||
return next;
|
||||
});
|
||||
prevActiveIdRef.current = newActive;
|
||||
}, [activeProject]);
|
||||
|
||||
// Default: alle Projekte einklappen außer dem aktiven (Stefan-Vision:
|
||||
// „beim ersten Öffnen sind alle projekte eingeklappt").
|
||||
const collapseInitialized = useRef(false);
|
||||
useEffect(() => {
|
||||
if (collapseInitialized.current) return;
|
||||
if (chatVisibleMessages.length === 0) return;
|
||||
const allPids = new Set<string>();
|
||||
for (const m of chatVisibleMessages) {
|
||||
if (m.projectId) allPids.add(m.projectId);
|
||||
}
|
||||
if (allPids.size === 0) return;
|
||||
const activePid = activeProject?.id || '';
|
||||
setCollapsedProjects(prev => {
|
||||
const next = new Set(prev);
|
||||
for (const pid of allPids) {
|
||||
if (pid !== activePid) next.add(pid);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
collapseInitialized.current = true;
|
||||
}, [chatVisibleMessages, activeProject]);
|
||||
|
||||
const toggleProjectCollapse = useCallback((projectId: string) => {
|
||||
setCollapsedProjects(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(projectId)) next.delete(projectId); else next.add(projectId);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
return chatVisibleMessages.filter(m => (m.projectId || '') === focusedProjectId);
|
||||
}, [chatVisibleMessages, focusedProjectId]);
|
||||
|
||||
const invertedMessages = useMemo(() => [...messagesForRender].reverse(), [messagesForRender]);
|
||||
|
||||
@@ -1909,7 +1880,7 @@ const ChatScreen: React.FC = () => {
|
||||
const location = await getCurrentLocation();
|
||||
|
||||
const cmid = nextClientMsgId();
|
||||
const activePid = activeProject?.id || '';
|
||||
const activePid = focusedProjectId;
|
||||
const userMsg: ChatMessage = {
|
||||
id: nextId(),
|
||||
sender: 'user',
|
||||
@@ -2428,44 +2399,6 @@ const ChatScreen: React.FC = () => {
|
||||
);
|
||||
};
|
||||
|
||||
// Wrapper: setzt einen einklappbaren Projekt-Header VOR die Bubble wenn
|
||||
// diese das erste Element ihrer Projekt-Gruppe ist. Bei collapsed
|
||||
// → nur Header, keine Bubble. Hauptchat-Nachrichten gehen ohne Header durch.
|
||||
const renderMessageWithProjectHeader = ({ item }: { item: ChatMessage }) => {
|
||||
const pid = item.projectId || '';
|
||||
if (!pid) return renderMessage({ item });
|
||||
const isFirstOfGroup = projectMeta.firstOfGroup.has(item.id);
|
||||
if (!isFirstOfGroup) return renderMessage({ item });
|
||||
const isCollapsed = collapsedProjects.has(pid);
|
||||
const projectName = projectNameById[pid] || pid;
|
||||
const projectCount = projectMeta.counts.get(pid) || 0;
|
||||
const header = (
|
||||
<TouchableOpacity
|
||||
onPress={() => toggleProjectCollapse(pid)}
|
||||
style={{
|
||||
marginVertical: 6, marginHorizontal: 8, paddingHorizontal: 10, paddingVertical: 8,
|
||||
borderRadius: 6, backgroundColor: 'rgba(52,199,89,0.10)',
|
||||
borderLeftWidth: 3, borderLeftColor: '#34C759',
|
||||
flexDirection: 'row', alignItems: 'center', gap: 6,
|
||||
}}
|
||||
>
|
||||
<Text style={{ fontSize: 14, color: '#34C759', fontWeight: '700', flex: 1 }} numberOfLines={1}>
|
||||
{isCollapsed ? '▶' : '▼'} 📁 {projectName}
|
||||
</Text>
|
||||
<Text style={{ fontSize: 11, color: '#8888AA' }}>
|
||||
{projectCount} {projectCount === 1 ? 'Nachricht' : 'Nachrichten'}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
);
|
||||
if (isCollapsed) return header;
|
||||
return (
|
||||
<View>
|
||||
{header}
|
||||
{renderMessage({ item })}
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
// Extrahiert kopierbare Items aus dem Bubble-Text (URLs, Mails, Telefon).
|
||||
// Wird vom Long-Press/Copy-Menu genutzt damit Stefan den einzelnen Wert
|
||||
// teilen kann ohne den umliegenden Text mitzunehmen.
|
||||
@@ -2618,41 +2551,63 @@ const ChatScreen: React.FC = () => {
|
||||
})()}
|
||||
|
||||
{/* Projekt-Indicator: zeigt Hauptchat oder aktives Projekt */}
|
||||
<View
|
||||
style={{
|
||||
flexDirection: 'row', alignItems: 'center',
|
||||
paddingHorizontal: 12, paddingVertical: 6,
|
||||
backgroundColor: activeProject ? 'rgba(52,199,89,0.10)' : 'transparent',
|
||||
borderBottomWidth: activeProject ? 2 : 1,
|
||||
borderColor: activeProject ? '#34C759' : '#1E1E2E',
|
||||
}}
|
||||
>
|
||||
<TouchableOpacity onPress={() => setProjectsVisible(true)} style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
|
||||
<Text style={{ fontSize: 13, color: activeProject ? '#34C759' : '#8888AA', fontWeight: activeProject ? '700' : '500', flex: 1 }} numberOfLines={1}>
|
||||
{activeProject ? `📁 ${activeProject.name}` : '💬 Hauptchat'}
|
||||
</Text>
|
||||
<Text style={{ fontSize: 11, color: '#555570', marginRight: 8 }}>
|
||||
{activeProject ? 'wechseln ›' : 'Projekte ›'}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
{activeProject && (
|
||||
<TouchableOpacity
|
||||
onPress={() => {
|
||||
brainApi.switchProject('').then(s => setActiveProject(s.active || null)).catch(() => {});
|
||||
{/* Focus-Indicator + Drawer-Toggle. Multi-Threading: das ist reine
|
||||
Anzeige „was sehe ich gerade" — ARIA arbeitet gleichzeitig in
|
||||
allen Kontexten weiter, wir zeigen hier nur einen. */}
|
||||
{(() => {
|
||||
const isMain = !focusedProjectId;
|
||||
const focusedName = isMain ? '' : (projectNameById[focusedProjectId] || focusedProjectId);
|
||||
const focusedQueue = queueStatus[isMain ? '__main__' : focusedProjectId];
|
||||
const dot = focusedQueue?.busy
|
||||
? { color: '#FF6E6E', label: 'arbeitet' }
|
||||
: focusedQueue?.queue_size
|
||||
? { color: '#FFD60A', label: `Queue: ${focusedQueue.queue_size}` }
|
||||
: { color: '#34C759', label: 'idle' };
|
||||
// Anzahl anderer Kontexte die gerade aktiv sind (fuer Drawer-Badge)
|
||||
const otherActive = Object.entries(queueStatus).filter(([k, v]) => {
|
||||
const kFocus = isMain ? '__main__' : focusedProjectId;
|
||||
if (k === kFocus) return false;
|
||||
return v.busy || v.queue_size > 0;
|
||||
}).length;
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
flexDirection: 'row', alignItems: 'center',
|
||||
paddingHorizontal: 12, paddingVertical: 8,
|
||||
backgroundColor: isMain ? '#1A1A26' : 'rgba(52,199,89,0.10)',
|
||||
borderBottomWidth: 2,
|
||||
borderColor: isMain ? '#1E1E2E' : '#34C759',
|
||||
}}
|
||||
style={{ paddingHorizontal: 8, paddingVertical: 2, borderRadius: 4, backgroundColor: 'rgba(255,255,255,0.08)' }}
|
||||
hitSlop={{top:8,bottom:8,left:8,right:8}}
|
||||
>
|
||||
<Text style={{ fontSize: 11, color: '#E0E0F0', fontWeight: '600' }}>× Hauptchat</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
<TouchableOpacity
|
||||
onPress={() => setProjectsVisible(true)}
|
||||
style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}
|
||||
hitSlop={{top:6,bottom:6,left:6,right:6}}
|
||||
>
|
||||
<Text style={{ fontSize: 20 }}>☰</Text>
|
||||
{otherActive > 0 && (
|
||||
<View style={{ backgroundColor: '#FF6E6E', borderRadius: 8, minWidth: 16, height: 16, paddingHorizontal: 4, alignItems: 'center', justifyContent: 'center' }}>
|
||||
<Text style={{ color: '#fff', fontSize: 10, fontWeight: '700' }}>{otherActive}</Text>
|
||||
</View>
|
||||
)}
|
||||
</TouchableOpacity>
|
||||
<View style={{ flex: 1, marginLeft: 10, flexDirection: 'row', alignItems: 'center', gap: 8 }}>
|
||||
<Text style={{ fontSize: 14, color: isMain ? '#E0E0F0' : '#34C759', fontWeight: '700', flex: 1 }} numberOfLines={1}>
|
||||
{isMain ? '💬 Hauptchat' : `📁 ${focusedName}`}
|
||||
</Text>
|
||||
<View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: dot.color }} />
|
||||
<Text style={{ fontSize: 10, color: '#8888AA' }}>{dot.label}</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* Projekt-Modal */}
|
||||
{/* Projekt-Drawer als Modal */}
|
||||
<ProjectsBrowser
|
||||
visible={projectsVisible}
|
||||
onClose={() => setProjectsVisible(false)}
|
||||
onActiveChanged={(p) => setActiveProject(p)}
|
||||
onActiveChanged={(p) => setFocusedProjectId(p?.id || '')}
|
||||
queueStatus={queueStatus}
|
||||
/>
|
||||
|
||||
{/* Suchleiste mit Treffer-Navigation */}
|
||||
@@ -2737,7 +2692,7 @@ const ChatScreen: React.FC = () => {
|
||||
}, 300);
|
||||
}}
|
||||
keyExtractor={item => item.id}
|
||||
renderItem={renderMessageWithProjectHeader}
|
||||
renderItem={renderMessage}
|
||||
contentContainerStyle={styles.messageList}
|
||||
showsVerticalScrollIndicator={false}
|
||||
ListEmptyComponent={
|
||||
|
||||
@@ -735,11 +735,11 @@ const SettingsScreen: React.FC = () => {
|
||||
brainApi.listProjects(true)
|
||||
.then(list => setFileFilterProjects(list.map(p => ({ id: p.id, name: p.name }))))
|
||||
.catch(() => {});
|
||||
// Default-Filter: aktives Projekt (falls vorhanden), sonst "alle".
|
||||
brainApi.getProjectStatus()
|
||||
.then(s => {
|
||||
if (s.active_id) setFileFilterProjectId(s.active_id);
|
||||
})
|
||||
// Default-Filter: fokussiertes Projekt aus AsyncStorage (falls Stefan
|
||||
// grade in einem drin ist), sonst "alle". Multi-Threading: Focus ist
|
||||
// App-lokal, kein Brain-Query mehr.
|
||||
AsyncStorage.getItem('aria_focused_project_id')
|
||||
.then(pid => { if (pid) setFileFilterProjectId(pid); })
|
||||
.catch(() => {});
|
||||
}, [fileManagerOpen]);
|
||||
|
||||
|
||||
@@ -169,6 +169,16 @@ export interface ProjectStatus {
|
||||
projects: Project[];
|
||||
}
|
||||
|
||||
/** Queue-Status pro Kontext — was gerade arbeitet, was wartet.
|
||||
* Key "__main__" = Hauptchat, sonst project_id. */
|
||||
export interface QueueContextStatus {
|
||||
busy: boolean;
|
||||
queue_size: number;
|
||||
}
|
||||
export interface ProjectQueueStatus {
|
||||
contexts: Record<string, QueueContextStatus>;
|
||||
}
|
||||
|
||||
/** Skill-Manifest wie aus Brain `/skills/list` zurueckkommt. */
|
||||
export interface Skill {
|
||||
name: string;
|
||||
@@ -590,6 +600,13 @@ export const brainApi = {
|
||||
body: patch,
|
||||
});
|
||||
},
|
||||
|
||||
/** Queue-Status: pro Kontext (project_id oder __main__ fuer Hauptchat)
|
||||
* ob gerade ein Request in Verarbeitung ist + wieviele in der Queue warten.
|
||||
* Wird fuer Status-Dots im Drawer periodisch gepollt. */
|
||||
getProjectQueueStatus(): Promise<ProjectQueueStatus> {
|
||||
return _send('/projects/queue-status');
|
||||
},
|
||||
};
|
||||
|
||||
export default brainApi;
|
||||
|
||||
+66
-29
@@ -836,10 +836,14 @@ META_TOOLS = [
|
||||
"function": {
|
||||
"name": "project_enter",
|
||||
"description": (
|
||||
"Wechselt in ein bestehendes Projekt. Fuzzy-Match auf Namen — "
|
||||
"'Spotify' findet das Projekt 'Spotify-Setup'. Nach dem Eintritt "
|
||||
"tagged jeder neue Turn die project_id. Bei sehr alten Projekten: "
|
||||
"vorher project_summary aufrufen damit Du Stefan abholst."
|
||||
"Signalisiert der App/Diagnostic 'wechsel zu diesem Projekt'. Fuzzy-"
|
||||
"Match auf Namen — 'Spotify' findet das Projekt 'Spotify-Setup'. "
|
||||
"Der AKTUELLE Turn bleibt aber in seinem Chat-Kontext — wir haben "
|
||||
"Multi-Threading, kein globales 'aktives Projekt' mehr. Wenn Stefan "
|
||||
"im Hauptchat sagt 'lass uns in Spotify weiter machen': "
|
||||
"project_enter aufrufen (App wechselt Ansicht), aber Deine Antwort "
|
||||
"geht trotzdem im Hauptchat raus. Bei sehr alten Projekten vorher "
|
||||
"project_summary aufrufen damit Du Stefan abholst."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
@@ -855,8 +859,10 @@ META_TOOLS = [
|
||||
"function": {
|
||||
"name": "project_exit",
|
||||
"description": (
|
||||
"Verlässt das aktuelle Projekt — zurück zum Hauptthread. Nutze "
|
||||
"wenn Stefan sagt 'Projekt Ende', 'zurück zum Hauptchat' o.ä."
|
||||
"Signalisiert der App/Diagnostic 'wechsel zurueck zum Hauptchat'. "
|
||||
"Nutze wenn Stefan sagt 'Projekt Ende' oder 'zurueck zum Hauptchat' "
|
||||
"waehrend er visuell in einem Projekt ist. Der aktuelle Turn bleibt "
|
||||
"in seinem Chat-Kontext — Multi-Threading."
|
||||
),
|
||||
"parameters": {"type": "object", "properties": {}},
|
||||
},
|
||||
@@ -1051,7 +1057,21 @@ class Agent:
|
||||
|
||||
MAX_TOOL_ITERATIONS = 8 # Schutz vor Endlos-Loops
|
||||
|
||||
def chat(self, user_message: str, source: str = "") -> str:
|
||||
def chat(self, user_message: str, source: str = "",
|
||||
project_id: Optional[str] = None,
|
||||
pending_queue: Optional[list[str]] = None) -> str:
|
||||
"""Verarbeitet eine User-Nachricht — pro Request project_id explizit
|
||||
angegeben (leer = Hauptchat). Kein globaler active_project-State mehr —
|
||||
so laufen parallele /chat-Requests fuer verschiedene Projekte echt
|
||||
parallel (Multi-Threading-Architektur seit 06/2026).
|
||||
|
||||
pending_queue: Liste weiterer User-Nachrichten die in DIESEM Projekt
|
||||
NACH dem aktuellen Turn warten. ARIA sieht sie im System-Prompt und
|
||||
soll pruefen ob eine spaetere Nachricht den aktuellen Task
|
||||
korrigiert / annuliert (dann Skip-Antwort statt Ausfuehren).
|
||||
|
||||
Wenn project_id=None (Backward-Compat fuer Aufrufer die den Param nicht
|
||||
setzen): wird als Hauptchat behandelt."""
|
||||
user_message = (user_message or "").strip()
|
||||
if not user_message:
|
||||
raise ValueError("Leere Nachricht")
|
||||
@@ -1059,9 +1079,8 @@ class Agent:
|
||||
# Events vom letzten Turn weglassen
|
||||
self._pending_events = []
|
||||
|
||||
# Aktives Projekt (leer = Hauptthread) — bestimmt das Tagging der
|
||||
# neuen Turns + das Conversation-Window-Filter fuer den LLM-Prompt.
|
||||
active_project_id = projects_mod.get_active()
|
||||
# Projekt-Kontext pro Request statt aus globalem State
|
||||
active_project_id = (project_id or "").strip()
|
||||
active_project = projects_mod.get_project(active_project_id) if active_project_id else None
|
||||
|
||||
# Fast-Path: einfache "reines Steuern"-Commands ueberspringen Claude komplett.
|
||||
@@ -1127,6 +1146,28 @@ class Agent:
|
||||
oauth_callback_host=oauth_host,
|
||||
oauth_callback_port=oauth_port,
|
||||
oauth_callback_tls=oauth_tls)
|
||||
# Queue-Aware Prompting: wenn nach diesem Turn weitere Nachrichten
|
||||
# in der Warteschlange liegen, muss ARIA pruefen ob eine spaetere die
|
||||
# aktuelle Aufgabe korrigiert/annuliert (→ Skip statt Doppelarbeit).
|
||||
if pending_queue:
|
||||
queue_lines = "\n".join(f" - {m[:280]}" for m in pending_queue[:5])
|
||||
more_hint = ""
|
||||
if len(pending_queue) > 5:
|
||||
more_hint = f"\n ... und {len(pending_queue) - 5} weitere"
|
||||
system_prompt += (
|
||||
f"\n\n## QUEUE — NACH DIESEM TASK WARTEN\n"
|
||||
f"{queue_lines}{more_hint}\n"
|
||||
f"\nBEVOR DU DEN AKTUELLEN TASK LOESST:\n"
|
||||
f" 1. Pruefe die Queue oben — widerspricht/annuliert eine der spaeteren "
|
||||
f"Nachrichten den aktuellen Task?\n"
|
||||
f" 2. Wenn ja: antworte ganz kurz 'Task ubersprungen — wird durch spaetere "
|
||||
f"Nachricht korrigiert' und mach KEINE Aktion. Der spaetere Task laeuft dann "
|
||||
f"ganz normal als naechste Anfrage durch.\n"
|
||||
f" 3. Wenn nein / unabhaengige Ergaenzung: Task normal loesen.\n"
|
||||
f"Beispiel: aktueller Task 'titelleiste rot', Queue enthaelt "
|
||||
f"'doch nicht, mach sie blau' → skip, blau kommt als naechste Anfrage."
|
||||
)
|
||||
|
||||
# Aktuelle Projekt-Bühne als System-Hinweis ergaenzen, damit Claude
|
||||
# weiss in welchem Kontext sie spricht und ihre project_* Tools korrekt
|
||||
# einsetzt (z.B. bei „Projekt Ende" project_exit aufruft).
|
||||
@@ -1217,19 +1258,17 @@ class Agent:
|
||||
err_text = f"[Fehler: {exc}]"
|
||||
logger.error("chat() Exception — schreibe Error-Marker als Assistant-Turn: %s", exc)
|
||||
try:
|
||||
# Aktive Projekt-ID NEU lesen — kann sich waehrend des Tool-Loops
|
||||
# geaendert haben (project_enter/exit als Tool-Call).
|
||||
# Turn-Kontext bleibt gleich — es gibt keinen globalen Wechsel
|
||||
# mehr, jeder Request laeuft in seinem eigenen project_id-Kontext.
|
||||
self.conversation.add("assistant", err_text,
|
||||
project_id=projects_mod.get_active())
|
||||
project_id=active_project_id)
|
||||
except Exception as add_exc:
|
||||
logger.warning("Konnte Error-Marker nicht persistieren: %s", add_exc)
|
||||
raise
|
||||
|
||||
# 7. Assistant-Turn (final reply) in die Conversation
|
||||
# NEU lesen — wenn der LLM project_enter/exit gerufen hat, ist der
|
||||
# Final-Reply schon im neuen Projekt-Kontext.
|
||||
self.conversation.add("assistant", final_reply,
|
||||
project_id=projects_mod.get_active())
|
||||
project_id=active_project_id)
|
||||
return final_reply
|
||||
|
||||
# ── Tool-Dispatcher ───────────────────────────────────────
|
||||
@@ -1804,7 +1843,10 @@ class Agent:
|
||||
"project": p,
|
||||
"action": "created",
|
||||
})
|
||||
return f"OK — Projekt '{p['name']}' angelegt (id={p['id']}) und aktiv. Alle weiteren Turns gehen jetzt da rein bis Du project_exit oder project_enter aufrufst."
|
||||
return (f"OK — Projekt '{p['name']}' angelegt (id={p['id']}). App/Diagnostic "
|
||||
f"kriegen ein project_changed-Event und koennen dahin wechseln. "
|
||||
f"Kommender Turn bleibt aber im aktuellen Chat-Kontext — "
|
||||
f"Multi-Threading, jeder Chat ist eigenstaendig.")
|
||||
if name == "project_enter":
|
||||
pname = (arguments.get("name") or "").strip()
|
||||
if not pname:
|
||||
@@ -1812,7 +1854,6 @@ class Agent:
|
||||
p = projects_mod.find_project(pname)
|
||||
if not p:
|
||||
return f"Kein Projekt '{pname}' gefunden. Nutze project_list zum Aufzaehlen oder project_create wenn's neu sein soll."
|
||||
projects_mod.set_active(p["id"])
|
||||
self._pending_events.append({
|
||||
"type": "project_changed",
|
||||
"project": p,
|
||||
@@ -1822,31 +1863,27 @@ class Agent:
|
||||
hint = ""
|
||||
if turn_count > 0:
|
||||
hint = " Wenn Stefan nach dem Stand fragt: project_summary aufrufen."
|
||||
return f"OK — in Projekt '{p['name']}' eingestiegen (id={p['id']}, {turn_count} bisherige Turns).{hint}"
|
||||
return (f"OK — App/Diagnostic wird zum Projekt '{p['name']}' "
|
||||
f"(id={p['id']}, {turn_count} bisherige Turns) umschalten. "
|
||||
f"Der aktuelle Turn bleibt aber im aktuellen Chat-Kontext.{hint}")
|
||||
if name == "project_exit":
|
||||
active_id = projects_mod.get_active()
|
||||
if not active_id:
|
||||
return "Es ist gerade kein Projekt aktiv — bereits im Hauptthread."
|
||||
p = projects_mod.get_project(active_id)
|
||||
projects_mod.set_active("")
|
||||
self._pending_events.append({
|
||||
"type": "project_changed",
|
||||
"project": p,
|
||||
"project": None,
|
||||
"action": "exited",
|
||||
})
|
||||
return f"OK — Projekt '{p['name'] if p else active_id}' verlassen. Zurueck im Hauptthread."
|
||||
return ("OK — App/Diagnostic bekommt Signal 'zurueck zum Hauptchat'. "
|
||||
"Der aktuelle Turn bleibt aber im aktuellen Chat-Kontext.")
|
||||
if name == "project_list":
|
||||
items = projects_mod.list_projects()
|
||||
if not items:
|
||||
return "(keine Projekte angelegt)"
|
||||
active_id = projects_mod.get_active()
|
||||
lines = []
|
||||
for p in items:
|
||||
marker = " ← AKTIV" if p["id"] == active_id else ""
|
||||
status_lbl = p.get("status", "active")
|
||||
lines.append(
|
||||
f"- {p['name']} (id={p['id']}, {p.get('turn_count', 0)} Turns, "
|
||||
f"status={status_lbl}){marker}"
|
||||
f"status={status_lbl})"
|
||||
)
|
||||
return "Projekte:\n" + "\n".join(lines)
|
||||
if name == "project_summary":
|
||||
|
||||
+119
-26
@@ -607,6 +607,11 @@ def memory_import_bootstrap(body: BootstrapBundle):
|
||||
class ChatIn(BaseModel):
|
||||
message: str
|
||||
source: str = "" # "app" / "diagnostic" / "stt" — optional
|
||||
# Multi-Threading: Client bestimmt pro Request welches Projekt (leer = Hauptchat).
|
||||
# Kein globaler active_project-State mehr im Brain — parallele Requests fuer
|
||||
# verschiedene Projekte laufen echt parallel, nur Requests fuers gleiche
|
||||
# Projekt queuen (per-Projekt-Lock).
|
||||
project_id: str = ""
|
||||
|
||||
|
||||
class ChatOut(BaseModel):
|
||||
@@ -614,36 +619,124 @@ class ChatOut(BaseModel):
|
||||
turns: int
|
||||
distilling: bool
|
||||
events: list = Field(default_factory=list)
|
||||
# Aktive Projekt-ID NACH dem Turn (kann durch project_enter/exit-Tools
|
||||
# waehrend des Turns gewechselt haben). Bridge gibt das an die Chat-
|
||||
# Bubble-Broadcasts weiter damit App + Diagnostic die Nachricht zum
|
||||
# richtigen Projekt-Block sortieren koennen.
|
||||
# Echo der project_id die dieser Turn hatte. Bridge nutzt sie damit die
|
||||
# ausgehende Chat-Bubble sauber getaggt in der richtigen Thread-Bahn der
|
||||
# UI landet.
|
||||
project_id: str = ""
|
||||
|
||||
|
||||
@app.post("/chat", response_model=ChatOut)
|
||||
def chat(body: ChatIn, background: BackgroundTasks):
|
||||
"""Hauptpfad. Antwort kommt synchron. Memory-Destillat laeuft
|
||||
im Hintergrund nachdem die Response rausging."""
|
||||
a = agent()
|
||||
try:
|
||||
reply = a.chat(body.message, source=body.source)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc))
|
||||
except RuntimeError as exc:
|
||||
logger.error("chat fehlgeschlagen: %s", exc)
|
||||
raise HTTPException(502, str(exc))
|
||||
# Per-Projekt async-Locks fuer Queue-Behavior: Requests fuers gleiche Projekt
|
||||
# warten aufeinander (queue), Requests fuer verschiedene Projekte laufen echt
|
||||
# parallel. Hauptchat = Lock unter key "" (leerer String).
|
||||
_project_locks: dict[str, asyncio.Lock] = {}
|
||||
_project_locks_meta_lock = asyncio.Lock()
|
||||
# Pro Projekt eine Liste noch-nicht-verarbeiteter Requests. Wird beim Enqueue
|
||||
# ergaenzt, beim Fertig-Werden gepoppt. Ermoeglicht Queue-Aware-Prompting:
|
||||
# waehrend ARIA an Task N arbeitet, sieht sie N+1..N+k als System-Prompt-Hinweis
|
||||
# und kann entscheiden ob eine spaetere Nachricht die aktuelle korrigiert/
|
||||
# annuliert → dann Skip-Antwort statt Ausfuehren.
|
||||
_project_pending: dict[str, list[dict]] = {}
|
||||
|
||||
needs_distill = a.conversation.needs_distill()
|
||||
if needs_distill:
|
||||
background.add_task(a.distill_old_turns)
|
||||
return ChatOut(
|
||||
reply=reply,
|
||||
turns=len(a.conversation.turns),
|
||||
distilling=needs_distill,
|
||||
events=a.pop_events(),
|
||||
project_id=projects_mod.get_active(),
|
||||
)
|
||||
|
||||
async def _get_project_lock(project_id: str) -> asyncio.Lock:
|
||||
"""Holt (oder erzeugt) den asyncio.Lock fuer ein bestimmtes Projekt.
|
||||
Nutzt _project_locks_meta_lock zur Vermeidung von Race Conditions
|
||||
beim ersten-Zugriff pro Projekt."""
|
||||
async with _project_locks_meta_lock:
|
||||
lock = _project_locks.get(project_id)
|
||||
if lock is None:
|
||||
lock = asyncio.Lock()
|
||||
_project_locks[project_id] = lock
|
||||
return lock
|
||||
|
||||
|
||||
def _project_queue_snapshot() -> dict:
|
||||
"""Snapshot fuer /projects/queue-status: welche Projekte arbeiten gerade,
|
||||
wieviele wait-in-queue haben, welche sind idle."""
|
||||
out = {}
|
||||
# Zeige nur Kontexte mit Aktivitaet — locked oder pending
|
||||
seen: set = set()
|
||||
for pid, lock in _project_locks.items():
|
||||
pending = len(_project_pending.get(pid, []))
|
||||
is_busy = lock.locked()
|
||||
# busy: gerade in Verarbeitung. queue: N weitere warten dahinter.
|
||||
# Der Busy-Request zaehlt NICHT in queue (er ist ja aus pending schon "raus").
|
||||
out[pid or "__main__"] = {
|
||||
"busy": is_busy,
|
||||
"queue_size": max(0, pending - (1 if is_busy else 0)),
|
||||
}
|
||||
seen.add(pid)
|
||||
for pid, pend in _project_pending.items():
|
||||
if pid in seen:
|
||||
continue
|
||||
out[pid or "__main__"] = {"busy": False, "queue_size": len(pend)}
|
||||
return out
|
||||
|
||||
|
||||
@app.post("/chat", response_model=ChatOut)
|
||||
async def chat(body: ChatIn, background: BackgroundTasks):
|
||||
"""Hauptpfad. Antwort kommt synchron. Memory-Destillat laeuft
|
||||
im Hintergrund nachdem die Response rausging.
|
||||
|
||||
Multi-Threading: Requests fuers gleiche Projekt (project_id gleich)
|
||||
laufen serialisiert durch den per-Projekt-Lock — Queue-Behavior.
|
||||
Verschiedene Projekte laufen parallel."""
|
||||
pid = (body.project_id or "").strip()
|
||||
lock = await _get_project_lock(pid)
|
||||
# Vor dem Lock in die Pending-Liste, damit die verlaufende Task sehen kann
|
||||
# was NACH ihr in der Warteschlange steht (Queue-Aware Prompting).
|
||||
import uuid as _uuid
|
||||
req_id = _uuid.uuid4().hex
|
||||
_project_pending.setdefault(pid, []).append({
|
||||
"id": req_id, "message": body.message, "source": body.source,
|
||||
})
|
||||
try:
|
||||
async with lock:
|
||||
# Snapshot: was liegt NACH mir in der Queue?
|
||||
after_me = [
|
||||
e["message"] for e in _project_pending.get(pid, [])
|
||||
if e["id"] != req_id
|
||||
]
|
||||
a = agent()
|
||||
try:
|
||||
# Sync-Aufruf im Executor damit wir den Event-Loop nicht blocken —
|
||||
# chat() macht HTTP-Calls (Proxy) die 30-60s dauern koennen.
|
||||
loop = asyncio.get_running_loop()
|
||||
reply = await loop.run_in_executor(
|
||||
None,
|
||||
lambda: a.chat(
|
||||
body.message, source=body.source, project_id=pid,
|
||||
pending_queue=after_me,
|
||||
),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc))
|
||||
except RuntimeError as exc:
|
||||
logger.error("chat fehlgeschlagen: %s", exc)
|
||||
raise HTTPException(502, str(exc))
|
||||
|
||||
needs_distill = a.conversation.needs_distill()
|
||||
if needs_distill:
|
||||
background.add_task(a.distill_old_turns)
|
||||
return ChatOut(
|
||||
reply=reply,
|
||||
turns=len(a.conversation.turns),
|
||||
distilling=needs_distill,
|
||||
events=a.pop_events(),
|
||||
project_id=pid,
|
||||
)
|
||||
finally:
|
||||
_project_pending[pid] = [
|
||||
e for e in _project_pending.get(pid, []) if e["id"] != req_id
|
||||
]
|
||||
|
||||
|
||||
@app.get("/projects/queue-status")
|
||||
def projects_queue_status():
|
||||
"""Snapshot: fuer jeden Projekt-Kontext (inkl. Hauptchat unter __main__)
|
||||
- busy: True wenn gerade ein Request in Verarbeitung
|
||||
- queue_size: wieviele weitere warten dahinter"""
|
||||
return {"contexts": _project_queue_snapshot()}
|
||||
|
||||
|
||||
# ── Projekte ────────────────────────────────────────────────────────
|
||||
|
||||
+168
-18
@@ -611,6 +611,13 @@ class ARIABridge:
|
||||
self._last_chat_final_at: float = 0.0
|
||||
# requestId → messageId Map fuer XTTS-Audio-Cache (App-seitige Zuordnung)
|
||||
self._xtts_request_to_message: dict[str, str] = {}
|
||||
# Voice-Router (Multi-Threading, 06/2026): sticky Projekt-Kontext fuer
|
||||
# STT-Voice-Nachrichten. Wechselt via „fuer <name>:"-Prefix, faellt nach
|
||||
# STICKY_TIMEOUT_SEC ohne neue Voice-Message zurueck auf Hauptchat.
|
||||
# Meta-Kommandos („zurueck zum hauptchat") werden client-seitig
|
||||
# interceptiert und aendern hier den Sticky OHNE Brain-Roundtrip.
|
||||
self._voice_sticky_project_id: str = ""
|
||||
self._voice_sticky_expires_at: float = 0.0
|
||||
# Voice-Override aus letzter Chat-Nachricht einer App.
|
||||
# Wird fuer die direkt folgende ARIA-Antwort genutzt und dann zurueckgesetzt.
|
||||
# So kann jedes Geraet seine bevorzugte Stimme bekommen (pro Request).
|
||||
@@ -1005,17 +1012,10 @@ class ARIABridge:
|
||||
cleaned = re.sub(r"\n{3,}", "\n\n", cleaned)
|
||||
return cleaned, files, missing
|
||||
|
||||
def _tag_file_to_active_project(self, file_path: str) -> None:
|
||||
"""Holt vom Brain das aktive Projekt + schreibt file_path → project_id
|
||||
in /shared/config/file_projects.json. Best-effort, fail-silent.
|
||||
Wird vom File-Save-Handler nach erfolgreichem Schreiben aufgerufen."""
|
||||
def _tag_file_to_project(self, file_path: str, project_id: str) -> None:
|
||||
"""Schreibt file_path → project_id in /shared/config/file_projects.json.
|
||||
Best-effort, fail-silent. project_id leer = Eintrag entfernen (Hauptchat)."""
|
||||
try:
|
||||
brain_url = os.environ.get("BRAIN_URL", "http://aria-brain:8080")
|
||||
with urllib.request.urlopen(f"{brain_url}/projects/status", timeout=5) as r:
|
||||
data = json.loads(r.read())
|
||||
active_id = (data.get("active_id") or "").strip()
|
||||
if not active_id:
|
||||
return
|
||||
manifest_path = "/shared/config/file_projects.json"
|
||||
os.makedirs("/shared/config", exist_ok=True)
|
||||
try:
|
||||
@@ -1027,15 +1027,35 @@ class ARIABridge:
|
||||
manifest = {}
|
||||
except Exception:
|
||||
manifest = {}
|
||||
manifest[file_path] = active_id
|
||||
if project_id:
|
||||
manifest[file_path] = project_id
|
||||
else:
|
||||
manifest.pop(file_path, None)
|
||||
tmp = manifest_path + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
json.dump(manifest, f, indent=2, ensure_ascii=False)
|
||||
os.replace(tmp, manifest_path)
|
||||
logger.info("[file-project] %s → %s", file_path, active_id)
|
||||
logger.info("[file-project] %s → %s", file_path, project_id or "(main)")
|
||||
except Exception as exc:
|
||||
logger.warning("[file-project] tag failed (%s): %s", file_path, exc)
|
||||
|
||||
def _tag_file_to_active_project(self, file_path: str) -> None:
|
||||
"""Convenience: Brain nach aktivem Projekt fragen + taggen.
|
||||
Wird vom App-Upload-Handler genutzt (dort wissen wir die Projekt-ID
|
||||
noch nicht aus dem Payload — Stefan kann ja zwischen App-Upload und
|
||||
Chat-Send das Projekt gewechselt haben). ARIA-eigene Dateien gehen
|
||||
ueber _tag_file_to_project mit turn_project_id direkt."""
|
||||
try:
|
||||
brain_url = os.environ.get("BRAIN_URL", "http://aria-brain:8080")
|
||||
with urllib.request.urlopen(f"{brain_url}/projects/status", timeout=5) as r:
|
||||
data = json.loads(r.read())
|
||||
active_id = (data.get("active_id") or "").strip()
|
||||
if not active_id:
|
||||
return
|
||||
self._tag_file_to_project(file_path, active_id)
|
||||
except Exception as exc:
|
||||
logger.warning("[file-project] active-query failed (%s): %s", file_path, exc)
|
||||
|
||||
async def _broadcast_aria_file(self, file_info: dict) -> None:
|
||||
"""ARIA hat eine Datei fuer den User erstellt — App+Diagnostic informieren."""
|
||||
logger.info("[rvs] ARIA-Datei rausgeben: %s (%s, %dKB)",
|
||||
@@ -1194,7 +1214,15 @@ class ARIABridge:
|
||||
# Der Marker wird aus dem Antworttext entfernt (TTS soll ihn nicht
|
||||
# vorlesen) und parallel als file_from_aria-Event geschickt.
|
||||
text, aria_files, missing_files = self._extract_file_markers(text)
|
||||
# ARIA-Dateien dem aktiven Projekt zuordnen (falls eines aktiv war).
|
||||
# turn_project_id kommt vom Brain mit dem /chat-Response und reflektiert
|
||||
# den Stand NACH dem Turn — passt fuer Dateien die ARIA waehrend des
|
||||
# Turns geschrieben hat (sie sind „im selben Projekt entstanden").
|
||||
turn_pid = (payload.get("projectId") or "").strip() if isinstance(payload, dict) else ""
|
||||
for f in aria_files:
|
||||
server_path = f.get("serverPath")
|
||||
if turn_pid and server_path:
|
||||
self._tag_file_to_project(server_path, turn_pid)
|
||||
await self._broadcast_aria_file(f)
|
||||
# Bei fehlenden Files: User informieren (sonst sieht er nur stille
|
||||
# Verluste — ARIA hat den Marker hingeschrieben aber das File nicht
|
||||
@@ -1216,6 +1244,7 @@ class ARIABridge:
|
||||
"text": display_text,
|
||||
"files": [{"serverPath": f["serverPath"], "name": f["name"],
|
||||
"mimeType": f["mimeType"], "size": f["size"]} for f in aria_files],
|
||||
"project_id": turn_pid,
|
||||
})
|
||||
|
||||
metadata = payload.get("metadata", {})
|
||||
@@ -1488,7 +1517,9 @@ class ARIABridge:
|
||||
asyncio.create_task(self.send_to_core(text, source="app-file+chat"))
|
||||
return True
|
||||
|
||||
async def send_to_core(self, text: str, source: str = "bridge", client_msg_id: Optional[str] = None) -> None:
|
||||
async def send_to_core(self, text: str, source: str = "bridge",
|
||||
client_msg_id: Optional[str] = None,
|
||||
project_id: str = "") -> None:
|
||||
"""Sendet Text an aria-brain (HTTP /chat) und broadcastet die Antwort.
|
||||
|
||||
Nicht-Streaming: wir warten bis Brain fertig ist, dann pushen wir
|
||||
@@ -1498,8 +1529,13 @@ class ARIABridge:
|
||||
"""
|
||||
brain_url = os.environ.get("BRAIN_URL", "http://aria-brain:8080")
|
||||
url = f"{brain_url}/chat"
|
||||
payload = json.dumps({"message": text, "source": source}).encode("utf-8")
|
||||
logger.info("[brain] chat ← %s '%s'", source, text[:80])
|
||||
# project_id kommt jetzt IM /chat-Body an das Brain (Multi-Threading:
|
||||
# per-Request-Routing statt globaler active_project-State).
|
||||
payload = json.dumps({
|
||||
"message": text, "source": source,
|
||||
"project_id": project_id or "",
|
||||
}).encode("utf-8")
|
||||
logger.info("[brain] chat ← %s '%s' project=%s", source, text[:80], project_id or "(main)")
|
||||
|
||||
# User-Nachricht in chat_backup.jsonl loggen — wird beim App-Reconnect
|
||||
# / Diagnostic-Reload als History-Quelle gelesen. clientMsgId speichern
|
||||
@@ -1508,6 +1544,8 @@ class ARIABridge:
|
||||
entry: dict = {"role": "user", "text": text, "source": source}
|
||||
if client_msg_id:
|
||||
entry["clientMsgId"] = client_msg_id
|
||||
if project_id:
|
||||
entry["project_id"] = project_id
|
||||
self._append_chat_backup(entry)
|
||||
|
||||
# agent_activity → thinking. _emit_activity statt direktem _send_to_rvs
|
||||
@@ -1936,6 +1974,7 @@ class ARIABridge:
|
||||
core_text,
|
||||
source="app" + (" [barge-in]" if interrupted else ""),
|
||||
client_msg_id=client_msg_id,
|
||||
project_id=str(payload.get("projectId") or ""),
|
||||
))
|
||||
return
|
||||
|
||||
@@ -2944,6 +2983,81 @@ class ARIABridge:
|
||||
else:
|
||||
logger.info("[rvs] Keine Sprache erkannt — ignoriert")
|
||||
|
||||
# Voice-Router-Konstanten
|
||||
_VOICE_STICKY_TIMEOUT_SEC = 30.0
|
||||
_VOICE_META_BACK_TO_MAIN = re.compile(
|
||||
r"^\s*(?:aria[,.]?\s+)?(?:zur(?:ü|ue)ck\s+zum\s+hauptchat|hauptchat\s+bitte|aria\s+hauptchat)\s*[.!?]?\s*$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_VOICE_META_PROJECT_PREFIX = re.compile(
|
||||
r"^\s*(?:aria[,.]?\s+)?(?:f(?:ü|ue)r|ins?)\s+([\w\-äöüßÄÖÜ]{2,40})[:\-,]\s*(.+?)\s*$",
|
||||
re.IGNORECASE | re.DOTALL,
|
||||
)
|
||||
|
||||
def _apply_voice_router(self, text: str) -> tuple[bool, str, str, str]:
|
||||
"""Voice-Router: entscheidet ob ein STT-Text ans Brain geht und wenn ja
|
||||
an welchen Projekt-Kontext.
|
||||
|
||||
Returns (should_forward, cleaned_text, project_id, meta_action):
|
||||
- should_forward=False: reines Meta-Kommando, kein Brain-Call.
|
||||
meta_action beschreibt was passiert ist (broadcastet an UI).
|
||||
- should_forward=True: cleaned_text ans Brain, project_id ist Focus.
|
||||
Bei Prefix wird der Prefix aus dem Text entfernt.
|
||||
|
||||
Sticky-Logik: nach einem projekt-getaggten Voice-Turn wird der Sticky
|
||||
30s lang gehalten. Innerhalb dieses Fensters gehen weitere Voice-Msgs
|
||||
OHNE Prefix in dasselbe Projekt. Nach Ablauf: Default Hauptchat.
|
||||
"""
|
||||
import time as _time
|
||||
now = _time.time()
|
||||
stripped = text.strip()
|
||||
|
||||
# 1) Meta: zurueck zum Hauptchat
|
||||
if self._VOICE_META_BACK_TO_MAIN.match(stripped):
|
||||
self._voice_sticky_project_id = ""
|
||||
self._voice_sticky_expires_at = 0.0
|
||||
return (False, "", "", "back_to_main")
|
||||
|
||||
# 2) Prefix: "fuer <name>: <text>"
|
||||
m = self._VOICE_META_PROJECT_PREFIX.match(stripped)
|
||||
if m:
|
||||
name = m.group(1)
|
||||
remainder = m.group(2).strip()
|
||||
# Fuzzy-Match auf Projekt via Brain-API
|
||||
try:
|
||||
brain_url = os.environ.get("BRAIN_URL", "http://aria-brain:8080")
|
||||
with urllib.request.urlopen(f"{brain_url}/projects/list", timeout=3) as r:
|
||||
projects = json.loads(r.read()).get("projects", [])
|
||||
from difflib import SequenceMatcher
|
||||
best, best_score = None, 0.0
|
||||
q = name.lower()
|
||||
for p in projects:
|
||||
pname = p.get("name", "").lower()
|
||||
if q == pname or q == p.get("id", ""):
|
||||
best, best_score = p, 1.0
|
||||
break
|
||||
s = SequenceMatcher(None, q, pname).ratio()
|
||||
if s > best_score:
|
||||
best, best_score = p, s
|
||||
if best and best_score >= 0.6:
|
||||
pid = best["id"]
|
||||
self._voice_sticky_project_id = pid
|
||||
self._voice_sticky_expires_at = now + self._VOICE_STICKY_TIMEOUT_SEC
|
||||
logger.info("[voice-router] Prefix → Projekt '%s' (id=%s, score=%.2f)",
|
||||
best.get("name"), pid, best_score)
|
||||
return (True, remainder or stripped, pid, "project_prefix")
|
||||
except Exception as exc:
|
||||
logger.warning("[voice-router] Prefix-Match fehlgeschlagen: %s", exc)
|
||||
# Kein Match → als normale Nachricht weiter (Sticky wenn aktiv)
|
||||
# 3) Kein Meta / Prefix → Sticky oder Default
|
||||
if self._voice_sticky_project_id and now < self._voice_sticky_expires_at:
|
||||
# Sticky refreshen
|
||||
self._voice_sticky_expires_at = now + self._VOICE_STICKY_TIMEOUT_SEC
|
||||
return (True, stripped, self._voice_sticky_project_id, "sticky")
|
||||
# Sticky abgelaufen — zurücksetzen
|
||||
self._voice_sticky_project_id = ""
|
||||
return (True, stripped, "", "default")
|
||||
|
||||
async def _process_endpoint_text(self, text: str,
|
||||
interrupted: bool = False,
|
||||
audio_request_id: str = "",
|
||||
@@ -2955,16 +3069,51 @@ class ARIABridge:
|
||||
Spiegel-Methode zu _process_app_audio NACH dem STT-Schritt. Bewusst
|
||||
eigene Methode statt Code-Pfade in _process_app_audio aufdroeseln,
|
||||
damit der Legacy-Pfad (App schickt 'audio') unangetastet bleibt.
|
||||
|
||||
Voice-Router: interceptiert Meta-Kommandos (zurueck zum Hauptchat)
|
||||
+ Prefix-Adressierung („fuer Frankreich: ...") + 30s-Sticky. Meta
|
||||
selbst geht NICHT ans Brain, sondern broadcastet als project_changed-
|
||||
Event → App+Diagnostic wechseln den Focus.
|
||||
"""
|
||||
should_forward, cleaned, project_id, meta_action = self._apply_voice_router(text)
|
||||
|
||||
if meta_action in ("back_to_main", "project_prefix"):
|
||||
# UI-Focus-Update broadcasten
|
||||
payload = {"action": "entered" if meta_action == "project_prefix" else "exited"}
|
||||
if meta_action == "project_prefix" and project_id:
|
||||
# Namen aus dem Cache holen — best effort
|
||||
try:
|
||||
brain_url = os.environ.get("BRAIN_URL", "http://aria-brain:8080")
|
||||
with urllib.request.urlopen(f"{brain_url}/projects/list", timeout=2) as r:
|
||||
for p in json.loads(r.read()).get("projects", []):
|
||||
if p.get("id") == project_id:
|
||||
payload["id"] = project_id
|
||||
payload["name"] = p.get("name", "")
|
||||
break
|
||||
except Exception:
|
||||
payload["id"] = project_id
|
||||
await self._send_to_rvs({
|
||||
"type": "project_changed",
|
||||
"payload": payload,
|
||||
"timestamp": int(asyncio.get_event_loop().time() * 1000),
|
||||
})
|
||||
|
||||
if not should_forward:
|
||||
logger.info("[voice-router] Meta-Kommando '%s' intercepted, kein Brain-Call",
|
||||
meta_action)
|
||||
return
|
||||
|
||||
try:
|
||||
stt_payload = {
|
||||
"text": text,
|
||||
"text": cleaned,
|
||||
"sender": "stt",
|
||||
}
|
||||
if audio_request_id:
|
||||
stt_payload["audioRequestId"] = audio_request_id
|
||||
if location:
|
||||
stt_payload["location"] = location
|
||||
if project_id:
|
||||
stt_payload["projectId"] = project_id
|
||||
ok = await self._send_to_rvs({
|
||||
"type": "chat",
|
||||
"payload": stt_payload,
|
||||
@@ -2977,10 +3126,11 @@ class ARIABridge:
|
||||
except Exception as e:
|
||||
logger.warning("[rvs] STT-Text (endpoint) konnte nicht broadcastet werden: %s", e)
|
||||
|
||||
core_text = self._build_core_text(text, interrupted, location)
|
||||
core_text = self._build_core_text(cleaned, interrupted, location)
|
||||
await self.send_to_core(core_text,
|
||||
source="app-voice-stream" + (" [barge-in]" if interrupted else ""),
|
||||
client_msg_id=client_msg_id)
|
||||
client_msg_id=client_msg_id,
|
||||
project_id=project_id)
|
||||
|
||||
async def _stt_remote(self, audio_b64: str, mime_type: str) -> Optional[str]:
|
||||
"""Schickt Audio an die whisper-bridge und wartet auf stt_response.
|
||||
|
||||
+105
-2
@@ -305,6 +305,12 @@
|
||||
<button class="btn secondary" onclick="toggleChatFullscreen()" id="btn-chat-fs" style="padding:4px 10px;font-size:11px;">Vollbild</button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Multi-Threading: Kontext-Strip ueber dem Chat. Jeder Kontext
|
||||
(Hauptchat + aktive Projekte) als kompakte Karte mit Status-Dot.
|
||||
Tap wechselt den Focus — Chat-Box filtert dann auf diesen Kontext. -->
|
||||
<div id="chat-context-strip" style="display:flex;gap:6px;overflow-x:auto;padding:6px 4px;margin-bottom:6px;border-bottom:1px solid #1E1E2E;">
|
||||
<!-- wird von renderContextStrip() befuellt -->
|
||||
</div>
|
||||
<div class="chat-box" id="chat-box"></div>
|
||||
<div id="thinking-indicator" style="display:none;padding:6px 10px;font-size:12px;color:#FFD60A;background:#1E1E2E;border-radius:0 0 6px 6px;margin-top:-8px;margin-bottom:8px;align-items:center;justify-content:space-between;">
|
||||
<span><span style="animation:pulse 1s infinite;">💭</span> <span id="thinking-text">ARIA denkt...</span></span>
|
||||
@@ -1317,6 +1323,94 @@
|
||||
|
||||
<script>
|
||||
const chatBox = document.getElementById('chat-box');
|
||||
|
||||
// ── Multi-Threading: Kontext-Focus fuer Diagnostic-Chat ─────
|
||||
// focusedContextId: leerer String = Hauptchat, sonst project_id.
|
||||
// Gefiltert werden Bubbles per data-project-id-Match (siehe addChat).
|
||||
// Send-Input uebergibt die Focus-ID ans Brain (via bridge → /chat).
|
||||
let focusedContextId = localStorage.getItem('diag_focused_context_id') || '';
|
||||
let diagQueueStatus = {};
|
||||
let diagProjectsCache = [];
|
||||
|
||||
function updateChatVisibilityByFocus() {
|
||||
for (const box of [chatBox, document.getElementById('chat-box-fs')]) {
|
||||
if (!box) continue;
|
||||
for (const el of box.querySelectorAll('.chat-msg')) {
|
||||
const pid = el.dataset.projectId || '';
|
||||
el.style.display = (pid === focusedContextId) ? '' : 'none';
|
||||
}
|
||||
box.scrollTop = box.scrollHeight;
|
||||
}
|
||||
}
|
||||
|
||||
function switchDiagFocus(id) {
|
||||
focusedContextId = id || '';
|
||||
localStorage.setItem('diag_focused_context_id', focusedContextId);
|
||||
updateChatVisibilityByFocus();
|
||||
renderContextStrip();
|
||||
}
|
||||
|
||||
function renderContextStrip() {
|
||||
const strip = document.getElementById('chat-context-strip');
|
||||
if (!strip) return;
|
||||
const chip = (id, name, isFocus, dotColor, subline) => {
|
||||
const bg = isFocus ? 'rgba(52,199,89,0.15)' : '#1E1E2E';
|
||||
const border = isFocus ? '#34C759' : '#2A2A3E';
|
||||
return `<div onclick="switchDiagFocus('${id}')" style="cursor:pointer;flex:0 0 auto;padding:6px 10px;background:${bg};border:1px solid ${border};border-radius:6px;display:flex;align-items:center;gap:6px;min-width:120px;">
|
||||
<div style="width:8px;height:8px;border-radius:4px;background:${dotColor};"></div>
|
||||
<div style="display:flex;flex-direction:column;min-width:0;">
|
||||
<div style="color:${isFocus?'#34C759':'#E0E0F0'};font-size:12px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:200px;">${escapeHtml(name)}</div>
|
||||
<div style="color:#8888AA;font-size:10px;">${subline}</div>
|
||||
</div>
|
||||
</div>`;
|
||||
};
|
||||
const dotFor = (key) => {
|
||||
const s = diagQueueStatus[key];
|
||||
if (!s) return { color: '#555570', label: '' };
|
||||
if (s.busy) return { color: '#FF6E6E', label: 'arbeitet' };
|
||||
if (s.queue_size > 0) return { color: '#FFD60A', label: `Queue: ${s.queue_size}` };
|
||||
return { color: '#34C759', label: 'idle' };
|
||||
};
|
||||
const cards = [];
|
||||
// Hauptchat
|
||||
const mainDot = dotFor('__main__');
|
||||
cards.push(chip('', '💬 Hauptchat', focusedContextId === '', mainDot.color, mainDot.label || 'idle'));
|
||||
// Projekte — nur active/ended, sortiert nach letzter Aktivitaet
|
||||
for (const p of diagProjectsCache) {
|
||||
if (p.status === 'archived') continue;
|
||||
const d = dotFor(p.id);
|
||||
const sub = d.label || `${p.turn_count} Turns`;
|
||||
cards.push(chip(p.id, `📁 ${p.name}`, focusedContextId === p.id, d.color, sub));
|
||||
}
|
||||
strip.innerHTML = cards.join('');
|
||||
}
|
||||
|
||||
async function refreshDiagQueueStatus() {
|
||||
try {
|
||||
const r = await fetch('/api/brain/projects/queue-status');
|
||||
const d = await r.json();
|
||||
diagQueueStatus = d?.contexts || {};
|
||||
renderContextStrip();
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async function refreshDiagProjectsCache() {
|
||||
try {
|
||||
const r = await fetch('/api/brain/projects/list?include_archived=false');
|
||||
const d = await r.json();
|
||||
diagProjectsCache = d?.projects || [];
|
||||
renderContextStrip();
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Beim Load: Projekte laden + Polling starten
|
||||
setTimeout(() => {
|
||||
refreshDiagProjectsCache();
|
||||
refreshDiagQueueStatus();
|
||||
setInterval(refreshDiagQueueStatus, 2000);
|
||||
// Projekt-Liste alle 15s neu holen (neue Anlagen, umbenennen)
|
||||
setInterval(refreshDiagProjectsCache, 15000);
|
||||
}, 500);
|
||||
const pauseHint = document.getElementById('pause-hint');
|
||||
const btnScroll = document.getElementById('btn-scroll');
|
||||
let ws;
|
||||
@@ -1723,6 +1817,7 @@
|
||||
location: p.location,
|
||||
ttsText: p.ttsText,
|
||||
backupTs: p.backupTs,
|
||||
projectId: p.projectId || '',
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -1911,8 +2006,10 @@
|
||||
if (!text && diagPendingFiles.length === 0) return;
|
||||
if (diagPendingFiles.length > 0) sendDiagAttachments();
|
||||
if (text) {
|
||||
addChat('sent', text, 'via RVS');
|
||||
send({ action: 'test_rvs', text });
|
||||
// Multi-Threading: mit fokussierter Kontext-ID senden.
|
||||
// Bridge routet an /chat body.project_id — Brain queued per Kontext.
|
||||
addChat('sent', text, 'via RVS', { projectId: focusedContextId });
|
||||
send({ action: 'test_rvs', text, projectId: focusedContextId });
|
||||
}
|
||||
input.value = '';
|
||||
}
|
||||
@@ -2178,12 +2275,18 @@
|
||||
// Thinking-Indikator ausblenden bei neuer Nachricht
|
||||
updateThinkingIndicator({ activity: 'idle' });
|
||||
|
||||
// Projekt-Tag fuer Focus-Filter (Multi-Threading, 06/2026)
|
||||
const projectId = (options && options.projectId) || '';
|
||||
const hiddenByFocus = (typeof focusedContextId === 'string' && projectId !== focusedContextId);
|
||||
|
||||
// In beide Chat-Boxen schreiben (normal + Vollbild)
|
||||
for (const box of [chatBox, document.getElementById('chat-box-fs')]) {
|
||||
if (!box) continue;
|
||||
const el = document.createElement('div');
|
||||
el.className = `chat-msg ${type}`;
|
||||
if (backupTs) el.dataset.ts = String(backupTs);
|
||||
el.dataset.projectId = projectId;
|
||||
if (hiddenByFocus) el.style.display = 'none';
|
||||
el.innerHTML = html;
|
||||
box.appendChild(el);
|
||||
box.scrollTop = box.scrollHeight;
|
||||
|
||||
+11
-3
@@ -1001,18 +1001,26 @@ function sendToRVS_raw(msgObj) {
|
||||
freshWs.on("error", () => {});
|
||||
}
|
||||
|
||||
function sendToRVS(text, isTrace) {
|
||||
function sendToRVS(text, isTrace, projectId) {
|
||||
// Brain-Pipeline: Diagnostic → RVS → Bridge → Brain (HTTP). OpenClaw-
|
||||
// Gateway-Pfad ist abgeschaltet. Sender 'diagnostic' damit die Bridge
|
||||
// den Text als User-Nachricht ans Brain weiterleitet und die App +
|
||||
// Diagnostic die Bubble live spiegeln koennen.
|
||||
//
|
||||
// projectId (Multi-Threading 06/2026): optional — leerer/undefined String
|
||||
// = Hauptchat, sonst project_id. Bridge liest payload.projectId und routet
|
||||
// an /chat body.project_id — Brain queued per Kontext.
|
||||
if (!rvsWs || rvsWs.readyState !== WebSocket.OPEN) {
|
||||
if (isTrace) traceEnd(false, "RVS nicht verbunden");
|
||||
return false;
|
||||
}
|
||||
sendToRVS_raw({
|
||||
type: "chat",
|
||||
payload: { text, sender: "diagnostic" },
|
||||
payload: {
|
||||
text,
|
||||
sender: "diagnostic",
|
||||
projectId: projectId || "",
|
||||
},
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
return true;
|
||||
@@ -2285,7 +2293,7 @@ wss.on("connection", (ws) => {
|
||||
sendToRVS(msg.text || "aria lebst du noch?", true);
|
||||
} else if (msg.action === "test_rvs") {
|
||||
traceStart("RVS", msg.text || "aria lebst du noch?");
|
||||
sendToRVS(msg.text || "aria lebst du noch?", true);
|
||||
sendToRVS(msg.text || "aria lebst du noch?", true, msg.projectId || "");
|
||||
} else if (msg.action === "reconnect_gateway") {
|
||||
connectGateway();
|
||||
} else if (msg.action === "reconnect_rvs") {
|
||||
|
||||
Reference in New Issue
Block a user