feat: Modell pro Chat waehlen — und sehen, welches gerade laeuft
Nach einem Sicherheitsfilter-Treffer fuhr ein Projekt still auf dem Ausweich-Modell weiter, und nirgends war zu sehen, auf welchem. Zurueck ging nur ueber "Liste leeren" im Filter-Panel, und das gleich fuer alle Chats. Jetzt drei Ebenen (aria-brain/context_model.py): Einstellung (brainModel) < pro Chat < Ausweich (Sicherheitsfilter) - Pro Chat: Hauptchat und jedes Projekt koennen ein eigenes Modell haben, in /shared/config/context_models.json. Bewusst kein Feld im Projekt-Manifest — der Hauptchat ist kein Projekt und waere sonst aussen vor. - "↩ zurueck" pro Chat: loescht nur die Filter-Vermerke DIESES Chats. Blockt der Filter erneut, weicht das Brain eben wieder aus. - Angezeigt wird, was wirklich laeuft: chat() gibt das Modell aus modelUsage der CLI zurueck (aufgeloeste Version statt Alias) samt Grund; Brain → Bridge → chat_backup + Live-Payload → App und Diagnostic. Als Grundeinstellung zaehlt das Modell, mit dem das Brain laeuft, nicht der Dateiwert — so faellt ein ausstehender Neustart nach brainModel-Aenderung auf. Diagnostic: 🧠-Auswahl neben "+ Projekt" fuer den fokussierten Chat, Modell im Untertitel jeder Kontext-Karte, Modell statt "Claude" am Bubble-Badge (orange mit ↪ bei Ausweich). App: hinter der Quell-Anzeige (Einstellungen, Default aus — Kopfzeile bleibt fuer Mama unveraendert) ein Modell-Chip in der Kopfzeile; Tippen oeffnet die Auswahl fuer diesen Chat inkl. "Zurueck". Laeuft ueber den vorhandenen brain_request-Kanal, also keine neuen RVS-Typen. Tests: 47/47 (12 neue fuer die Aufloesungsreihenfolge gegen agent.chat()), tsc ohne Fehler. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -545,6 +545,7 @@ Erreichbar unter `http://<VM-IP>:3001`. Teilt das Netzwerk mit der Bridge.
|
||||
- `GET /api/agent-stream?lines=N` — gleiche Mechanik fuer den persistierten Live-Stream (Tool-Calls + Inputs + Outputs).
|
||||
- **OAuth-Callback-Pipeline**: Caddy davor terminiert TLS via Let's Encrypt, RVS hat einen HTTP-Listener auf demselben Port wie der WebSocket. Provider (Spotify/Dropbox/Discord/...) redirecten den User an `https://{RVS_HOST}/oauth/callback/{service}` → RVS broadcastet als `oauth_callback`-WS-Message → aria-bridge forwarded an Brain → Brain matched `state`, tauscht `code` gegen Token, persistiert in `/shared/config/oauth_tokens.json`. Token-Refresh laeuft automatisch. ARIA hat fuenf Brain-Tools: **`oauth_register_provider`** (legt URLs eines neuen Providers wie Dropbox/Discord/Notion/... on-demand in `oauth_apps.json` an — Credentials bleiben Stefans Job), `oauth_authorize`, `oauth_get_token`, **`oauth_call`**, `oauth_revoke`
|
||||
- **Sprachmodell**: die Auswahlliste kommt aus **Anthropics eigenem Modell-Katalog** (`downloads.claude.ai/model-catalog/v1/catalog.json`, Surface `cc`) — dieselbe Quelle, aus der sich Claude Code bedient. Oeffentlich, ohne API-Key. Oben die **Tier-Aliase** (opus/sonnet/haiku/fable), die automatisch der neuesten Version folgen; darunter die **exakten Versionen**, aeltere als solche markiert. „↻ Aktualisieren" holt frisch, sonst 6h-Cache mit Datei-Fallback fuer offline. **🔬 Testen** schickt eine echte Mini-Anfrage durch den ganzen Weg und zeigt, welches Modell tatsaechlich geantwortet hat (aus `modelUsage.canonicalModel` der CLI — das Modell selbst zu fragen waere unzuverlaessig). Vier Ergebnisse: Tier aufgeloest (gruen), exakte Version (gruen), **nicht erkannt** (gelb — der Proxy haette still `opus` eingesetzt), ungueltig (rot, mit CLI-Begruendung)
|
||||
- **Modell pro Chat**: jeder Chat (Hauptchat und jedes Projekt) kann sein eigenes Modell haben, ohne die Einstellung fuer alle umzustellen. Reihenfolge: **Einstellung** (`brainModel`) < **pro Chat** (`/shared/config/context_models.json`, gesetzt per 🧠-Auswahl neben „+ Projekt") < **Ausweich** (Sicherheitsfilter, s.u.). Angezeigt wird immer, was der **naechste Turn wirklich nutzt**: in den Kontext-Karten, in der Auswahl (orange „↪ läuft auf …" plus **„↩ zurück zu …"**, wenn gerade ausgewichen wird) und an jeder ARIA-Bubble — dort das Modell, das tatsaechlich geantwortet hat (aus `modelUsage` der CLI, also die aufgeloeste Version statt des Alias). Als Grundeinstellung zaehlt das Modell, mit dem das Brain **laeuft**, nicht der Dateiwert — ein ausstehender Neustart nach Aenderung von `brainModel` faellt so auf. In der **App** dasselbe hinter der Quell-Anzeige (Einstellungen, Default aus): Modell-Chip in der Kopfzeile, Tippen oeffnet die Auswahl fuer diesen Chat, die Bubbles zeigen das Modell statt nur „Claude"
|
||||
- **Sicherheitsfilter-Rettung** (🛡 Sicherheitsfilter): Anthropics Filter („*... safeguards flagged this message*", `Details: [cyber]`) trifft gern genau die Themen, um die es hier geht — Ports, Tunnel, Zugangsdaten. Die Meldung kommt **nicht** als HTTP-Fehler: die CLI liefert ein normales Ergebnis mit `is_error:true` und dem Fehlertext im `content`, also genau dort, wo sonst ARIAs Antwort steht. Ungeprueft landete dieser Text als ARIAs Wort im Verlauf — und weil der Verlauf bei jedem Turn mitgeht, kippte danach **jede** weitere Frage im selben Projekt an derselben Stelle. Jetzt zwei Stufen: **(1)** derselbe Turn wird automatisch mit dem **Ausweich-Modell** neu gefragt (einstellbar unter Sprachmodell, Default: anderes Tier — der Filter haengt am Modell, Anthropic raet selbst zu „change your model"); der ausloesende Turn wird vermerkt, damit die naechsten Turns nicht erst wieder gegen die Wand laufen, und der Vermerk verfaellt von selbst, sobald der Turn aus dem Rolling Window gerollt ist. **(2)** Blockt auch das Ausweich-Modell, liegt es am Verlauf: der ausloesende Turn fliegt aus dem Prompt-Fenster (**Quarantaene**) — nicht geloescht, er bleibt in `conversation.jsonl`, steht mit Text im Panel und ist per „↩ Zurueckholen" wieder drin. Der rohe API-Fehlertext wird nie persistiert; ARIA sagt in eigenen Worten, was passiert ist. Das Panel zeigt pro Vorfall Projekt, Modell, Klassifikator-Code und ob die Blockade **noch wirkt** (= Turn liegt noch im Fenster). Zustand in `/data/safeguard.json`, Code in [`aria-brain/safeguard.py`](aria-brain/safeguard.py); gilt auch fuer das Memory-Destillat, das denselben Verlauf nochmal durchschickt. **Altlasten** — Fehlertexte, die vor diesem Fix schon in `conversation.jsonl` stehen und dort weiter vergiften — raeumt [`aria-brain/clean_poisoned_turns.py`](aria-brain/clean_poisoned_turns.py) einmalig weg (Dry-Run per Default, `--apply` schreibt mit Backup; findet jetzt beide Giftsorten und in Projekten genauso wie im Hauptchat)
|
||||
- **Datenschutz-Schalter**: die drei Kanaele, ueber die Claude Code zusaetzlich sendet (`DISABLE_ERROR_REPORTING`, `DISABLE_TELEMETRY`, `DISABLE_FEEDBACK_COMMAND`) pruefen und setzen. Geschrieben wird nach `~/.claude/settings.json` unter `env` — die CLI liest das bei jedem Aufruf, **kein Neustart noetig**. Geprueft wird, was wirklich im Prozess ankommt: eine per docker-compose gesetzte Variable gewinnt und wird als gesperrt angezeigt, statt einen wirkungslosen Haken anzubieten. **Nicht** dasselbe wie die Trainings-Einstellung — die steht im Anthropic-Konto (Link daneben)
|
||||
- **Warnung bei veralteten Proxy-Patches**: der Proxy kopiert `proxy-patches/` beim **Start**. Wer nach einem `git pull` nur neu startet — oder neu startet, bevor der Pull durch ist — laeuft still mit der alten Fassung. Nichts deutet darauf hin. Die Einstellungen vergleichen jetzt die Zeitstempel und zeigen den fertigen Befehl (`--force-recreate proxy`)
|
||||
|
||||
@@ -37,7 +37,7 @@ import rvs, { RVSMessage, ConnectionState } from '../services/rvs';
|
||||
import audioService from '../services/audio';
|
||||
import wakeWordService from '../services/wakeword';
|
||||
import ProjectsBrowser from '../components/ProjectsBrowser';
|
||||
import brainApi, { Project as BrainProject } from '../services/brainApi';
|
||||
import brainApi, { Project as BrainProject, ContextModels, prettyModel } from '../services/brainApi';
|
||||
import projectFocus from '../services/projectFocus';
|
||||
import phoneCallService from '../services/phoneCall';
|
||||
import { playWakeReadySound } from '../services/wakeReadySound';
|
||||
@@ -87,6 +87,11 @@ interface ChatMessage {
|
||||
/** Welcher Backend die Antwort erzeugt hat: 'local' | 'claude' | 'fast-path'.
|
||||
* Fuer den optionalen Quell-Badge (Einstellung aria_show_source, default aus). */
|
||||
answeredBy?: string;
|
||||
/** Welches Claude-Modell geantwortet hat (aufgeloeste Version) und warum:
|
||||
* 'einstellung' | 'pro-chat' | 'ausweich' (Sicherheitsfilter). Leer bei
|
||||
* Fast-Path/lokal und bei aelteren Bubbles. */
|
||||
model?: string;
|
||||
modelReason?: string;
|
||||
/** Bridge-Message-ID zur Zuordnung von TTS-Audio */
|
||||
messageId?: string;
|
||||
/** Lokaler Pfad zur gecachten TTS-Audio-Datei (file://...) */
|
||||
@@ -349,6 +354,11 @@ const ChatScreen: React.FC = () => {
|
||||
// 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>('');
|
||||
// Modell pro Chat (Brain /context-model/list). Nur geladen, wenn die
|
||||
// Quell-Anzeige an ist — Mama braucht weder Chip noch Netzlast dafuer.
|
||||
const [ctxModels, setCtxModels] = useState<ContextModels | null>(null);
|
||||
const [modelPickerVisible, setModelPickerVisible] = useState(false);
|
||||
const refreshCtxModelsRef = useRef<() => void>(() => {});
|
||||
// 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
|
||||
@@ -760,6 +770,17 @@ const ChatScreen: React.FC = () => {
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
// Modell pro Chat laden — bei eingeschalteter Quell-Anzeige und bei jedem
|
||||
// Kontextwechsel. Kein Polling: ein Ausweich-Vermerk aendert sich nur durch
|
||||
// einen Turn, und nach jedem Turn wird ohnehin neu geladen (s. chat-Handler).
|
||||
useEffect(() => {
|
||||
refreshCtxModelsRef.current = () => {
|
||||
if (!showSource) return;
|
||||
brainApi.getContextModels().then(setCtxModels).catch(() => {});
|
||||
};
|
||||
refreshCtxModelsRef.current();
|
||||
}, [showSource, focusedProjectId]);
|
||||
|
||||
// Wake Word: einmalig laden + Porcupine vorbereiten (wenn Access Key gesetzt)
|
||||
useEffect(() => {
|
||||
wakeWordService.loadFromStorage().catch(() => {});
|
||||
@@ -1045,6 +1066,8 @@ const ChatScreen: React.FC = () => {
|
||||
backupTs: typeof m.ts === 'number' ? m.ts : undefined,
|
||||
projectId: typeof m.project_id === 'string' ? m.project_id : '',
|
||||
answeredBy: typeof m.answeredBy === 'string' ? m.answeredBy : '',
|
||||
model: typeof m.model === 'string' ? m.model : '',
|
||||
modelReason: typeof m.modelReason === 'string' ? m.modelReason : '',
|
||||
...(cmid && { clientMsgId: cmid }),
|
||||
// Server-Bubble = vom Brain verarbeitet → 'delivered' (✓✓)
|
||||
...(role === 'user' && cmid && { deliveryStatus: 'delivered' as const }),
|
||||
@@ -1439,7 +1462,12 @@ const ChatScreen: React.FC = () => {
|
||||
backupTs: (message.payload.backupTs as number) || undefined,
|
||||
projectId: ((message.payload as any).projectId as string) || '',
|
||||
answeredBy: ((message.payload as any).answeredBy as string) || '',
|
||||
model: ((message.payload as any).model as string) || '',
|
||||
modelReason: ((message.payload as any).modelReason as string) || '',
|
||||
};
|
||||
// Modell-Chip oben nachziehen — ein Turn kann aufs Ausweich-Modell
|
||||
// gewechselt sein, das soll man sofort sehen.
|
||||
if ((message.payload as any).model) refreshCtxModelsRef.current();
|
||||
// Die separate file_from_aria-Bubble (leerer Text, nur Datei), die kurz
|
||||
// zuvor fuer DIESE Datei ankam, entfernen — sonst doppelt (einmal solo,
|
||||
// einmal an der Text-Bubble). Nur solche mit passendem serverPath.
|
||||
@@ -3137,7 +3165,15 @@ const ChatScreen: React.FC = () => {
|
||||
claude: { t: 'Claude', c: '#0096FF' },
|
||||
'fast-path': { t: '⚡ fast', c: '#AF7BFF' },
|
||||
};
|
||||
const b = map[ab] || { t: ab, c: '#8A8AA0' };
|
||||
let b = map[ab] || { t: ab, c: '#8A8AA0' };
|
||||
// Bei Claude das echte Modell — aeltere Bubbles ohne Modell
|
||||
// bleiben bei "Claude".
|
||||
if (ab === 'claude' && item.model) {
|
||||
const n = prettyModel(item.model, ctxModels?.names);
|
||||
b = item.modelReason === 'ausweich'
|
||||
? { t: '↪ ' + n, c: '#FF9F0A' }
|
||||
: { t: n, c: '#0096FF' };
|
||||
}
|
||||
return <Text style={{ fontSize: 9, fontWeight: 'bold', color: b.c, marginLeft: 6 }}>{b.t}</Text>;
|
||||
})() : null}
|
||||
{item.text.length > 0 ? (
|
||||
@@ -3383,6 +3419,27 @@ const ChatScreen: React.FC = () => {
|
||||
</Text>
|
||||
<View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: dot.color }} />
|
||||
<Text style={{ fontSize: 10, color: '#8888AA' }}>{dot.label}</Text>
|
||||
{/* Modell dieses Chats — nur mit Quell-Anzeige (Einstellungen),
|
||||
sonst bleibt die Kopfzeile so schlicht wie bisher. Orange mit
|
||||
↪, wenn der Chat gerade aufs Ausweich-Modell ausweicht. */}
|
||||
{showSource && (() => {
|
||||
const row = ctxModels?.rows.find(r => r.context_id === (focusedProjectId || ''));
|
||||
if (!row) return null;
|
||||
const fb = row.reason === 'ausweich';
|
||||
const color = fb ? '#FF9F0A' : row.reason === 'pro-chat' ? '#0096FF' : '#8888AA';
|
||||
return (
|
||||
<TouchableOpacity
|
||||
onPress={() => setModelPickerVisible(true)}
|
||||
hitSlop={{top:8,bottom:8,left:8,right:8}}
|
||||
style={{ paddingHorizontal: 8, paddingVertical: 3, borderRadius: 10,
|
||||
borderWidth: 1, borderColor: color + '88', backgroundColor: color + '22' }}
|
||||
>
|
||||
<Text style={{ color, fontSize: 10, fontWeight: '700' }} numberOfLines={1}>
|
||||
{(fb ? '↪ ' : '🧠 ') + prettyModel(row.effective, ctxModels?.names)}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
);
|
||||
})()}
|
||||
{/* Direkter Zurueck-zum-Hauptchat-Button — nur wenn man in einem
|
||||
Projekt ist. Ein Tap statt Drawer→Hauptchat. */}
|
||||
{!isMain && (
|
||||
@@ -3403,6 +3460,83 @@ const ChatScreen: React.FC = () => {
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* Modell-Auswahl fuer den fokussierten Chat */}
|
||||
<Modal visible={modelPickerVisible} transparent animationType="fade"
|
||||
onRequestClose={() => setModelPickerVisible(false)}>
|
||||
<Pressable style={{ flex: 1, backgroundColor: 'rgba(0,0,0,0.6)', justifyContent: 'center', padding: 24 }}
|
||||
onPress={() => setModelPickerVisible(false)}>
|
||||
<Pressable style={{ backgroundColor: '#15151E', borderRadius: 12, padding: 16, maxHeight: '80%' }}
|
||||
onPress={() => {}}>
|
||||
{(() => {
|
||||
const cid = focusedProjectId || '';
|
||||
const row = ctxModels?.rows.find(r => r.context_id === cid);
|
||||
const names = ctxModels?.names;
|
||||
const pick = (model: string) => {
|
||||
brainApi.setContextModel(cid, model)
|
||||
.then(d => { setCtxModels(d); setModelPickerVisible(false); })
|
||||
.catch(e => Alert.alert('Modell', 'Setzen fehlgeschlagen: ' + (e?.message || e)));
|
||||
};
|
||||
const Item = ({ id, label, active }: { id: string; label: string; active: boolean }) => (
|
||||
<TouchableOpacity onPress={() => pick(id)}
|
||||
style={{ paddingVertical: 10, paddingHorizontal: 10, borderRadius: 8,
|
||||
backgroundColor: active ? 'rgba(0,150,255,0.18)' : 'transparent' }}>
|
||||
<Text style={{ color: active ? '#0096FF' : '#E0E0F0', fontSize: 14, fontWeight: active ? '700' : '400' }}>
|
||||
{(active ? '● ' : '○ ') + label}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
);
|
||||
const sections: [string, string][] = [
|
||||
['tier', 'Automatisch (neueste Version)'],
|
||||
['main', 'Aktuelle Versionen'],
|
||||
['overflow', 'Ältere Versionen'],
|
||||
];
|
||||
return (
|
||||
<>
|
||||
<Text style={{ color: '#E0E0F0', fontSize: 16, fontWeight: '700' }}>
|
||||
Modell für {cid ? (projectNameById[cid] || cid) : 'den Hauptchat'}
|
||||
</Text>
|
||||
<Text style={{ color: '#8888AA', fontSize: 12, marginTop: 4, marginBottom: 10 }}>
|
||||
{row ? 'Läuft gerade auf ' + prettyModel(row.effective, names)
|
||||
+ (row.reason === 'ausweich' ? ' (Ausweich — Sicherheitsfilter)'
|
||||
: row.reason === 'pro-chat' ? ' (für diesen Chat gewählt)' : ' (aus der Einstellung)')
|
||||
: 'Lade …'}
|
||||
</Text>
|
||||
{row?.reason === 'ausweich' && (
|
||||
<TouchableOpacity
|
||||
onPress={() => brainApi.contextModelBack(cid)
|
||||
.then(d => { setCtxModels(d); setModelPickerVisible(false); })
|
||||
.catch(e => Alert.alert('Modell', 'Zurück fehlgeschlagen: ' + (e?.message || e)))}
|
||||
style={{ backgroundColor: 'rgba(255,159,10,0.18)', borderColor: '#FF9F0A', borderWidth: 1,
|
||||
borderRadius: 8, padding: 10, marginBottom: 10 }}>
|
||||
<Text style={{ color: '#FF9F0A', fontSize: 13, fontWeight: '700' }}>
|
||||
↩ Zurück zu {prettyModel(row.selected, names)}
|
||||
</Text>
|
||||
<Text style={{ color: '#B0905A', fontSize: 11, marginTop: 2 }}>
|
||||
Blockt der Filter erneut, weicht ARIA eben wieder aus.
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
<ScrollView>
|
||||
<Item id="" label={'Einstellung (' + prettyModel(ctxModels?.default || '', names) + ')'}
|
||||
active={!row?.override} />
|
||||
{sections.map(([sec, label]) => {
|
||||
const list = (ctxModels?.choices || []).filter(c => (c.section || 'tier') === sec);
|
||||
if (!list.length) return null;
|
||||
return (
|
||||
<View key={sec} style={{ marginTop: 8 }}>
|
||||
<Text style={{ color: '#555570', fontSize: 11, marginBottom: 2 }}>{label}</Text>
|
||||
{list.map(c => <Item key={c.id} id={c.id} label={c.name} active={row?.override === c.id} />)}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
</Pressable>
|
||||
</Pressable>
|
||||
</Modal>
|
||||
|
||||
{/* Projekt-Drawer als Modal */}
|
||||
<ProjectsBrowser
|
||||
visible={projectsVisible}
|
||||
|
||||
@@ -260,6 +260,43 @@ export interface Trigger {
|
||||
|
||||
// ── Memory CRUD ──────────────────────────────────────────────────────
|
||||
|
||||
// ── Modell pro Chat ──────────────────────────────────────────────────
|
||||
// reason: 'einstellung' (brainModel) | 'pro-chat' (fuer diesen Chat gewaehlt)
|
||||
// | 'ausweich' (Sicherheitsfilter hat das gewaehlte Modell blockiert)
|
||||
export interface ContextModelRow {
|
||||
context_id: string;
|
||||
name: string;
|
||||
override: string; // '' = folgt der Einstellung
|
||||
selected: string; // gewaehlt (Einstellung oder pro Chat)
|
||||
effective: string; // was der naechste Turn tatsaechlich nutzt
|
||||
reason: 'einstellung' | 'pro-chat' | 'ausweich' | string;
|
||||
blocked: string[];
|
||||
}
|
||||
|
||||
export interface ContextModelChoice {
|
||||
id: string;
|
||||
name: string;
|
||||
section: 'tier' | 'main' | 'overflow' | string;
|
||||
}
|
||||
|
||||
export interface ContextModels {
|
||||
default: string;
|
||||
rows: ContextModelRow[];
|
||||
choices: ContextModelChoice[];
|
||||
names: Record<string, string>;
|
||||
}
|
||||
|
||||
/** "claude-sonnet-5-5" → "Sonnet 5.5". Katalog-Namen (names) haben Vorrang;
|
||||
* Datums-Suffixe ("-20251001") gehoeren nicht zur Version. Gleiche Logik wie
|
||||
* prettyModel() in der Diagnostic. */
|
||||
export function prettyModel(id: string, names?: Record<string, string>): string {
|
||||
if (!id) return '';
|
||||
if (names && names[id]) return names[id];
|
||||
const m = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-|$)/.exec(id);
|
||||
if (m) return m[1][0].toUpperCase() + m[1].slice(1) + ' ' + m[2] + (m[3] ? '.' + m[3] : '');
|
||||
return id.charAt(0).toUpperCase() + id.slice(1);
|
||||
}
|
||||
|
||||
export const brainApi = {
|
||||
/** Einzelne Memory holen (mit allen Feldern inkl. Anhaenge) */
|
||||
getMemory(id: string): Promise<Memory> {
|
||||
@@ -682,6 +719,25 @@ export const brainApi = {
|
||||
getProjectQueueStatus(): Promise<ProjectQueueStatus> {
|
||||
return _send('/projects/queue-status');
|
||||
},
|
||||
|
||||
/** Modelle aller Chats: gewaehlt, effektiv, Grund + Auswahl-Liste. */
|
||||
getContextModels(): Promise<ContextModels> {
|
||||
return _send('/context-model/list');
|
||||
},
|
||||
/** Modell fuer einen Chat setzen ('' als Modell = wieder die Einstellung). */
|
||||
setContextModel(contextId: string, model: string): Promise<ContextModels> {
|
||||
return _send('/context-model/set', {
|
||||
method: 'POST',
|
||||
body: { context_id: contextId || '', model: model || '' },
|
||||
});
|
||||
},
|
||||
/** Ausweich-Modell beenden: zurueck aufs gewaehlte Modell dieses Chats. */
|
||||
contextModelBack(contextId: string): Promise<ContextModels> {
|
||||
return _send('/context-model/back-to-selected', {
|
||||
method: 'POST',
|
||||
body: { context_id: contextId || '' },
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
export default brainApi;
|
||||
|
||||
+33
-6
@@ -39,9 +39,13 @@ import watcher as watcher_mod
|
||||
import oauth as oauth_mod
|
||||
import projects as projects_mod
|
||||
import safeguard
|
||||
import context_model
|
||||
import project_vms as project_vms_mod
|
||||
|
||||
BRIDGE_URL = os.environ.get("BRIDGE_URL", "http://aria-bridge:8090")
|
||||
# Modell-Info fuer Antworten, an denen kein Claude-Modell beteiligt war
|
||||
# (Fast-Path, Wake-Befehle, lokales LLM). Leer statt geraten.
|
||||
_NO_MODEL = {"model": "", "requested": "", "reason": ""}
|
||||
# SearXNG (self-hosted Meta-Suche) — Backend fuers web_search-Tool (B1b).
|
||||
SEARXNG_URL = os.environ.get("SEARXNG_URL", "http://searxng:8080").rstrip("/")
|
||||
# FLUX-Render kann bis ~90s dauern, beim ersten Render nach Container-Start
|
||||
@@ -2529,7 +2533,7 @@ class Agent:
|
||||
project_id=active_project_id)
|
||||
self.conversation.add("assistant", reply, project_id=active_project_id)
|
||||
logger.info("[wake-off] Sprachbefehl erkannt — App stoppt Listener")
|
||||
return reply, "wake-off", False, False, False
|
||||
return reply, "wake-off", False, False, False, _NO_MODEL
|
||||
|
||||
# Wake-Word AN per Befehl (Text/Aufnahme-Button): App startet den Listener.
|
||||
if _user_wants_wake_on(user_message):
|
||||
@@ -2538,7 +2542,7 @@ class Agent:
|
||||
project_id=active_project_id)
|
||||
self.conversation.add("assistant", reply, project_id=active_project_id)
|
||||
logger.info("[wake-on] Befehl erkannt — App startet Listener")
|
||||
return reply, "wake-on", False, False, False
|
||||
return reply, "wake-on", False, False, False, _NO_MODEL
|
||||
|
||||
# Fast-Path: einfache "reines Steuern"-Commands ueberspringen Claude komplett.
|
||||
# Jeder Skill kann in seinem Manifest fast_patterns deklarieren — das Brain
|
||||
@@ -2565,7 +2569,7 @@ class Agent:
|
||||
elif _wants_continue:
|
||||
converse = True
|
||||
# Fast-Path = reiner Steuerbefehl, nie eine Rueckfrage → awaiting=False.
|
||||
return fast_reply, "fast-path", speak, converse, False
|
||||
return fast_reply, "fast-path", speak, converse, False, _NO_MODEL
|
||||
|
||||
# 1. User-Turn an die Konversation. Den Zeitstempel behalten wir: er
|
||||
# identifiziert diesen Turn, wenn Anthropics Sicherheitsfilter
|
||||
@@ -2591,7 +2595,7 @@ class Agent:
|
||||
elif _wants_continue:
|
||||
converse = True
|
||||
# Local ist tool-loses Reden; blockierende Rueckfragen macht Claude.
|
||||
return local_reply, "local", speak, converse, False
|
||||
return local_reply, "local", speak, converse, False, _NO_MODEL
|
||||
|
||||
# 2. Hot Memory (alle pinned Punkte)
|
||||
hot = self.store.list_pinned()
|
||||
@@ -2733,14 +2737,20 @@ class Agent:
|
||||
# Filter gescheitert, nehmen wir direkt das Ausweich-Modell — sonst
|
||||
# laeuft jeder Turn erst gegen dieselbe Wand. Rollt der Turn aus dem
|
||||
# Fenster, gilt wieder das Hauptmodell; das verfaellt von selbst.
|
||||
primary_model = self.proxy.model
|
||||
# Reihenfolge: Einstellung (brainModel) < pro Chat < Ausweich.
|
||||
primary_model, model_reason = context_model.resolve(
|
||||
active_project_id, self.proxy.model)
|
||||
turn_model = primary_model
|
||||
_blocked = safeguard.blocked_models(active_project_id,
|
||||
[t.ts for t in window])
|
||||
if safeguard.norm_model(primary_model) in _blocked:
|
||||
turn_model = safeguard.fallback_for(primary_model)
|
||||
model_reason = context_model.REASON_FALLBACK
|
||||
logger.warning("[safeguard] %s ist in diesem Fenster blockiert — "
|
||||
"Turn laeuft direkt auf %s", primary_model, turn_model)
|
||||
if model_reason == context_model.REASON_PER_CHAT:
|
||||
logger.info("[context-model] %s nutzt %s (pro Chat gesetzt)",
|
||||
active_project_id or "(Hauptchat)", turn_model)
|
||||
|
||||
logger.info("chat: pinned=%d cold=%d skills=%d/%d window=%d project=%r prompt_chars=%d",
|
||||
len(hot), len(cold), len(active_skills), len(all_skills),
|
||||
@@ -2753,6 +2763,9 @@ class Agent:
|
||||
# zwei Turns, was OpenAI/Anthropic verwirrt und bei strict tools-Aufrufen
|
||||
# zu 400-Errors fuehren kann.
|
||||
final_reply = ""
|
||||
# Welches Modell hat am Ende geantwortet — fuer die Anzeige in App und
|
||||
# Diagnostic. Default: das angefragte; die CLI darf es praezisieren.
|
||||
answered_model = turn_model
|
||||
# Vorlesen ja/nein fuer diesen Claude-Turn. Default True (Gespraech).
|
||||
# Fuehrt Claude einen Steuerbefehl-Skill (run_*, speak=false) erfolgreich
|
||||
# aus, wird die Antwort NICHT vorgelesen — der Text landet aber normal in
|
||||
@@ -2763,8 +2776,16 @@ class Agent:
|
||||
self._ear_control = None # ear_control-Tool: 'off'|'on' oder None
|
||||
try:
|
||||
for iteration in range(self.MAX_TOOL_ITERATIONS):
|
||||
_model_before = turn_model
|
||||
result, turn_model = self._llm_call(
|
||||
messages, tools, active_project_id, turn_model, user_turn_ts)
|
||||
if turn_model != _model_before:
|
||||
# _llm_call ist auf das Ausweich-Modell gewechselt.
|
||||
model_reason = context_model.REASON_FALLBACK
|
||||
# modelUsage der CLI ist die Wahrheit: bei einem Tier-Alias
|
||||
# steht hier die aufgeloeste Version ("sonnet" → "claude-...").
|
||||
if result.model_used:
|
||||
answered_model = result.model_used
|
||||
if result.tool_calls:
|
||||
# Assistant-Turn mit tool_calls in messages anhaengen (nicht in Conversation!)
|
||||
messages.append(ProxyMessage(
|
||||
@@ -2915,7 +2936,13 @@ class Agent:
|
||||
elif self._ear_control == "on":
|
||||
answered_by, speak, converse = "wake-on", False, False
|
||||
# awaiting_reply = ARIA stellt eine blockierende Rueckfrage (Queue pausiert).
|
||||
return (final_reply, answered_by, speak, converse, awaiting_reply)
|
||||
# Modell-Info: was hat geantwortet und warum genau dieses. Die
|
||||
# Oberflaechen zeigen das an — sonst merkt niemand, dass ein Projekt
|
||||
# gerade auf dem Ausweich-Modell faehrt.
|
||||
model_info = {"model": answered_model or turn_model,
|
||||
"requested": turn_model,
|
||||
"reason": model_reason}
|
||||
return (final_reply, answered_by, speak, converse, awaiting_reply, model_info)
|
||||
|
||||
# ── Tool-Dispatcher ───────────────────────────────────────
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Welches Modell gilt in welchem Chat.
|
||||
|
||||
Drei Ebenen, von unten nach oben:
|
||||
|
||||
1. Einstellung — `brainModel` aus runtime.json (Diagnostic → Sprachmodell).
|
||||
Gilt fuer alles, was keine eigene Wahl hat.
|
||||
2. Pro Chat — ein Override je Kontext ("" = Hauptchat, sonst project_id).
|
||||
Damit kann ein Projekt bewusst auf einem anderen Modell laufen, ohne das
|
||||
Hauptmodell fuer alles umzustellen.
|
||||
3. Ausweich — Anthropics Sicherheitsfilter hat das gewaehlte Modell an einem
|
||||
Turn blockiert, der noch im Fenster liegt (safeguard.py). Das sticht alles,
|
||||
ist aber nur so lange aktiv, wie der Turn im Fenster steht.
|
||||
|
||||
Warum ueberhaupt ein eigener Speicher und kein Feld im Projekt-Manifest: der
|
||||
Hauptchat IST kein Projekt. Ein Manifest-Feld haette ihn aussen vor gelassen,
|
||||
und genau dort faellt eine Modellwahl am ehesten an.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Tuple
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STORE_FILE = Path(os.environ.get("CONTEXT_MODELS_FILE",
|
||||
"/shared/config/context_models.json"))
|
||||
|
||||
# Begruendungen, wie sie die Oberflaechen anzeigen. Bewusst kurze Schluessel —
|
||||
# App und Diagnostic uebersetzen sie selbst, damit die Texte dort hingehoeren,
|
||||
# wo sie gelesen werden.
|
||||
REASON_SETTING = "einstellung"
|
||||
REASON_PER_CHAT = "pro-chat"
|
||||
REASON_FALLBACK = "ausweich"
|
||||
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def _load() -> dict:
|
||||
try:
|
||||
if STORE_FILE.exists():
|
||||
data = json.loads(STORE_FILE.read_text(encoding="utf-8")) or {}
|
||||
if isinstance(data, dict):
|
||||
# Nur String→String; alles andere waere ein Schreibfehler von
|
||||
# aussen und wuerde sonst still als Modellname durchgehen.
|
||||
return {str(k): str(v) for k, v in data.items() if isinstance(v, str)}
|
||||
except Exception as exc:
|
||||
logger.warning("[context-model] lesen fehlgeschlagen: %s", exc)
|
||||
return {}
|
||||
|
||||
|
||||
def _save(data: dict) -> None:
|
||||
try:
|
||||
STORE_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = STORE_FILE.with_suffix(".json.tmp")
|
||||
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
tmp.replace(STORE_FILE)
|
||||
except Exception as exc:
|
||||
logger.warning("[context-model] schreiben fehlgeschlagen: %s", exc)
|
||||
|
||||
|
||||
def all_overrides() -> dict:
|
||||
return _load()
|
||||
|
||||
|
||||
def get(context_id: str) -> str:
|
||||
"""Der Override dieses Kontexts, oder "" wenn keiner gesetzt ist."""
|
||||
return _load().get(context_id or "", "")
|
||||
|
||||
|
||||
def set(context_id: str, model: str) -> str:
|
||||
"""Override setzen. Leerer Modellname loescht ihn (= wieder Einstellung)."""
|
||||
cid = context_id or ""
|
||||
m = (model or "").strip()
|
||||
with _lock:
|
||||
data = _load()
|
||||
if m:
|
||||
data[cid] = m
|
||||
else:
|
||||
data.pop(cid, None)
|
||||
_save(data)
|
||||
logger.info("[context-model] %s → %s", cid or "(Hauptchat)", m or "(Einstellung)")
|
||||
return m
|
||||
|
||||
|
||||
def resolve(context_id: str, default_model: str) -> Tuple[str, str]:
|
||||
"""(Modell, Begruendung) ohne Sicherheitsfilter — den kennt nur der Agent."""
|
||||
ov = get(context_id)
|
||||
if ov:
|
||||
return ov, REASON_PER_CHAT
|
||||
return default_model, REASON_SETTING
|
||||
+115
-1
@@ -39,6 +39,7 @@ import background as background_mod
|
||||
import oauth as oauth_mod
|
||||
import seed_rules as seed_rules_mod
|
||||
import safeguard as safeguard_mod
|
||||
import context_model as context_model_mod
|
||||
import projects as projects_mod
|
||||
import project_vms as project_vms_mod
|
||||
|
||||
@@ -680,6 +681,11 @@ class ChatOut(BaseModel):
|
||||
# Welcher Backend die Antwort erzeugt hat: "local" (Qwen), "claude",
|
||||
# "fast-path" (Skill/Regex). Fuer den Quell-Badge in Diagnostic.
|
||||
answered_by: str = "claude"
|
||||
# Welches Claude-Modell geantwortet hat (aus modelUsage der CLI, also die
|
||||
# aufgeloeste Version) und WARUM dieses: "einstellung" | "pro-chat" |
|
||||
# "ausweich" (Sicherheitsfilter). Leer, wenn kein Claude-Modell lief.
|
||||
model: str = ""
|
||||
model_reason: str = ""
|
||||
# Soll die Antwort vorgelesen werden? Fast-Path (reiner Steuerbefehl) = False;
|
||||
# ARIA-Antworten (local/claude) = True. System-Flag statt <voice>-Tag.
|
||||
speak: bool = True
|
||||
@@ -778,7 +784,7 @@ async def chat(body: ChatIn, background: BackgroundTasks):
|
||||
# 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, answered_by, speak, converse, awaiting_reply = await loop.run_in_executor(
|
||||
reply, answered_by, speak, converse, awaiting_reply, model_info = await loop.run_in_executor(
|
||||
None,
|
||||
lambda: a.chat(
|
||||
body.message, source=body.source, project_id=pid,
|
||||
@@ -801,6 +807,8 @@ async def chat(body: ChatIn, background: BackgroundTasks):
|
||||
events=a.pop_events(),
|
||||
project_id=pid,
|
||||
answered_by=answered_by,
|
||||
model=(model_info or {}).get("model", ""),
|
||||
model_reason=(model_info or {}).get("reason", ""),
|
||||
speak=speak,
|
||||
converse=converse,
|
||||
awaiting_reply=awaiting_reply,
|
||||
@@ -1265,6 +1273,112 @@ def safeguard_clear(body: SafeguardClearBody):
|
||||
return {"ok": True, "removed": removed}
|
||||
|
||||
|
||||
# ─── Modell pro Chat ────────────────────────────────────────────────
|
||||
# Einstellung (brainModel) < pro Chat < Ausweich (Sicherheitsfilter). Siehe
|
||||
# context_model.py. Diese Endpunkte liefern fuer jede Oberflaeche dieselbe
|
||||
# Sicht: was ist eingestellt, was laeuft WIRKLICH, und warum.
|
||||
|
||||
_MODEL_CHOICES_CACHE: dict = {"at": 0.0, "data": []}
|
||||
|
||||
|
||||
def _model_choices() -> list:
|
||||
"""Modell-Auswahl fuer die Pickers — dieselbe Liste wie in der Diagnostic
|
||||
(Proxy /v1/models, aus Anthropics Katalog). 10 Minuten im Speicher, denn
|
||||
die App fragt bei jedem Oeffnen des Pickers. Fail-soft: ohne Proxy eine
|
||||
leere Liste, die Anzeige des aktiven Modells funktioniert trotzdem."""
|
||||
import time as _t
|
||||
import httpx as _httpx
|
||||
now = _t.time()
|
||||
if _MODEL_CHOICES_CACHE["data"] and now - _MODEL_CHOICES_CACHE["at"] < 600:
|
||||
return _MODEL_CHOICES_CACHE["data"]
|
||||
try:
|
||||
base = os.environ.get("PROXY_URL", "http://proxy:3456").rstrip("/")
|
||||
r = _httpx.get(f"{base}/v1/models", timeout=8)
|
||||
data = [{
|
||||
"id": m.get("id", ""),
|
||||
"name": m.get("display_name") or m.get("id", ""),
|
||||
"section": m.get("section") or "tier",
|
||||
} for m in (r.json().get("data") or []) if m.get("id")]
|
||||
if data:
|
||||
_MODEL_CHOICES_CACHE.update(at=now, data=data)
|
||||
return data
|
||||
except Exception as exc:
|
||||
logger.warning("[context-model] Modell-Liste vom Proxy nicht ladbar: %s", exc)
|
||||
return _MODEL_CHOICES_CACHE["data"]
|
||||
|
||||
|
||||
def _context_model_rows() -> dict:
|
||||
a = agent()
|
||||
conv = conversation()
|
||||
# Das Modell, mit dem das Brain gerade wirklich laeuft — NICHT neu aus
|
||||
# runtime.json gelesen. brainModel greift erst nach Neustart; zeigten wir
|
||||
# hier den Dateiwert, saehe ein ausstehender Neustart aus wie erledigt.
|
||||
default = a.proxy.model
|
||||
contexts = [("", "Hauptchat")] + [
|
||||
(p["id"], p.get("name") or p["id"])
|
||||
for p in projects_mod.list_projects()
|
||||
]
|
||||
rows = []
|
||||
for cid, name in contexts:
|
||||
override = context_model_mod.get(cid)
|
||||
model, reason = context_model_mod.resolve(cid, default)
|
||||
window = safeguard_mod.filter_window(conv.window(project_id=cid))
|
||||
blocked = safeguard_mod.blocked_models(cid, [t.ts for t in window])
|
||||
fallback = ""
|
||||
if safeguard_mod.norm_model(model) in blocked:
|
||||
fallback = safeguard_mod.fallback_for(model)
|
||||
reason = context_model_mod.REASON_FALLBACK
|
||||
rows.append({
|
||||
"context_id": cid,
|
||||
"name": name,
|
||||
"override": override, # "" = folgt der Einstellung
|
||||
"selected": model, # was gewaehlt ist (Einstellung/pro Chat)
|
||||
"effective": fallback or model, # was der naechste Turn nutzt
|
||||
"reason": reason,
|
||||
"blocked": sorted(blocked),
|
||||
})
|
||||
choices = _model_choices()
|
||||
names = {c["id"]: c["name"] for c in choices}
|
||||
return {"default": default, "rows": rows, "choices": choices, "names": names}
|
||||
|
||||
|
||||
@app.get("/context-model/list")
|
||||
def context_model_list():
|
||||
return _context_model_rows()
|
||||
|
||||
|
||||
class ContextModelBody(BaseModel):
|
||||
context_id: str = ""
|
||||
model: str = "" # leer = Override loeschen, Einstellung gilt wieder
|
||||
|
||||
|
||||
@app.post("/context-model/set")
|
||||
def context_model_set(body: ContextModelBody):
|
||||
cid = (body.context_id or "").strip()
|
||||
if cid and not projects_mod.get_project(cid):
|
||||
raise HTTPException(404, f"Projekt {cid} nicht gefunden")
|
||||
context_model_mod.set(cid, body.model)
|
||||
return _context_model_rows()
|
||||
|
||||
|
||||
class ContextModelResetBody(BaseModel):
|
||||
context_id: str = ""
|
||||
|
||||
|
||||
@app.post("/context-model/back-to-selected")
|
||||
def context_model_back(body: ContextModelResetBody):
|
||||
"""Ausweich beenden: Sicherheitsfilter-Vermerke dieses Chats loeschen.
|
||||
|
||||
Danach laeuft der naechste Turn wieder auf dem gewaehlten Modell. Steht
|
||||
der ausloesende Text noch im Verlauf, kann der Filter erneut greifen —
|
||||
dann weicht das Brain eben wieder aus. Das ist gewollt: zurueck soll
|
||||
jederzeit gehen, ohne dass man vorher irgendwas aufraeumen muss."""
|
||||
removed = safeguard_mod.clear((body.context_id or "").strip())
|
||||
out = _context_model_rows()
|
||||
out["removed"] = removed
|
||||
return out
|
||||
|
||||
|
||||
# ─── Call-Metrics (Token / Quota-Monitoring) ────────────────────────
|
||||
|
||||
@app.get("/metrics/calls")
|
||||
|
||||
+20
-2
@@ -1593,14 +1593,22 @@ class ARIABridge:
|
||||
# File-Marker werden separat als file_from_aria-Events ausgeliefert.
|
||||
display_text = strip_voice_tag_for_display(text)
|
||||
_answered_by = (payload.get("answeredBy") or "") if isinstance(payload, dict) else ""
|
||||
assistant_backup_ts = self._append_chat_backup({
|
||||
_model = (payload.get("model") or "") if isinstance(payload, dict) else ""
|
||||
_model_reason = (payload.get("modelReason") or "") if isinstance(payload, dict) else ""
|
||||
_backup_rec = {
|
||||
"role": "assistant",
|
||||
"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,
|
||||
"answeredBy": _answered_by,
|
||||
})
|
||||
}
|
||||
# Nur wenn ein Claude-Modell lief — sonst bliebe ein leeres Feld in
|
||||
# jeder Fast-Path-Zeile stehen.
|
||||
if _model:
|
||||
_backup_rec["model"] = _model
|
||||
_backup_rec["modelReason"] = _model_reason
|
||||
assistant_backup_ts = self._append_chat_backup(_backup_rec)
|
||||
|
||||
metadata = payload.get("metadata", {})
|
||||
is_critical = metadata.get("critical", False)
|
||||
@@ -1651,6 +1659,10 @@ class ARIABridge:
|
||||
"projectId": (payload.get("projectId") or "") if isinstance(payload, dict) else "",
|
||||
# Quell-Backend (local/claude/fast-path) fuer den Diagnostic-Badge.
|
||||
"answeredBy": (payload.get("answeredBy") or "") if isinstance(payload, dict) else "",
|
||||
# Welches Claude-Modell + warum ("einstellung"/"pro-chat"/
|
||||
# "ausweich"). Leer bei Fast-Path/lokal.
|
||||
"model": _model,
|
||||
"modelReason": _model_reason,
|
||||
# Wird diese Antwort vorgelesen? Fast-Path/Steuerbefehl = False.
|
||||
# Die App braucht das: ohne TTS feuert onPlaybackFinished nie,
|
||||
# und daran haengt das Wake-Word-Re-Arm — sonst bleibt das Ohr
|
||||
@@ -2079,6 +2091,10 @@ class ARIABridge:
|
||||
# Welcher Backend geantwortet hat (local/claude/fast-path) — fuer den
|
||||
# Quell-Badge in Diagnostic.
|
||||
answered_by = (data.get("answered_by") or "claude").strip()
|
||||
# Welches Claude-Modell geantwortet hat + warum (einstellung/pro-chat/
|
||||
# ausweich). Fuer die Anzeige in App und Diagnostic.
|
||||
answered_model = (data.get("model") or "").strip()
|
||||
model_reason = (data.get("model_reason") or "").strip()
|
||||
# Soll vorgelesen werden? Fast-Path (Steuerbefehl) = False. System-Flag
|
||||
# vom Brain — robust, unabhaengig von <voice>-Tags im Reply-Text.
|
||||
speak = data.get("speak", True)
|
||||
@@ -2181,6 +2197,8 @@ class ARIABridge:
|
||||
try:
|
||||
await self._process_core_response(reply, {"projectId": turn_project_id,
|
||||
"answeredBy": answered_by,
|
||||
"model": answered_model,
|
||||
"modelReason": model_reason,
|
||||
"speak": speak,
|
||||
"converse": converse,
|
||||
"awaiting_reply": awaiting_reply,
|
||||
|
||||
+137
-7
@@ -417,6 +417,7 @@
|
||||
<div id="chat-context-strip" style="display:flex;gap:6px;overflow-x:auto;padding:6px 4px;flex:1;min-width:0;">
|
||||
<!-- wird von renderContextStrip() befuellt -->
|
||||
</div>
|
||||
<div id="ctx-model-bar" style="flex:0 0 auto;display:flex;align-items:center;gap:6px;"></div>
|
||||
<button class="btn secondary" onclick="openCreateProjectModal()"
|
||||
title="Neues Projekt anlegen — wird direkt angelegt, aktiviert und hier fokussiert"
|
||||
style="flex:0 0 auto;padding:4px 10px;font-size:11px;margin-right:4px;">+ Projekt</button>
|
||||
@@ -1993,6 +1994,7 @@
|
||||
localStorage.setItem('diag_focused_context_id', focusedContextId);
|
||||
updateChatVisibilityByFocus();
|
||||
renderContextStrip();
|
||||
renderCtxModelBar();
|
||||
renderDiagQueue();
|
||||
}
|
||||
|
||||
@@ -2039,7 +2041,7 @@
|
||||
const cards = [];
|
||||
// Hauptchat
|
||||
const mainDot = dotFor('__main__');
|
||||
cards.push(chip('', '💬 Hauptchat', focusedContextId === '', mainDot.color, mainDot.label || 'idle'));
|
||||
cards.push(chip('', '💬 Hauptchat', focusedContextId === '', mainDot.color, (mainDot.label || 'idle') + ctxModelSub('')));
|
||||
// Projekte — nur active/ended, sortiert nach letzter Aktivitaet.
|
||||
// Versteckte standardmaessig raus; per Toggle-Chip einblendbar.
|
||||
let hiddenCount = 0;
|
||||
@@ -2050,7 +2052,7 @@
|
||||
if (!diagShowHiddenStrip) continue;
|
||||
}
|
||||
const d = dotFor(p.id);
|
||||
const sub = d.label || `${p.turn_count} Turns`;
|
||||
const sub = (d.label || `${p.turn_count} Turns`) + ctxModelSub(p.id);
|
||||
cards.push(projChip(p, focusedContextId === p.id, d.color, sub));
|
||||
}
|
||||
// Toggle-Chip am Ende (nur wenn es versteckte gibt oder gerade gezeigt werden)
|
||||
@@ -2131,6 +2133,9 @@
|
||||
diagProjectsCache = d?.projects || [];
|
||||
renderContextStrip();
|
||||
} catch {}
|
||||
// Modelle pro Chat im selben Takt — neue Projekte brauchen eine Zeile,
|
||||
// und ein abgelaufener Ausweich-Vermerk soll von selbst verschwinden.
|
||||
refreshCtxModels();
|
||||
}
|
||||
|
||||
// Beim Load: Projekte laden + Polling starten
|
||||
@@ -2678,7 +2683,12 @@
|
||||
backupTs: p.backupTs,
|
||||
projectId: p.projectId || '',
|
||||
answeredBy: p.answeredBy || '',
|
||||
model: p.model || '',
|
||||
modelReason: p.modelReason || '',
|
||||
});
|
||||
// Wechselt ein Turn aufs Ausweich-Modell, soll Streifen + Auswahl
|
||||
// das sofort zeigen, nicht erst beim naechsten 15s-Poll.
|
||||
if (sender === 'aria' && p.model) refreshCtxModels();
|
||||
// ── Pro-Kontext-Queue-Automat: auf ARIAs Antwort reagieren ──
|
||||
if (sender === 'aria') {
|
||||
const apid = p.projectId || '';
|
||||
@@ -2788,7 +2798,7 @@
|
||||
const trashBtn = m.ts
|
||||
? `<button class="bubble-trash" title="Diese Bubble loeschen" onclick="deleteDiagBubble(${m.ts})">🗑</button>`
|
||||
: '';
|
||||
const histBadge = srcBadgeHtml(m.type, m.answeredBy || '');
|
||||
const histBadge = srcBadgeHtml(m.type, m.answeredBy || '', m.model || '', m.modelReason || '');
|
||||
const innerHtml = `${trashBtn}${linked}<div class="meta">${escapeHtml(m.meta)}${histBadge} — ${time}</div>`;
|
||||
for (const b of boxes) {
|
||||
const el = document.createElement('div');
|
||||
@@ -3278,15 +3288,134 @@
|
||||
}
|
||||
|
||||
// Quell-Badge (local/claude/fast-path) fuer ARIA-Bubbles — in Live + History genutzt.
|
||||
function srcBadgeHtml(type, answeredBy) {
|
||||
function srcBadgeHtml(type, answeredBy, model, reason) {
|
||||
if (type !== 'received' || !answeredBy) return '';
|
||||
const M = {
|
||||
'local': { t: '⚡ lokal', c: '#34C759' },
|
||||
'claude': { t: 'Claude', c: '#0096FF' },
|
||||
'fast-path': { t: '⚡ Fast-Path', c: '#AF7BFF' },
|
||||
};
|
||||
const b = M[answeredBy] || { t: answeredBy, c: '#8888AA' };
|
||||
return `<span title="Antwort erzeugt von: ${escapeHtml(answeredBy)}" style="display:inline-block;margin-left:6px;padding:1px 6px;border-radius:8px;font-size:9px;font-weight:bold;background:${b.c}22;color:${b.c};border:1px solid ${b.c}55;">${b.t}</span>`;
|
||||
let b = M[answeredBy] || { t: answeredBy, c: '#8888AA' };
|
||||
let title = 'Antwort erzeugt von: ' + answeredBy;
|
||||
// Bei Claude das tatsaechliche Modell zeigen. Aeltere Bubbles (vor der
|
||||
// Modell-Anzeige) haben keins — die bleiben bei "Claude".
|
||||
if (answeredBy === 'claude' && model) {
|
||||
const name = prettyModel(model);
|
||||
if (reason === 'ausweich') {
|
||||
b = { t: '↪ ' + name, c: '#FF9F0A' };
|
||||
title = name + ' — Ausweich-Modell, weil Anthropics Sicherheitsfilter das gewählte Modell blockiert hat';
|
||||
} else if (reason === 'pro-chat') {
|
||||
b = { t: name + ' ·', c: '#0096FF' };
|
||||
title = name + ' — für diesen Chat gewählt (' + model + ')';
|
||||
} else {
|
||||
b = { t: name, c: '#0096FF' };
|
||||
title = name + ' — aus der Einstellung (' + model + ')';
|
||||
}
|
||||
}
|
||||
return `<span title="${escapeHtml(title)}" style="display:inline-block;margin-left:6px;padding:1px 6px;border-radius:8px;font-size:9px;font-weight:bold;background:${b.c}22;color:${b.c};border:1px solid ${b.c}55;">${escapeHtml(b.t)}</span>`;
|
||||
}
|
||||
|
||||
// ── Modell pro Chat ───────────────────────────────────────────────
|
||||
// Zustand vom Brain (/context-model/list): pro Kontext gewaehltes und
|
||||
// effektives Modell + Grund, dazu die Auswahl aus Anthropics Katalog.
|
||||
let diagCtxModels = { default: '', rows: [], choices: [], names: {} };
|
||||
let diagModelNames = {};
|
||||
|
||||
// "claude-sonnet-5-5" → "Sonnet 5.5". Katalog-Namen haben Vorrang; der
|
||||
// Fallback greift fuer Aliase und Versionen, die der Katalog nicht kennt.
|
||||
// Datums-Suffixe ("-20251001") gehoeren nicht zur Version.
|
||||
function prettyModel(id) {
|
||||
if (!id) return '';
|
||||
if (diagModelNames[id]) return diagModelNames[id];
|
||||
const m = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-|$)/.exec(id);
|
||||
if (m) return m[1][0].toUpperCase() + m[1].slice(1) + ' ' + m[2] + (m[3] ? '.' + m[3] : '');
|
||||
return id.charAt(0).toUpperCase() + id.slice(1);
|
||||
}
|
||||
|
||||
function ctxModelRow(cid) {
|
||||
return (diagCtxModels.rows || []).find(r => r.context_id === (cid || '')) || null;
|
||||
}
|
||||
|
||||
async function refreshCtxModels() {
|
||||
try {
|
||||
const r = await fetch('/api/brain/context-model/list');
|
||||
if (!r.ok) return;
|
||||
diagCtxModels = await r.json();
|
||||
diagModelNames = diagCtxModels.names || {};
|
||||
renderContextStrip();
|
||||
renderCtxModelBar();
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Auswahl fuer den fokussierten Chat — neben "+ Projekt".
|
||||
function renderCtxModelBar() {
|
||||
const bar = document.getElementById('ctx-model-bar');
|
||||
if (!bar) return;
|
||||
const row = ctxModelRow(focusedContextId);
|
||||
if (!row) { bar.innerHTML = ''; return; }
|
||||
const def = prettyModel(diagCtxModels.default) || diagCtxModels.default || '?';
|
||||
const groups = { tier: 'Automatisch (neueste Version)', main: 'Aktuelle Versionen', overflow: 'Ältere Versionen' };
|
||||
let opts = `<option value="">Einstellung (${escapeHtml(def)})</option>`;
|
||||
for (const [sec, label] of Object.entries(groups)) {
|
||||
const inSec = (diagCtxModels.choices || []).filter(c => (c.section || 'tier') === sec);
|
||||
if (!inSec.length) continue;
|
||||
opts += `<optgroup label="${escapeHtml(label)}">` + inSec.map(c =>
|
||||
`<option value="${escapeHtml(c.id)}"${c.id === row.override ? ' selected' : ''}>${escapeHtml(c.name)}</option>`
|
||||
).join('') + '</optgroup>';
|
||||
}
|
||||
// Ein gesetzter Override, den der Katalog nicht (mehr) kennt, darf nicht
|
||||
// still aus der Auswahl fallen — sonst saehe es aus wie "Einstellung".
|
||||
if (row.override && !(diagCtxModels.choices || []).some(c => c.id === row.override)) {
|
||||
opts += `<option value="${escapeHtml(row.override)}" selected>${escapeHtml(row.override)}</option>`;
|
||||
}
|
||||
let status = '';
|
||||
if (row.reason === 'ausweich') {
|
||||
status = `<span title="Anthropics Sicherheitsfilter hat ${escapeHtml(row.selected)} in diesem Chat blockiert — der Turn liegt noch im Fenster" style="color:#FF9F0A;font-size:10px;font-weight:600;white-space:nowrap;">↪ läuft auf ${escapeHtml(prettyModel(row.effective))}</span>
|
||||
<button class="btn secondary" onclick="ctxModelBack()" title="Vermerk löschen — der nächste Turn nutzt wieder ${escapeHtml(prettyModel(row.selected))}. Blockt der Filter erneut, weicht ARIA eben wieder aus." style="padding:2px 8px;font-size:10px;white-space:nowrap;">↩ zurück zu ${escapeHtml(prettyModel(row.selected))}</button>`;
|
||||
}
|
||||
bar.innerHTML = `<span style="font-size:11px;color:#8888AA;" title="Modell für diesen Chat">🧠</span>
|
||||
<select onchange="setCtxModel(this.value)" title="Modell für diesen Chat — gilt nur hier, die Einstellung bleibt für alle anderen"
|
||||
style="max-width:180px;background:#1E1E2E;border:1px solid #333;border-radius:4px;padding:3px 6px;color:#E0E0F0;font-family:inherit;font-size:11px;">${opts}</select>
|
||||
${status}`;
|
||||
}
|
||||
|
||||
async function setCtxModel(model) {
|
||||
try {
|
||||
const r = await fetch('/api/brain/context-model/set', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ context_id: focusedContextId || '', model }),
|
||||
});
|
||||
if (!r.ok) throw new Error('HTTP ' + r.status);
|
||||
diagCtxModels = await r.json();
|
||||
diagModelNames = diagCtxModels.names || {};
|
||||
renderContextStrip();
|
||||
renderCtxModelBar();
|
||||
} catch (e) { alert('Modell setzen fehlgeschlagen: ' + e.message); }
|
||||
}
|
||||
|
||||
async function ctxModelBack() {
|
||||
try {
|
||||
const r = await fetch('/api/brain/context-model/back-to-selected', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ context_id: focusedContextId || '' }),
|
||||
});
|
||||
if (!r.ok) throw new Error('HTTP ' + r.status);
|
||||
diagCtxModels = await r.json();
|
||||
diagModelNames = diagCtxModels.names || {};
|
||||
renderContextStrip();
|
||||
renderCtxModelBar();
|
||||
try { loadSafeguard(); } catch {}
|
||||
} catch (e) { alert('Zurückschalten fehlgeschlagen: ' + e.message); }
|
||||
}
|
||||
|
||||
// Untertitel der Kontext-Karten: welches Modell der naechste Turn nutzt.
|
||||
function ctxModelSub(cid) {
|
||||
const row = ctxModelRow(cid);
|
||||
if (!row || !row.effective) return '';
|
||||
const name = escapeHtml(prettyModel(row.effective));
|
||||
if (row.reason === 'ausweich') return ` · <span style="color:#FF9F0A;" title="Ausweich-Modell (Sicherheitsfilter)">↪ ${name}</span>`;
|
||||
if (row.reason === 'pro-chat') return ` · <span style="color:#0096FF;" title="Für diesen Chat gewählt">${name}</span>`;
|
||||
return ` · ${name}`;
|
||||
}
|
||||
|
||||
function addChat(type, text, meta, options) {
|
||||
@@ -3324,7 +3453,8 @@
|
||||
? `<button class="bubble-trash" title="Diese Bubble loeschen" onclick="deleteDiagBubble(${backupTs})">🗑</button>`
|
||||
: '';
|
||||
// Quell-Badge: welcher Backend die Antwort erzeugt hat (nur ARIA-Bubbles)
|
||||
const srcBadge = srcBadgeHtml(type, (options && options.answeredBy) || '');
|
||||
const srcBadge = srcBadgeHtml(type, (options && options.answeredBy) || '',
|
||||
(options && options.model) || '', (options && options.modelReason) || '');
|
||||
const html = `${trashBtn}${linked}${ttsBlock}${gpsBlock}<div class="meta">${escapeHtml(meta)}${srcBadge} — ${new Date().toLocaleTimeString('de-DE')}</div>`;
|
||||
|
||||
// Thinking-Indikator ausblenden bei neuer Nachricht
|
||||
|
||||
@@ -3581,6 +3581,8 @@ async function handleLoadChatHistory(clientWs) {
|
||||
const text = String(obj.text || "");
|
||||
const projectId = String(obj.project_id || ""); // Multi-Threading: Kontext-Zuordnung
|
||||
const answeredBy = String(obj.answeredBy || ""); // Quell-Badge (local/claude/fast-path)
|
||||
const model = String(obj.model || ""); // welches Claude-Modell
|
||||
const modelReason = String(obj.modelReason || ""); // einstellung/pro-chat/ausweich
|
||||
if (obj.role === "user") {
|
||||
if (text) messages.push({ type: "sent", text, meta: "Gateway direkt", ts, projectId });
|
||||
continue;
|
||||
@@ -3607,7 +3609,7 @@ async function handleLoadChatHistory(clientWs) {
|
||||
projectId,
|
||||
});
|
||||
}
|
||||
if (text) messages.push({ type: "received", text, meta: "chat:final", ts, projectId, answeredBy });
|
||||
if (text) messages.push({ type: "received", text, meta: "chat:final", ts, projectId, answeredBy, model, modelReason });
|
||||
}
|
||||
|
||||
clientWs.send(JSON.stringify({ type: "chat_history", messages }));
|
||||
|
||||
Reference in New Issue
Block a user